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