6a3e88961c2749d567ff7b406896f6d9fffc42da
[saartuer.git] / statemachine.py
1 from libtuer import ThreadFunction, logger, fire_and_forget
2 from actor import Actor
3 import os, random
4
5 # logger.{debug,info,warning,error,critical}
6
7 def play_sound (what):
8         try:
9                 soundfiles = os.listdir(SOUNDS_DIRECTORY+what)
10         except FileNotFoundError:
11                 logger.error("StateMachine: Unable to list sound files in %s" % (SOUNDS_DIRECTORY+what))
12                 return
13         soundfile = SOUNDS_DIRECTORY + what + '/' + random.choice(soundfiles)
14         fire_and_forget ([SOUNDS_PLAYER,soundfile], logger.error, "StateMachine: ")
15
16
17 # StateUnlocking constants
18 OPEN_REPEAT_TIMEOUT = 8
19 OPEN_REPEAT_NUMBER = 3
20
21 # StateLocking constants
22 CLOSE_REPEAT_TIMEOUT = 8
23 CLOSE_REPEAT_NUMBER = 3
24
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"))]
29
30 # StateAuf constants
31 #  time that must pass between two bell_ringing events to buzz the door again (seconds)
32 AUF_BELLBUZZ_REPEAT_TIME = 2
33
34 # Timeout we wait after the switch was switched to "Closed", until we assume nobody will open the door and we just lock it
35 LEAVE_TIMEOUT = 30
36
37 # play_sound constants
38 SOUNDS_DIRECTORY = "/opt/tuer/sounds/"
39 SOUNDS_PLAYER = "/usr/bin/mplayer"
40
41
42 class Nerver():
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         
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
54                                 return f()
55
56
57 class StateMachine():
58         # commands you can send
59         CMD_PINS = 0
60         CMD_BUZZ = 1
61         CMD_UNLOCK = 2
62         CMD_WAKEUP = 3
63         CMD_LAST = 4
64         
65         class State():
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):
76                         if arg is not None:
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)
81                 def pins(self):
82                         return self.state_machine.pins
83                 def actor(self):
84                         return self.state_machine.actor
85                 def handle_event(self,ev,arg): # don't override
86                         if arg is CMD_PINS:
87                                 self.handle_pins_event()
88                         elif arg is CMD_BUZZ:
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()
94                         else:
95                                 raise Exception("Unknown command number: %d" % ev)
96         
97         class StateStart(State):
98                 def handle_pins_event(self):
99                         super().handle_pins_event()
100                         thepins = self.pins()
101                         for pin in thepins:
102                                 if pin is None:
103                                         return None
104                         if thepins.door_locked:
105                                 return StateZu
106                         else:
107                                 return StateAuf
108
109         class StateZu(State):
110                 def handle_pins_event(self):
111                         super().handle_pins_event()
112                         pins = self.pins()
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)
118         
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
132                                         cb(s)
133                 def handle_pins_event(self):
134                         super().handle_pins_event()
135                         pins = self.pins()
136                         if not pins.door_locked:
137                                 self.notify(True)
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)
145                         self.notify(False)
146                         return StateZu(self.state_machine)
147         
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)
154         
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()
160                         pins = self.pins()
161                         if pins.door_locked:
162                                 return StateZu(self.state_machine)
163                         elif pins.space_active:
164                                 return StateAuf(self.state_machine)
165         
166         class StateAuf(AbstractStateWhereOpeningIsRedundant):
167                 def __init__(self,sm):
168                         super().__init__(sm)
169                         self.last_buzzed = None
170                 def handle_pins_event(self):
171                         super().handle_pins_event()
172                         pins = self.pins()
173                         if pins.bell_ringing:
174                                 now = time.time()
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)
182                         if pins.door_locked:
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
187         
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)
196                         self.callbacks=[]
197                         # FIXME: can we send "202 processing: Trying to close the door" here? Are the callbacks multi-use?
198                         self.tries = 0
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:
204                                 if cb is not None:
205                                         cb(s)
206                 def handle_pins_event(self):
207                         pins = self.pins()
208                         if not pins.door_closed:
209                                 # TODO play a sound? This shouldn't happen, door was opened while we are locking
210                                 self.notify(True)
211                                 return StateAboutToOpen(self.state_machine)
212                         if pins.door_locked:
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)
218                         self.notify(False)
219                         return StateAboutToOpen(self.state_machine)
220         
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)
231         
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)
242         
243         def __init__(self, actor):
244                 self.actor = actor
245                 self.callback = ThreadFunction(self._callback)
246                 self.current_state = StateStart(self)
247                 self.pins = None
248                 self.old_pins = None
249         
250         def stop (self):
251                 self.callback.stop()
252         
253         def _callback(self, cmd, arg=None):
254                 # update pins
255                 if cmd == StateMachine.CMD_PINS:
256                         self.pins = arg
257                 # handle stuff
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)