From: Bernhard Tittelbach Date: Tue, 24 Sep 2013 01:33:44 +0000 (+0000) Subject: move r3-netstatus to go-dir X-Git-Url: https://git.realraum.at/?a=commitdiff_plain;h=70bd6ea215fdd1dbd2eb9556ff4aa0a2acde24bc;p=svn42.git move r3-netstatus to go-dir --- diff --git a/go/r3-netstatus/brain/brain.go b/go/r3-netstatus/brain/brain.go new file mode 100644 index 0000000..cc9b83c --- /dev/null +++ b/go/r3-netstatus/brain/brain.go @@ -0,0 +1,116 @@ +package brain + +import "errors" + +type informationtuple struct { + name string + value interface{} +} + +type informationretrievalpath struct { + name string + returnpath chan interface{} +} + +type hippocampus map[string]interface{} + +type Brain struct { + storeTuple chan informationtuple + retrieveValue chan informationretrievalpath + shutdown chan bool +} + +func New() *Brain { + b := new(Brain) + b.storeTuple = make(chan informationtuple) + b.retrieveValue = make(chan informationretrievalpath) + go b.runBrain() + return b +} + +func (b *Brain) runBrain() { + var h hippocampus = make(hippocampus) + for { + select { + case newtuple := <- b.storeTuple: + h[newtuple.name] = newtuple.value + + case retrievvalue := <- b.retrieveValue: + v, e := h[retrievvalue.name] + if e { + retrievvalue.returnpath <- v + } else { + retrievvalue.returnpath <- nil + } + + case <- b.shutdown: + break + } + } +} + +func (b *Brain) Shutdown() { + b.shutdown <- true +} + +func (b *Brain) Oboite(name string, value interface{}) { + b.storeTuple <- informationtuple{name, value} +} + +func (b *Brain) OmoiDashite(name string) (interface{}, error) { + rc := make(chan interface{}) + b.retrieveValue <- informationretrievalpath{name, rc} + v := <- rc + if v == nil { + return v, errors.New("name not in brain") + } + return v, nil +} + +func (b *Brain) OmoiDashiteBool(name string) (bool, error) { + v, e := b.OmoiDashite(name) + if e != nil { + return false, e + } + vc, ok := v.(bool) + if !ok { + return false, errors.New(name + " does not have type bool") + } + return vc, nil +} + +func (b *Brain) OmoiDashiteInt(name string) (int, error) { + v, e := b.OmoiDashite(name) + if e != nil { + return 0, e + } + vc, ok := v.(int) + if !ok { + return 0, errors.New(name + " does not have type int") + } + return vc, nil +} + +func (b *Brain) OmoiDashiteFloat(name string) (float64, error) { + v, e := b.OmoiDashite(name) + if e != nil { + return 0, e + } + vc, ok := v.(float64) + if !ok { + return 0, errors.New(name + " does not have type float64") + } + return vc, nil +} + +func (b *Brain) OmoiDashiteString(name string) (string, error) { + v, e := b.OmoiDashite(name) + if e != nil { + return "", e + } + vc, ok := v.(string) + if !ok { + return "", errors.New(name + " does not have type string") + } + return vc, nil +} \ No newline at end of file diff --git a/go/r3-netstatus/main.go b/go/r3-netstatus/main.go new file mode 100644 index 0000000..6f53ac3 --- /dev/null +++ b/go/r3-netstatus/main.go @@ -0,0 +1,140 @@ +package main + +import ( + "./r3xmppbot" + pubsub "github.com/tuxychandru/pubsub" + "flag" + "time" + "fmt" + //~ "./brain" +) + +type SpaceState struct { + present bool + buttonpress_until int64 + door_locked bool + door_shut bool +} + +var ( + presence_socket_path_ string + xmpp_presence_events_chan_ chan interface{} + xmpp_login_ struct {jid string; pass string} + xmpp_bot_authstring_ string + xmpp_state_save_dir_ string + button_press_timeout_ int64 = 3600 +) + +//------- + +func init() { + flag.StringVar(&xmpp_login_.jid, "xjid", "realrauminfo@realraum.at/Tuer", "XMPP Bot Login JID") + flag.StringVar(&xmpp_login_.pass, "xpass", "", "XMPP Bot Login Password") + flag.StringVar(&xmpp_bot_authstring_, "xbotauth", "", "String that user use to authenticate themselves to the bot") + flag.StringVar(&presence_socket_path_,"presencesocket", "/var/run/tuer/presence.socket", "Path to presence socket") + flag.StringVar(&xmpp_state_save_dir_,"xstatedir","/flash/var/lib/r3netstatus/", "Directory to save XMPP bot state in") + flag.Parse() +} + +//------- + +func IfThenElseStr(c bool, strue, sfalse string) string { + if c {return strue} else {return sfalse} +} + +func composeMessage(present, locked, shut bool, who string, ts int64) string { + return fmt.Sprintf("%s (Door is %s and %s and was last used%s at %s)", + IfThenElseStr(present, "Somebody is present!" , "Everybody left."), + IfThenElseStr(locked, "locked","unlocked"), + IfThenElseStr(shut, "shut","ajar"), + IfThenElseStr(len(who) == 0,"", " by " + who), + time.Unix(ts,0).String()) +} + +func EventToXMPP(ps *pubsub.PubSub, xmpp_presence_events_chan_ chan <- interface{}) { + events := ps.Sub("presence","door","buttons","updateinterval") + + defer func() { + if x := recover(); x != nil { + fmt.Printf("handleIncomingXMPPStanzas: run time panic: %v", x) + ps.Unsub(events, "presence","door","buttons","updateinterval") + close(xmpp_presence_events_chan_) + } + }() + + var present, locked, shut bool = false, true, true + var last_buttonpress int64 = 0 + var who string + button_msg := "The button has been pressed ! Propably someone is bored and in need of company ! ;-)" + present_status := r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowOnline,"Somebody is present"} + notpresent_status := r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowNotAvailabe,"Nobody is here"} + button_status := r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowFreeForChat, "The button has been pressed :-)"} + + xmpp_presence_events_chan_ <- r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowNotAvailabe, "Nobody is here"} + + for eventinterface := range(events) { + switch event := eventinterface.(type) { + case PresenceUpdate: + present = event.Present + xmpp_presence_events_chan_ <- r3xmppbot.XMPPMsgEvent{Msg: composeMessage(present, locked, shut, who, event.Ts), DistributeLevel: r3xmppbot.R3OnlineOnlyInfo, RememberAsStatus: true} + if present { + xmpp_presence_events_chan_ <- present_status + } else { + xmpp_presence_events_chan_ <- notpresent_status + } + case DoorCommandEvent: + if len(event.Who) > 0 && len(event.Using) > 0 { + who = fmt.Sprintf("%s (%s)",event.Who, event.Using) + } else { + who = event.Who + } + xmpp_presence_events_chan_ <- fmt.Sprintln("DoorCommand:",event.Command, "using", event.Using, "by", event.Who, time.Unix(event.Ts,0)) + case DoorStatusUpdate: + locked = event.Locked + shut = event.Shut + xmpp_presence_events_chan_ <- r3xmppbot.XMPPMsgEvent{Msg: composeMessage(present, locked, shut, who, event.Ts), DistributeLevel: r3xmppbot.R3DebugInfo, RememberAsStatus: true} + case ButtonPressUpdate: + xmpp_presence_events_chan_ <- r3xmppbot.XMPPMsgEvent{Msg: button_msg, DistributeLevel: r3xmppbot.R3OnlineOnlyInfo} + xmpp_presence_events_chan_ <- button_status + last_buttonpress = event.Ts + case TimeTick: + if present && last_buttonpress > 0 && time.Now().Unix() - last_buttonpress > button_press_timeout_ { + xmpp_presence_events_chan_ <- present_status + last_buttonpress = 0 + } + } + } +} + +func main() { + var xmpperr error + var bot *r3xmppbot.XmppBot + bot, xmpp_presence_events_chan_, xmpperr = r3xmppbot.NewStartedBot(xmpp_login_.jid, xmpp_login_.pass, xmpp_bot_authstring_, xmpp_state_save_dir_, true) + + newlinequeue := make(chan string, 1) + ps := pubsub.New(1) + //~ brn := brain.New() + defer close(newlinequeue) + defer ps.Shutdown() + //~ defer brn.Shutdown() + + go EventToWeb(ps) + if xmpperr == nil { + defer bot.StopBot() + go EventToXMPP(ps, xmpp_presence_events_chan_) + } else { + fmt.Println(xmpperr) + fmt.Println("XMPP Bot disabled") + } + go ReadFromUSocket(presence_socket_path_, newlinequeue) + ticker := time.NewTicker(time.Duration(7) * time.Minute) + + for { + select { + case e := <-newlinequeue: + ParseSocketInputLine(e, ps) //, brn) + case <-ticker.C: + ps.Pub(TimeTick{time.Now().Unix()}, "updateinterval") + } + } +} diff --git a/go/r3-netstatus/make_deploy.zsh b/go/r3-netstatus/make_deploy.zsh new file mode 100644 index 0000000..408b049 --- /dev/null +++ b/go/r3-netstatus/make_deploy.zsh @@ -0,0 +1,6 @@ +#!/bin/zsh +export GO386=387 +go-linux-386 clean +#go-linux-386 build +#strip ${PWD:t} +go-linux-386 build -ldflags "-s" && rsync -v ${PWD:t} wuzzler.realraum.at:/flash/tuer/ diff --git a/go/r3-netstatus/r3xmppbot/r3xmppbot.go b/go/r3-netstatus/r3xmppbot/r3xmppbot.go new file mode 100644 index 0000000..48a9f5c --- /dev/null +++ b/go/r3-netstatus/r3xmppbot/r3xmppbot.go @@ -0,0 +1,421 @@ +package r3xmppbot + +import ( + xmpp "code.google.com/p/goexmpp" + "log" + "crypto/tls" + "os" + "time" + "encoding/json" + "path" +) + +//~ type StdLogger struct { +//~ } + +//~ func (s *StdLogger) Log(v ...interface{}) { + //~ log.Println(v...) +//~ } + +//~ func (s *StdLogger) Logf(fmt string, v ...interface{}) { + //~ log.Printf(fmt, v...) +//~ } + + +func (botdata *XmppBot) makeXMPPMessage(to string, message interface{}, subject interface{}) *xmpp.Message { + xmppmsgheader := xmpp.Header{To: to, + From: botdata.my_jid_, + Id: <-xmpp.Id, + Type: "chat", + Lang: "", + Innerxml: "", + Error: nil, + Nested: make([]interface{},0)} + + var msgsubject, msgbody *xmpp.Generic + switch cast_msg := message.(type) { + case string: + msgbody = &xmpp.Generic{Chardata: cast_msg} + case *string: + msgbody = &xmpp.Generic{Chardata: *cast_msg} + case *xmpp.Generic: + msgbody = cast_msg + default: + msgbody = &xmpp.Generic{} + } + switch cast_msg := subject.(type) { + case string: + msgsubject = &xmpp.Generic{Chardata: cast_msg} + case *string: + msgsubject = &xmpp.Generic{Chardata: *cast_msg} + case *xmpp.Generic: + msgsubject = cast_msg + default: + msgsubject = &xmpp.Generic{} + } + return &xmpp.Message{Header: xmppmsgheader , Subject: msgsubject, Body: msgbody, Thread: &xmpp.Generic{}} +} + +func (botdata *XmppBot) makeXMPPPresence(to, ptype, show, status string) *xmpp.Presence { + xmppmsgheader := xmpp.Header{To: to, + From: botdata.my_jid_, + Id: <-xmpp.Id, + Type: ptype, + Lang: "", + Innerxml: "", + Error: nil, + Nested: make([]interface{},0)} + var gen_show, gen_status *xmpp.Generic + if len(show) == 0 { + gen_show = nil + } else { + gen_show = &xmpp.Generic{Chardata: show} + } + if len(status) == 0 { + gen_status = nil + } else { + gen_status = &xmpp.Generic{Chardata: status} + } + return &xmpp.Presence{Header: xmppmsgheader, Show: gen_show, Status: gen_status} +} + +type R3JIDDesire int + +const ( + R3NoChange R3JIDDesire = -1 + R3NeverInfo R3JIDDesire = iota // ignore first value by assigning to blank identifier + R3OnlineOnlyInfo + R3OnlineOnlyWithRecapInfo + R3AlwaysInfo + R3DebugInfo +) + +const ( + ShowOnline string = "" + ShowAway string = "away" + ShowNotAvailabe string = "xa" + ShowDoNotDisturb string = "dnd" + ShowFreeForChat string = "chat" +) + +type JidData struct { + Online bool + Wants R3JIDDesire +} + +type JabberEvent struct { + JID string + Online bool + Wants R3JIDDesire + StatusNow bool +} + +type XMPPMsgEvent struct { + Msg string + DistributeLevel R3JIDDesire + RememberAsStatus bool +} + +type XMPPStatusEvent struct { + Show string + Status string +} + +type RealraumXmppNotifierConfig map[string]JidData + +type XmppBot struct { + jid_lastauthtime_ map[string]int64 + realraum_jids_ RealraumXmppNotifierConfig + password_ string + auth_cmd_ string + auth_cmd2_ string + my_jid_ string + auth_timeout_ int64 + config_file_ string + my_login_password_ string + xmppclient_ *xmpp.Client + presence_events_ *chan interface{} +} + + +func (data RealraumXmppNotifierConfig) saveTo(filepath string) () { + fh, err := os.Create(filepath) + if err != nil { + log.Println(err) + return + } + defer fh.Close() + enc := json.NewEncoder(fh) + if err = enc.Encode(&data); err != nil { + log.Println(err) + return + } +} + +func (data RealraumXmppNotifierConfig) loadFrom(filepath string) () { + fh, err := os.Open(filepath) + if err != nil { + log.Println(err) + return + } + defer fh.Close() + dec := json.NewDecoder(fh) + if err = dec.Decode(&data); err != nil { + log.Println(err) + return + } + for to, jiddata := range data { + jiddata.Online = false + data[to]=jiddata + } +} + + +func init() { + //~ logger := &StdLogger{} + //~ xmpp.Debug = logger + //~ xmpp.Info = logger + //~ xmpp.Warn = logger +} + +func (botdata *XmppBot) handleEventsforXMPP(xmppout chan <- xmpp.Stanza, presence_events <- chan interface{}, jabber_events <- chan JabberEvent) { + var last_status_msg *string + + defer func() { + if x := recover(); x != nil { + log.Printf("handleEventsforXMPP: run time panic: %v", x) + } + }() + + for { + select { + case pe := <-presence_events: + switch pec := pe.(type) { + case xmpp.Stanza: + xmppout <- pec + continue + case string: + for to, jiddata := range botdata.realraum_jids_ { + if jiddata.Wants >= R3DebugInfo { + xmppout <- botdata.makeXMPPMessage(to, pec, nil) + } + } + + case XMPPStatusEvent: + xmppout <- botdata.makeXMPPPresence("", "", pec.Show, pec.Status) + + case XMPPMsgEvent: + if pec.RememberAsStatus { + last_status_msg = &pec.Msg + } + for to, jiddata := range botdata.realraum_jids_ { + if jiddata.Wants >= pec.DistributeLevel && ((jiddata.Wants >= R3OnlineOnlyInfo && jiddata.Online) || jiddata.Wants >= R3AlwaysInfo) { + xmppout <- botdata.makeXMPPMessage(to, pec.Msg, nil) + } + } + default: + break + } + + case je := <-jabber_events: + simple_jid := removeJIDResource(je.JID) + jid_data, jid_in_map := botdata.realraum_jids_[simple_jid] + if jid_in_map { + if last_status_msg != nil && (je.StatusNow || (! jid_data.Online && je.Online && jid_data.Wants == R3OnlineOnlyWithRecapInfo) ) { + xmppout <- botdata.makeXMPPMessage(je.JID, last_status_msg, nil) + } + jid_data.Online = je.Online + if je.Wants > R3NoChange { + jid_data.Wants = je.Wants + } + botdata.realraum_jids_[simple_jid] = jid_data + botdata.realraum_jids_.saveTo(botdata.config_file_) + } else if je.Wants > R3NoChange { + botdata.realraum_jids_[simple_jid] = JidData{je.Online, je.Wants} + botdata.realraum_jids_.saveTo(botdata.config_file_) + } + } + } +} + +func removeJIDResource(jid string) string { + var jidjid xmpp.JID + jidjid.Set(jid) + jidjid.Resource = "" + return jidjid.String() +} + +func (botdata *XmppBot) isAuthenticated(jid string) bool { + authtime, in_map := botdata.jid_lastauthtime_[jid] + //~ log.Println("isAuthenticated", in_map, authtime, time.Now().Unix(), auth_timeout_, time.Now().Unix() - authtime > auth_timeout_) + return in_map && time.Now().Unix() - authtime < botdata.auth_timeout_ +} + +const help_text_ string = "\n*auth** ...Enables you to use more commands.\n*time* ...Returns bot time." +const help_text_auth string = "You are authorized to use the following commands:\n*off* ...You will no longer receive notifications.\n*on* ...You will be notified of r3 status changes while you are online.\n*on_with_recap* ...Like *on* but additionally you will receive the current status when you come online.\n*on_while_offline* ...You will receive all r3 status changes, wether you are online or offline.\n*status* ...Use it to query the current status.\n*time* ...Returns bot time.\n*bye* ...Logout." + +//~ var re_msg_auth_ *regexp.Regexp = regexp.MustCompile("auth\s+(\S+)") + +func (botdata *XmppBot) handleIncomingMessageDialog(inmsg xmpp.Message, xmppout chan<- xmpp.Stanza, jabber_events chan JabberEvent) { + if inmsg.Body == nil || inmsg.GetHeader() == nil { + return + } + bodytext :=inmsg.Body.Chardata + //~ log.Println("Message Body:", bodytext) + if botdata.isAuthenticated(inmsg.GetHeader().From) { + switch bodytext { + case "on", "*on*": + jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3OnlineOnlyInfo, false} + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 status updates while online." , "Your New Status") + case "off", "*off*": + jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NeverInfo, false} + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Do not receive anything." , "Your New Status") + case "on_with_recap", "*on_with_recap*": + jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3OnlineOnlyWithRecapInfo, false} + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 status updates while and current status on coming, online." , "Your New Status") + case "on_while_offline", "*on_while_offline*": + jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3AlwaysInfo, false} + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive all r3 status updates, even if you are offline." , "Your New Status") + case "debug": + jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3DebugInfo, false} + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Debug mode enabled" , "Your New Status") + case "bye", "Bye", "quit", "logout", "*bye*": + botdata.jid_lastauthtime_[inmsg.GetHeader().From] = 0 + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Bye Bye !" ,nil) + case "open","close": + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, I can't operate the door for you." ,nil) + case "status", "*status*": + jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NoChange, true} + case "time", "*time*": + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, time.Now().String() , nil) + default: + //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata) + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil) + } + } else { + switch bodytext { + case "Hilfe","hilfe","help","Help","?","hallo","Hallo","Yes","yes","ja","ja bitte","bitte","sowieso": + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_, "Available Commands") + case botdata.auth_cmd_, botdata.auth_cmd2_: + botdata.jid_lastauthtime_[inmsg.GetHeader().From] = time.Now().Unix() + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil) + case "status", "*status*", "off", "*off*", "on", "*on*", "on_while_offline", "*on_while_offline*", "on_with_recap", "*on_with_recap*": + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, you need to be authorized to do that." , nil) + case "time", "*time*": + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, time.Now().String() , nil) + default: + //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata) + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "A nice day to you too !\nDo you need \"help\" ?", nil) + } + } +} + +func (botdata *XmppBot) handleIncomingXMPPStanzas(xmppin <- chan xmpp.Stanza, xmppout chan<- xmpp.Stanza, jabber_events chan JabberEvent) { + + defer func() { + if x := recover(); x != nil { + log.Printf("handleIncomingXMPPStanzas: run time panic: %v", x) + close(jabber_events) + } + }() + + var incoming_stanza interface{} + for incoming_stanza = range xmppin { + switch stanza := incoming_stanza.(type) { + case *xmpp.Message: + botdata.handleIncomingMessageDialog(*stanza, xmppout, jabber_events) + case *xmpp.Presence: + if stanza.GetHeader() == nil { + continue + } + switch stanza.GetHeader().Type { + case "subscribe": + xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribed", "", "") + jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false} + xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribe", "", "") + case "unsubscribe", "unsubscribed": + jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NeverInfo, false} + botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout + xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "unsubscribe", "","") + case "unavailable": + jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NoChange, false} + botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout + default: + jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false} + } + case *xmpp.Iq: + if stanza.GetHeader() == nil { + continue + } + } + } +} + +func NewStartedBot(loginjid, loginpwd, password, state_save_dir string, insecuretls bool) (*XmppBot, chan interface{}, error) { + var err error + botdata := new(XmppBot) + + botdata.realraum_jids_ = make(map[string]JidData, 1) + botdata.jid_lastauthtime_ = make(map[string]int64,1) + botdata.auth_cmd_ = "auth " + password + botdata.auth_cmd2_ = "*auth*" + password+"*" + botdata.my_jid_ = loginjid + botdata.my_login_password_ = loginpwd + botdata.auth_timeout_ = 3600*2 + + botdata.config_file_ = path.Join(state_save_dir, "r3xmpp."+removeJIDResource(loginjid)+".json") + + //~ log.Println(botdata.config_file_) + + //~ logger := &StdLogger{} + //~ xmpp.Debug = logger + //~ xmpp.Info = logger + //~ xmpp.Warn = logger + + xmpp.TlsConfig = tls.Config{InsecureSkipVerify: insecuretls} + botdata.realraum_jids_.loadFrom(botdata.config_file_) + + client_jid := new(xmpp.JID) + client_jid.Set(botdata.my_jid_) + botdata.xmppclient_, err = xmpp.NewClient(client_jid, botdata.my_login_password_, nil) + if err != nil { + log.Println("Error connecting to xmpp server", err) + return nil, nil, err + } + + err = botdata.xmppclient_.StartSession(true, &xmpp.Presence{}) + if err != nil { + log.Println("'Error StartSession:", err) + return nil, nil, err + } + + roster := xmpp.Roster(botdata.xmppclient_) + for _, entry := range roster { + if entry.Subscription == "from" { + botdata.xmppclient_.Out <- botdata.makeXMPPPresence(entry.Jid, "subscribe", "","") + } + if entry.Subscription == "none" { + delete(botdata.realraum_jids_, entry.Jid) + } + } + + presence_events := make(chan interface{},1) + jabber_events := make(chan JabberEvent,1) + + go botdata.handleEventsforXMPP(botdata.xmppclient_.Out, presence_events, jabber_events) + go botdata.handleIncomingXMPPStanzas(botdata.xmppclient_.In, botdata.xmppclient_.Out, jabber_events) + + botdata.presence_events_ = &presence_events + + return botdata, presence_events, nil +} + +func (botdata *XmppBot) StopBot() { + if botdata.xmppclient_ != nil { + close(botdata.xmppclient_.Out) + } + if botdata.presence_events_ != nil { + *botdata.presence_events_ <- false + close(*botdata.presence_events_) + } +} diff --git a/go/r3-netstatus/sockettoevent.go b/go/r3-netstatus/sockettoevent.go new file mode 100644 index 0000000..a5ae25a --- /dev/null +++ b/go/r3-netstatus/sockettoevent.go @@ -0,0 +1,134 @@ +package main + +import ( + pubsub "github.com/tuxychandru/pubsub" + "regexp" + "strconv" + "bufio" + "time" + //~ "./brain" + "net" + ) + +var ( + re_presence_ *regexp.Regexp = regexp.MustCompile("Presence: (yes|no)(?:, (opened|closed), (.+))?") + re_state_ *regexp.Regexp = regexp.MustCompile("State: (closed|opened|manual movement|error|reset|timeout after open|timeout after close|opening|closing).*") + re_infocard_ *regexp.Regexp = regexp.MustCompile("Info\(card\): card\(([a-fA-F0-9]+)\) (found|not found).*") + re_infoajar_ *regexp.Regexp = regexp.MustCompile("Info\(ajar\): door is now (ajar|shut)") + re_command_ *regexp.Regexp = regexp.MustCompile("(open|close|toggle|reset)(?: +(Card|Phone|SSH|ssh))?(?: +(.+))?") + re_button_ *regexp.Regexp = regexp.MustCompile("PanicButton|button\\d?") + re_temp_ *regexp.Regexp = regexp.MustCompile("temp0: (\\d+\\.\\d+)") + re_photo_ *regexp.Regexp = regexp.MustCompile("photo0: (\\d+)") +) + + +type PresenceUpdate struct { + Present bool + Ts int64 +} + +type DoorStatusUpdate struct { + Locked bool + Shut bool + Ts int64 +} + +type DoorCommandEvent struct { + Command string + Using string + Who string + Ts int64 +} + +type ButtonPressUpdate struct { + Buttonindex int + Ts int64 +} + +type TempSensorUpdate struct { + Sensorindex int + Value float64 + Ts int64 +} + +type IlluminationSensorUpdate struct { + Sensorindex int + Value int64 + Ts int64 +} + +type TimeTick struct { + Ts int64 +} + +type MovementSensorUpdate struct { + Sensorindex int + Ts int64 +} + +func ParseSocketInputLine(line string, ps *pubsub.PubSub) { //, brn *brain.Brain) { + match_presence := re_presence_.FindStringSubmatch(line) + match_status := re_status_.FindStringSubmatch(line) + match_command := re_command_.FindStringSubmatch(line) + match_button := re_button_.FindStringSubmatch(line) + match_temp := re_temp_.FindStringSubmatch(line) + match_photo := re_photo_.FindStringSubmatch(line) + + //~ log.Println("ParseSocketInputLine",line) + var tidbit interface{} + ts := time.Now().Unix() + if match_presence != nil { + if match_presence[2] != "" { ps.Pub(DoorStatusUpdate{match_presence[2] == "closed", true, ts}, "door"); } + tidbit = PresenceUpdate{match_presence[1] == "yes", ts} + //~ brn.Oboite("presence", tidbit) + ps.Pub(tidbit, "presence") + } else if match_status != nil { + tidbit = DoorStatusUpdate{match_status[1] == "closed", match_status[3] == "shut", ts} + //~ brn.Oboite("door", tidbit) + ps.Pub(tidbit, "door") + } else if match_command != nil { + tidbit = DoorCommandEvent{match_command[1], match_command[2], match_command[3], ts} + //~ brn.Oboite("doorcmd", tidbit) + ps.Pub(tidbit, "door") + } else if match_button != nil { + //~ brn.Oboite("button0", ts) + ps.Pub(ButtonPressUpdate{0, ts}, "buttons") + } else if match_temp != nil { + newtemp, err := strconv.ParseFloat((match_temp[1]), 32) + if err == nil { + //~ brn.Oboite( "temp0", newtemp) + ps.Pub(TempSensorUpdate{0, newtemp, ts}, "sensors") + } + } else if match_photo != nil { + newphoto, err := strconv.ParseInt(match_photo[1], 10, 32) + if err == nil { + //~ brn.Oboite("photo0", newphoto) + ps.Pub(IlluminationSensorUpdate{0, newphoto, ts}, "sensors") + } + } else if line == "movement" { + //~ brn.Oboite("movement", ts) + ps.Pub(MovementSensorUpdate{0, ts}, "movements") + } +} + +func ReadFromUSocket(path string, c chan string) { +ReOpenSocket: + for { + presence_socket, err := net.Dial("unix", path) + if err != nil { + //Waiting on Socket + time.Sleep(5 * time.Second) + continue ReOpenSocket + } + presence_reader := bufio.NewReader(presence_socket) + for { + line, err := presence_reader.ReadString('\n') + if err != nil { + //Socket closed + presence_socket.Close() + continue ReOpenSocket + } + c <- line + } + } +} \ No newline at end of file diff --git a/go/r3-netstatus/spaceapi/spaceapi.go b/go/r3-netstatus/spaceapi/spaceapi.go new file mode 100644 index 0000000..4162295 --- /dev/null +++ b/go/r3-netstatus/spaceapi/spaceapi.go @@ -0,0 +1,242 @@ +// spaceapi.go +package spaceapi + +import ( + "encoding/json" + "time" +) + +const max_num_events int = 4 + +type SpaceInfo map[string]interface{} + +type SpaceDoorLockSensor struct { + value bool + location string + name string + description string +} + +type SpaceDoorAjarSensor struct { + value bool + location string + name string + description string +} + +func MakeTempSensor(name, where, unit string, value float64) SpaceInfo { + listofwhats := make([]SpaceInfo, 1) + listofwhats[0] = SpaceInfo{ + "value": value, + "unit": unit, + "location": where, + "name": name, + "description": ""} + return SpaceInfo{"temperature": listofwhats} +} + +func MakeTempCSensor(name, where string, value float64) SpaceInfo { + return MakeTempSensor(name,where,"\u00b0C",value) +} + +func MakeIlluminationSensor(name, where, unit string, value int64) SpaceInfo { + listofwhats := make([]SpaceInfo, 1) + listofwhats[0] = SpaceInfo{ + "value": value, + "unit": unit, + "location": where, + "name": name, + "description": ""} + return SpaceInfo{"ext_illumination": listofwhats} +} + +func MakePowerConsumptionSensor(name, where, unit string, value int64) SpaceInfo { + listofwhats := make([]SpaceInfo, 1) + listofwhats[0] = SpaceInfo{ + "value": value, + "unit": unit, + "location": where, + "name": name, + "description": ""} + return SpaceInfo{"power_consumption": listofwhats} +} + +func MakeNetworkConnectionsSensor(name, where, nettype string, value, machines int64) SpaceInfo { + listofwhats := make([]SpaceInfo, 1) + listofwhats[0] = SpaceInfo{ + "value": value, + "type": nettype, + "machines": machines, + "location": where, + "name": name, + "description": ""} + return SpaceInfo{"network_connections": listofwhats} +} + +func MakeMemberCountSensor(name, where string, value int64) SpaceInfo { + listofwhats := make([]SpaceInfo, 1) + listofwhats[0] = SpaceInfo{ + "value": value, + "location": where, + "name": name, + "description": ""} + return SpaceInfo{"total_member_count": listofwhats} +} + +func MakeDoorLockSensor(name, where string, value bool) SpaceInfo { + listofwhats := make([]SpaceInfo, 1) + listofwhats[0] = SpaceInfo{ + "value": value, + "location": where, + "name": name, + "description": ""} + return SpaceInfo{"door_locked": listofwhats} +} + +func MakeDoorAjarSensor(name, where string, value bool) SpaceInfo { + listofwhats := make([]SpaceInfo, 1) + listofwhats[0] = SpaceInfo{ + "value": value, + "location": where, + "name": name, + "description": ""} + return SpaceInfo{"ext_door_ajar": listofwhats} +} + +func (nsi SpaceInfo) MergeInSensor(sensorinfo SpaceInfo) { + if nsi["sensors"] == nil { + nsi["sensors"] = SpaceInfo{} + //~ listofwhats := make([]SpaceInfo, 1) + //~ listofwhats[0] = sensortype.(SpaceInfo) + //~ sensorobj := SpaceInfo{what: listofwhats} + //~ nsi["sensors"] = sensorobj + } + sensorobj := nsi["sensors"].(SpaceInfo) + for what, subsensorobjlist := range sensorinfo { + if sensorobj[what] == nil { + sensorobj[what] = subsensorobjlist + } else { + existingsensorobjslist := sensorobj[what].([]SpaceInfo) + for _, newsensorobj := range subsensorobjlist.([]SpaceInfo) { + foundandsubstituted := false + for i:=0; i< len(existingsensorobjslist); i++ { + if existingsensorobjslist[i]["name"] == newsensorobj["name"] { + existingsensorobjslist[i] = newsensorobj + foundandsubstituted = true + } + } + if foundandsubstituted == false { + sensorobj[what] = append(sensorobj[what].([]SpaceInfo), newsensorobj) + //note that we do not change existingsensorobjslist here but directly sensorobj[what] !! + //the implications being that, if we have several newsensorobj in the list: + // a) optimisation: we only check them against the existing ones and spare ourselves the work of checking a newsensorobj's name against a just added other newsensorobjs's name + // b) if the array sensorinfo[what] has several objects with the same name, nsi["sensors"] will also end up with these name conflicts + } + } + } + } +} + +func (nsi SpaceInfo) AddSpaceContactInfo(phone, irc, email, ml, jabber, issuemail string) SpaceInfo { + nsi["contact"] = SpaceInfo{ + "phone": phone, + "email": email, + "ml": ml, + "jabber": jabber, + "issue_mail": issuemail} + nsi["issue_report_channels"] = [3]string{"issue_mail","email","ml"} + return nsi +} + +func (nsi SpaceInfo) AddSpaceFeed(feedtype, url string) SpaceInfo { + newfeed := SpaceInfo{"url": url} + if nsi["feeds"] == nil { + nsi["feeds"] = SpaceInfo{feedtype: newfeed} + } else { + feedobj, ok := nsi["feeds"].(SpaceInfo) //type assertion (panics if false) + if ok { + feedobj[feedtype] = newfeed + } else { + panic("Wrong Type of feedobj: Should never happen") + } + } + return nsi +} + +func (nsi SpaceInfo) AddSpaceEvent(name, eventtype, extra string) SpaceInfo { + newevent := SpaceInfo{"name": name, "type": eventtype, "timestamp": time.Now().Unix(), "extra": extra} + if nsi["events"] == nil { + eventlist := make([]SpaceInfo, 1) + eventlist[0] = newevent + nsi["events"] = eventlist + } else { + eventlist, ok := nsi["events"].([]SpaceInfo) //type assertion + if ok { + if len(eventlist) >= max_num_events { + eventlist = eventlist[1:] + } + nsi["events"] = append(eventlist, newevent) + } else { + panic("Wrong Type of eventlist: Should never happen") + } + } + return nsi +} + +func (nsi SpaceInfo) AddSpaceAddress(address string) SpaceInfo { + nsi["address"] = address + if nsi["location"] != nil { + location, ok := nsi["location"].(SpaceInfo) + if ok { + location["address"] = address + } + } + return nsi +} + +func (nsi SpaceInfo) SetStatus(open bool, status string) { + nsi["status"] = status + nsi["open"] = open + nsi["lastchange"] = time.Now().Unix() + state, ok := nsi["state"].(SpaceInfo) + if ok { + state["message"] = status + state["open"] = open + state["lastchange"] = nsi["lastchange"] + } +} + +func NewSpaceInfo(space string, url string, logo string, open_icon string, closed_icon string, lat float64, lon float64) SpaceInfo { + nsi := map[string]interface{}{ + "api": "0.13", + "space": space, + "url": url, + "logo": logo, + "open": false, + "lastchange": time.Now().Unix(), + "icon": SpaceInfo{ + "open": open_icon, + "closed": closed_icon, + }, + "state": SpaceInfo{ + "open": false, + "lastchange":time.Now().Unix(), + "icon": SpaceInfo{ + "open": open_icon, + "closed": closed_icon}, + }, + "location": SpaceInfo{ + "lat": lat, + "lon": lon}, + "contact" : SpaceInfo {}, + } + return nsi +} + +func (data SpaceInfo) MakeJSON() ([]byte, error) { + msg, err := json.Marshal(data) + if err == nil { + return msg, nil + } + return nil, err +} diff --git a/go/r3-netstatus/webstatus.go b/go/r3-netstatus/webstatus.go new file mode 100644 index 0000000..d303b13 --- /dev/null +++ b/go/r3-netstatus/webstatus.go @@ -0,0 +1,95 @@ +package main + +import ( + pubsub "github.com/tuxychandru/pubsub" + "./spaceapi" + "regexp" + "net/http" + "net/url" + "log" + "time" + ) + + +type spaceState struct { + present bool + buttonpress_until int64 +} + +var ( + spaceapidata spaceapi.SpaceInfo = spaceapi.NewSpaceInfo("realraum", "http://realraum.at", "http://realraum.at/logo-red_250x250.png", "http://realraum.at/logo-re_open_100x100.png", "http://realraum.at/logo-re_empty_100x100.png",47.065554, 15.450435).AddSpaceAddress("Brockmanngasse 15, 8010 Graz, Austria") + statusstate *spaceState = new(spaceState) + re_querystresc_ *regexp.Regexp = regexp.MustCompile("[^\x30-\x39\x41-\x7E]") +) + + +func init() { + spaceapidata.AddSpaceFeed("calendar", "http://grical.realraum.at/s/?query=!realraum&view=rss") + spaceapidata.AddSpaceFeed("blog", "https://plus.google.com/113737596421797426873") + spaceapidata.AddSpaceFeed("wiki", "http://realraum.at/wiki") + spaceapidata.AddSpaceContactInfo("+43780700888524", "irc://irc.oftc.net/#realraum", "realraum@realraum.at", "realraum@realraum.at", "realraum@realraum.at", "vorstand@realraum.at") +} + + +func updateStatusString() { + var spacestatus string + if statusstate.present { + if statusstate.buttonpress_until > time.Now().Unix() { + spacestatus = "Panic! Present&Bored" + } else { + spacestatus = "Leute Anwesend" + } + } else { + spacestatus = "Keiner Da" + } + spaceapidata.SetStatus(statusstate.present, spacestatus) +} + +func publishStateToWeb() { + updateStatusString() + jsondata_b, err := spaceapidata.MakeJSON() + if err != nil { + log.Println("Error:", err) + return + } + //jsondata_b := re_querystresc_.ReplaceAllFunc(jsondata_b, func(in []byte) []byte { + // out := make([]byte, 4) + // out[0] = '%' + // copy(out[1:], []byte(strconv.FormatInt(int64(in[0]), 16))) + // return out + //}) + jsondata := url.QueryEscape(string(jsondata_b)) + resp, err := http.Get("http://www.realraum.at/cgi/status.cgi?pass=jako16&set=" + jsondata) + if err != nil { + log.Println("Error publishing realraum info", err) + return + } + resp.Body.Close() +} + +func EventToWeb(ps *pubsub.PubSub) { + events := ps.Sub("presence","door","sensors","buttons","updateinterval") + + for eventinterface := range(events) { + switch event := eventinterface.(type) { + case TimeTick: + publishStateToWeb() + case PresenceUpdate: + statusstate.present = event.Present + publishStateToWeb() + case DoorStatusUpdate: + spaceapidata.MergeInSensor(spaceapi.MakeDoorLockSensor("TorwaechterLock", "Türschloß", event.Locked)) + spaceapidata.MergeInSensor(spaceapi.MakeDoorLockSensor("TorwaechterAjarSensor", "Türkontakt", event.Shut)) + publishStateToWeb() + case ButtonPressUpdate: + statusstate.buttonpress_until = event.Ts + 3600 + spaceapidata.AddSpaceEvent("PanicButton", "check-in", "The button has been pressed") + publishStateToWeb() + case TempSensorUpdate: + spaceapidata.MergeInSensor(spaceapi.MakeTempCSensor("Temp0","Decke", event.Value)) + case IlluminationSensorUpdate: + spaceapidata.MergeInSensor(spaceapi.MakeIlluminationSensor("Photodiode","Decke","1024V/5V", event.Value)) + } + } +} + diff --git a/r3-netstatus/brain/brain.go b/r3-netstatus/brain/brain.go deleted file mode 100644 index cc9b83c..0000000 --- a/r3-netstatus/brain/brain.go +++ /dev/null @@ -1,116 +0,0 @@ -package brain - -import "errors" - -type informationtuple struct { - name string - value interface{} -} - -type informationretrievalpath struct { - name string - returnpath chan interface{} -} - -type hippocampus map[string]interface{} - -type Brain struct { - storeTuple chan informationtuple - retrieveValue chan informationretrievalpath - shutdown chan bool -} - -func New() *Brain { - b := new(Brain) - b.storeTuple = make(chan informationtuple) - b.retrieveValue = make(chan informationretrievalpath) - go b.runBrain() - return b -} - -func (b *Brain) runBrain() { - var h hippocampus = make(hippocampus) - for { - select { - case newtuple := <- b.storeTuple: - h[newtuple.name] = newtuple.value - - case retrievvalue := <- b.retrieveValue: - v, e := h[retrievvalue.name] - if e { - retrievvalue.returnpath <- v - } else { - retrievvalue.returnpath <- nil - } - - case <- b.shutdown: - break - } - } -} - -func (b *Brain) Shutdown() { - b.shutdown <- true -} - -func (b *Brain) Oboite(name string, value interface{}) { - b.storeTuple <- informationtuple{name, value} -} - -func (b *Brain) OmoiDashite(name string) (interface{}, error) { - rc := make(chan interface{}) - b.retrieveValue <- informationretrievalpath{name, rc} - v := <- rc - if v == nil { - return v, errors.New("name not in brain") - } - return v, nil -} - -func (b *Brain) OmoiDashiteBool(name string) (bool, error) { - v, e := b.OmoiDashite(name) - if e != nil { - return false, e - } - vc, ok := v.(bool) - if !ok { - return false, errors.New(name + " does not have type bool") - } - return vc, nil -} - -func (b *Brain) OmoiDashiteInt(name string) (int, error) { - v, e := b.OmoiDashite(name) - if e != nil { - return 0, e - } - vc, ok := v.(int) - if !ok { - return 0, errors.New(name + " does not have type int") - } - return vc, nil -} - -func (b *Brain) OmoiDashiteFloat(name string) (float64, error) { - v, e := b.OmoiDashite(name) - if e != nil { - return 0, e - } - vc, ok := v.(float64) - if !ok { - return 0, errors.New(name + " does not have type float64") - } - return vc, nil -} - -func (b *Brain) OmoiDashiteString(name string) (string, error) { - v, e := b.OmoiDashite(name) - if e != nil { - return "", e - } - vc, ok := v.(string) - if !ok { - return "", errors.New(name + " does not have type string") - } - return vc, nil -} \ No newline at end of file diff --git a/r3-netstatus/main.go b/r3-netstatus/main.go deleted file mode 100644 index 6f53ac3..0000000 --- a/r3-netstatus/main.go +++ /dev/null @@ -1,140 +0,0 @@ -package main - -import ( - "./r3xmppbot" - pubsub "github.com/tuxychandru/pubsub" - "flag" - "time" - "fmt" - //~ "./brain" -) - -type SpaceState struct { - present bool - buttonpress_until int64 - door_locked bool - door_shut bool -} - -var ( - presence_socket_path_ string - xmpp_presence_events_chan_ chan interface{} - xmpp_login_ struct {jid string; pass string} - xmpp_bot_authstring_ string - xmpp_state_save_dir_ string - button_press_timeout_ int64 = 3600 -) - -//------- - -func init() { - flag.StringVar(&xmpp_login_.jid, "xjid", "realrauminfo@realraum.at/Tuer", "XMPP Bot Login JID") - flag.StringVar(&xmpp_login_.pass, "xpass", "", "XMPP Bot Login Password") - flag.StringVar(&xmpp_bot_authstring_, "xbotauth", "", "String that user use to authenticate themselves to the bot") - flag.StringVar(&presence_socket_path_,"presencesocket", "/var/run/tuer/presence.socket", "Path to presence socket") - flag.StringVar(&xmpp_state_save_dir_,"xstatedir","/flash/var/lib/r3netstatus/", "Directory to save XMPP bot state in") - flag.Parse() -} - -//------- - -func IfThenElseStr(c bool, strue, sfalse string) string { - if c {return strue} else {return sfalse} -} - -func composeMessage(present, locked, shut bool, who string, ts int64) string { - return fmt.Sprintf("%s (Door is %s and %s and was last used%s at %s)", - IfThenElseStr(present, "Somebody is present!" , "Everybody left."), - IfThenElseStr(locked, "locked","unlocked"), - IfThenElseStr(shut, "shut","ajar"), - IfThenElseStr(len(who) == 0,"", " by " + who), - time.Unix(ts,0).String()) -} - -func EventToXMPP(ps *pubsub.PubSub, xmpp_presence_events_chan_ chan <- interface{}) { - events := ps.Sub("presence","door","buttons","updateinterval") - - defer func() { - if x := recover(); x != nil { - fmt.Printf("handleIncomingXMPPStanzas: run time panic: %v", x) - ps.Unsub(events, "presence","door","buttons","updateinterval") - close(xmpp_presence_events_chan_) - } - }() - - var present, locked, shut bool = false, true, true - var last_buttonpress int64 = 0 - var who string - button_msg := "The button has been pressed ! Propably someone is bored and in need of company ! ;-)" - present_status := r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowOnline,"Somebody is present"} - notpresent_status := r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowNotAvailabe,"Nobody is here"} - button_status := r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowFreeForChat, "The button has been pressed :-)"} - - xmpp_presence_events_chan_ <- r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowNotAvailabe, "Nobody is here"} - - for eventinterface := range(events) { - switch event := eventinterface.(type) { - case PresenceUpdate: - present = event.Present - xmpp_presence_events_chan_ <- r3xmppbot.XMPPMsgEvent{Msg: composeMessage(present, locked, shut, who, event.Ts), DistributeLevel: r3xmppbot.R3OnlineOnlyInfo, RememberAsStatus: true} - if present { - xmpp_presence_events_chan_ <- present_status - } else { - xmpp_presence_events_chan_ <- notpresent_status - } - case DoorCommandEvent: - if len(event.Who) > 0 && len(event.Using) > 0 { - who = fmt.Sprintf("%s (%s)",event.Who, event.Using) - } else { - who = event.Who - } - xmpp_presence_events_chan_ <- fmt.Sprintln("DoorCommand:",event.Command, "using", event.Using, "by", event.Who, time.Unix(event.Ts,0)) - case DoorStatusUpdate: - locked = event.Locked - shut = event.Shut - xmpp_presence_events_chan_ <- r3xmppbot.XMPPMsgEvent{Msg: composeMessage(present, locked, shut, who, event.Ts), DistributeLevel: r3xmppbot.R3DebugInfo, RememberAsStatus: true} - case ButtonPressUpdate: - xmpp_presence_events_chan_ <- r3xmppbot.XMPPMsgEvent{Msg: button_msg, DistributeLevel: r3xmppbot.R3OnlineOnlyInfo} - xmpp_presence_events_chan_ <- button_status - last_buttonpress = event.Ts - case TimeTick: - if present && last_buttonpress > 0 && time.Now().Unix() - last_buttonpress > button_press_timeout_ { - xmpp_presence_events_chan_ <- present_status - last_buttonpress = 0 - } - } - } -} - -func main() { - var xmpperr error - var bot *r3xmppbot.XmppBot - bot, xmpp_presence_events_chan_, xmpperr = r3xmppbot.NewStartedBot(xmpp_login_.jid, xmpp_login_.pass, xmpp_bot_authstring_, xmpp_state_save_dir_, true) - - newlinequeue := make(chan string, 1) - ps := pubsub.New(1) - //~ brn := brain.New() - defer close(newlinequeue) - defer ps.Shutdown() - //~ defer brn.Shutdown() - - go EventToWeb(ps) - if xmpperr == nil { - defer bot.StopBot() - go EventToXMPP(ps, xmpp_presence_events_chan_) - } else { - fmt.Println(xmpperr) - fmt.Println("XMPP Bot disabled") - } - go ReadFromUSocket(presence_socket_path_, newlinequeue) - ticker := time.NewTicker(time.Duration(7) * time.Minute) - - for { - select { - case e := <-newlinequeue: - ParseSocketInputLine(e, ps) //, brn) - case <-ticker.C: - ps.Pub(TimeTick{time.Now().Unix()}, "updateinterval") - } - } -} diff --git a/r3-netstatus/make_deploy.zsh b/r3-netstatus/make_deploy.zsh deleted file mode 100644 index 408b049..0000000 --- a/r3-netstatus/make_deploy.zsh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/zsh -export GO386=387 -go-linux-386 clean -#go-linux-386 build -#strip ${PWD:t} -go-linux-386 build -ldflags "-s" && rsync -v ${PWD:t} wuzzler.realraum.at:/flash/tuer/ diff --git a/r3-netstatus/r3xmppbot/r3xmppbot.go b/r3-netstatus/r3xmppbot/r3xmppbot.go deleted file mode 100644 index 48a9f5c..0000000 --- a/r3-netstatus/r3xmppbot/r3xmppbot.go +++ /dev/null @@ -1,421 +0,0 @@ -package r3xmppbot - -import ( - xmpp "code.google.com/p/goexmpp" - "log" - "crypto/tls" - "os" - "time" - "encoding/json" - "path" -) - -//~ type StdLogger struct { -//~ } - -//~ func (s *StdLogger) Log(v ...interface{}) { - //~ log.Println(v...) -//~ } - -//~ func (s *StdLogger) Logf(fmt string, v ...interface{}) { - //~ log.Printf(fmt, v...) -//~ } - - -func (botdata *XmppBot) makeXMPPMessage(to string, message interface{}, subject interface{}) *xmpp.Message { - xmppmsgheader := xmpp.Header{To: to, - From: botdata.my_jid_, - Id: <-xmpp.Id, - Type: "chat", - Lang: "", - Innerxml: "", - Error: nil, - Nested: make([]interface{},0)} - - var msgsubject, msgbody *xmpp.Generic - switch cast_msg := message.(type) { - case string: - msgbody = &xmpp.Generic{Chardata: cast_msg} - case *string: - msgbody = &xmpp.Generic{Chardata: *cast_msg} - case *xmpp.Generic: - msgbody = cast_msg - default: - msgbody = &xmpp.Generic{} - } - switch cast_msg := subject.(type) { - case string: - msgsubject = &xmpp.Generic{Chardata: cast_msg} - case *string: - msgsubject = &xmpp.Generic{Chardata: *cast_msg} - case *xmpp.Generic: - msgsubject = cast_msg - default: - msgsubject = &xmpp.Generic{} - } - return &xmpp.Message{Header: xmppmsgheader , Subject: msgsubject, Body: msgbody, Thread: &xmpp.Generic{}} -} - -func (botdata *XmppBot) makeXMPPPresence(to, ptype, show, status string) *xmpp.Presence { - xmppmsgheader := xmpp.Header{To: to, - From: botdata.my_jid_, - Id: <-xmpp.Id, - Type: ptype, - Lang: "", - Innerxml: "", - Error: nil, - Nested: make([]interface{},0)} - var gen_show, gen_status *xmpp.Generic - if len(show) == 0 { - gen_show = nil - } else { - gen_show = &xmpp.Generic{Chardata: show} - } - if len(status) == 0 { - gen_status = nil - } else { - gen_status = &xmpp.Generic{Chardata: status} - } - return &xmpp.Presence{Header: xmppmsgheader, Show: gen_show, Status: gen_status} -} - -type R3JIDDesire int - -const ( - R3NoChange R3JIDDesire = -1 - R3NeverInfo R3JIDDesire = iota // ignore first value by assigning to blank identifier - R3OnlineOnlyInfo - R3OnlineOnlyWithRecapInfo - R3AlwaysInfo - R3DebugInfo -) - -const ( - ShowOnline string = "" - ShowAway string = "away" - ShowNotAvailabe string = "xa" - ShowDoNotDisturb string = "dnd" - ShowFreeForChat string = "chat" -) - -type JidData struct { - Online bool - Wants R3JIDDesire -} - -type JabberEvent struct { - JID string - Online bool - Wants R3JIDDesire - StatusNow bool -} - -type XMPPMsgEvent struct { - Msg string - DistributeLevel R3JIDDesire - RememberAsStatus bool -} - -type XMPPStatusEvent struct { - Show string - Status string -} - -type RealraumXmppNotifierConfig map[string]JidData - -type XmppBot struct { - jid_lastauthtime_ map[string]int64 - realraum_jids_ RealraumXmppNotifierConfig - password_ string - auth_cmd_ string - auth_cmd2_ string - my_jid_ string - auth_timeout_ int64 - config_file_ string - my_login_password_ string - xmppclient_ *xmpp.Client - presence_events_ *chan interface{} -} - - -func (data RealraumXmppNotifierConfig) saveTo(filepath string) () { - fh, err := os.Create(filepath) - if err != nil { - log.Println(err) - return - } - defer fh.Close() - enc := json.NewEncoder(fh) - if err = enc.Encode(&data); err != nil { - log.Println(err) - return - } -} - -func (data RealraumXmppNotifierConfig) loadFrom(filepath string) () { - fh, err := os.Open(filepath) - if err != nil { - log.Println(err) - return - } - defer fh.Close() - dec := json.NewDecoder(fh) - if err = dec.Decode(&data); err != nil { - log.Println(err) - return - } - for to, jiddata := range data { - jiddata.Online = false - data[to]=jiddata - } -} - - -func init() { - //~ logger := &StdLogger{} - //~ xmpp.Debug = logger - //~ xmpp.Info = logger - //~ xmpp.Warn = logger -} - -func (botdata *XmppBot) handleEventsforXMPP(xmppout chan <- xmpp.Stanza, presence_events <- chan interface{}, jabber_events <- chan JabberEvent) { - var last_status_msg *string - - defer func() { - if x := recover(); x != nil { - log.Printf("handleEventsforXMPP: run time panic: %v", x) - } - }() - - for { - select { - case pe := <-presence_events: - switch pec := pe.(type) { - case xmpp.Stanza: - xmppout <- pec - continue - case string: - for to, jiddata := range botdata.realraum_jids_ { - if jiddata.Wants >= R3DebugInfo { - xmppout <- botdata.makeXMPPMessage(to, pec, nil) - } - } - - case XMPPStatusEvent: - xmppout <- botdata.makeXMPPPresence("", "", pec.Show, pec.Status) - - case XMPPMsgEvent: - if pec.RememberAsStatus { - last_status_msg = &pec.Msg - } - for to, jiddata := range botdata.realraum_jids_ { - if jiddata.Wants >= pec.DistributeLevel && ((jiddata.Wants >= R3OnlineOnlyInfo && jiddata.Online) || jiddata.Wants >= R3AlwaysInfo) { - xmppout <- botdata.makeXMPPMessage(to, pec.Msg, nil) - } - } - default: - break - } - - case je := <-jabber_events: - simple_jid := removeJIDResource(je.JID) - jid_data, jid_in_map := botdata.realraum_jids_[simple_jid] - if jid_in_map { - if last_status_msg != nil && (je.StatusNow || (! jid_data.Online && je.Online && jid_data.Wants == R3OnlineOnlyWithRecapInfo) ) { - xmppout <- botdata.makeXMPPMessage(je.JID, last_status_msg, nil) - } - jid_data.Online = je.Online - if je.Wants > R3NoChange { - jid_data.Wants = je.Wants - } - botdata.realraum_jids_[simple_jid] = jid_data - botdata.realraum_jids_.saveTo(botdata.config_file_) - } else if je.Wants > R3NoChange { - botdata.realraum_jids_[simple_jid] = JidData{je.Online, je.Wants} - botdata.realraum_jids_.saveTo(botdata.config_file_) - } - } - } -} - -func removeJIDResource(jid string) string { - var jidjid xmpp.JID - jidjid.Set(jid) - jidjid.Resource = "" - return jidjid.String() -} - -func (botdata *XmppBot) isAuthenticated(jid string) bool { - authtime, in_map := botdata.jid_lastauthtime_[jid] - //~ log.Println("isAuthenticated", in_map, authtime, time.Now().Unix(), auth_timeout_, time.Now().Unix() - authtime > auth_timeout_) - return in_map && time.Now().Unix() - authtime < botdata.auth_timeout_ -} - -const help_text_ string = "\n*auth** ...Enables you to use more commands.\n*time* ...Returns bot time." -const help_text_auth string = "You are authorized to use the following commands:\n*off* ...You will no longer receive notifications.\n*on* ...You will be notified of r3 status changes while you are online.\n*on_with_recap* ...Like *on* but additionally you will receive the current status when you come online.\n*on_while_offline* ...You will receive all r3 status changes, wether you are online or offline.\n*status* ...Use it to query the current status.\n*time* ...Returns bot time.\n*bye* ...Logout." - -//~ var re_msg_auth_ *regexp.Regexp = regexp.MustCompile("auth\s+(\S+)") - -func (botdata *XmppBot) handleIncomingMessageDialog(inmsg xmpp.Message, xmppout chan<- xmpp.Stanza, jabber_events chan JabberEvent) { - if inmsg.Body == nil || inmsg.GetHeader() == nil { - return - } - bodytext :=inmsg.Body.Chardata - //~ log.Println("Message Body:", bodytext) - if botdata.isAuthenticated(inmsg.GetHeader().From) { - switch bodytext { - case "on", "*on*": - jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3OnlineOnlyInfo, false} - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 status updates while online." , "Your New Status") - case "off", "*off*": - jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NeverInfo, false} - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Do not receive anything." , "Your New Status") - case "on_with_recap", "*on_with_recap*": - jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3OnlineOnlyWithRecapInfo, false} - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 status updates while and current status on coming, online." , "Your New Status") - case "on_while_offline", "*on_while_offline*": - jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3AlwaysInfo, false} - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive all r3 status updates, even if you are offline." , "Your New Status") - case "debug": - jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3DebugInfo, false} - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Debug mode enabled" , "Your New Status") - case "bye", "Bye", "quit", "logout", "*bye*": - botdata.jid_lastauthtime_[inmsg.GetHeader().From] = 0 - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Bye Bye !" ,nil) - case "open","close": - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, I can't operate the door for you." ,nil) - case "status", "*status*": - jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NoChange, true} - case "time", "*time*": - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, time.Now().String() , nil) - default: - //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata) - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil) - } - } else { - switch bodytext { - case "Hilfe","hilfe","help","Help","?","hallo","Hallo","Yes","yes","ja","ja bitte","bitte","sowieso": - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_, "Available Commands") - case botdata.auth_cmd_, botdata.auth_cmd2_: - botdata.jid_lastauthtime_[inmsg.GetHeader().From] = time.Now().Unix() - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil) - case "status", "*status*", "off", "*off*", "on", "*on*", "on_while_offline", "*on_while_offline*", "on_with_recap", "*on_with_recap*": - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, you need to be authorized to do that." , nil) - case "time", "*time*": - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, time.Now().String() , nil) - default: - //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata) - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "A nice day to you too !\nDo you need \"help\" ?", nil) - } - } -} - -func (botdata *XmppBot) handleIncomingXMPPStanzas(xmppin <- chan xmpp.Stanza, xmppout chan<- xmpp.Stanza, jabber_events chan JabberEvent) { - - defer func() { - if x := recover(); x != nil { - log.Printf("handleIncomingXMPPStanzas: run time panic: %v", x) - close(jabber_events) - } - }() - - var incoming_stanza interface{} - for incoming_stanza = range xmppin { - switch stanza := incoming_stanza.(type) { - case *xmpp.Message: - botdata.handleIncomingMessageDialog(*stanza, xmppout, jabber_events) - case *xmpp.Presence: - if stanza.GetHeader() == nil { - continue - } - switch stanza.GetHeader().Type { - case "subscribe": - xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribed", "", "") - jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false} - xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribe", "", "") - case "unsubscribe", "unsubscribed": - jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NeverInfo, false} - botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout - xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "unsubscribe", "","") - case "unavailable": - jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NoChange, false} - botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout - default: - jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false} - } - case *xmpp.Iq: - if stanza.GetHeader() == nil { - continue - } - } - } -} - -func NewStartedBot(loginjid, loginpwd, password, state_save_dir string, insecuretls bool) (*XmppBot, chan interface{}, error) { - var err error - botdata := new(XmppBot) - - botdata.realraum_jids_ = make(map[string]JidData, 1) - botdata.jid_lastauthtime_ = make(map[string]int64,1) - botdata.auth_cmd_ = "auth " + password - botdata.auth_cmd2_ = "*auth*" + password+"*" - botdata.my_jid_ = loginjid - botdata.my_login_password_ = loginpwd - botdata.auth_timeout_ = 3600*2 - - botdata.config_file_ = path.Join(state_save_dir, "r3xmpp."+removeJIDResource(loginjid)+".json") - - //~ log.Println(botdata.config_file_) - - //~ logger := &StdLogger{} - //~ xmpp.Debug = logger - //~ xmpp.Info = logger - //~ xmpp.Warn = logger - - xmpp.TlsConfig = tls.Config{InsecureSkipVerify: insecuretls} - botdata.realraum_jids_.loadFrom(botdata.config_file_) - - client_jid := new(xmpp.JID) - client_jid.Set(botdata.my_jid_) - botdata.xmppclient_, err = xmpp.NewClient(client_jid, botdata.my_login_password_, nil) - if err != nil { - log.Println("Error connecting to xmpp server", err) - return nil, nil, err - } - - err = botdata.xmppclient_.StartSession(true, &xmpp.Presence{}) - if err != nil { - log.Println("'Error StartSession:", err) - return nil, nil, err - } - - roster := xmpp.Roster(botdata.xmppclient_) - for _, entry := range roster { - if entry.Subscription == "from" { - botdata.xmppclient_.Out <- botdata.makeXMPPPresence(entry.Jid, "subscribe", "","") - } - if entry.Subscription == "none" { - delete(botdata.realraum_jids_, entry.Jid) - } - } - - presence_events := make(chan interface{},1) - jabber_events := make(chan JabberEvent,1) - - go botdata.handleEventsforXMPP(botdata.xmppclient_.Out, presence_events, jabber_events) - go botdata.handleIncomingXMPPStanzas(botdata.xmppclient_.In, botdata.xmppclient_.Out, jabber_events) - - botdata.presence_events_ = &presence_events - - return botdata, presence_events, nil -} - -func (botdata *XmppBot) StopBot() { - if botdata.xmppclient_ != nil { - close(botdata.xmppclient_.Out) - } - if botdata.presence_events_ != nil { - *botdata.presence_events_ <- false - close(*botdata.presence_events_) - } -} diff --git a/r3-netstatus/sockettoevent.go b/r3-netstatus/sockettoevent.go deleted file mode 100644 index e1f3379..0000000 --- a/r3-netstatus/sockettoevent.go +++ /dev/null @@ -1,132 +0,0 @@ -package main - -import ( - pubsub "github.com/tuxychandru/pubsub" - "regexp" - "strconv" - "bufio" - "time" - //~ "./brain" - "net" - ) - -var ( - re_presence_ *regexp.Regexp = regexp.MustCompile("Presence: (yes|no)(?:, (opened|closed), (.+))?") - re_status_ *regexp.Regexp = regexp.MustCompile("Status: (closed|opened), (opening|waiting|closing|idle), (ajar|shut).*") - re_command_ *regexp.Regexp = regexp.MustCompile("(open|close|toggle|reset)(?: +(Card|Phone|SSH|ssh))?(?: +(.+))?") - re_button_ *regexp.Regexp = regexp.MustCompile("PanicButton|button\\d?") - re_temp_ *regexp.Regexp = regexp.MustCompile("temp0: (\\d+\\.\\d+)") - re_photo_ *regexp.Regexp = regexp.MustCompile("photo0: (\\d+)") -) - - -type PresenceUpdate struct { - Present bool - Ts int64 -} - -type DoorStatusUpdate struct { - Locked bool - Shut bool - Ts int64 -} - -type DoorCommandEvent struct { - Command string - Using string - Who string - Ts int64 -} - -type ButtonPressUpdate struct { - Buttonindex int - Ts int64 -} - -type TempSensorUpdate struct { - Sensorindex int - Value float64 - Ts int64 -} - -type IlluminationSensorUpdate struct { - Sensorindex int - Value int64 - Ts int64 -} - -type TimeTick struct { - Ts int64 -} - -type MovementSensorUpdate struct { - Sensorindex int - Ts int64 -} - -func ParseSocketInputLine(line string, ps *pubsub.PubSub) { //, brn *brain.Brain) { - match_presence := re_presence_.FindStringSubmatch(line) - match_status := re_status_.FindStringSubmatch(line) - match_command := re_command_.FindStringSubmatch(line) - match_button := re_button_.FindStringSubmatch(line) - match_temp := re_temp_.FindStringSubmatch(line) - match_photo := re_photo_.FindStringSubmatch(line) - - //~ log.Println("ParseSocketInputLine",line) - var tidbit interface{} - ts := time.Now().Unix() - if match_presence != nil { - if match_presence[2] != "" { ps.Pub(DoorStatusUpdate{match_presence[2] == "closed", true, ts}, "door"); } - tidbit = PresenceUpdate{match_presence[1] == "yes", ts} - //~ brn.Oboite("presence", tidbit) - ps.Pub(tidbit, "presence") - } else if match_status != nil { - tidbit = DoorStatusUpdate{match_status[1] == "closed", match_status[3] == "shut", ts} - //~ brn.Oboite("door", tidbit) - ps.Pub(tidbit, "door") - } else if match_command != nil { - tidbit = DoorCommandEvent{match_command[1], match_command[2], match_command[3], ts} - //~ brn.Oboite("doorcmd", tidbit) - ps.Pub(tidbit, "door") - } else if match_button != nil { - //~ brn.Oboite("button0", ts) - ps.Pub(ButtonPressUpdate{0, ts}, "buttons") - } else if match_temp != nil { - newtemp, err := strconv.ParseFloat((match_temp[1]), 32) - if err == nil { - //~ brn.Oboite( "temp0", newtemp) - ps.Pub(TempSensorUpdate{0, newtemp, ts}, "sensors") - } - } else if match_photo != nil { - newphoto, err := strconv.ParseInt(match_photo[1], 10, 32) - if err == nil { - //~ brn.Oboite("photo0", newphoto) - ps.Pub(IlluminationSensorUpdate{0, newphoto, ts}, "sensors") - } - } else if line == "movement" { - //~ brn.Oboite("movement", ts) - ps.Pub(MovementSensorUpdate{0, ts}, "movements") - } -} - -func ReadFromUSocket(path string, c chan string) { -ReOpenSocket: - for { - presence_socket, err := net.Dial("unix", path) - if err != nil { - //Waiting on Socket - time.Sleep(5 * time.Second) - continue ReOpenSocket - } - presence_reader := bufio.NewReader(presence_socket) - for { - line, err := presence_reader.ReadString('\n') - if err != nil { - //Socket closed - presence_socket.Close() - continue ReOpenSocket - } - c <- line - } - } -} \ No newline at end of file diff --git a/r3-netstatus/spaceapi/spaceapi.go b/r3-netstatus/spaceapi/spaceapi.go deleted file mode 100644 index 4162295..0000000 --- a/r3-netstatus/spaceapi/spaceapi.go +++ /dev/null @@ -1,242 +0,0 @@ -// spaceapi.go -package spaceapi - -import ( - "encoding/json" - "time" -) - -const max_num_events int = 4 - -type SpaceInfo map[string]interface{} - -type SpaceDoorLockSensor struct { - value bool - location string - name string - description string -} - -type SpaceDoorAjarSensor struct { - value bool - location string - name string - description string -} - -func MakeTempSensor(name, where, unit string, value float64) SpaceInfo { - listofwhats := make([]SpaceInfo, 1) - listofwhats[0] = SpaceInfo{ - "value": value, - "unit": unit, - "location": where, - "name": name, - "description": ""} - return SpaceInfo{"temperature": listofwhats} -} - -func MakeTempCSensor(name, where string, value float64) SpaceInfo { - return MakeTempSensor(name,where,"\u00b0C",value) -} - -func MakeIlluminationSensor(name, where, unit string, value int64) SpaceInfo { - listofwhats := make([]SpaceInfo, 1) - listofwhats[0] = SpaceInfo{ - "value": value, - "unit": unit, - "location": where, - "name": name, - "description": ""} - return SpaceInfo{"ext_illumination": listofwhats} -} - -func MakePowerConsumptionSensor(name, where, unit string, value int64) SpaceInfo { - listofwhats := make([]SpaceInfo, 1) - listofwhats[0] = SpaceInfo{ - "value": value, - "unit": unit, - "location": where, - "name": name, - "description": ""} - return SpaceInfo{"power_consumption": listofwhats} -} - -func MakeNetworkConnectionsSensor(name, where, nettype string, value, machines int64) SpaceInfo { - listofwhats := make([]SpaceInfo, 1) - listofwhats[0] = SpaceInfo{ - "value": value, - "type": nettype, - "machines": machines, - "location": where, - "name": name, - "description": ""} - return SpaceInfo{"network_connections": listofwhats} -} - -func MakeMemberCountSensor(name, where string, value int64) SpaceInfo { - listofwhats := make([]SpaceInfo, 1) - listofwhats[0] = SpaceInfo{ - "value": value, - "location": where, - "name": name, - "description": ""} - return SpaceInfo{"total_member_count": listofwhats} -} - -func MakeDoorLockSensor(name, where string, value bool) SpaceInfo { - listofwhats := make([]SpaceInfo, 1) - listofwhats[0] = SpaceInfo{ - "value": value, - "location": where, - "name": name, - "description": ""} - return SpaceInfo{"door_locked": listofwhats} -} - -func MakeDoorAjarSensor(name, where string, value bool) SpaceInfo { - listofwhats := make([]SpaceInfo, 1) - listofwhats[0] = SpaceInfo{ - "value": value, - "location": where, - "name": name, - "description": ""} - return SpaceInfo{"ext_door_ajar": listofwhats} -} - -func (nsi SpaceInfo) MergeInSensor(sensorinfo SpaceInfo) { - if nsi["sensors"] == nil { - nsi["sensors"] = SpaceInfo{} - //~ listofwhats := make([]SpaceInfo, 1) - //~ listofwhats[0] = sensortype.(SpaceInfo) - //~ sensorobj := SpaceInfo{what: listofwhats} - //~ nsi["sensors"] = sensorobj - } - sensorobj := nsi["sensors"].(SpaceInfo) - for what, subsensorobjlist := range sensorinfo { - if sensorobj[what] == nil { - sensorobj[what] = subsensorobjlist - } else { - existingsensorobjslist := sensorobj[what].([]SpaceInfo) - for _, newsensorobj := range subsensorobjlist.([]SpaceInfo) { - foundandsubstituted := false - for i:=0; i< len(existingsensorobjslist); i++ { - if existingsensorobjslist[i]["name"] == newsensorobj["name"] { - existingsensorobjslist[i] = newsensorobj - foundandsubstituted = true - } - } - if foundandsubstituted == false { - sensorobj[what] = append(sensorobj[what].([]SpaceInfo), newsensorobj) - //note that we do not change existingsensorobjslist here but directly sensorobj[what] !! - //the implications being that, if we have several newsensorobj in the list: - // a) optimisation: we only check them against the existing ones and spare ourselves the work of checking a newsensorobj's name against a just added other newsensorobjs's name - // b) if the array sensorinfo[what] has several objects with the same name, nsi["sensors"] will also end up with these name conflicts - } - } - } - } -} - -func (nsi SpaceInfo) AddSpaceContactInfo(phone, irc, email, ml, jabber, issuemail string) SpaceInfo { - nsi["contact"] = SpaceInfo{ - "phone": phone, - "email": email, - "ml": ml, - "jabber": jabber, - "issue_mail": issuemail} - nsi["issue_report_channels"] = [3]string{"issue_mail","email","ml"} - return nsi -} - -func (nsi SpaceInfo) AddSpaceFeed(feedtype, url string) SpaceInfo { - newfeed := SpaceInfo{"url": url} - if nsi["feeds"] == nil { - nsi["feeds"] = SpaceInfo{feedtype: newfeed} - } else { - feedobj, ok := nsi["feeds"].(SpaceInfo) //type assertion (panics if false) - if ok { - feedobj[feedtype] = newfeed - } else { - panic("Wrong Type of feedobj: Should never happen") - } - } - return nsi -} - -func (nsi SpaceInfo) AddSpaceEvent(name, eventtype, extra string) SpaceInfo { - newevent := SpaceInfo{"name": name, "type": eventtype, "timestamp": time.Now().Unix(), "extra": extra} - if nsi["events"] == nil { - eventlist := make([]SpaceInfo, 1) - eventlist[0] = newevent - nsi["events"] = eventlist - } else { - eventlist, ok := nsi["events"].([]SpaceInfo) //type assertion - if ok { - if len(eventlist) >= max_num_events { - eventlist = eventlist[1:] - } - nsi["events"] = append(eventlist, newevent) - } else { - panic("Wrong Type of eventlist: Should never happen") - } - } - return nsi -} - -func (nsi SpaceInfo) AddSpaceAddress(address string) SpaceInfo { - nsi["address"] = address - if nsi["location"] != nil { - location, ok := nsi["location"].(SpaceInfo) - if ok { - location["address"] = address - } - } - return nsi -} - -func (nsi SpaceInfo) SetStatus(open bool, status string) { - nsi["status"] = status - nsi["open"] = open - nsi["lastchange"] = time.Now().Unix() - state, ok := nsi["state"].(SpaceInfo) - if ok { - state["message"] = status - state["open"] = open - state["lastchange"] = nsi["lastchange"] - } -} - -func NewSpaceInfo(space string, url string, logo string, open_icon string, closed_icon string, lat float64, lon float64) SpaceInfo { - nsi := map[string]interface{}{ - "api": "0.13", - "space": space, - "url": url, - "logo": logo, - "open": false, - "lastchange": time.Now().Unix(), - "icon": SpaceInfo{ - "open": open_icon, - "closed": closed_icon, - }, - "state": SpaceInfo{ - "open": false, - "lastchange":time.Now().Unix(), - "icon": SpaceInfo{ - "open": open_icon, - "closed": closed_icon}, - }, - "location": SpaceInfo{ - "lat": lat, - "lon": lon}, - "contact" : SpaceInfo {}, - } - return nsi -} - -func (data SpaceInfo) MakeJSON() ([]byte, error) { - msg, err := json.Marshal(data) - if err == nil { - return msg, nil - } - return nil, err -} diff --git a/r3-netstatus/webstatus.go b/r3-netstatus/webstatus.go deleted file mode 100644 index d303b13..0000000 --- a/r3-netstatus/webstatus.go +++ /dev/null @@ -1,95 +0,0 @@ -package main - -import ( - pubsub "github.com/tuxychandru/pubsub" - "./spaceapi" - "regexp" - "net/http" - "net/url" - "log" - "time" - ) - - -type spaceState struct { - present bool - buttonpress_until int64 -} - -var ( - spaceapidata spaceapi.SpaceInfo = spaceapi.NewSpaceInfo("realraum", "http://realraum.at", "http://realraum.at/logo-red_250x250.png", "http://realraum.at/logo-re_open_100x100.png", "http://realraum.at/logo-re_empty_100x100.png",47.065554, 15.450435).AddSpaceAddress("Brockmanngasse 15, 8010 Graz, Austria") - statusstate *spaceState = new(spaceState) - re_querystresc_ *regexp.Regexp = regexp.MustCompile("[^\x30-\x39\x41-\x7E]") -) - - -func init() { - spaceapidata.AddSpaceFeed("calendar", "http://grical.realraum.at/s/?query=!realraum&view=rss") - spaceapidata.AddSpaceFeed("blog", "https://plus.google.com/113737596421797426873") - spaceapidata.AddSpaceFeed("wiki", "http://realraum.at/wiki") - spaceapidata.AddSpaceContactInfo("+43780700888524", "irc://irc.oftc.net/#realraum", "realraum@realraum.at", "realraum@realraum.at", "realraum@realraum.at", "vorstand@realraum.at") -} - - -func updateStatusString() { - var spacestatus string - if statusstate.present { - if statusstate.buttonpress_until > time.Now().Unix() { - spacestatus = "Panic! Present&Bored" - } else { - spacestatus = "Leute Anwesend" - } - } else { - spacestatus = "Keiner Da" - } - spaceapidata.SetStatus(statusstate.present, spacestatus) -} - -func publishStateToWeb() { - updateStatusString() - jsondata_b, err := spaceapidata.MakeJSON() - if err != nil { - log.Println("Error:", err) - return - } - //jsondata_b := re_querystresc_.ReplaceAllFunc(jsondata_b, func(in []byte) []byte { - // out := make([]byte, 4) - // out[0] = '%' - // copy(out[1:], []byte(strconv.FormatInt(int64(in[0]), 16))) - // return out - //}) - jsondata := url.QueryEscape(string(jsondata_b)) - resp, err := http.Get("http://www.realraum.at/cgi/status.cgi?pass=jako16&set=" + jsondata) - if err != nil { - log.Println("Error publishing realraum info", err) - return - } - resp.Body.Close() -} - -func EventToWeb(ps *pubsub.PubSub) { - events := ps.Sub("presence","door","sensors","buttons","updateinterval") - - for eventinterface := range(events) { - switch event := eventinterface.(type) { - case TimeTick: - publishStateToWeb() - case PresenceUpdate: - statusstate.present = event.Present - publishStateToWeb() - case DoorStatusUpdate: - spaceapidata.MergeInSensor(spaceapi.MakeDoorLockSensor("TorwaechterLock", "Türschloß", event.Locked)) - spaceapidata.MergeInSensor(spaceapi.MakeDoorLockSensor("TorwaechterAjarSensor", "Türkontakt", event.Shut)) - publishStateToWeb() - case ButtonPressUpdate: - statusstate.buttonpress_until = event.Ts + 3600 - spaceapidata.AddSpaceEvent("PanicButton", "check-in", "The button has been pressed") - publishStateToWeb() - case TempSensorUpdate: - spaceapidata.MergeInSensor(spaceapi.MakeTempCSensor("Temp0","Decke", event.Value)) - case IlluminationSensorUpdate: - spaceapidata.MergeInSensor(spaceapi.MakeIlluminationSensor("Photodiode","Decke","1024V/5V", event.Value)) - } - } -} -