temp sensor location names
[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 )
14
15 type SpaceState struct {
16     present           bool
17     buttonpress_until int64
18     door_locked bool
19     door_shut bool
20 }
21
22 var (
23     xmpp_presence_events_chan_     chan interface{}
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 composeMessage(present, locked, shut bool, who string, ts int64) string {
54     return fmt.Sprintf("%s (Door is %s and %s and was last used%s at %s)",
55         IfThenElseStr(present,  "Somebody is present!" , "Everybody left."),
56         IfThenElseStr(locked, "locked","unlocked"),
57         IfThenElseStr(shut, "shut","ajar"),
58         IfThenElseStr(len(who) == 0,"", " by " + who),
59         time.Unix(ts,0).String())
60 }
61
62 func EventToXMPP(ps *pubsub.PubSub, xmpp_presence_events_chan_ chan <- interface{}) {
63     events := ps.Sub("presence","door","buttons","updateinterval")
64
65     defer func() {
66         if x := recover(); x != nil {
67             Syslog_.Printf("handleIncomingXMPPStanzas: run time panic: %v", x)
68             ps.Unsub(events, "presence","door","buttons","updateinterval")
69             close(xmpp_presence_events_chan_)
70         }
71     }()
72
73     var present, locked, shut bool = false, true, true
74     var last_buttonpress int64 = 0
75     var who string
76     button_msg := "Dooom ! The button has been pressed ! Propably someone is bored and in need of company ! ;-)"
77     present_status := r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowOnline,"Somebody is present"}
78     notpresent_status := r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowNotAvailabe,"Nobody is here"}
79     button_status := r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowFreeForChat, "The button has been pressed :-)"}
80
81     xmpp_presence_events_chan_ <- r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowNotAvailabe, "Nobody is here"}
82
83     for eventinterface := range(events) {
84         Debug_.Printf("event2xmpp: %T %+v", eventinterface, eventinterface)
85         switch event := eventinterface.(type) {
86             case r3events.PresenceUpdate:
87                 present = event.Present
88                 xmpp_presence_events_chan_ <- r3xmppbot.XMPPMsgEvent{Msg: composeMessage(present, locked, shut, who, event.Ts), DistributeLevel: r3xmppbot.R3OnlineOnlyInfo, RememberAsStatus: true}
89                 if present {
90                     xmpp_presence_events_chan_ <- present_status
91                 } else {
92                     xmpp_presence_events_chan_ <- notpresent_status
93                 }
94             case r3events.DoorCommandEvent:
95                 if len(event.Who) > 0 && len(event.Using) > 0 {
96                     who = fmt.Sprintf("%s (%s)",event.Who, event.Using)
97                 } else {
98                     who = event.Who
99                 }
100                 xmpp_presence_events_chan_ <- fmt.Sprintln("DoorCommand:",event.Command, "using", event.Using, "by", event.Who, time.Unix(event.Ts,0))
101             case r3events.DoorLockUpdate:
102                 locked = event.Locked
103                 xmpp_presence_events_chan_ <- r3xmppbot.XMPPMsgEvent{Msg: composeMessage(present, locked, shut, who, event.Ts), DistributeLevel: r3xmppbot.R3DebugInfo, RememberAsStatus: true}
104            case r3events.DoorAjarUpdate:
105                 shut = event.Shut
106                 xmpp_presence_events_chan_ <- r3xmppbot.XMPPMsgEvent{Msg: composeMessage(present, locked, shut, who, event.Ts), DistributeLevel: r3xmppbot.R3DebugInfo, RememberAsStatus: true}
107             case r3events.BoreDoomButtonPressEvent:
108                 xmpp_presence_events_chan_ <- r3xmppbot.XMPPMsgEvent{Msg: button_msg, DistributeLevel: r3xmppbot.R3OnlineOnlyInfo}
109                 xmpp_presence_events_chan_ <- button_status
110                 last_buttonpress = event.Ts
111             case r3events.TimeTick:
112                 if present && last_buttonpress > 0 && time.Now().Unix() - last_buttonpress > button_press_timeout_ {
113                     xmpp_presence_events_chan_ <- present_status
114                     last_buttonpress = 0
115                 }
116         }
117         }
118 }
119
120 func ParseZMQr3Event(lines [][]byte, ps *pubsub.PubSub) {
121     evnt, pubsubcat, err := r3events.UnmarshalByteByte2Event(lines)
122     Debug_.Printf("ParseZMQr3Event: %s %s %s", evnt, pubsubcat, err)
123     if err != nil { return }
124     ps.Pub(evnt, pubsubcat)
125 }
126
127 func main() {
128     if enable_syslog_ { LogEnableSyslog(); r3xmppbot.LogEnableSyslog() }
129     if enable_debug_ { LogEnableDebuglog(); r3xmppbot.LogEnableDebuglog() }
130     Syslog_.Print("started")
131     defer Syslog_.Print("exiting")
132     zmqctx, zmqsub := ZmqsInit(r3eventssub_port_)
133     defer zmqctx.Close()
134     if zmqsub != nil {defer zmqsub.Close()}
135     if zmqsub == nil {
136         panic("zmq sockets must not be nil !!")
137     }
138
139     var xmpperr error
140     var bot *r3xmppbot.XmppBot
141     bot, xmpp_presence_events_chan_, xmpperr = r3xmppbot.NewStartedBot(xmpp_login_.jid, xmpp_login_.pass, xmpp_bot_authstring_, xmpp_state_save_dir_, true)
142
143     ps := pubsub.New(1)
144     defer ps.Shutdown()
145     //~ brn := brain.New()
146     //~ defer brn.Shutdown()
147
148     go EventToWeb(ps)
149     if xmpperr == nil {
150         defer bot.StopBot()
151         go EventToXMPP(ps, xmpp_presence_events_chan_)
152     } else {
153         fmt.Println(xmpperr)
154         fmt.Println("XMPP Bot disabled")
155         Syslog_.Printf("XMPP Bot disabled due to error: %s", xmpperr.Error())
156     }
157
158     // --- get update on most recent events ---
159     answ := ZmqsAskQuestionsAndClose(zmqctx, brain_connect_addr_, [][][]byte{[][]byte{[]byte("DoorLockUpdate")}, [][]byte{[]byte("DoorAjarUpdate")}, [][]byte{[]byte("DoorCommandEvent")}, [][]byte{[]byte("PresenceUpdate")}, [][]byte{[]byte("IlluminationSensorUpdate")}, [][]byte{[]byte("TempSensorUpdate")}})
160     for _, a := range(answ) {
161         ParseZMQr3Event(a, ps)
162     }
163
164     // --- receive and distribute events ---
165     ticker := time.NewTicker(time.Duration(7) * time.Minute)
166     for {
167     select {
168         case e := <-zmqsub.In():
169             ParseZMQr3Event(e, ps) //, brn)
170         case <-ticker.C:
171             ps.Pub(r3events.TimeTick{time.Now().Unix()}, "updateinterval")
172         }
173     }
174 }