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
5 # logger.{debug,info,warning,error,critical}
9 soundfiles = os.listdir(SOUNDS_DIRECTORY+what)
10 except FileNotFoundError:
11 logger.error("StateMachine: Unable to list sound files in %s" % (SOUNDS_DIRECTORY+what))
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: ")
18 # convert an absolute nervlist to a relative one
19 def nervlist_abs2rel(nervlist_abs):
22 for (t, f) in nervlist_abs:
24 nervlist_rel.append((t-last_t, f))
29 HELLO_PROBABILITY = 0.2
31 # StateUnlocking constants
32 OPEN_REPEAT_TIMEOUT = 7
33 OPEN_REPEAT_NUMBER = 3
35 # StateLocking constants
36 CLOSE_REPEAT_TIMEOUT = 7
37 CLOSE_REPEAT_NUMBER = 3
39 # StateFallback constants
40 FALLBACK_LEAVE_DELAY_LOCK = 5 # seconds
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"))])
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
55 # play_sound constants
56 SOUNDS_DIRECTORY = "/opt/tuer/sounds/"
57 SOUNDS_PLAYER = "/usr/bin/mplayer"
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()
68 if len(self.nervlist):
69 (wait_time, f) = self.nervlist[0]
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
80 # commands you can send
91 def __init__(self, state_machine, nervlist = None):
92 self.state_machine = state_machine
93 self._nerver = None if nervlist is None else Nerver(nervlist)
94 def handle_pins_event(self):
95 pass # one needn't implement this
96 def handle_buzz_event(self,arg): # this shouldn't be overwritten
97 self.actor().act(Actor.CMD_BUZZ)
98 arg("200 okay: buzz executed")
99 def handle_cmd_unlock_event(self,arg):
101 arg("412 Precondition Failed: The current state (%s) cannot handle the UNLOCK command. Try again later." % self.__class__.__name__)
102 def handle_wakeup_event(self):
103 if self._nerver is not None:
104 return self._nerver.nerv()
105 def handle_cmd_lock_event(self,arg):
106 arg("412 Precondition Failed: If not in fallback mode, use the hardware switch to lock the space.")
107 def handle_cmd_fallback_on_event(self,arg):
108 arg("200 okay: Entering fallback mode and notifying admins.")
109 logger.critical("Entering fallback mode. Somebody thinks, the hardware sensors are broken.")
110 return StateMachine.StateFallback(self.state_machine)
111 def handle_cmd_fallback_off_event(self,arg):
112 arg("412 Precondition Failed: Not in fallback mode!")
116 return self.state_machine.pins
118 return self.state_machine.old_pins
120 return self.state_machine.actor
122 return self.state_machine.api
123 def handle_event(self,ev,arg): # don't override
124 if ev == StateMachine.CMD_PINS:
125 return self.handle_pins_event()
126 elif ev == StateMachine.CMD_BUZZ:
127 return self.handle_buzz_event(arg)
128 elif ev == StateMachine.CMD_UNLOCK:
129 return self.handle_cmd_unlock_event(arg)
130 elif ev == StateMachine.CMD_WAKEUP:
131 return self.handle_wakeup_event()
132 elif ev == StateMachine.CMD_LOCK:
133 return self.handle_cmd_lock_event(arg)
134 elif ev == StateMachine.CMD_FALLBACK_ON:
135 return self.handle_cmd_fallback_on_event(arg)
136 elif ev == StateMachine.CMD_FALLBACK_OFF:
137 return self.handle_cmd_fallback_off_event(arg)
139 raise Exception("Unknown command number: %d" % ev)
141 class AbstractNonStartState(State):
142 def handle_pins_event(self):
143 if self.pins().door_locked != (not self.pins().space_active):
144 self.actor().act(Actor.CMD_RED_ON)
146 self.actor().act(Actor.CMD_RED_OFF)
147 return super().handle_pins_event()
149 class AbstractLockedState(AbstractNonStartState):
150 '''A state with invariant "The space is locked", switching to StateAboutToOpen when the space becomes unlocked'''
151 def __init__(self, sm, nervlist = None):
152 super().__init__(sm, nervlist)
153 self.actor().act(Actor.CMD_GREEN_OFF)
154 def handle_pins_event(self):
155 if not self.pins().door_locked:
156 logger.info("Door unlocked, space is about to open")
157 return StateMachine.StateAboutToOpen(self.state_machine)
158 return super().handle_pins_event()
160 class AbstractUnlockedState(AbstractNonStartState):
161 '''A state with invariant "The space is unlocked", switching to StateZu when the space becomes locked'''
162 def __init__(self, sm, nervlist = None):
163 super().__init__(sm, nervlist)
164 self.actor().act(Actor.CMD_GREEN_ON)
165 def handle_pins_event(self):
166 if self.pins().door_locked:
167 logger.info("Door locked, closing space")
168 if self.pins().space_active:
169 logger.warning("StateMachine: door manually locked, but space switch is still on - going to StateZu")
170 play_sound("manual_lock")
171 return StateMachine.StateZu(self.state_machine)
172 return super().handle_pins_event()
174 class StateStart(State):
175 def __init__(self, sm, nervlist = None, fallback=False):
176 super().__init__(sm, nervlist)
177 self.fallback = fallback
178 def handle_pins_event(self):
180 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):
182 logger.info("Going to StateFallback because running in fallback mode")
183 return StateMachine.StateFallback(self.state_machine)
185 logger.info("All sensors got a value, switching to a proper state: Space is closed")
186 return StateMachine.StateZu(self.state_machine)
188 logger.info("All sensors got a value, switching to a proper state: Space is (about to) open")
189 return StateMachine.StateAboutToOpen(self.state_machine)
190 return super().handle_pins_event()
192 class StateFallback(State):
193 def __init__(self, sm, nervlist = None):
194 super().__init__(sm, nervlist)
195 self._red_state = False
196 def handle_pins_event(self):
198 # set green LED according to space switch
199 if pins.space_active:
200 self.actor().act(Actor.CMD_GREEN_ON)
202 self.actor().act(Actor.CMD_GREEN_OFF)
203 # primitive leaving procedure if space switch turned off
204 if not pins.space_active and self.old_pins().space_active:
205 def _close_after_time():
206 time.sleep(FALLBACK_LEAVE_DELAY_LOCK)
207 self.actor().act(Actor.CMD_LOCK)
208 fire_and_forget(_close_after_time)
209 # not calling superclass because we want to stay in fallback mode
210 def handle_wakeup_event(self):
213 self.actor().act(Actor.CMD_RED_OFF)
214 self._red_state = False
216 self.actor().act(Actor.CMD_RED_ON)
217 self._red_state = True
218 def handle_cmd_unlock_event(self,arg):
220 arg("200 okay: Trying to unlock the door. The System is in fallback mode, success information is not available.")
221 self.actor().act(Actor.CMD_UNLOCK)
222 def handle_cmd_lock_event(self,arg):
224 arg("200 okay: Trying to lock the door. The System is in fallback mode, success information is not available.")
225 self.actor().act(Actor.CMD_LOCK)
226 def handle_cmd_fallback_on_event(self,arg):
227 arg("412 Precondition Failed: Fallback mode already active.")
228 def handle_cmd_fallback_off_event(self,arg):
229 arg("200 okay: Leaving fallback mode and notifying admins.")
230 logger.critical("Leaving fallback mode. Somebody thinks, the sensors are working again.")
231 return StateMachine.StateStart(self.state_machine)
233 class StateZu(AbstractLockedState):
234 def handle_cmd_unlock_event(self,callback):
235 return StateMachine.StateUnlocking(self.state_machine, callback)
236 def handle_pins_event(self):
237 if not self.old_pins().space_active and self.pins().space_active: # first thing to check: edge detection
238 logger.info("Space toggled to active while it was closed - unlocking the door")
239 return StateMachine.StateUnlocking(self.state_machine)
240 return super().handle_pins_event()
242 class StateUnlocking(AbstractLockedState):
243 def __init__(self,sm,callback=None):
244 # construct a nervlist
245 nervlist = [(OPEN_REPEAT_TIMEOUT, lambda: self.actor().act(Actor.CMD_UNLOCK)) for t in range(OPEN_REPEAT_NUMBER)]
246 nervlist += [(OPEN_REPEAT_TIMEOUT, self.could_not_open)]
247 super().__init__(sm,nervlist)
249 self.actor().act(Actor.CMD_UNLOCK)
250 # enqueue the callback
251 self.handle_cmd_unlock_event(callback)
252 def notify(self, s, lastMsg):
253 for cb in self.callbacks:
256 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))
257 self.notify(s, lastMsg=True)
258 def handle_cmd_unlock_event(self,callback):
259 if callback is not None:
260 callback("202 processing: Trying to unlock the door", lastMsg=False)
261 self.callbacks.append(callback)
262 def could_not_open(self):
263 logger.critical("StateMachine: Couldn't open door after %d tries. Going back to StateZu." % OPEN_REPEAT_NUMBER)
264 return StateMachine.StateZu(self.state_machine)
266 class AbstractStateWhereUnlockingIsRedundant(AbstractUnlockedState):
267 def handle_cmd_unlock_event(self, callback):
268 callback("299 redundant: Space seems to be already open. Still processing your request tough.")
269 logger.info("StateMachine: Received UNLOCK command in %s. This should not be necessary." % self.__class__.__name__)
270 self.actor().act(Actor.CMD_UNLOCK)
272 class StateAboutToOpen(AbstractStateWhereUnlockingIsRedundant):
273 def __init__(self, sm):
274 super().__init__(sm, ABOUTOPEN_NERVLIST)
275 def handle_pins_event(self):
277 if pins.space_active:
278 logger.info("Space activated, opening procedure completed")
279 if not self.old_pins().space_active and random.random() <= SWITCH_PRAISE_PROBABILITY:
280 play_sound("success")
281 return StateMachine.StateAuf(self.state_machine)
282 return super().handle_pins_event()
284 class StateAuf(AbstractStateWhereUnlockingIsRedundant):
285 def __init__(self,sm):
286 nervlist = [(24*60*60, lambda: logger.critical("Space is now open for 24h. Is everything all right?"))]
287 super().__init__(sm, nervlist)
288 self.last_buzzed = None
289 self.api().set_state(True)
290 def handle_pins_event(self):
292 if pins.bell_ringing and not self.old_pins().bell_ringing: # first thing to check: edge detection
293 # someone just pressed the bell
294 logger.info("StateMachine: buzzing because of bell ringing in StateAuf")
295 self.actor().act(Actor.CMD_BUZZ)
296 if not pins.space_active:
297 logger.info("StateMachine: space switch turned off - starting leaving procedure")
298 return StateMachine.StateAboutToLeave(self.state_machine)
299 if not pins.door_closed and self.old_pins().door_closed and random.random() <= HELLO_PROBABILITY:
301 return super().handle_pins_event()
303 self.api().set_state(False)
305 class StateLocking(AbstractUnlockedState):
306 def __init__(self,sm):
307 # construct a nervlist
308 nervlist = [(CLOSE_REPEAT_TIMEOUT, lambda: self.actor().act(Actor.CMD_LOCK)) for t in range(CLOSE_REPEAT_NUMBER)]
309 nervlist += [(CLOSE_REPEAT_TIMEOUT, self.could_not_close)]
310 super().__init__(sm, nervlist)
311 if self.pins().door_closed: # this should always be true, but just to be sure...
312 self.actor().act(Actor.CMD_LOCK)
313 def handle_pins_event(self):
315 if not pins.door_closed:
316 # TODO play a sound? This shouldn't happen, door was opened while we are locking
317 logger.warning("StateMachine: door manually opened during locking")
318 return StateMachine.StateAboutToOpen(self.state_machine)
319 # TODO do anything here if the switch is activated now?
320 return super().handle_pins_event()
321 def handle_cmd_unlock_event(self,callback):
322 callback("409 conflict: The sphinx is currently trying to lock the door. Try again later.")
323 def could_not_close(self):
324 logger.critical("StateMachine: Couldn't close door after %d tries. Going back to StateAboutToOpen." % CLOSE_REPEAT_NUMBER)
325 return StateMachine.StateAboutToOpen(self.state_machine)
327 class StateAboutToLeave(AbstractUnlockedState):
328 def __init__(self, sm):
329 nervlist = [(LEAVE_TIMEOUT, lambda: StateMachine.StateLocking(self.state_machine))]
330 super().__init__(sm, nervlist)
331 def handle_pins_event(self):
332 if not self.pins().door_closed:
333 return StateMachine.StateLeaving(self.state_machine)
334 if self.pins().space_active:
335 logger.info("Space re-activated, cancelling leaving procedure")
336 return StateMachine.StateAuf(self.state_machine)
337 return super().handle_pins_event()
339 class StateLeaving(AbstractUnlockedState):
340 def __init__(self, sm):
341 nervlist = [(LEAVE_TIMEOUT, lambda: StateMachine.StateAboutToOpen(self.state_machine))]
342 super().__init__(sm, nervlist)
343 def handle_pins_event(self):
344 if self.pins().door_closed:
345 logger.info("The space was left, locking the door")
346 return StateMachine.StateLocking(self.state_machine)
347 if self.pins().space_active:
348 logger.info("Space re-activated, cancelling leaving procedure")
349 return StateMachine.StateAuf(self.state_machine)
350 return super().handle_pins_event()
352 def __init__(self, actor, waker, api, fallback = False):
355 self.callback = ThreadFunction(self._callback, name="StateMachine")
356 self.current_state = StateMachine.StateStart(self, fallback=fallback)
359 waker.register(lambda: self.callback(StateMachine.CMD_WAKEUP), 1.0) # wake up every second
360 # initially, the space is closed
366 # actually call this.callback (is set in the constructor to make this thread safe)
367 def _callback(self, cmd, arg=None):
369 if cmd == StateMachine.CMD_PINS:
372 newstate = self.current_state.handle_event(cmd,arg) # returns None or an instance of the new state
373 self.old_pins = self.pins
374 while newstate is not None:
375 assert isinstance(newstate, StateMachine.State), "I should get a state"
376 self.current_state.on_leave()
377 logger.debug("StateMachine: Doing state transition %s -> %s" % (self.current_state.__class__.__name__, newstate.__class__.__name__))
378 self.current_state = newstate
379 newstate = self.current_state.handle_event(StateMachine.CMD_PINS, self.pins)