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