Make nervlists relative
[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                 self.last_event_time = time.time()
48         
49         def nerv(self):
50                 if len(self.nervlist):
51                         (time, f) = self.nervlist[0]
52                         now = time.time()
53                         time_gone = now-self.last_event_time
54                         # check if the first element is to be triggered
55                         if time_gone >= time:
56                                 self.nervlist = self.nervlist[1:] # "pop" the first element, but do not modify original list
57                                 self.last_event_time = now
58                                 return f()
59
60
61 class StateMachine():
62         # commands you can send
63         CMD_PINS = 0
64         CMD_BUZZ = 1
65         CMD_UNLOCK = 2
66         CMD_WAKEUP = 3
67         CMD_LAST = 4
68         
69         class State():
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):
79                         if arg is not None:
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()
84                 def pins(self):
85                         return self.state_machine.pins
86                 def actor(self):
87                         return self.state_machine.actor
88                 def handle_event(self,ev,arg): # don't override
89                         if arg is CMD_PINS:
90                                 self.handle_pins_event()
91                         elif arg is CMD_BUZZ:
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()
97                         else:
98                                 raise Exception("Unknown command number: %d" % ev)
99         
100         class StateStart(State):
101                 def handle_pins_event(self):
102                         super().handle_pins_event()
103                         thepins = self.pins()
104                         for pin in thepins:
105                                 if pin is None:
106                                         return None
107                         if thepins.door_locked:
108                                 return StateZu
109                         else:
110                                 return StateAuf
111
112         class StateZu(State):
113                 def handle_pins_event(self):
114                         super().handle_pins_event()
115                         pins = self.pins()
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)
121         
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
135                                         cb(s)
136                 def handle_pins_event(self):
137                         super().handle_pins_event()
138                         pins = self.pins()
139                         if not pins.door_locked:
140                                 self.notify(True)
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)
148                         self.notify(False)
149                         return StateZu(self.state_machine)
150         
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)
157         
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()
163                         pins = self.pins()
164                         if pins.door_locked:
165                                 return StateZu(self.state_machine)
166                         elif pins.space_active:
167                                 return StateAuf(self.state_machine)
168         
169         class StateAuf(AbstractStateWhereOpeningIsRedundant):
170                 def __init__(self,sm):
171                         super().__init__(sm)
172                         self.last_buzzed = None
173                 def handle_pins_event(self):
174                         super().handle_pins_event()
175                         pins = self.pins()
176                         if pins.bell_ringing:
177                                 now = time.time()
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)
185                         if pins.door_locked:
186                                 logger.error("door manually locked, but space switch on - going to StateZu")
187                                 play_sound("manual_lock")
188                                 return StateZu(self.state_machine)
189         
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)
198                         self.callbacks=[]
199                         # FIXME: can we send "202 processing: Trying to close the door" here? Are the callbacks multi-use?
200                         self.tries = 0
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:
206                                 if cb is not None:
207                                         cb(s)
208                 def handle_pins_event(self):
209                         pins = self.pins()
210                         if not pins.door_closed:
211                                 # TODO play a sound? This shouldn't happen, door was opened while we are locking
212                                 self.notify(True)
213                                 return StateAboutToOpen(self.state_machine)
214                         if pins.door_locked:
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)
220                         self.notify(False)
221                         return StateAboutToOpen(self.state_machine)
222         
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)
232         
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)
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)