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 # StateOpening constants
18 OPEN_REPEAT_TIMEOUT = 8
19 OPEN_REPEAT_NUMBER = 3
21 # StateClosing 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 # commands you can send
51 def __init__(self, state_machine):
52 self.state_machine = state_machine
53 self.time_entered = time.time()
55 self.last_wakeup = self.time_entered
56 def handle_pins_event(self):
57 pass # one needn't implement this
58 def handle_buzz_event(self,arg): # this shouldn't be overwritten
59 self.actor.act(Actor.CMD_BUZZ)
60 arg("200 okay: buzz executed")
61 def handle_open_event(self,arg):
63 arg("412 Precondition Failed: The current state (%s) cannot handle the OPEN event" % self.__class__.__name__)
64 def handle_wakeup_event(self):
65 self.last_wakeup = time.time()
67 return self.state_machine.pins
69 return self.state_machine.actor
70 def handle_event(self,ev,arg): # don't override
72 self.handle_pins_event()
74 self.handle_buzz_event(arg)
76 self.handle_open_event(arg)
77 elif arg is CMD_WAKEUP:
78 self.handle_wakeup_event()
80 raise Exception("Unknown command number: %d" % ev)
82 class StateStart(State):
83 def handle_pins_event(self):
84 super().handle_pins_event()
89 if thepins.door_locked:
95 def handle_pins_event(self):
96 super().handle_pins_event()
98 if not pins.door_locked:
99 return StateAboutToOpen(self.state_machine)
100 def handle_open_event(self,callback):
101 # intentionally not calling super() implementation
102 return StateOpening(callback,self.state_machine)
104 class StateOpening(State):
105 def __init__(self,callback,sm):
106 super().__init__(self,sm)
107 self.callbacks=[callback]
108 # FIXME: can we send "202 processing: Trying to open the door" here? Are the callbacks multi-use?
110 self.actor().act(Actor.CMD_OPEN)
111 def notify(self, did_it_work):
112 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))
113 for cb in self.callbacks:
116 def handle_pins_event(self):
117 super().handle_pins_event()
119 if not pins.door_locked:
121 return StateAboutToOpen(self.state_machine)
122 def handle_open_event(self,callback):
123 # intentionally not calling super() implementation
124 # FIXME: 202 notification also here if possible
125 self.callbacks.append(callback)
126 def handle_wakeup_event(self):
127 super().handle_wakeup_event()
128 over = time.time() - self.time_entered
129 nexttry = (self.tries+1) * OPEN_REPEAT_TIMEOUT
131 if self.tries < OPEN_REPEAT_NUMBER:
132 self.actor().act(Actor.CMD_OPEN)
135 logger.critical("Couldn't open door after %d tries. Going back to StateZu." % OPEN_REPEAT_NUMBER)
137 return StateZu(self.state_machine)
139 class AbstractStateWhereOpeningIsRedundant(State):
140 def handle_open_event(self, callback):
141 # intentionally not calling super() implementation
142 callback("299 redundant: Space seems to be already open. Still processing your request tough.")
143 logger.warning("Received OPEN command in StateAboutToOpen. This should not be necessary.")
144 self.actor().act(Actor.CMD_OPEN)
146 class StateAboutToOpen(AbstractStateWhereOpeningIsRedundant):
147 def handle_pins_event(self):
148 super().handle_pins_event()
151 return StateZu(self.state_machine)
152 elif pins.space_active:
153 return StateAuf(self.state_machine)
154 def handle_wakeup_event(self):
155 super().handle_wakeup_event()
157 lasttime = self.last_wakeup - self.time_entered
158 thistime = now - self.time_entered
159 for (t,f) in filter(lambda (t,f): t<=thistime and t>lasttime, ABOUTOPEN_NERVLIST):
164 class StateAuf(AbstractStateWhereOpeningIsRedundant):
165 def __init__(self,sm):
167 self.last_buzzed = None
168 def handle_pins_event(self):
169 super().handle_pins_event()
171 if pins.bell_ringing:
173 if self.last_buzzed is None or now-self.last_buzzed < AUF_BELLBUZZ_REPEAT_TIME:
174 logger.info("buzzing because of bell ringing in state auf")
175 self.actor().act(Actor.CMD_BUZZ)
176 self.last_buzzed = now
177 if not pins.space_active:
178 logger.info("space switch off - starting leaving procedure")
179 return StateAboutToLeave(self.state_machine)
181 logger.error("door manually locked, but space switch on - going to StateZu")
182 play_sound("manual_lock")
183 return StateZu(self.state_machine)
184 # handle_wakeup_event intentionally not overwritten
186 class StateClosing(State):
187 # FIXME: Why does this even have callbacks?
188 # TODO: share code with StateOpening, and possibly also with the nerv-mechanism from StateAboutToOpen
189 def __init__(self,sm):
192 # FIXME: can we send "202 processing: Trying to close the door" here? Are the callbacks multi-use?
194 assert self.pins().door_closed, "Door is open while we should close it, this must not happen"
195 self.actor().act(Actor.CMD_CLOSE)
196 def notify(self, did_it_work):
197 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))
198 for cb in self.callbacks:
201 def handle_pins_event(self):
203 if not pins.door_locked:
205 return StateAboutToOpen(self.state_machine)
206 def handle_open_event(self,callback):
207 callback("409 conflict: The server is currently trying to close the door. Try again later.")
208 def handle_wakeup_event(self):
209 over = time.time() - self.time_entered
210 nexttry = (self.tries+1) * CLOSE_REPEAT_TIMEOUT
212 if self.tries < CLOSE_REPEAT_NUMBER:
213 self.actor().act(Actor.CMD_CLOSE)
216 logger.critical("Couldn't close door after %d tries. Going back to StateAboutToOpen." % CLOSE_REPEAT_NUMBER)
218 return StateAboutToOpen(self.state_machine)
220 class StateAboutToLeave(State):
221 def handle_pins_event(self):
222 if not self.pins().door_closed:
223 return StateLeaving(self.state_machine)
224 if self.pins().door_locked:
225 return StateZu(self.state_machine)
226 def handle_wakeup_event(self):
227 over = time.time() - self.time_entered
228 if over >= LEAVE_TIMEOUT:
229 return StateClosing(self.state_machine)
231 class StateLeaving(State):
232 def handle_pins_event(self):
233 if self.pins().door_closed:
234 return StateClosing(self.state_machine)
235 if self.pins().door_locked:
236 return StateZu(self.state_machine)
237 def handle_wakeup_event(self):
238 over = time.time() - self.time_entered
239 if over >= LEAVE_TIMEOUT:
240 return StateAboutToOpen(self.state_machine)
242 def __init__(self, actor):
244 self.callback = ThreadFunction(self._callback)
245 self.current_state = StateStart(self)
252 def _callback(self, cmd, arg=None):
254 if cmd == StateMachine.CMD_PINS:
257 newstate = self.current_state.handle_event(cmd,arg) # returns None or an instance of the new state
258 self.old_pins = self.pins # FIXME not used?
259 while newstate is not None:
260 logger.info("StateMachine: new state = %s" % newstate.__class__.__name__)
261 self.current_state = newstate
262 newstate = self.current_state.handle_event(StateMachine.CMD_PINS, self.pins)