fix presence bug
[svn42.git] / go / r3-netstatus / main.go
1 // (c) Bernhard Tittelbach, 2013
2
3 package main
4
5 import (
6     "./r3xmppbot"
7     pubsub "github.com/tuxychandru/pubsub"
8     "flag"
9     "time"
10     "fmt"
11     //~ "./brain"
12     r3events "svn.spreadspace.org/realraum/go.svn/r3events"
13     zmq "github.com/vaughan0/go-zmq"
14 )
15
16 type SpaceState struct {
17     present           bool
18     buttonpress_until int64
19     door_locked bool
20     door_shut bool
21 }
22
23 var (
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
31 )
32
33 type EventToXMPPStartupFinished struct{}
34
35 //-------
36
37 func init() {
38     flag.StringVar(&xmpp_login_.jid, "xjid", "realrauminfo@realraum.at/Tuer", "XMPP Bot Login JID")
39     flag.StringVar(&xmpp_login_.pass, "xpass", "", "XMPP Bot Login Password")
40     flag.StringVar(&xmpp_bot_authstring_, "xbotauth", "", "String that user use to authenticate themselves to the bot")
41     flag.StringVar(&xmpp_state_save_dir_,"xstatedir","/flash/var/lib/r3netstatus/",  "Directory to save XMPP bot state in")
42     flag.StringVar(&r3eventssub_port_, "eventsubport", "tcp://wuzzler.realraum.at:4244", "zmq address to subscribe r3events")
43     flag.StringVar(&brain_connect_addr_, "brainconnect", "tcp://wuzzler.realraum.at:4245", "address to ask about most recent stored events")
44     flag.BoolVar(&enable_syslog_, "syslog", false, "enable logging to syslog")
45     flag.BoolVar(&enable_debug_, "debug", false, "enable debug output")
46     flag.Parse()
47 }
48
49 //-------
50
51 func IfThenElseStr(c bool, strue, sfalse string) string {
52     if c {return strue} else {return sfalse}
53 }
54
55 func composeDoorLockMessage(locked bool, frontshut r3events.DoorAjarUpdate, doorcmd r3events.DoorCommandEvent, ts int64) string {
56     var ajarstring string = "";
57     if frontshut.Shut == false && frontshut.Ts < doorcmd.Ts {
58         ajarstring = " (still ajar)"
59     }
60     if ts - doorcmd.Ts < 30 {
61         if len(doorcmd.Who) == 0 || doorcmd.Who == "-" {
62             return fmt.Sprintf("The%s frontdoor was %s by %s at %s.",ajarstring, IfThenElseStr(locked, "locked","unlocked"), doorcmd.Using, time.Unix(ts,0).String())
63         } else {
64             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         }
66     } else {
67         return fmt.Sprintf("The%s frontdoor was %s manually at %s.", ajarstring, IfThenElseStr(locked, "locked","unlocked"), time.Unix(ts,0).String())
68     }
69 }
70
71 func composePresence(present bool, temp_cx float64, light_lothr, last_buttonpress int64) r3xmppbot.XMPPStatusEvent {
72     present_msg := "Somebody is present"
73     notpresent_msg := "Nobody is here"
74     button_msg := "The button has been pressed :-)"
75     msg := "%s (CX: %.2f°C, LoTHR light: %d)"
76     
77     if present {
78         if last_buttonpress > 0 && time.Now().Unix() - last_buttonpress < button_press_timeout_ {
79             return r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowFreeForChat, fmt.Sprintf(msg, button_msg, temp_cx, light_lothr)}
80         } else {
81             return r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowOnline, fmt.Sprintf(msg, present_msg, temp_cx, light_lothr)}
82         }
83     } else {
84         return r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowNotAvailabe, fmt.Sprintf(msg, notpresent_msg, temp_cx, light_lothr)}
85     }
86 }
87
88 func EventToXMPP(bot *r3xmppbot.XmppBot, events <- chan interface{}, xmpp_presence_events_chan chan <- interface{}) {
89     button_msg := "Dooom ! The button has been pressed ! Propably someone is bored and in need of company ! ;-)"
90     defer func() {
91         if x := recover(); x != nil {
92             //defer ist called _after_ EventToXMPP function has returned. Thus we recover after returning from this function.
93             Syslog_.Printf("handleIncomingXMPPStanzas: run time panic: %v", x)
94         }
95     }()
96
97     var present, frontlock bool = false, true
98     var last_buttonpress, light_lothr int64 = 0, 0
99     var temp_cx float64 = 0.0
100     var last_door_cmd r3events.DoorCommandEvent
101     var last_frontdoor_ajar r3events.DoorAjarUpdate = r3events.DoorAjarUpdate{true, 0}
102     var standard_distribute_level r3xmppbot.R3JIDDesire = r3xmppbot.R3DebugInfo // initial state, changed after startup finished event recieved
103
104     xmpp_presence_events_chan <- r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowNotAvailabe, "Nobody is here"}
105
106     for eventinterface := range(events) {
107         Debug_.Printf("event2xmpp: %T %+v", eventinterface, eventinterface)
108         switch event := eventinterface.(type) {
109             case EventToXMPPStartupFinished:
110                 //after we received all events from QueryLatestEventsAndInjectThem, we get this event and start sending new events normally
111                 standard_distribute_level = r3xmppbot.R3OnlineOnlyInfo
112             case r3events.PresenceUpdate:
113                 present = event.Present
114                 if ! present { last_buttonpress = 0 }
115                 xmpp_presence_events_chan <- composePresence(present, temp_cx, light_lothr, last_buttonpress)
116             case r3events.DoorCommandEvent:
117                 last_door_cmd = event
118                 xmpp_presence_events_chan <- fmt.Sprintln("DoorCommand:",event.Command, "using", event.Using, "by", event.Who, time.Unix(event.Ts,0))
119             case r3events.DoorLockUpdate:
120                 if frontlock != event.Locked {
121                     xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: composeDoorLockMessage(event.Locked, last_frontdoor_ajar, last_door_cmd, event.Ts), DistributeLevel:standard_distribute_level, RememberAsStatus: true}
122                 }
123                 frontlock = event.Locked
124            case r3events.DoorAjarUpdate:
125                 if last_frontdoor_ajar.Shut != event.Shut {
126                     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}
127                 }
128                 last_frontdoor_ajar = event
129            case r3events.BackdoorAjarUpdate:
130                 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: standard_distribute_level, RememberAsStatus: false}
131            case r3events.GasLeakAlert:
132                 xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg:  fmt.Sprintf("ALERT !! GasLeak Detected !!! (%s)", time.Unix(event.Ts,0).String()), DistributeLevel: r3xmppbot.R3NeverInfo, RememberAsStatus: false}
133             case r3events.IlluminationSensorUpdate:
134                 light_lothr = event.Value
135             case r3events.TempSensorUpdate:
136                 if event.Sensorindex == 1 {
137                     temp_cx = event.Value
138                 }
139             case r3events.BoreDoomButtonPressEvent:
140                 last_buttonpress = event.Ts
141                 xmpp_presence_events_chan <- composePresence(present, temp_cx, light_lothr, last_buttonpress)
142                 xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: button_msg, DistributeLevel: standard_distribute_level}
143             case r3events.TimeTick:
144                 // update presence text with sensor and button info
145                 xmpp_presence_events_chan <- composePresence(present, temp_cx, light_lothr, last_buttonpress)
146                 // Try to XMPP Ping the server and if that fails, quit XMPPBot
147                 if bot.PingServer(900) == false && bot.PingServer(900) == false && bot.PingServer(900) == false && bot.PingServer(900) == false && bot.PingServer(900) == false { return }
148             case r3events.DoorProblemEvent:
149                 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}
150         }
151         }
152 }
153
154 func RunXMPPBot(ps *pubsub.PubSub, zmqctx *zmq.Context) {
155     var xmpperr error
156     var bot *r3xmppbot.XmppBot
157     var xmpp_presence_events_chan chan interface{}
158     for {
159         bot, xmpp_presence_events_chan, xmpperr = r3xmppbot.NewStartedBot(xmpp_login_.jid, xmpp_login_.pass, xmpp_bot_authstring_, xmpp_state_save_dir_, true)
160         if xmpperr == nil {
161             Syslog_.Printf("Successfully (re)started XMPP Bot")
162             // subscribe before QueryLatestEventsAndInjectThem and EventToXMPP
163             psevents := ps.Sub("presence","door","buttons","updateinterval","sensors","xmppmeta")
164             QueryLatestEventsAndInjectThem(ps, zmqctx)
165             ps.Pub(EventToXMPPStartupFinished{}, "xmppmeta")
166             EventToXMPP(bot, psevents, xmpp_presence_events_chan)
167             // unsubscribe right away, since we don't known when reconnect will succeed and we don't want to block PubSub
168             ps.Unsub(psevents, "presence","door","buttons","updateinterval","sensors","xmppmeta")
169             bot.StopBot()
170         } else {
171             Syslog_.Printf("Error starting XMPP Bot: %s", xmpperr.Error())
172         }
173         time.Sleep(10 * time.Second)
174     }
175 }
176
177 func ParseZMQr3Event(lines [][]byte, ps *pubsub.PubSub) {
178     evnt, pubsubcat, err := r3events.UnmarshalByteByte2Event(lines)
179     Debug_.Printf("ParseZMQr3Event: %s %s %s", evnt, pubsubcat, err)
180     if err != nil { return }
181     ps.Pub(evnt, pubsubcat)
182 }
183
184 func QueryLatestEventsAndInjectThem(ps *pubsub.PubSub, zmqctx *zmq.Context) {
185     answ := ZmqsAskQuestionsAndClose(zmqctx, brain_connect_addr_, [][][]byte{
186         [][]byte{[]byte("BackdoorAjarUpdate")},
187         [][]byte{[]byte("DoorCommandEvent")},
188         [][]byte{[]byte("DoorLockUpdate")},
189         [][]byte{[]byte("DoorAjarUpdate")},
190         [][]byte{[]byte("PresenceUpdate")},
191         [][]byte{[]byte("IlluminationSensorUpdate")},
192         [][]byte{[]byte("TempSensorUpdate")}})
193     for _, a := range(answ) {
194         ParseZMQr3Event(a, ps)
195     }
196 }
197
198 func main() {
199     if enable_syslog_ { LogEnableSyslog(); r3xmppbot.LogEnableSyslog() }
200     if enable_debug_ { LogEnableDebuglog(); r3xmppbot.LogEnableDebuglog() }
201     Syslog_.Print("started")
202     defer Syslog_.Print("exiting")
203     zmqctx, zmqsub := ZmqsInit(r3eventssub_port_)
204     defer zmqctx.Close()
205     if zmqsub != nil {defer zmqsub.Close()}
206     if zmqsub == nil {
207         panic("zmq sockets must not be nil !!")
208     }
209
210     ps := pubsub.New(10)
211     defer ps.Shutdown()
212     //~ brn := brain.New()
213     //~ defer brn.Shutdown()
214
215     go EventToWeb(ps)
216     // --- get update on most recent events ---
217     QueryLatestEventsAndInjectThem(ps, zmqctx)
218     go RunXMPPBot(ps, zmqctx)
219
220     // --- receive and distribute events ---
221     ticker := time.NewTicker(time.Duration(6) * time.Minute)
222     for {
223     select {
224         case e := <-zmqsub.In():
225             ParseZMQr3Event(e, ps) //, brn)
226         case <-ticker.C:
227             ps.Pub(r3events.TimeTick{time.Now().Unix()}, "updateinterval")
228         }
229     }
230 }