f2fb8178a608b9623a1f08781d63e2a0d5971813
[saartuer.git] / statemachine.py
1 from libtuer import ThreadFunction, logger, fire_and_forget
2 from actor import Actor
3 import os, random, time
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 = 7
19 OPEN_REPEAT_NUMBER = 3
20
21 # StateLocking constants
22 CLOSE_REPEAT_TIMEOUT = 7
23 CLOSE_REPEAT_NUMBER = 3
24
25 # StateAboutToOpen constants
26 ABOUTOPEN_NERVLIST = [(5, lambda : play_sound("flipswitch")), (5, lambda:play_sound("flipswitch")), (0, lambda:logger.warning("Space open but switch not flipped for 10 seconds")),\
27         (10, lambda:play_sound("flipswitch")), (10, lambda:play_sound("flipswitch")), (0, lambda:logger.error("Space open but switch not flipped for 30 seconds")),\
28         (10, lambda:play_sound("flipswitch")), (10, lambda:play_sound("flipswitch")), (6, lambda:play_sound("flipswitch")), (4, lambda:logger.critical("Space open but switch not flipped for 60 seconds")),
29         (59*60, lambda:logger.critical("Space open but switch not flipped for one hour"))]
30
31 # Timeout we wait after the switch was switched to "Closed", until we assume nobody will open the door and we just lock it
32 # ALso the time we wait after the door was opend, till we assume something went wrong and start nerving
33 LEAVE_TIMEOUT = 20
34
35 # play_sound constants
36 SOUNDS_DIRECTORY = "/opt/tuer/sounds/"
37 SOUNDS_PLAYER = "/usr/bin/mplayer"
38
39
40 class Nerver():
41         # 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.
42         # If f returns something, that's also returned by nerv.
43         def __init__(self, nervlist):
44                 self.nervlist = list(nervlist)
45                 self.last_event_time = time.time()
46         
47         def nerv(self):
48                 if len(self.nervlist):
49                         (wait_time, f) = self.nervlist[0]
50                         now = time.time()
51                         time_gone = now-self.last_event_time
52                         # check if the first element is to be triggered
53                         if time_gone >= wait_time:
54                                 self.nervlist = self.nervlist[1:] # "pop" the first element, but do not modify original list
55                                 self.last_event_time = now
56                                 return f()
57
58
59 class StateMachine():
60         # commands you can send
61         CMD_PINS = 0
62         CMD_BUZZ = 1
63         CMD_UNLOCK = 2
64         CMD_WAKEUP = 3
65         CMD_LAST = 4
66         
67         class State():
68                 def __init__(self, state_machine, nervlist = None):
69                         self.state_machine = state_machine
70                         self._nerver = None if nervlist is None else Nerver(nervlist)
71                 def handle_pins_event(self):
72                         pass # one needn't implement this
73                 def handle_buzz_event(self,arg): # this shouldn't be overwritten
74                         self.actor().act(Actor.CMD_BUZZ)
75                         arg("200 okay: buzz executed")
76                 def handle_cmd_unlock_event(self,arg):
77                         if arg is not None:
78                                 arg("412 Precondition Failed: The current state (%s) cannot handle the UNLOCK command. Try again later." % self.__class__.__name__)
79                 def handle_wakeup_event(self):
80                         if self._nerver is not None:
81                                 return self._nerver.nerv()
82                 def pins(self):
83                         return self.state_machine.pins
84                 def old_pins(self):
85                         return self.state_machine.old_pins
86                 def actor(self):
87                         return self.state_machine.actor
88                 def handle_event(self,ev,arg): # don't override
89                         if ev == StateMachine.CMD_PINS:
90                                 return self.handle_pins_event()
91                         elif ev == StateMachine.CMD_BUZZ:
92                                 return self.handle_buzz_event(arg)
93                         elif ev == StateMachine.CMD_UNLOCK:
94                                 return self.handle_cmd_unlock_event(arg)
95                         elif ev == StateMachine.CMD_WAKEUP:
96                                 return self.handle_wakeup_event()
97                         else:
98                                 raise Exception("Unknown command number: %d" % ev)
99         
100         class AbstractLockedState(State):
101                 '''A state with invariant "The space is locked", switching to StateAboutToOpen when the space becomes unlocked'''
102                 def handle_pins_event(self):
103                         if not self.pins().door_locked:
104                                 return StateAboutToOpen(self.state_machine)
105                         return super().handle_pins_event
106         
107         class AbstractUnlockedState(State):
108                 '''A state with invariant "The space is unlocked", switching to StateZu when the space becomes locked'''
109                 def handle_pins_event(self):
110                         if self.pins().door_locked:
111                                 if self.pins().space_active:
112                                         # FIXME the same state can be reached by first locking the door, and then activating the space. What to do then?
113                                         logger.info("StateMachine: door manually locked, but space switch is still on - going to StateZu")
114                                         play_sound("manual_lock")
115                                 return StateZu(self.state_machine)
116                         return super().handle_pins_event
117         
118         class StateStart(State):
119                 def handle_pins_event(self):
120                         pins = self.pins()
121                         if not (pins.door_locked is None or pins.door_closed is None or pins.space_active is None or pins.bell_ringing is None):
122                                 # All sensors got a value, switch to a proper state
123                                 if pins.door_locked:
124                                         return StateMachine.StateZu(self.state_machine)
125                                 else:
126                                         return StateMachine.StateAboutToOpen(self.state_machine)
127                         return super().handle_pins_event()
128         
129         class StateZu(AbstractLockedState):
130                 def handle_cmd_unlock_event(self,callback):
131                         return StateMachine.StateUnlocking(self.state_machine, callback)
132         
133         class StateUnlocking(AbstractLockedState):
134                 def __init__(self,sm,callback=None):
135                         # construct a nervlist
136                         nervlist = [(OPEN_REPEAT_TIMEOUT, lambda: self.actor().act(Actor.CMD_UNLOCK)) for t in range(OPEN_REPEAT_NUMBER)]
137                         nervlist += [(OPEN_REPEAT_TIMEOUT, self.could_not_open)]
138                         super().__init__(sm,nervlist)
139                         self.callbacks=[callback]
140                         # TODO: can we send "202 processing: Trying to unlock the door" here? Are the callbacks multi-use?
141                         self.actor().act(Actor.CMD_UNLOCK)
142                 def notify(self, did_it_work):
143                         s = "200 okay: door unlocked" if did_it_work else ("500 internal server error: Couldn't unlock door with %d tries à %f seconds" % (OPEN_REPEAT_NUMBER,OPEN_REPEAT_TIMEOUT))
144                         for cb in self.callbacks:
145                                 if cb is not None:
146                                         cb(s)
147                 def handle_pins_event(self):
148                         # overriding superclass as we need to do notification (TODO can this be done better? on_leave?)
149                         if not self.pins().door_locked:
150                                 self.notify(True)
151                                 return StateMachine.StateAboutToOpen(self.state_machine)
152                 def handle_cmd_unlock_event(self,callback):
153                         # TODO: 202 notification also here if possible
154                         self.callbacks.append(callback)
155                 def could_not_open(self):
156                         logger.critical("StateMachine: Couldn't open door after %d tries. Going back to StateZu." % OPEN_REPEAT_NUMBER)
157                         self.notify(False)
158                         return StateMachine.StateZu(self.state_machine)
159         
160         class AbstractStateWhereOpeningIsRedundant(AbstractUnlockedState):
161                 def handle_cmd_unlock_event(self, callback):
162                         callback("299 redundant: Space seems to be already open. Still processing your request tough.")
163                         logger.info("StateMachine: Received UNLOCK command in %s. This should not be necessary." % self.__class__.__name__)
164                         self.actor().act(Actor.CMD_UNLOCK)
165         
166         class StateAboutToOpen(AbstractStateWhereOpeningIsRedundant):
167                 def __init__(self, sm):
168                         super().__init__(sm, ABOUTOPEN_NERVLIST)
169                 def handle_pins_event(self):
170                         pins = self.pins()
171                         if pins.space_active:
172                                 return StateMachine.StateAuf(self.state_machine)
173                         return super().handle_pins_event()
174         
175         class StateAuf(AbstractStateWhereOpeningIsRedundant):
176                 def __init__(self,sm):
177                         super().__init__(sm)
178                         self.last_buzzed = None
179                 def handle_pins_event(self):
180                         pins = self.pins()
181                         if pins.bell_ringing and not self.old_pins().bell_ringing:
182                                 # someone just pressed the bell
183                                 logger.info("StateMachine: buzzing because of bell ringing in StateAuf")
184                                 self.actor().act(Actor.CMD_BUZZ)
185                         if not pins.space_active:
186                                 logger.info("StateMachine: space switch turned off - starting leaving procedure")
187                                 return StateMachine.StateAboutToLeave(self.state_machine)
188                         return super().handle_pins_event()
189         
190         class StateLocking(AbstractUnlockedState):
191                 def __init__(self,sm):
192                         # construct a nervlist
193                         nervlist = [(CLOSE_REPEAT_TIMEOUT, lambda: self.actor().act(Actor.CMD_LOCK)) for t in range(CLOSE_REPEAT_NUMBER)]
194                         nervlist += [(CLOSE_REPEAT_TIMEOUT, self.could_not_close)]
195                         super().__init__(sm, nervlist)
196                         if self.pins().door_closed: # this should always be true, but just to be sure...
197                                 self.actor().act(Actor.CMD_LOCK)
198                 def handle_pins_event(self):
199                         pins = self.pins()
200                         if not pins.door_closed:
201                                 # TODO play a sound? This shouldn't happen, door was opened while we are locking
202                                 logger.warning("StateMachine: door manually opened during locking")
203                                 return StateMachine.StateAboutToOpen(self.state_machine)
204                         # TODO do anything here if the switch is activated now?
205                         return super().handle_pins_event()
206                 def handle_cmd_unlock_event(self,callback):
207                         callback("409 conflict: The sphinx is currently trying to lock the door. Try again later.")
208                 def could_not_close(self):
209                         logger.critical("StateMachine: Couldn't close door after %d tries. Going back to StateAboutToOpen." % CLOSE_REPEAT_NUMBER)
210                         return StateMachine.StateAboutToOpen(self.state_machine)
211         
212         class StateAboutToLeave(AbstractUnlockedState):
213                 def __init__(self, sm):
214                         nervlist = [(LEAVE_TIMEOUT, lambda: StateMachine.StateLocking(self.state_machine))]
215                         super().__init__(sm, nervlist)
216                 def handle_pins_event(self):
217                         if not self.pins().door_closed:
218                                 return StateMachine.StateLeaving(self.state_machine)
219                         if self.pins().space_active:
220                                 return StateMachine.StateAuf(self.state_machine)
221                         return super().handle_pins_event()
222         
223         class StateLeaving(AbstractUnlockedState):
224                 def __init__(self, sm):
225                         nervlist = [(LEAVE_TIMEOUT, lambda: StateMachine.StateAboutToOpen(self.state_machine))]
226                         super().__init__(sm, nervlist)
227                 def handle_pins_event(self):
228                         if self.pins().door_closed:
229                                 return StateMachine.StateLocking(self.state_machine)
230                         if self.pins().space_active:
231                                 return StateMachine.StateAuf(self.state_machine)
232                         return super().handle_pins_event()
233         
234         def __init__(self, actor):
235                 self.actor = actor
236                 self.callback = ThreadFunction(self._callback, name="StateMachine")
237                 self.current_state = StateMachine.StateStart(self)
238                 self.pins = None
239                 self.old_pins = None
240         
241         def stop (self):
242                 self.callback.stop()
243         
244         def _callback(self, cmd, arg=None):
245                 # update pins
246                 if cmd == StateMachine.CMD_PINS:
247                         self.pins = arg
248                 # handle stuff
249                 newstate = self.current_state.handle_event(cmd,arg) # returns None or an instance of the new state
250                 self.old_pins = self.pins
251                 while newstate is not None:
252                         logger.debug("StateMachine: Doing state transition %s -> %s" % (self.current_state.__class__.__name__, newstate.__class__.__name__))
253                         self.current_state = newstate
254                         newstate = self.current_state.handle_event(StateMachine.CMD_PINS, self.pins)