a5e52f69b9bbe522ef839a3f98b23158116ad25a
[saartuer.git] / statemachine.py
1 from libtuer import ThreadFunction, logger, fire_and_forget, fire_and_forget_cmd
2 from actor import Actor
3 import os, random, time, threading, datetime
4
5 # logger.{debug,info,warning,error,critical}
6
7 def play_sound (what):
8         try:
9                 soundfiles = os.listdir(SOUNDS_DIRECTORY+what)
10         except FileNotFoundError:
11                 logger.error("StateMachine: Unable to list sound files in %s" % (SOUNDS_DIRECTORY+what))
12                 return
13         soundfile = SOUNDS_DIRECTORY + what + '/' + random.choice(soundfiles)
14         hour = datetime.datetime.time(datetime.datetime.now()).hour
15         volume = 60 if hour >= 22 or hour <= 6 else 90
16         fire_and_forget_cmd ([SOUNDS_PLAYER, "-volume", str(volume), soundfile], "StateMachine: ")
17
18 # convert an absolute nervlist to a relative one
19 def nervlist_abs2rel(nervlist_abs):
20         nervlist_rel = []
21         last_t = 0
22         for (t, f) in nervlist_abs:
23                 assert t >= last_t
24                 nervlist_rel.append((t-last_t, f))
25                 last_t = t
26         return nervlist_rel
27
28 # StateAuf constants
29 HELLO_PROBABILITY = 0.2
30
31 # StateUnlocking constants
32 OPEN_REPEAT_TIMEOUT = 7
33 OPEN_REPEAT_NUMBER = 3
34
35 # StateLocking constants
36 CLOSE_REPEAT_TIMEOUT = 7
37 CLOSE_REPEAT_NUMBER = 3
38
39 # StateFallback constants
40 FALLBACK_LEAVE_DELAY_LOCK = 5 # seconds
41
42 # StateAboutToOpen constants
43 SWITCH_PRAISE_PROBABILITY = 0.5
44 ABOUTOPEN_NERVLIST = nervlist_abs2rel([(10, lambda:play_sound("flipswitch")),\
45         (20, lambda:play_sound("flipswitch")), (30, lambda:play_sound("flipswitch")), (30, lambda:logger.error("Space open but switch not flipped for 30 seconds")),\
46         (40, lambda:play_sound("flipswitch")), (50, lambda:play_sound("flipswitch")), (60, lambda:play_sound("mail_sent")),
47         (60, lambda:logger.critical("Space open but switch not flipped for 60 seconds")), (120, lambda:play_sound("mail_sent")),
48         (10*60, lambda:logger.critical("Space open but switch not flipped for 10 minutes")),
49         (60*60, lambda:logger.critical("Space open but switch not flipped for one hour"))])
50
51 # Timeout we wait after the switch was switched to "Closed", until we assume nobody will open the door and we just lock it
52 # ALso the time we wait after the door was opend, till we assume something went wrong and start nerving
53 LEAVE_TIMEOUT = 20
54
55 # play_sound constants
56 SOUNDS_DIRECTORY = "/opt/tuer/sounds/"
57 SOUNDS_PLAYER = "/usr/bin/mplayer"
58
59
60 class Nerver():
61         # A little utility class used to run the nervlists. A nervlist is a list of (n, f) tuples where f() is run after n seconds.
62         # If f returns something, that's also returned by nerv.
63         def __init__(self, nervlist):
64                 self.nervlist = list(nervlist)
65                 self.last_event_time = time.time()
66         
67         def nerv(self):
68                 if len(self.nervlist):
69                         (wait_time, f) = self.nervlist[0]
70                         now = time.time()
71                         time_gone = now-self.last_event_time
72                         # check if the first element is to be triggered
73                         if time_gone >= wait_time:
74                                 self.nervlist = self.nervlist[1:] # "pop" the first element, but do not modify original list
75                                 self.last_event_time = now
76                                 return f()
77
78
79 class StateMachine():
80         # commands you can send
81         CMD_PINS = 0
82         CMD_BUZZ = 1
83         CMD_UNLOCK = 2
84         CMD_WAKEUP = 3
85         CMD_LAST = 4
86         CMD_LOCK = 5
87         CMD_FALLBACK_ON = 6
88         CMD_FALLBACK_OFF = 7
89         CMD_STATUS = 8
90         
91         class State():
92                 def __init__(self, state_machine, nervlist = None):
93                         self.state_machine = state_machine
94                         self._nerver = None if nervlist is None else Nerver(nervlist)
95                 def handle_pins_event(self):
96                         pass # one needn't implement this
97                 def handle_buzz_event(self,arg): # this shouldn't be overwritten
98                         # Buzz twice to give users more time to run ;-)
99                         self.actor().act(Actor.CMD_BUZZ)
100                         self.actor().act(Actor.CMD_BUZZ)
101                         arg("200 okay: buzz executed")
102                 def handle_cmd_unlock_event(self,arg):
103                         if arg is not None:
104                                 arg("412 Precondition Failed: The current state (%s) cannot handle the UNLOCK command. Try again later." % self.__class__.__name__)
105                 def handle_wakeup_event(self):
106                         if self._nerver is not None:
107                                 return self._nerver.nerv()
108                 def handle_cmd_lock_event(self,arg):
109                         arg("412 Precondition Failed: If not in fallback mode, use the hardware switch to lock the space.")
110                 def handle_cmd_fallback_on_event(self,arg):
111                         arg("200 okay: Entering fallback mode and notifying admins.")
112                         logger.critical("Entering fallback mode. Somebody thinks, the hardware sensors are broken.")
113                         return StateMachine.StateFallback(self.state_machine)
114                 def handle_cmd_fallback_off_event(self,arg):
115                         arg("412 Precondition Failed: Not in fallback mode!")
116                 def handle_cmd_status_event(self,arg):
117                         # TODO use a proper JSON lib
118                         arg('200 okay: {state:\"%s\"}' % self.__class__.__name__)
119                 def on_leave(self):
120                         pass
121                 def pins(self):
122                         return self.state_machine.pins
123                 def old_pins(self):
124                         return self.state_machine.old_pins
125                 def actor(self):
126                         return self.state_machine.actor
127                 def api(self):
128                         return self.state_machine.api
129                 def handle_event(self,ev,arg): # don't override
130                         if ev == StateMachine.CMD_PINS:
131                                 return self.handle_pins_event()
132                         elif ev == StateMachine.CMD_BUZZ:
133                                 return self.handle_buzz_event(arg)
134                         elif ev == StateMachine.CMD_UNLOCK:
135                                 return self.handle_cmd_unlock_event(arg)
136                         elif ev == StateMachine.CMD_WAKEUP:
137                                 return self.handle_wakeup_event()
138                         elif ev == StateMachine.CMD_LOCK:
139                                 return self.handle_cmd_lock_event(arg)
140                         elif ev == StateMachine.CMD_FALLBACK_ON:
141                                 return self.handle_cmd_fallback_on_event(arg)
142                         elif ev == StateMachine.CMD_FALLBACK_OFF:
143                                 return self.handle_cmd_fallback_off_event(arg)
144                         elif ev == StateMachine.CMD_STATUS:
145                                 return self.handle_cmd_status_event(arg)
146                         else:
147                                 raise Exception("Unknown command number: %d" % ev)
148         
149         class AbstractNonStartState(State):
150                 def handle_pins_event(self):
151                         if self.pins().door_locked != (not self.pins().space_active):
152                                 self.actor().act(Actor.CMD_RED_ON)
153                         else:
154                                 self.actor().act(Actor.CMD_RED_OFF)
155                         return super().handle_pins_event()
156         
157         class AbstractLockedState(AbstractNonStartState):
158                 '''A state with invariant "The space is locked", switching to StateAboutToOpen when the space becomes unlocked'''
159                 def __init__(self, sm, nervlist = None):
160                         super().__init__(sm, nervlist)
161                         self.actor().act(Actor.CMD_GREEN_OFF)
162                 def handle_pins_event(self):
163                         if not self.pins().door_locked:
164                                 logger.info("Door unlocked, space is about to open")
165                                 return StateMachine.StateAboutToOpen(self.state_machine)
166                         return super().handle_pins_event()
167         
168         class AbstractUnlockedState(AbstractNonStartState):
169                 '''A state with invariant "The space is unlocked", switching to StateZu when the space becomes locked'''
170                 def __init__(self, sm, nervlist = None):
171                         super().__init__(sm, nervlist)
172                         self.actor().act(Actor.CMD_GREEN_ON)
173                 def handle_pins_event(self):
174                         if self.pins().door_locked:
175                                 logger.info("Door locked, closing space")
176                                 if self.pins().space_active:
177                                         logger.warning("StateMachine: door manually locked, but space switch is still on - going to StateZu")
178                                         play_sound("manual_lock")
179                                 return StateMachine.StateZu(self.state_machine)
180                         return super().handle_pins_event()
181         
182         class StateStart(State):
183                 def __init__(self, sm, nervlist = None, fallback=False):
184                         super().__init__(sm, nervlist)
185                         self.fallback = fallback
186                 def handle_pins_event(self):
187                         pins = self.pins()
188                         if not (pins.door_locked is None or pins.door_closed is None or pins.space_active is None or pins.bell_ringing is None):
189                                 if self.fallback:
190                                         logger.info("Going to StateFallback because running in fallback mode")
191                                         return StateMachine.StateFallback(self.state_machine)
192                                 if pins.door_locked:
193                                         logger.info("All sensors got a value, switching to a proper state: Space is closed")
194                                         return StateMachine.StateZu(self.state_machine)
195                                 else:
196                                         logger.info("All sensors got a value, switching to a proper state: Space is (about to) open")
197                                         return StateMachine.StateAboutToOpen(self.state_machine)
198                         return super().handle_pins_event()
199         
200         class StateFallback(State):
201                 def __init__(self, sm, nervlist = None):
202                         super().__init__(sm, nervlist)
203                         self._red_state = False
204                 def handle_pins_event(self):
205                         pins = self.pins()
206                         # set green LED according to space switch
207                         if pins.space_active:
208                                 self.actor().act(Actor.CMD_GREEN_ON)
209                         else:
210                                 self.actor().act(Actor.CMD_GREEN_OFF)
211                         # primitive leaving procedure if space switch turned off
212                         if not pins.space_active and self.old_pins().space_active:
213                                 def _close_after_time():
214                                         time.sleep(FALLBACK_LEAVE_DELAY_LOCK)
215                                         self.actor().act(Actor.CMD_LOCK)
216                                 fire_and_forget(_close_after_time)
217                         # not calling superclass because we want to stay in fallback mode
218                 def handle_wakeup_event(self):
219                         # blink red LED
220                         if self._red_state:
221                                 self.actor().act(Actor.CMD_RED_OFF)
222                                 self._red_state = False
223                         else:
224                                 self.actor().act(Actor.CMD_RED_ON)
225                                 self._red_state = True
226                 def handle_cmd_unlock_event(self,arg):
227                         if arg is not None:
228                                 arg("200 okay: Trying to unlock the door. The System is in fallback mode, success information is not available.")
229                         self.actor().act(Actor.CMD_UNLOCK)
230                 def handle_cmd_lock_event(self,arg):
231                         if arg is not None:
232                                 arg("200 okay: Trying to lock the door. The System is in fallback mode, success information is not available.")
233                         self.actor().act(Actor.CMD_LOCK)
234                 def handle_cmd_fallback_on_event(self,arg):
235                         arg("412 Precondition Failed: Fallback mode already active.")
236                 def handle_cmd_fallback_off_event(self,arg):
237                         arg("200 okay: Leaving fallback mode and notifying admins.")
238                         logger.critical("Leaving fallback mode. Somebody thinks, the sensors are working again.")
239                         return StateMachine.StateStart(self.state_machine)
240         
241         class StateZu(AbstractLockedState):
242                 def handle_cmd_unlock_event(self,callback):
243                         return StateMachine.StateUnlocking(self.state_machine, callback)
244                 def handle_pins_event(self):
245                         if not self.old_pins().space_active and self.pins().space_active: # first thing to check: edge detection
246                                 logger.info("Space toggled to active while it was closed - unlocking the door")
247                                 return StateMachine.StateUnlocking(self.state_machine)
248                         return super().handle_pins_event()
249         
250         class StateUnlocking(AbstractLockedState):
251                 def __init__(self,sm,callback=None):
252                         # construct a nervlist
253                         nervlist = [(OPEN_REPEAT_TIMEOUT, lambda: self.actor().act(Actor.CMD_UNLOCK)) for t in range(OPEN_REPEAT_NUMBER)]
254                         nervlist += [(OPEN_REPEAT_TIMEOUT, self.could_not_open)]
255                         super().__init__(sm,nervlist)
256                         self.callbacks = []
257                         self.actor().act(Actor.CMD_UNLOCK)
258                         # enqueue the callback
259                         self.handle_cmd_unlock_event(callback)
260                 def notify(self, s, lastMsg):
261                         for cb in self.callbacks:
262                                 cb(s, lastMsg)
263                 def on_leave(self):
264                         s = "200 okay: door unlocked" if not self.pins().door_locked else ("500 internal server error: Couldn't unlock door with %d tries à %f seconds" % (OPEN_REPEAT_NUMBER,OPEN_REPEAT_TIMEOUT))
265                         self.notify(s, lastMsg=True)
266                 def handle_cmd_unlock_event(self,callback):
267                         if callback is not None:
268                                 callback("202 processing: Trying to unlock the door", lastMsg=False)
269                                 self.callbacks.append(callback)
270                 def could_not_open(self):
271                         logger.critical("StateMachine: Couldn't open door after %d tries. Going back to StateZu." % OPEN_REPEAT_NUMBER)
272                         return StateMachine.StateZu(self.state_machine)
273         
274         class AbstractStateWhereUnlockingIsRedundant(AbstractUnlockedState):
275                 def handle_cmd_unlock_event(self, callback):
276                         callback("299 redundant: Space seems to be already open. Still processing your request tough.")
277                         logger.info("StateMachine: Received UNLOCK command in %s. This should not be necessary." % self.__class__.__name__)
278                         self.actor().act(Actor.CMD_UNLOCK)
279         
280         class StateAboutToOpen(AbstractStateWhereUnlockingIsRedundant):
281                 def __init__(self, sm):
282                         super().__init__(sm, ABOUTOPEN_NERVLIST)
283                 def handle_pins_event(self):
284                         pins = self.pins()
285                         if pins.space_active:
286                                 logger.info("Space activated, opening procedure completed")
287                                 if not self.old_pins().space_active and random.random() <= SWITCH_PRAISE_PROBABILITY:
288                                         play_sound("success")
289                                 return StateMachine.StateAuf(self.state_machine)
290                         return super().handle_pins_event()
291         
292         class StateAuf(AbstractStateWhereUnlockingIsRedundant):
293                 def __init__(self,sm):
294                         nervlist = [(24*60*60, lambda: logger.critical("Space is now open for 24h. Is everything all right?"))]
295                         super().__init__(sm, nervlist)
296                         self.last_buzzed = None
297                         self.api().set_state(True)
298                 def handle_pins_event(self):
299                         pins = self.pins()
300                         if pins.bell_ringing and not self.old_pins().bell_ringing: # first thing to check: edge detection
301                                 # someone just pressed the bell
302                                 logger.info("StateMachine: buzzing because of bell ringing in StateAuf")
303                                 self.actor().act(Actor.CMD_BUZZ)
304                         if not pins.space_active:
305                                 logger.info("StateMachine: space switch turned off - starting leaving procedure")
306                                 return StateMachine.StateAboutToLeave(self.state_machine)
307                         if not pins.door_closed and self.old_pins().door_closed and random.random() <= HELLO_PROBABILITY:
308                                 play_sound("hello")
309                         return super().handle_pins_event()
310                 def on_leave(self):
311                         self.api().set_state(False)
312         
313         class StateLocking(AbstractUnlockedState):
314                 def __init__(self,sm):
315                         # construct a nervlist
316                         nervlist = [(CLOSE_REPEAT_TIMEOUT, lambda: self.actor().act(Actor.CMD_LOCK)) for t in range(CLOSE_REPEAT_NUMBER)]
317                         nervlist += [(CLOSE_REPEAT_TIMEOUT, self.could_not_close)]
318                         super().__init__(sm, nervlist)
319                         if self.pins().door_closed: # this should always be true, but just to be sure...
320                                 self.actor().act(Actor.CMD_LOCK)
321                 def handle_pins_event(self):
322                         pins = self.pins()
323                         if not pins.door_closed:
324                                 # TODO play a sound? This shouldn't happen, door was opened while we are locking
325                                 logger.warning("StateMachine: door manually opened during locking")
326                                 return StateMachine.StateAboutToOpen(self.state_machine)
327                         # TODO do anything here if the switch is activated now?
328                         return super().handle_pins_event()
329                 def handle_cmd_unlock_event(self,callback):
330                         callback("409 conflict: The sphinx is currently trying to lock the door. Try again later.")
331                 def could_not_close(self):
332                         logger.critical("StateMachine: Couldn't close door after %d tries. Going back to StateAboutToOpen." % CLOSE_REPEAT_NUMBER)
333                         return StateMachine.StateAboutToOpen(self.state_machine)
334         
335         class StateAboutToLeave(AbstractUnlockedState):
336                 def __init__(self, sm):
337                         nervlist = [(LEAVE_TIMEOUT, lambda: StateMachine.StateLocking(self.state_machine))]
338                         super().__init__(sm, nervlist)
339                 def handle_pins_event(self):
340                         if not self.pins().door_closed:
341                                 return StateMachine.StateLeaving(self.state_machine)
342                         if self.pins().space_active:
343                                 logger.info("Space re-activated, cancelling leaving procedure")
344                                 return StateMachine.StateAuf(self.state_machine)
345                         return super().handle_pins_event()
346         
347         class StateLeaving(AbstractUnlockedState):
348                 def __init__(self, sm):
349                         nervlist = [(LEAVE_TIMEOUT, lambda: StateMachine.StateAboutToOpen(self.state_machine))]
350                         super().__init__(sm, nervlist)
351                 def handle_pins_event(self):
352                         if self.pins().door_closed:
353                                 logger.info("The space was left, locking the door")
354                                 return StateMachine.StateLocking(self.state_machine)
355                         if self.pins().space_active:
356                                 logger.info("Space re-activated, cancelling leaving procedure")
357                                 return StateMachine.StateAuf(self.state_machine)
358                         return super().handle_pins_event()
359         
360         def __init__(self, actor, waker, api, fallback = False):
361                 self.actor = actor
362                 self.api = api
363                 self.callback = ThreadFunction(self._callback, name="StateMachine")
364                 self.current_state = StateMachine.StateStart(self, fallback=fallback)
365                 self.pins = None
366                 self.old_pins = None
367                 waker.register(lambda: self.callback(StateMachine.CMD_WAKEUP), 1.0) # wake up every second
368                 # initially, the space is closed
369                 api.set_state(False)
370         
371         def stop (self):
372                 self.callback.stop()
373         
374         # actually call this.callback (is set in the constructor to make this thread safe)
375         def _callback(self, cmd, arg=None):
376                 # update pins
377                 if cmd == StateMachine.CMD_PINS:
378                         self.pins = arg
379                 # handle stuff
380                 newstate = self.current_state.handle_event(cmd,arg) # returns None or an instance of the new state
381                 self.old_pins = self.pins
382                 while newstate is not None:
383                         assert isinstance(newstate, StateMachine.State), "I should get a state"
384                         self.current_state.on_leave()
385                         logger.info("StateMachine: Doing state transition %s -> %s" % (self.current_state.__class__.__name__, newstate.__class__.__name__))
386                         self.current_state = newstate
387                         newstate = self.current_state.handle_event(StateMachine.CMD_PINS, self.pins)