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)
47 self.last_event_time = time.time()
50 if len(self.nervlist):
51 (time, f) = self.nervlist[0]
53 time_gone = now-self.last_event_time
54 # check if the first element is to be triggered
56 self.nervlist = self.nervlist[1:] # "pop" the first element, but do not modify original list
57 self.last_event_time = now
62 # commands you can send
70 def __init__(self, state_machine, nervlist = None):
71 self.state_machine = state_machine
72 self._nerver = None if nervlist is None else Nerver(nervlist)
73 def handle_pins_event(self):
74 pass # one needn't implement this
75 def handle_buzz_event(self,arg): # this shouldn't be overwritten
76 self.actor.act(Actor.CMD_BUZZ)
77 arg("200 okay: buzz executed")
78 def handle_cmd_unlock_event(self,arg):
80 arg("412 Precondition Failed: The current state (%s) cannot handle the OPEN event" % self.__class__.__name__)
81 def handle_wakeup_event(self):
82 if self._nerver is not None:
83 return self._nerver.nerv()
85 return self.state_machine.pins
87 return self.state_machine.actor
88 def handle_event(self,ev,arg): # don't override
90 self.handle_pins_event()
92 self.handle_buzz_event(arg)
93 elif arg is CMD_UNLOCK:
94 self.handle_cmd_unlock_event(arg)
95 elif arg is CMD_WAKEUP:
96 self.handle_wakeup_event()
98 raise Exception("Unknown command number: %d" % ev)
100 class StateStart(State):
101 def handle_pins_event(self):
102 super().handle_pins_event()
103 thepins = self.pins()
107 if thepins.door_locked:
112 class StateZu(State):
113 def handle_pins_event(self):
114 super().handle_pins_event()
116 if not pins.door_locked:
117 return StateAboutToOpen(self.state_machine)
118 def handle_cmd_unlock_event(self,callback):
119 # intentionally not calling super() implementation
120 return StateUnlocking(callback,self.state_machine)
122 class StateUnlocking(State):
123 def __init__(self,callback,sm):
124 # construct a nervlist
125 nervlist = [(OPEN_REPEAT_TIMEOUT, lambda: self.actor().act(Actor.CMD_UNLOCK)) for t in xrange(OPEN_REPEAT_NUMBER)]
126 nervlist += [(OPEN_REPEAT_TIMEOUT, self.could_not_open)]
127 super().__init__(sm,nervlist)
128 self.callbacks=[callback]
129 # FIXME: can we send "202 processing: Trying to open the door" here? Are the callbacks multi-use?
130 self.actor().act(Actor.CMD_UNLOCK)
131 def notify(self, did_it_work):
132 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))
133 for cb in self.callbacks:
134 if cb is not None: # FIXME why this check? shouldn't be needed
136 def handle_pins_event(self):
137 super().handle_pins_event()
139 if not pins.door_locked:
141 return StateAboutToOpen(self.state_machine)
142 def handle_cmd_unlock_event(self,callback):
143 # intentionally not calling super() implementation
144 # FIXME: 202 notification also here if possible
145 self.callbacks.append(callback)
146 def could_not_open(self):
147 logger.critical("Couldn't open door after %d tries. Going back to StateZu." % OPEN_REPEAT_NUMBER)
149 return StateZu(self.state_machine)
151 class AbstractStateWhereOpeningIsRedundant(State):
152 def handle_cmd_unlock_event(self, callback):
153 # intentionally not calling super() implementation
154 callback("299 redundant: Space seems to be already open. Still processing your request tough.")
155 logger.warning("Received OPEN command in StateAboutToOpen. This should not be necessary.")
156 self.actor().act(Actor.CMD_UNLOCK)
158 class StateAboutToOpen(AbstractStateWhereOpeningIsRedundant):
159 def __init__(self, sm):
160 super().__init__(sm, ABOUTOPEN_NERVLIST)
161 def handle_pins_event(self):
162 super().handle_pins_event()
165 return StateZu(self.state_machine)
166 elif pins.space_active:
167 return StateAuf(self.state_machine)
169 class StateAuf(AbstractStateWhereOpeningIsRedundant):
170 def __init__(self,sm):
172 self.last_buzzed = None
173 def handle_pins_event(self):
174 super().handle_pins_event()
176 if pins.bell_ringing:
178 if self.last_buzzed is None or now-self.last_buzzed < AUF_BELLBUZZ_REPEAT_TIME:
179 logger.info("buzzing because of bell ringing in state auf")
180 self.actor().act(Actor.CMD_BUZZ)
181 self.last_buzzed = now
182 if not pins.space_active:
183 logger.info("space switch off - starting leaving procedure")
184 return StateAboutToLeave(self.state_machine)
186 logger.error("door manually locked, but space switch on - going to StateZu")
187 play_sound("manual_lock")
188 return StateZu(self.state_machine)
190 class StateLocking(State):
191 # FIXME: Why does this even have callbacks?
192 # TODO: share code with StateUnlocking
193 def __init__(self,sm):
194 # construct a nervlist
195 nervlist = [(t*CLOSE_REPEAT_TIMEOUT, lambda: self.actor().act(Actor.CMD_LOCK)) for t in range(1, CLOSE_REPEAT_NUMBER+1)]
196 nervlist += [((CLOSE_REPEAT_NUMBER+1)*CLOSE_REPEAT_TIMEOUT, self.could_not_close)]
197 super().__init__(sm, nervlist)
199 # FIXME: can we send "202 processing: Trying to close the door" here? Are the callbacks multi-use?
201 assert self.pins().door_closed, "Door is open while we should close it, this must not happen"
202 self.actor().act(Actor.CMD_LOCK)
203 def notify(self, did_it_work):
204 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))
205 for cb in self.callbacks:
208 def handle_pins_event(self):
210 if not pins.door_closed:
211 # TODO play a sound? This shouldn't happen, door was opened while we are locking
213 return StateAboutToOpen(self.state_machine)
215 return SpaceZu(self.state_machine)
216 def handle_cmd_unlock_event(self,callback):
217 callback("409 conflict: The server is currently trying to close the door. Try again later.")
218 def could_not_close(self):
219 logger.critical("Couldn't close door after %d tries. Going back to StateAboutToOpen." % CLOSE_REPEAT_NUMBER)
221 return StateAboutToOpen(self.state_machine)
223 class StateAboutToLeave(State):
224 def __init__(self, sm):
225 nervlist = [(LEAVE_TIMEOUT, lambda: StateLocking(self.state_machine))]
226 super().__init__(sm, nervlist)
227 def handle_pins_event(self):
228 if not self.pins().door_closed:
229 return StateLeaving(self.state_machine)
230 if self.pins().door_locked:
231 return StateZu(self.state_machine)
233 class StateLeaving(State):
234 def __init__(self, sm):
235 nervlist = [(LEAVE_TIMEOUT, lambda: StateAboutToOpen(self.state_machine))]
236 super().__init__(sm, nervlist)
237 def handle_pins_event(self):
238 if self.pins().door_closed:
239 return StateLocking(self.state_machine)
240 if self.pins().door_locked:
241 return StateZu(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)