dd9dc542bbe51524c24978bc5263bade5b1650de
[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 95
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                         self.actor().act(Actor.CMD_BUZZ)
99                         arg("200 okay: buzz executed")
100                 def handle_cmd_unlock_event(self,arg):
101                         if arg is not None:
102                                 arg("412 Precondition Failed: The current state (%s) cannot handle the UNLOCK command. Try again later." % self.__class__.__name__)
103                 def handle_wakeup_event(self):
104                         if self._nerver is not None:
105                                 return self._nerver.nerv()
106                 def handle_cmd_lock_event(self,arg):
107                         arg("412 Precondition Failed: If not in fallback mode, use the hardware switch to lock the space.")
108                 def handle_cmd_fallback_on_event(self,arg):
109                         arg("200 okay: Entering fallback mode and notifying admins.")
110                         logger.critical("Entering fallback mode. Somebody thinks, the hardware sensors are broken.")
111                         return StateMachine.StateFallback(self.state_machine)
112                 def handle_cmd_fallback_off_event(self,arg):
113                         arg("412 Precondition Failed: Not in fallback mode!")
114                 def handle_cmd_status_event(self,arg):
115                         # TODO use a proper JSON lib
116                         arg('200 okay: {state:\"%s\"}' % self.__class__.__name__)
117                 def on_leave(self):
118                         pass
119                 def pins(self):
120                         return self.state_machine.pins
121                 def old_pins(self):
122                         return self.state_machine.old_pins
123                 def actor(self):
124                         return self.state_machine.actor
125                 def api(self):
126                         return self.state_machine.api
127                 def handle_event(self,ev,arg): # don't override
128                         if ev == StateMachine.CMD_PINS:
129                                 return self.handle_pins_event()
130                         elif ev == StateMachine.CMD_BUZZ:
131                                 return self.handle_buzz_event(arg)
132                         elif ev == StateMachine.CMD_UNLOCK:
133                                 return self.handle_cmd_unlock_event(arg)
134                         elif ev == StateMachine.CMD_WAKEUP:
135                                 return self.handle_wakeup_event()
136                         elif ev == StateMachine.CMD_LOCK:
137                                 return self.handle_cmd_lock_event(arg)
138                         elif ev == StateMachine.CMD_FALLBACK_ON:
139                                 return self.handle_cmd_fallback_on_event(arg)
140                         elif ev == StateMachine.CMD_FALLBACK_OFF:
141                                 return self.handle_cmd_fallback_off_event(arg)
142                         elif ev == StateMachine.CMD_STATUS:
143                                 return self.handle_cmd_status_event(arg)
144                         else:
145                                 raise Exception("Unknown command number: %d" % ev)
146         
147         class AbstractNonStartState(State):
148                 def handle_pins_event(self):
149                         if self.pins().door_locked != (not self.pins().space_active):
150                                 self.actor().act(Actor.CMD_RED_ON)
151                         else:
152                                 self.actor().act(Actor.CMD_RED_OFF)
153                         return super().handle_pins_event()
154         
155         class AbstractLockedState(AbstractNonStartState):
156                 '''A state with invariant "The space is locked", switching to StateAboutToOpen when the space becomes unlocked'''
157                 def __init__(self, sm, nervlist = None):
158                         super().__init__(sm, nervlist)
159                         self.actor().act(Actor.CMD_GREEN_OFF)
160                 def handle_pins_event(self):
161                         if not self.pins().door_locked:
162                                 logger.info("Door unlocked, space is about to open")
163                                 return StateMachine.StateAboutToOpen(self.state_machine)
164                         return super().handle_pins_event()
165         
166         class AbstractUnlockedState(AbstractNonStartState):
167                 '''A state with invariant "The space is unlocked", switching to StateZu when the space becomes locked'''
168                 def __init__(self, sm, nervlist = None):
169                         super().__init__(sm, nervlist)
170                         self.actor().act(Actor.CMD_GREEN_ON)
171                 def handle_pins_event(self):
172                         if self.pins().door_locked:
173                                 logger.info("Door locked, closing space")
174                                 if self.pins().space_active:
175                                         logger.warning("StateMachine: door manually locked, but space switch is still on - going to StateZu")
176                                         play_sound("manual_lock")
177                                 return StateMachine.StateZu(self.state_machine)
178                         return super().handle_pins_event()
179         
180         class StateStart(State):
181                 def __init__(self, sm, nervlist = None, fallback=False):
182                         super().__init__(sm, nervlist)
183                         self.fallback = fallback
184                 def handle_pins_event(self):
185                         pins = self.pins()
186                         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):
187                                 if self.fallback:
188                                         logger.info("Going to StateFallback because running in fallback mode")
189                                         return StateMachine.StateFallback(self.state_machine)
190                                 if pins.door_locked:
191                                         logger.info("All sensors got a value, switching to a proper state: Space is closed")
192                                         return StateMachine.StateZu(self.state_machine)
193                                 else:
194                                         logger.info("All sensors got a value, switching to a proper state: Space is (about to) open")
195                                         return StateMachine.StateAboutToOpen(self.state_machine)
196                         return super().handle_pins_event()
197         
198         class StateFallback(State):
199                 def __init__(self, sm, nervlist = None):
200                         super().__init__(sm, nervlist)
201                         self._red_state = False
202                 def handle_pins_event(self):
203                         pins = self.pins()
204                         # set green LED according to space switch
205                         if pins.space_active:
206                                 self.actor().act(Actor.CMD_GREEN_ON)
207                         else:
208                                 self.actor().act(Actor.CMD_GREEN_OFF)
209                         # primitive leaving procedure if space switch turned off
210                         if not pins.space_active and self.old_pins().space_active:
211                                 def _close_after_time():
212                                         time.sleep(FALLBACK_LEAVE_DELAY_LOCK)
213                                         self.actor().act(Actor.CMD_LOCK)
214                                 fire_and_forget(_close_after_time)
215                         # not calling superclass because we want to stay in fallback mode
216                 def handle_wakeup_event(self):
217                         # blink red LED
218                         if self._red_state:
219                                 self.actor().act(Actor.CMD_RED_OFF)
220                                 self._red_state = False
221                         else:
222                                 self.actor().act(Actor.CMD_RED_ON)
223                                 self._red_state = True
224                 def handle_cmd_unlock_event(self,arg):
225                         if arg is not None:
226                                 arg("200 okay: Trying to unlock the door. The System is in fallback mode, success information is not available.")
227                         self.actor().act(Actor.CMD_UNLOCK)
228                 def handle_cmd_lock_event(self,arg):
229                         if arg is not None:
230                                 arg("200 okay: Trying to lock the door. The System is in fallback mode, success information is not available.")
231                         self.actor().act(Actor.CMD_LOCK)
232                 def handle_cmd_fallback_on_event(self,arg):
233                         arg("412 Precondition Failed: Fallback mode already active.")
234                 def handle_cmd_fallback_off_event(self,arg):
235                         arg("200 okay: Leaving fallback mode and notifying admins.")
236                         logger.critical("Leaving fallback mode. Somebody thinks, the sensors are working again.")
237                         return StateMachine.StateStart(self.state_machine)
238         
239         class StateZu(AbstractLockedState):
240                 def handle_cmd_unlock_event(self,callback):
241                         return StateMachine.StateUnlocking(self.state_machine, callback)
242                 def handle_pins_event(self):
243                         if not self.old_pins().space_active and self.pins().space_active: # first thing to check: edge detection
244                                 logger.info("Space toggled to active while it was closed - unlocking the door")
245                                 return StateMachine.StateUnlocking(self.state_machine)
246                         return super().handle_pins_event()
247         
248         class StateUnlocking(AbstractLockedState):
249                 def __init__(self,sm,callback=None):
250                         # construct a nervlist
251                         nervlist = [(OPEN_REPEAT_TIMEOUT, lambda: self.actor().act(Actor.CMD_UNLOCK)) for t in range(OPEN_REPEAT_NUMBER)]
252                         nervlist += [(OPEN_REPEAT_TIMEOUT, self.could_not_open)]
253                         super().__init__(sm,nervlist)
254                         self.callbacks = []
255                         self.actor().act(Actor.CMD_UNLOCK)
256                         # enqueue the callback
257                         self.handle_cmd_unlock_event(callback)
258                 def notify(self, s, lastMsg):
259                         for cb in self.callbacks:
260                                 cb(s, lastMsg)
261                 def on_leave(self):
262                         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))
263                         self.notify(s, lastMsg=True)
264                 def handle_cmd_unlock_event(self,callback):
265                         if callback is not None:
266                                 callback("202 processing: Trying to unlock the door", lastMsg=False)
267                                 self.callbacks.append(callback)
268                 def could_not_open(self):
269                         logger.critical("StateMachine: Couldn't open door after %d tries. Going back to StateZu." % OPEN_REPEAT_NUMBER)
270                         return StateMachine.StateZu(self.state_machine)
271         
272         class AbstractStateWhereUnlockingIsRedundant(AbstractUnlockedState):
273                 def handle_cmd_unlock_event(self, callback):
274                         callback("299 redundant: Space seems to be already open. Still processing your request tough.")
275                         logger.info("StateMachine: Received UNLOCK command in %s. This should not be necessary." % self.__class__.__name__)
276                         self.actor().act(Actor.CMD_UNLOCK)
277         
278         class StateAboutToOpen(AbstractStateWhereUnlockingIsRedundant):
279                 def __init__(self, sm):
280                         super().__init__(sm, ABOUTOPEN_NERVLIST)
281                 def handle_pins_event(self):
282                         pins = self.pins()
283                         if pins.space_active:
284                                 logger.info("Space activated, opening procedure completed")
285                                 if not self.old_pins().space_active and random.random() <= SWITCH_PRAISE_PROBABILITY:
286                                         play_sound("success")
287                                 return StateMachine.StateAuf(self.state_machine)
288                         return super().handle_pins_event()
289         
290         class StateAuf(AbstractStateWhereUnlockingIsRedundant):
291                 def __init__(self,sm):
292                         nervlist = [(24*60*60, lambda: logger.critical("Space is now open for 24h. Is everything all right?"))]
293                         super().__init__(sm, nervlist)
294                         self.last_buzzed = None
295                         self.api().set_state(True)
296                 def handle_pins_event(self):
297                         pins = self.pins()
298                         if pins.bell_ringing and not self.old_pins().bell_ringing: # first thing to check: edge detection
299                                 # someone just pressed the bell
300                                 logger.info("StateMachine: buzzing because of bell ringing in StateAuf")
301                                 self.actor().act(Actor.CMD_BUZZ)
302                         if not pins.space_active:
303                                 logger.info("StateMachine: space switch turned off - starting leaving procedure")
304                                 return StateMachine.StateAboutToLeave(self.state_machine)
305                         if not pins.door_closed and self.old_pins().door_closed and random.random() <= HELLO_PROBABILITY:
306                                 play_sound("hello")
307                         return super().handle_pins_event()
308                 def on_leave(self):
309                         self.api().set_state(False)
310         
311         class StateLocking(AbstractUnlockedState):
312                 def __init__(self,sm):
313                         # construct a nervlist
314                         nervlist = [(CLOSE_REPEAT_TIMEOUT, lambda: self.actor().act(Actor.CMD_LOCK)) for t in range(CLOSE_REPEAT_NUMBER)]
315                         nervlist += [(CLOSE_REPEAT_TIMEOUT, self.could_not_close)]
316                         super().__init__(sm, nervlist)
317                         if self.pins().door_closed: # this should always be true, but just to be sure...
318                                 self.actor().act(Actor.CMD_LOCK)
319                 def handle_pins_event(self):
320                         pins = self.pins()
321                         if not pins.door_closed:
322                                 # TODO play a sound? This shouldn't happen, door was opened while we are locking
323                                 logger.warning("StateMachine: door manually opened during locking")
324                                 return StateMachine.StateAboutToOpen(self.state_machine)
325                         # TODO do anything here if the switch is activated now?
326                         return super().handle_pins_event()
327                 def handle_cmd_unlock_event(self,callback):
328                         callback("409 conflict: The sphinx is currently trying to lock the door. Try again later.")
329                 def could_not_close(self):
330                         logger.critical("StateMachine: Couldn't close door after %d tries. Going back to StateAboutToOpen." % CLOSE_REPEAT_NUMBER)
331                         return StateMachine.StateAboutToOpen(self.state_machine)
332         
333         class StateAboutToLeave(AbstractUnlockedState):
334                 def __init__(self, sm):
335                         nervlist = [(LEAVE_TIMEOUT, lambda: StateMachine.StateLocking(self.state_machine))]
336                         super().__init__(sm, nervlist)
337                 def handle_pins_event(self):
338                         if not self.pins().door_closed:
339                                 return StateMachine.StateLeaving(self.state_machine)
340                         if self.pins().space_active:
341                                 logger.info("Space re-activated, cancelling leaving procedure")
342                                 return StateMachine.StateAuf(self.state_machine)
343                         return super().handle_pins_event()
344         
345         class StateLeaving(AbstractUnlockedState):
346                 def __init__(self, sm):
347                         nervlist = [(LEAVE_TIMEOUT, lambda: StateMachine.StateAboutToOpen(self.state_machine))]
348                         super().__init__(sm, nervlist)
349                 def handle_pins_event(self):
350                         if self.pins().door_closed:
351                                 logger.info("The space was left, locking the door")
352                                 return StateMachine.StateLocking(self.state_machine)
353                         if self.pins().space_active:
354                                 logger.info("Space re-activated, cancelling leaving procedure")
355                                 return StateMachine.StateAuf(self.state_machine)
356                         return super().handle_pins_event()
357         
358         def __init__(self, actor, waker, api, fallback = False):
359                 self.actor = actor
360                 self.api = api
361                 self.callback = ThreadFunction(self._callback, name="StateMachine")
362                 self.current_state = StateMachine.StateStart(self, fallback=fallback)
363                 self.pins = None
364                 self.old_pins = None
365                 waker.register(lambda: self.callback(StateMachine.CMD_WAKEUP), 1.0) # wake up every second
366                 # initially, the space is closed
367                 api.set_state(False)
368         
369         def stop (self):
370                 self.callback.stop()
371         
372         # actually call this.callback (is set in the constructor to make this thread safe)
373         def _callback(self, cmd, arg=None):
374                 # update pins
375                 if cmd == StateMachine.CMD_PINS:
376                         self.pins = arg
377                 # handle stuff
378                 newstate = self.current_state.handle_event(cmd,arg) # returns None or an instance of the new state
379                 self.old_pins = self.pins
380                 while newstate is not None:
381                         assert isinstance(newstate, StateMachine.State), "I should get a state"
382                         self.current_state.on_leave()
383                         logger.debug("StateMachine: Doing state transition %s -> %s" % (self.current_state.__class__.__name__, newstate.__class__.__name__))
384                         self.current_state = newstate
385                         newstate = self.current_state.handle_event(StateMachine.CMD_PINS, self.pins)