a15c4ba68457b062cc149070038cc8c090fad27e
[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 //-------
34
35 func init() {
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")
44     flag.Parse()
45 }
46
47 //-------
48
49 func IfThenElseStr(c bool, strue, sfalse string) string {
50     if c {return strue} else {return sfalse}
51 }
52
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)"
57     }
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())
61         } else {
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())
63         }
64     } else {
65         return fmt.Sprintf("The%s frontdoor was %s manually at %s.", ajarstring, IfThenElseStr(locked, "locked","unlocked"), time.Unix(ts,0).String())
66     }
67 }
68
69 func EventToXMPP(bot *r3xmppbot.XmppBot, events <- chan interface{}, xmpp_presence_events_chan chan <- interface{}) {
70
71     defer func() {
72         if x := recover(); x != nil {
73             //defer ist called _after_ EventToXMPP function has returned. Thus we recover after returning from this function.
74             Syslog_.Printf("handleIncomingXMPPStanzas: run time panic: %v", x)
75         }
76     }()
77
78     var present, frontlock bool = false, true
79     var last_buttonpress int64 = 0
80     var last_door_cmd r3events.DoorCommandEvent;
81     var last_frontdoor_ajar r3events.DoorAjarUpdate = r3events.DoorAjarUpdate{true, 0};
82     button_msg := "Dooom ! The button has been pressed ! Propably someone is bored and in need of company ! ;-)"
83     present_status := r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowOnline,"Somebody is present"}
84     notpresent_status := r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowNotAvailabe,"Nobody is here"}
85     button_status := r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowFreeForChat, "The button has been pressed :-)"}
86
87     xmpp_presence_events_chan <- r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowNotAvailabe, "Nobody is here"}
88
89     for eventinterface := range(events) {
90         Debug_.Printf("event2xmpp: %T %+v", eventinterface, eventinterface)
91         switch event := eventinterface.(type) {
92             case r3events.PresenceUpdate:
93                 present = event.Present
94                 if present {
95                     xmpp_presence_events_chan <- present_status
96                 } else {
97                     xmpp_presence_events_chan <- notpresent_status
98                 }
99             case r3events.DoorCommandEvent:
100                 last_door_cmd = event
101                 xmpp_presence_events_chan <- fmt.Sprintln("DoorCommand:",event.Command, "using", event.Using, "by", event.Who, time.Unix(event.Ts,0))
102             case r3events.DoorLockUpdate:
103                 if frontlock != event.Locked {
104                     xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: composeDoorLockMessage(event.Locked, last_frontdoor_ajar, last_door_cmd, event.Ts), DistributeLevel: r3xmppbot.R3OnlineOnlyInfo, RememberAsStatus: true}
105                 }
106                 frontlock = event.Locked
107            case r3events.DoorAjarUpdate:
108                 if last_frontdoor_ajar.Shut != event.Shut {
109                     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}
110                 }
111                 last_frontdoor_ajar = event
112            case r3events.BackdoorAjarUpdate:
113                 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}
114            case r3events.GasLeakAlert:
115                 xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg:  fmt.Sprintf("ALERT !! GasLeak Detected !!! (%s)", time.Unix(event.Ts,0).String()), DistributeLevel: r3xmppbot.R3NeverInfo, RememberAsStatus: false}
116             case r3events.BoreDoomButtonPressEvent:
117                 xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: button_msg, DistributeLevel: r3xmppbot.R3OnlineOnlyInfo}
118                 xmpp_presence_events_chan <- button_status
119                 last_buttonpress = event.Ts
120             case r3events.TimeTick:
121                 if present && last_buttonpress > 0 && time.Now().Unix() - last_buttonpress > button_press_timeout_ {
122                     xmpp_presence_events_chan <- present_status
123                     last_buttonpress = 0
124                 }
125                 // Try to XMPP Ping the server and if that fails, quit XMPPBot
126                 if bot.PingServer(900) == false && bot.PingServer(900) == false && bot.PingServer(900) == false && bot.PingServer(900) == false{ return }
127             case r3events.DoorProblemEvent:
128                 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}
129         }
130         }
131 }
132
133 func RunXMPPBot(ps *pubsub.PubSub, zmqctx *zmq.Context) {
134     var xmpperr error
135     var bot *r3xmppbot.XmppBot
136     var xmpp_presence_events_chan chan interface{}
137     for {
138         bot, xmpp_presence_events_chan, xmpperr = r3xmppbot.NewStartedBot(xmpp_login_.jid, xmpp_login_.pass, xmpp_bot_authstring_, xmpp_state_save_dir_, true)
139         if xmpperr == nil {
140             Syslog_.Printf("Successfully (re)started XMPP Bot")
141             // subscribe before QueryLatestEventsAndInjectThem and EventToXMPP
142             psevents := ps.Sub("presence","door","buttons","updateinterval")
143             QueryLatestEventsAndInjectThem(ps, zmqctx)
144             EventToXMPP(bot, psevents, xmpp_presence_events_chan)
145             // unsubscribe right away, since we don't known when reconnect will succeed and we don't want to block PubSub
146             ps.Unsub(psevents, "presence","door","buttons","updateinterval")
147             bot.StopBot()
148         } else {
149             Syslog_.Printf("Error starting XMPP Bot: %s", xmpperr.Error())
150         }
151         time.Sleep(10 * time.Second)
152     }
153 }
154
155 func ParseZMQr3Event(lines [][]byte, ps *pubsub.PubSub) {
156     evnt, pubsubcat, err := r3events.UnmarshalByteByte2Event(lines)
157     Debug_.Printf("ParseZMQr3Event: %s %s %s", evnt, pubsubcat, err)
158     if err != nil { return }
159     ps.Pub(evnt, pubsubcat)
160 }
161
162 func QueryLatestEventsAndInjectThem(ps *pubsub.PubSub, zmqctx *zmq.Context) {
163     answ := ZmqsAskQuestionsAndClose(zmqctx, brain_connect_addr_, [][][]byte{
164         [][]byte{[]byte("BackdoorAjarUpdate")},
165         [][]byte{[]byte("DoorCommandEvent")},
166         [][]byte{[]byte("DoorLockUpdate")},
167         [][]byte{[]byte("DoorAjarUpdate")},
168         [][]byte{[]byte("PresenceUpdate")},
169         [][]byte{[]byte("IlluminationSensorUpdate")},
170         [][]byte{[]byte("TempSensorUpdate")}})
171     for _, a := range(answ) {
172         ParseZMQr3Event(a, ps)
173     }
174 }
175
176 func main() {
177     if enable_syslog_ { LogEnableSyslog(); r3xmppbot.LogEnableSyslog() }
178     if enable_debug_ { LogEnableDebuglog(); r3xmppbot.LogEnableDebuglog() }
179     Syslog_.Print("started")
180     defer Syslog_.Print("exiting")
181     zmqctx, zmqsub := ZmqsInit(r3eventssub_port_)
182     defer zmqctx.Close()
183     if zmqsub != nil {defer zmqsub.Close()}
184     if zmqsub == nil {
185         panic("zmq sockets must not be nil !!")
186     }
187
188     ps := pubsub.New(10)
189     defer ps.Shutdown()
190     //~ brn := brain.New()
191     //~ defer brn.Shutdown()
192
193     go EventToWeb(ps)
194     // --- get update on most recent events ---
195     QueryLatestEventsAndInjectThem(ps, zmqctx)
196     go RunXMPPBot(ps, zmqctx)
197
198     // --- receive and distribute events ---
199     ticker := time.NewTicker(time.Duration(6) * time.Minute)
200     for {
201     select {
202         case e := <-zmqsub.In():
203             ParseZMQr3Event(e, ps) //, brn)
204         case <-ticker.C:
205             ps.Pub(r3events.TimeTick{time.Now().Unix()}, "updateinterval")
206         }
207     }
208 }