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
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):
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()
105 return self.state_machine.pins
107 return self.state_machine.old_pins
109 return self.state_machine.actor
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()
122 raise Exception("Unknown command number: %d" % ev)
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)
129 self.actor().act(Actor.CMD_RED_OFF)
130 return super().handle_pins_event()
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()
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()
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):
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):
165 logger.info("Going to StateFallback because running in fallback mode")
166 return StateMachine.StateFallback(self.state_machine)
168 logger.info("All sensors got a value, switching to a proper state: Space is closed")
169 return StateMachine.StateZu(self.state_machine)
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()
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):
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)
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):
200 self.actor().act(Actor.CMD_RED_OFF)
201 self._red_state = False
203 self.actor().act(Actor.CMD_RED_ON)
204 self._red_state = True
205 def handle_cmd_unlock_event(self,arg):
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)
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()
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)
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:
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)
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)
249 class StateAboutToOpen(AbstractStateWhereUnlockingIsRedundant):
250 def __init__(self, sm):
251 super().__init__(sm, ABOUTOPEN_NERVLIST)
252 def handle_pins_event(self):
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()
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):
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:
278 return super().handle_pins_event()
280 self.api().set_state(False)
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):
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)
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()
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()
329 def __init__(self, actor, waker, api, fallback = False):
332 self.callback = ThreadFunction(self._callback, name="StateMachine")
333 self.current_state = StateMachine.StateStart(self, fallback=fallback)
336 waker.register(lambda: self.callback(StateMachine.CMD_WAKEUP), 1.0) # wake up every second
337 # initially, the space is closed
343 def _callback(self, cmd, arg=None):
345 if cmd == StateMachine.CMD_PINS:
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)