remove now-unused variable
[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_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 handle_event(self,ev,arg): # don't override
94                         if ev == StateMachine.CMD_PINS:
95                                 return self.handle_pins_event()
96                         elif ev == StateMachine.CMD_BUZZ:
97                                 return self.handle_buzz_event(arg)
98                         elif ev == StateMachine.CMD_UNLOCK:
99                                 return self.handle_cmd_unlock_event(arg)
100                         elif ev == StateMachine.CMD_WAKEUP:
101                                 return self.handle_wakeup_event()
102                         else:
103                                 raise Exception("Unknown command number: %d" % ev)
104         
105         class AbstractNonStartState(State):
106                 def handle_pins_event(self):
107                         if self.pins().door_locked != (not self.pins().space_active):
108                                 self.actor().act(Actor.CMD_RED_ON)
109                         else:
110                                 self.actor().act(Actor.CMD_RED_OFF)
111                         return super().handle_pins_event()
112         
113         class AbstractLockedState(AbstractNonStartState):
114                 '''A state with invariant "The space is locked", switching to StateAboutToOpen when the space becomes unlocked'''
115                 def __init__(self, sm, nervlist = None):
116                         super().__init__(sm, nervlist)
117                         self.actor().act(Actor.CMD_GREEN_OFF)
118                 def handle_pins_event(self):
119                         if not self.pins().door_locked:
120                                 logger.info("Door unlocked, space is about to open")
121                                 return StateMachine.StateAboutToOpen(self.state_machine)
122                         return super().handle_pins_event()
123         
124         class AbstractUnlockedState(AbstractNonStartState):
125                 '''A state with invariant "The space is unlocked", switching to StateZu when the space becomes locked'''
126                 def __init__(self, sm, nervlist = None):
127                         super().__init__(sm, nervlist)
128                         self.actor().act(Actor.CMD_GREEN_ON)
129                 def handle_pins_event(self):
130                         if self.pins().door_locked:
131                                 logger.info("Door locked, closing space")
132                                 if self.pins().space_active:
133                                         logger.warning("StateMachine: door manually locked, but space switch is still on - going to StateZu")
134                                         play_sound("manual_lock")
135                                 return StateMachine.StateZu(self.state_machine)
136                         return super().handle_pins_event()
137         
138         class StateStart(State):
139                 def __init__(self, sm, nervlist = None, fallback=False):
140                         super().__init__(sm, nervlist)
141                         self.fallback = fallback
142                 def handle_pins_event(self):
143                         pins = self.pins()
144                         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):
145                                 if self.fallback:
146                                         logger.info("Going to StateFallback because running in fallback mode")
147                                         return StateMachine.StateFallback(self.state_machine)
148                                 if pins.door_locked:
149                                         logger.info("All sensors got a value, switching to a proper state: Space is closed")
150                                         return StateMachine.StateZu(self.state_machine)
151                                 else:
152                                         logger.info("All sensors got a value, switching to a proper state: Space is (about to) open")
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__(sm, nervlist)
159                         self._red_state = False
160                 def handle_pins_event(self):
161                         pins = self.pins()
162                         # buzz if open and bell rang
163                         if pins.space_active and pins.bell_ringing and not self.old_pins().bell_ringing:
164                                 logger.info("StateFallback: Space switch on and door bell rung => buzzing")
165                                 self.actor().act(Actor.CMD_BUZZ)
166                         # set green LED according to space switch
167                         if pins.space_active:
168                                 self.actor().act(Actor.CMD_GREEN_ON)
169                         else:
170                                 self.actor().act(Actor.CMD_GREEN_OFF)
171                         # primitive leaving procedure if space switch turned off
172                         if not pins.space_active and self.old_pins().space_active:
173                                 def _close_after_time():
174                                         time.sleep(FALLBACK_LEAVE_DELAY_LOCK)
175                                         self.actor().act(Actor.CMD_LOCK)
176                                 fire_and_forget(_close_after_time)
177                         # not calling superclass because we want to stay in fallback mode
178                 def handle_wakeup_event(self):
179                         # blink red LED
180                         if self._red_state:
181                                 self.actor().act(Actor.CMD_RED_OFF)
182                                 self._red_state = False
183                         else:
184                                 self.actor().act(Actor.CMD_RED_ON)
185                                 self._red_state = True
186                 def handle_cmd_unlock_event(self,arg):
187                         if arg is not None:
188                                 arg("298 Fallback Okay: Trying to unlock the door. The System is in fallback mode, success information is not available.")
189                         self.actor().act(Actor.CMD_UNLOCK)
190         
191         class StateZu(AbstractLockedState):
192                 def handle_cmd_unlock_event(self,callback):
193                         return StateMachine.StateUnlocking(self.state_machine, callback)
194                 def handle_pins_event(self):
195                         if not self.old_pins().space_active and self.pins().space_active: # first thing to check: edge detection
196                                 logger.info("Space toggled to active while it was closed - unlocking the door")
197                                 return StateMachine.StateUnlocking(self.state_machine)
198                         return super().handle_pins_event()
199         
200         class StateUnlocking(AbstractLockedState):
201                 def __init__(self,sm,callback=None):
202                         # construct a nervlist
203                         nervlist = [(OPEN_REPEAT_TIMEOUT, lambda: self.actor().act(Actor.CMD_UNLOCK)) for t in range(OPEN_REPEAT_NUMBER)]
204                         nervlist += [(OPEN_REPEAT_TIMEOUT, self.could_not_open)]
205                         super().__init__(sm,nervlist)
206                         self.callbacks=[callback]
207                         # TODO: can we send "202 processing: Trying to unlock the door" here? Are the callbacks multi-use?
208                         self.actor().act(Actor.CMD_UNLOCK)
209                 def notify(self, did_it_work):
210                         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))
211                         for cb in self.callbacks:
212                                 if cb is not None:
213                                         cb(s)
214                 def on_leave(self):
215                         self.notify(not self.pins().door_locked)
216                 def handle_cmd_unlock_event(self,callback):
217                         # TODO: 202 notification also here if possible
218                         self.callbacks.append(callback)
219                 def could_not_open(self):
220                         logger.critical("StateMachine: Couldn't open door after %d tries. Going back to StateZu." % OPEN_REPEAT_NUMBER)
221                         return StateMachine.StateZu(self.state_machine)
222         
223         class AbstractStateWhereUnlockingIsRedundant(AbstractUnlockedState):
224                 def handle_cmd_unlock_event(self, callback):
225                         callback("299 redundant: Space seems to be already open. Still processing your request tough.")
226                         logger.info("StateMachine: Received UNLOCK command in %s. This should not be necessary." % self.__class__.__name__)
227                         self.actor().act(Actor.CMD_UNLOCK)
228         
229         class StateAboutToOpen(AbstractStateWhereUnlockingIsRedundant):
230                 def __init__(self, sm):
231                         super().__init__(sm, ABOUTOPEN_NERVLIST)
232                 def handle_pins_event(self):
233                         pins = self.pins()
234                         if pins.space_active:
235                                 logger.info("Space activated, opening procedure completed")
236                                 return StateMachine.StateAuf(self.state_machine)
237                         return super().handle_pins_event()
238         
239         class StateAuf(AbstractStateWhereUnlockingIsRedundant):
240                 def __init__(self,sm):
241                         nervlist = [(24*60*60, lambda: logger.critical("Space is now open for 24h. Is everything all right?"))]
242                         super().__init__(sm, nervlist)
243                         self.last_buzzed = None
244                 def handle_pins_event(self):
245                         pins = self.pins()
246                         if pins.bell_ringing and not self.old_pins().bell_ringing: # first thing to check: edge detection
247                                 # someone just pressed the bell
248                                 logger.info("StateMachine: buzzing because of bell ringing in StateAuf")
249                                 self.actor().act(Actor.CMD_BUZZ)
250                         if not pins.space_active:
251                                 logger.info("StateMachine: space switch turned off - starting leaving procedure")
252                                 return StateMachine.StateAboutToLeave(self.state_machine)
253                         return super().handle_pins_event()
254         
255         class StateLocking(AbstractUnlockedState):
256                 def __init__(self,sm):
257                         # construct a nervlist
258                         nervlist = [(CLOSE_REPEAT_TIMEOUT, lambda: self.actor().act(Actor.CMD_LOCK)) for t in range(CLOSE_REPEAT_NUMBER)]
259                         nervlist += [(CLOSE_REPEAT_TIMEOUT, self.could_not_close)]
260                         super().__init__(sm, nervlist)
261                         if self.pins().door_closed: # this should always be true, but just to be sure...
262                                 self.actor().act(Actor.CMD_LOCK)
263                 def handle_pins_event(self):
264                         pins = self.pins()
265                         if not pins.door_closed:
266                                 # TODO play a sound? This shouldn't happen, door was opened while we are locking
267                                 logger.warning("StateMachine: door manually opened during locking")
268                                 return StateMachine.StateAboutToOpen(self.state_machine)
269                         # TODO do anything here if the switch is activated now?
270                         return super().handle_pins_event()
271                 def handle_cmd_unlock_event(self,callback):
272                         callback("409 conflict: The sphinx is currently trying to lock the door. Try again later.")
273                 def could_not_close(self):
274                         logger.critical("StateMachine: Couldn't close door after %d tries. Going back to StateAboutToOpen." % CLOSE_REPEAT_NUMBER)
275                         return StateMachine.StateAboutToOpen(self.state_machine)
276         
277         class StateAboutToLeave(AbstractUnlockedState):
278                 def __init__(self, sm):
279                         nervlist = [(LEAVE_TIMEOUT, lambda: StateMachine.StateLocking(self.state_machine))]
280                         super().__init__(sm, nervlist)
281                 def handle_pins_event(self):
282                         if not self.pins().door_closed:
283                                 return StateMachine.StateLeaving(self.state_machine)
284                         if self.pins().space_active:
285                                 logger.info("Space re-activated, cancelling leaving procedure")
286                                 return StateMachine.StateAuf(self.state_machine)
287                         return super().handle_pins_event()
288         
289         class StateLeaving(AbstractUnlockedState):
290                 def __init__(self, sm):
291                         nervlist = [(LEAVE_TIMEOUT, lambda: StateMachine.StateAboutToOpen(self.state_machine))]
292                         super().__init__(sm, nervlist)
293                 def handle_pins_event(self):
294                         if self.pins().door_closed:
295                                 logger.info("The space was left, locking the door")
296                                 return StateMachine.StateLocking(self.state_machine)
297                         if self.pins().space_active:
298                                 logger.info("Space re-activated, cancelling leaving procedure")
299                                 return StateMachine.StateAuf(self.state_machine)
300                         return super().handle_pins_event()
301         
302         def __init__(self, actor, waker, fallback = False):
303                 self.actor = actor
304                 self.callback = ThreadFunction(self._callback, name="StateMachine")
305                 self.current_state = StateMachine.StateStart(self, fallback=fallback)
306                 self.pins = None
307                 self.old_pins = None
308                 waker.register(lambda: self.callback(StateMachine.CMD_WAKEUP), 1.0) # wake up every second
309         
310         def stop (self):
311                 self.callback.stop()
312         
313         def _callback(self, cmd, arg=None):
314                 # update pins
315                 if cmd == StateMachine.CMD_PINS:
316                         self.pins = arg
317                 # handle stuff
318                 newstate = self.current_state.handle_event(cmd,arg) # returns None or an instance of the new state
319                 self.old_pins = self.pins
320                 while newstate is not None:
321                         assert isinstance(newstate, StateMachine.State), "I should get a state"
322                         self.current_state.on_leave()
323                         logger.debug("StateMachine: Doing state transition %s -> %s" % (self.current_state.__class__.__name__, newstate.__class__.__name__))
324                         self.current_state = newstate
325                         newstate = self.current_state.handle_event(StateMachine.CMD_PINS, self.pins)