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