1 from libtuer import ThreadFunction, logger, fire_and_forget
2 from actor import Actor
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 fire_and_forget ([SOUNDS_PLAYER,soundfile], logger.error, "StateMachine: ")
17 # StateUnlocking constants
18 OPEN_REPEAT_TIMEOUT = 8
19 OPEN_REPEAT_NUMBER = 3
21 # StateLocking constants
22 CLOSE_REPEAT_TIMEOUT = 8
23 CLOSE_REPEAT_NUMBER = 3
25 # StateAboutToOpen constants
26 ABOUTOPEN_NERVLIST = [(5, lambda : play_sound("flipswitch")), (10, lambda:play_sound("flipswitch")), (10, lambda:Logger.warning("Space open but switch not flipped for 10 seconds")),\
27 (20, lambda:play_sound("flipswitch")), (30, lambda:play_sound("flipswitch")), (30, lambda:Logger.error("Space open but switch not flipped for 30 seconds")),\
28 (40, lambda:play_sound("flipswitch")), (50, lambda:play_sound("flipswitch")), (56, lambda:play_sound("flipswitch")), (60, lambda:Logger.critical("Space open but switch not flipped for 60 seconds"))]
31 # time that must pass between two bell_ringing events to buzz the door again (seconds)
32 AUF_BELLBUZZ_REPEAT_TIME = 2
34 # Timeout we wait after the switch was switched to "Closed", until we assume nobody will open the door and we just lock it
37 # play_sound constants
38 SOUNDS_DIRECTORY = "/opt/tuer/sounds/"
39 SOUNDS_PLAYER = "/usr/bin/mplayer"
43 # 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.
44 # If f returns something, that's also returned by nerv.
45 def __init__(self, nervlist):
46 self.nervlist = list(nervlist)
48 def nerv(self, total_time):
49 if len(self.nervlist):
50 (time, f) = self.nervlist[0]
51 # check if the first element is to be triggered
52 if time >= total_time:
53 self.nervlist = self.nervlist[1:] # "pop" the first element, but do not modify original list
58 # commands you can send
66 def __init__(self, state_machine, nervlist = None):
67 self.state_machine = state_machine
68 self.time_entered = time.time()
69 self._nerver = None if nervlist is None else Nerver(nervlist)
70 def handle_pins_event(self):
71 pass # one needn't implement this
72 def handle_buzz_event(self,arg): # this shouldn't be overwritten
73 self.actor.act(Actor.CMD_BUZZ)
74 arg("200 okay: buzz executed")
75 def handle_cmd_unlock_event(self,arg):
77 arg("412 Precondition Failed: The current state (%s) cannot handle the OPEN event" % self.__class__.__name__)
78 def handle_wakeup_event(self):
79 if self._nerver is not None:
80 return self._nerver.nerv(time.time() - self.time_entered)
82 return self.state_machine.pins
84 return self.state_machine.actor
85 def handle_event(self,ev,arg): # don't override
87 self.handle_pins_event()
89 self.handle_buzz_event(arg)
90 elif arg is CMD_UNLOCK:
91 self.handle_cmd_unlock_event(arg)
92 elif arg is CMD_WAKEUP:
93 self.handle_wakeup_event()
95 raise Exception("Unknown command number: %d" % ev)
97 class StateStart(State):
98 def handle_pins_event(self):
99 super().handle_pins_event()
100 thepins = self.pins()
104 if thepins.door_locked:
109 class StateZu(State):
110 def handle_pins_event(self):
111 super().handle_pins_event()
113 if not pins.door_locked:
114 return StateAboutToOpen(self.state_machine)
115 def handle_cmd_unlock_event(self,callback):
116 # intentionally not calling super() implementation
117 return StateUnlocking(callback,self.state_machine)
119 class StateUnlocking(State):
120 def __init__(self,callback,sm):
121 # construct a nervlist
122 nervlist = [(t*OPEN_REPEAT_TIMEOUT, lambda: self.actor().act(Actor.CMD_UNLOCK)) for t in xrange(1, OPEN_REPEAT_NUMBER+1)]
123 nervlist += [((OPEN_REPEAT_NUMBER+1)*OPEN_REPEAT_TIMEOUT, self.could_not_open)]
124 super().__init__(sm,nervlist)
125 self.callbacks=[callback]
126 # FIXME: can we send "202 processing: Trying to open the door" here? Are the callbacks multi-use?
127 self.actor().act(Actor.CMD_UNLOCK)
128 def notify(self, did_it_work):
129 s = "200 okay: door open" if did_it_work else ("500 internal server error: Couldn't open door with %d tries à %f seconds" % (OPEN_REPEAT_NUMBER,OPEN_REPEAT_TIMEOUT))
130 for cb in self.callbacks:
131 if cb is not None: # FIXME why this check? shouldn't be needed
133 def handle_pins_event(self):
134 super().handle_pins_event()
136 if not pins.door_locked:
138 return StateAboutToOpen(self.state_machine)
139 def handle_cmd_unlock_event(self,callback):
140 # intentionally not calling super() implementation
141 # FIXME: 202 notification also here if possible
142 self.callbacks.append(callback)
143 def could_not_open(self):
144 logger.critical("Couldn't open door after %d tries. Going back to StateZu." % OPEN_REPEAT_NUMBER)
146 return StateZu(self.state_machine)
148 class AbstractStateWhereOpeningIsRedundant(State):
149 def handle_cmd_unlock_event(self, callback):
150 # intentionally not calling super() implementation
151 callback("299 redundant: Space seems to be already open. Still processing your request tough.")
152 logger.warning("Received OPEN command in StateAboutToOpen. This should not be necessary.")
153 self.actor().act(Actor.CMD_UNLOCK)
155 class StateAboutToOpen(AbstractStateWhereOpeningIsRedundant):
156 def __init__(self, sm):
157 super().__init__(sm, ABOUTOPEN_NERVLIST)
158 def handle_pins_event(self):
159 super().handle_pins_event()
162 return StateZu(self.state_machine)
163 elif pins.space_active:
164 return StateAuf(self.state_machine)
166 class StateAuf(AbstractStateWhereOpeningIsRedundant):
167 def __init__(self,sm):
169 self.last_buzzed = None
170 def handle_pins_event(self):
171 super().handle_pins_event()
173 if pins.bell_ringing:
175 if self.last_buzzed is None or now-self.last_buzzed < AUF_BELLBUZZ_REPEAT_TIME:
176 logger.info("buzzing because of bell ringing in state auf")
177 self.actor().act(Actor.CMD_BUZZ)
178 self.last_buzzed = now
179 if not pins.space_active:
180 logger.info("space switch off - starting leaving procedure")
181 return StateAboutToLeave(self.state_machine)
183 logger.error("door manually locked, but space switch on - going to StateZu")
184 play_sound("manual_lock")
185 return StateZu(self.state_machine)
186 # handle_wakeup_event intentionally not overwritten
188 class StateLocking(State):
189 # FIXME: Why does this even have callbacks?
190 # TODO: share code with StateUnlocking
191 def __init__(self,sm):
192 # construct a nervlist
193 nervlist = [(t*CLOSE_REPEAT_TIMEOUT, lambda: self.actor().act(Actor.CMD_LOCK)) for t in xrange(1, CLOSE_REPEAT_NUMBER+1)]
194 nervlist += [((CLOSE_REPEAT_NUMBER+1)*CLOSE_REPEAT_TIMEOUT, self.could_not_close)]
195 super().__init__(sm, nervlist)
197 # FIXME: can we send "202 processing: Trying to close the door" here? Are the callbacks multi-use?
199 assert self.pins().door_closed, "Door is open while we should close it, this must not happen"
200 self.actor().act(Actor.CMD_LOCK)
201 def notify(self, did_it_work):
202 s = "200 okay: door closed" if did_it_work else ("500 internal server error: Couldn't close door with %d tries à %f seconds" % (CLOSE_REPEAT_NUMBER,CLOSE_REPEAT_TIMEOUT))
203 for cb in self.callbacks:
206 def handle_pins_event(self):
208 if not pins.door_closed:
209 # TODO play a sound? This shouldn't happen, door was opened while we are locking
211 return StateAboutToOpen(self.state_machine)
213 return SpaceZu(self.state_machine)
214 def handle_cmd_unlock_event(self,callback):
215 callback("409 conflict: The server is currently trying to close the door. Try again later.")
216 def could_not_close(self):
217 logger.critical("Couldn't close door after %d tries. Going back to StateAboutToOpen." % CLOSE_REPEAT_NUMBER)
219 return StateAboutToOpen(self.state_machine)
221 class StateAboutToLeave(State):
222 def handle_pins_event(self):
223 if not self.pins().door_closed:
224 return StateLeaving(self.state_machine)
225 if self.pins().door_locked:
226 return StateZu(self.state_machine)
227 def handle_wakeup_event(self):
228 over = time.time() - self.time_entered
229 if over >= LEAVE_TIMEOUT:
230 return StateLocking(self.state_machine)
232 class StateLeaving(State):
233 def handle_pins_event(self):
234 if self.pins().door_closed:
235 return StateLocking(self.state_machine)
236 if self.pins().door_locked:
237 return StateZu(self.state_machine)
238 def handle_wakeup_event(self):
239 over = time.time() - self.time_entered
240 if over >= LEAVE_TIMEOUT:
241 return StateAboutToOpen(self.state_machine)
243 def __init__(self, actor):
245 self.callback = ThreadFunction(self._callback)
246 self.current_state = StateStart(self)
253 def _callback(self, cmd, arg=None):
255 if cmd == StateMachine.CMD_PINS:
258 newstate = self.current_state.handle_event(cmd,arg) # returns None or an instance of the new state
259 self.old_pins = self.pins # FIXME not used?
260 while newstate is not None:
261 logger.info("StateMachine: new state = %s" % newstate.__class__.__name__)
262 self.current_state = newstate
263 newstate = self.current_state.handle_event(StateMachine.CMD_PINS, self.pins)