1 // (c) Bernhard Tittelbach, 2013
7 pubsub "github.com/tuxychandru/pubsub"
12 r3events "svn.spreadspace.org/realraum/go.svn/r3events"
13 zmq "github.com/vaughan0/go-zmq"
16 type SpaceState struct {
18 buttonpress_until int64
24 xmpp_login_ struct {jid string; pass string}
25 xmpp_bot_authstring_ string
26 xmpp_state_save_dir_ string
27 r3eventssub_port_ string
28 button_press_timeout_ int64 = 3600
29 brain_connect_addr_ string
30 enable_syslog_, enable_debug_ bool
36 flag.StringVar(&xmpp_login_.jid, "xjid", "realrauminfo@realraum.at/Tuer", "XMPP Bot Login JID")
37 flag.StringVar(&xmpp_login_.pass, "xpass", "", "XMPP Bot Login Password")
38 flag.StringVar(&xmpp_bot_authstring_, "xbotauth", "", "String that user use to authenticate themselves to the bot")
39 flag.StringVar(&xmpp_state_save_dir_,"xstatedir","/flash/var/lib/r3netstatus/", "Directory to save XMPP bot state in")
40 flag.StringVar(&r3eventssub_port_, "eventsubport", "tcp://wuzzler.realraum.at:4244", "zmq address to subscribe r3events")
41 flag.StringVar(&brain_connect_addr_, "brainconnect", "tcp://wuzzler.realraum.at:4245", "address to ask about most recent stored events")
42 flag.BoolVar(&enable_syslog_, "syslog", false, "enable logging to syslog")
43 flag.BoolVar(&enable_debug_, "debug", false, "enable debug output")
49 func IfThenElseStr(c bool, strue, sfalse string) string {
50 if c {return strue} else {return sfalse}
53 func composeDoorLockMessage(locked bool, frontshut r3events.DoorAjarUpdate, doorcmd r3events.DoorCommandEvent, ts int64) string {
54 var ajarstring string = "";
55 if frontshut.Shut == false && frontshut.Ts < doorcmd.Ts {
56 ajarstring = " (still ajar)"
58 if ts - doorcmd.Ts < 30 {
59 if len(doorcmd.Who) == 0 || doorcmd.Who == "-" {
60 return fmt.Sprintf("The%s frontdoor was %s by %s at %s.",ajarstring, IfThenElseStr(locked, "locked","unlocked"), doorcmd.Using, time.Unix(ts,0).String())
62 return fmt.Sprintf("%s %s the%s frontdoor by %s at %s.",doorcmd.Who, IfThenElseStr(locked, "locked","unlocked"), ajarstring, doorcmd.Using, time.Unix(ts,0).String())
65 return fmt.Sprintf("The%s frontdoor was %s manually at %s.", ajarstring, IfThenElseStr(locked, "locked","unlocked"), time.Unix(ts,0).String())
69 func composePresence(present bool, temp_cx float64, light_lothr, last_buttonpress int64) r3xmppbot.XMPPStatusEvent {
70 present_msg := "Somebody is present"
71 notpresent_msg := "Nobody is here"
72 button_msg := "The button has been pressed :-)"
73 msg := "%s (CX: %.2f°C, LoTHR light: %d)"
76 if last_buttonpress > 0 && time.Now().Unix() - last_buttonpress < button_press_timeout_ {
77 return r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowFreeForChat, fmt.Sprintf(msg, button_msg, temp_cx, light_lothr)}
79 return r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowOnline, fmt.Sprintf(msg, present_msg, temp_cx, light_lothr)}
82 return r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowNotAvailabe, fmt.Sprintf(msg, notpresent_msg, temp_cx, light_lothr)}
86 func EventToXMPP(bot *r3xmppbot.XmppBot, events <- chan interface{}, xmpp_presence_events_chan chan <- interface{}) {
87 button_msg := "Dooom ! The button has been pressed ! Propably someone is bored and in need of company ! ;-)"
89 if x := recover(); x != nil {
90 //defer ist called _after_ EventToXMPP function has returned. Thus we recover after returning from this function.
91 Syslog_.Printf("handleIncomingXMPPStanzas: run time panic: %v", x)
95 var present, frontlock bool = false, true
96 var last_buttonpress, light_lothr int64 = 0, 0
97 var temp_cx float64 = 0.0
98 var last_door_cmd r3events.DoorCommandEvent;
99 var last_frontdoor_ajar r3events.DoorAjarUpdate = r3events.DoorAjarUpdate{true, 0};
101 xmpp_presence_events_chan <- r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowNotAvailabe, "Nobody is here"}
103 for eventinterface := range(events) {
104 Debug_.Printf("event2xmpp: %T %+v", eventinterface, eventinterface)
105 switch event := eventinterface.(type) {
106 case r3events.PresenceUpdate:
107 present = event.Present
108 if ! present { last_buttonpress = 0 }
109 xmpp_presence_events_chan <- composePresence(present, temp_cx, light_lothr, last_buttonpress)
110 case r3events.DoorCommandEvent:
111 last_door_cmd = event
112 xmpp_presence_events_chan <- fmt.Sprintln("DoorCommand:",event.Command, "using", event.Using, "by", event.Who, time.Unix(event.Ts,0))
113 case r3events.DoorLockUpdate:
114 if frontlock != event.Locked {
115 xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: composeDoorLockMessage(event.Locked, last_frontdoor_ajar, last_door_cmd, event.Ts), DistributeLevel: r3xmppbot.R3OnlineOnlyInfo, RememberAsStatus: true}
117 frontlock = event.Locked
118 case r3events.DoorAjarUpdate:
119 if last_frontdoor_ajar.Shut != event.Shut {
120 xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: fmt.Sprintf("Frontdoor is %s (%s)",IfThenElseStr(event.Shut,"now shut.","ajar."),time.Unix(event.Ts,0).String()), DistributeLevel: r3xmppbot.R3DebugInfo, RememberAsStatus: false}
122 last_frontdoor_ajar = event
123 case r3events.BackdoorAjarUpdate:
124 xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: fmt.Sprintf("Backdoor is %s (%s)",IfThenElseStr(event.Shut,"now shut.","ajar!"),time.Unix(event.Ts,0).String()), DistributeLevel: r3xmppbot.R3OnlineOnlyInfo, RememberAsStatus: false}
125 case r3events.GasLeakAlert:
126 xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: fmt.Sprintf("ALERT !! GasLeak Detected !!! (%s)", time.Unix(event.Ts,0).String()), DistributeLevel: r3xmppbot.R3NeverInfo, RememberAsStatus: false}
127 case r3events.IlluminationSensorUpdate:
128 light_lothr = event.Value
129 case r3events.TempSensorUpdate:
130 if event.Sensorindex == 1 {
131 temp_cx = event.Value
133 case r3events.BoreDoomButtonPressEvent:
134 last_buttonpress = event.Ts
135 xmpp_presence_events_chan <- composePresence(present, temp_cx, light_lothr, last_buttonpress)
136 xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: button_msg, DistributeLevel: r3xmppbot.R3OnlineOnlyInfo}
137 case r3events.TimeTick:
138 // update presence text with sensor and button info
139 xmpp_presence_events_chan <- composePresence(present, temp_cx, light_lothr, last_buttonpress)
140 // Try to XMPP Ping the server and if that fails, quit XMPPBot
141 if bot.PingServer(900) == false && bot.PingServer(900) == false && bot.PingServer(900) == false && bot.PingServer(900) == false{ return }
142 case r3events.DoorProblemEvent:
143 xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: fmt.Sprintf("Door Problem: %s. SeverityLevel: %d (%s)",event.Problem, event.Severity, time.Unix(event.Ts,0).String()), DistributeLevel: r3xmppbot.R3OnlineOnlyInfo, RememberAsStatus: false}
148 func RunXMPPBot(ps *pubsub.PubSub, zmqctx *zmq.Context) {
150 var bot *r3xmppbot.XmppBot
151 var xmpp_presence_events_chan chan interface{}
153 bot, xmpp_presence_events_chan, xmpperr = r3xmppbot.NewStartedBot(xmpp_login_.jid, xmpp_login_.pass, xmpp_bot_authstring_, xmpp_state_save_dir_, true)
155 Syslog_.Printf("Successfully (re)started XMPP Bot")
156 // subscribe before QueryLatestEventsAndInjectThem and EventToXMPP
157 psevents := ps.Sub("presence","door","buttons","updateinterval","sensors")
158 QueryLatestEventsAndInjectThem(ps, zmqctx)
159 EventToXMPP(bot, psevents, xmpp_presence_events_chan)
160 // unsubscribe right away, since we don't known when reconnect will succeed and we don't want to block PubSub
161 ps.Unsub(psevents, "presence","door","buttons","updateinterval","sensors")
164 Syslog_.Printf("Error starting XMPP Bot: %s", xmpperr.Error())
166 time.Sleep(10 * time.Second)
170 func ParseZMQr3Event(lines [][]byte, ps *pubsub.PubSub) {
171 evnt, pubsubcat, err := r3events.UnmarshalByteByte2Event(lines)
172 Debug_.Printf("ParseZMQr3Event: %s %s %s", evnt, pubsubcat, err)
173 if err != nil { return }
174 ps.Pub(evnt, pubsubcat)
177 func QueryLatestEventsAndInjectThem(ps *pubsub.PubSub, zmqctx *zmq.Context) {
178 answ := ZmqsAskQuestionsAndClose(zmqctx, brain_connect_addr_, [][][]byte{
179 [][]byte{[]byte("BackdoorAjarUpdate")},
180 [][]byte{[]byte("DoorCommandEvent")},
181 [][]byte{[]byte("DoorLockUpdate")},
182 [][]byte{[]byte("DoorAjarUpdate")},
183 [][]byte{[]byte("PresenceUpdate")},
184 [][]byte{[]byte("IlluminationSensorUpdate")},
185 [][]byte{[]byte("TempSensorUpdate")}})
186 for _, a := range(answ) {
187 ParseZMQr3Event(a, ps)
192 if enable_syslog_ { LogEnableSyslog(); r3xmppbot.LogEnableSyslog() }
193 if enable_debug_ { LogEnableDebuglog(); r3xmppbot.LogEnableDebuglog() }
194 Syslog_.Print("started")
195 defer Syslog_.Print("exiting")
196 zmqctx, zmqsub := ZmqsInit(r3eventssub_port_)
198 if zmqsub != nil {defer zmqsub.Close()}
200 panic("zmq sockets must not be nil !!")
205 //~ brn := brain.New()
206 //~ defer brn.Shutdown()
209 // --- get update on most recent events ---
210 QueryLatestEventsAndInjectThem(ps, zmqctx)
211 go RunXMPPBot(ps, zmqctx)
213 // --- receive and distribute events ---
214 ticker := time.NewTicker(time.Duration(6) * time.Minute)
217 case e := <-zmqsub.In():
218 ParseZMQr3Event(e, ps) //, brn)
220 ps.Pub(r3events.TimeTick{time.Now().Unix()}, "updateinterval")