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