07d6574ff7dd601396669640f8a9dd62eed07543
[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
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 # ALso the time we wait after the door was opend, till we assume something went wrong and start nerving
36 LEAVE_TIMEOUT = 20
37
38 # play_sound constants
39 SOUNDS_DIRECTORY = "/opt/tuer/sounds/"
40 SOUNDS_PLAYER = "/usr/bin/mplayer"
41
42
43 class Nerver():
44         # 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.
45         # If f returns something, that's also returned by nerv.
46         def __init__(self, nervlist):
47                 self.nervlist = list(nervlist)
48                 self.last_event_time = time.time()
49         
50         def nerv(self):
51                 if len(self.nervlist):
52                         (wait_time, f) = self.nervlist[0]
53                         now = time.time()
54                         time_gone = now-self.last_event_time
55                         # check if the first element is to be triggered
56                         if time_gone >= wait_time:
57                                 self.nervlist = self.nervlist[1:] # "pop" the first element, but do not modify original list
58                                 self.last_event_time = now
59                                 return f()
60
61
62 class StateMachine():
63         # commands you can send
64         CMD_PINS = 0
65         CMD_BUZZ = 1
66         CMD_UNLOCK = 2
67         CMD_WAKEUP = 3
68         CMD_LAST = 4
69         
70         class State():
71                 def __init__(self, state_machine, nervlist = None):
72                         self.state_machine = state_machine
73                         self._nerver = None if nervlist is None else Nerver(nervlist)
74                 def handle_pins_event(self):
75                         pass # one needn't implement this
76                 def handle_buzz_event(self,arg): # this shouldn't be overwritten
77                         self.actor().act(Actor.CMD_BUZZ)
78                         arg("200 okay: buzz executed")
79                 def handle_cmd_unlock_event(self,arg):
80                         if arg is not None:
81                                 arg("412 Precondition Failed: The current state (%s) cannot handle the OPEN event" % self.__class__.__name__)
82                 def handle_wakeup_event(self):
83                         if self._nerver is not None:
84                                 return self._nerver.nerv()
85                 def pins(self):
86                         return self.state_machine.pins
87                 def actor(self):
88                         return self.state_machine.actor
89                 def handle_event(self,ev,arg): # don't override
90                         if ev == StateMachine.CMD_PINS:
91                                 return self.handle_pins_event()
92                         elif ev == StateMachine.CMD_BUZZ:
93                                 return self.handle_buzz_event(arg)
94                         elif ev == StateMachine.CMD_UNLOCK:
95                                 return self.handle_cmd_unlock_event(arg)
96                         elif ev == StateMachine.CMD_WAKEUP:
97                                 return self.handle_wakeup_event()
98                         else:
99                                 raise Exception("Unknown command number: %d" % ev)
100         
101         class StateStart(State):
102                 def handle_pins_event(self):
103                         super().handle_pins_event()
104                         pins = self.pins()
105                         if pins.door_locked is None or pins.door_closed is None or pins.space_dactive is None or pins.bell_ringing is None:
106                                 return None # wait till we have all sensors non-None
107                         if pins.door_locked:
108                                 return StateMachine.StateZu(self.state_machine)
109                         else:
110                                 return StateMachine.StateAuf(self.state_machine)
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 StateMachine.StateAboutToOpen(self.state_machine)
118                 def handle_cmd_unlock_event(self,callback):
119                         # intentionally not calling super() implementation
120                         return StateMachine.StateUnlocking(self.state_machine, callback)
121         
122         class StateUnlocking(State):
123                 def __init__(self,sm,callback=None):
124                         # construct a nervlist
125                         nervlist = [(OPEN_REPEAT_TIMEOUT, lambda: self.actor().act(Actor.CMD_UNLOCK)) for t in range(OPEN_REPEAT_NUMBER)]
126                         nervlist += [(OPEN_REPEAT_TIMEOUT, self.could_not_open)]
127                         super().__init__(sm,nervlist)
128                         self.callbacks=[callback]
129                         # TODO: 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:
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 StateMachine.StateAboutToOpen(self.state_machine)
142                 def handle_cmd_unlock_event(self,callback):
143                         # intentionally not calling super() implementation
144                         # TODO: 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 StateMachine.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.info("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 StateMachine.StateZu(self.state_machine)
166                         elif pins.space_active:
167                                 return StateMachine.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                                 # TODO: use old_pins instead of a timer
178                                 now = time.time()
179                                 if self.last_buzzed is None or now-self.last_buzzed < AUF_BELLBUZZ_REPEAT_TIME:
180                                         logger.info("buzzing because of bell ringing in state auf")
181                                         self.actor().act(Actor.CMD_BUZZ)
182                                         self.last_buzzed = now
183                         if not pins.space_active:
184                                 logger.info("space switch off - starting leaving procedure")
185                                 return StateMachine.StateAboutToLeave(self.state_machine)
186                         if pins.door_locked:
187                                 logger.info("door manually locked, but space switch on - going to StateZu")
188                                 play_sound("manual_lock")
189                                 return StateMachine.StateZu(self.state_machine)
190         
191         class StateLocking(State):
192                 # TODO: share code with StateUnlocking
193                 def __init__(self,sm):
194                         # construct a nervlist
195                         nervlist = [(CLOSE_REPEAT_TIMEOUT, lambda: self.actor().act(Actor.CMD_LOCK)) for t in range(CLOSE_REPEAT_NUMBER)]
196                         nervlist += [(CLOSE_REPEAT_TIMEOUT, self.could_not_close)]
197                         super().__init__(sm, nervlist)
198                         if self.pins().door_closed: # this should always be true, but just to be sure...
199                                 self.actor().act(Actor.CMD_LOCK)
200                 def handle_pins_event(self):
201                         pins = self.pins()
202                         if not pins.door_closed:
203                                 # TODO play a sound? This shouldn't happen, door was opened while we are locking
204                                 logger.warning("door manually opened during locking")
205                                 return StateMachine.StateAboutToOpen(self.state_machine)
206                         if pins.door_locked:
207                                 return StateMachine.StateZu(self.state_machine)
208                 def handle_cmd_unlock_event(self,callback):
209                         callback("409 conflict: The server is currently trying to lock the door. Try again later.")
210                 def could_not_close(self):
211                         logger.critical("Couldn't close door after %d tries. Going back to StateAboutToOpen." % CLOSE_REPEAT_NUMBER)
212                         return StateMachine.StateAboutToOpen(self.state_machine)
213         
214         class StateAboutToLeave(State):
215                 def __init__(self, sm):
216                         nervlist = [(LEAVE_TIMEOUT, lambda: StateMachine.StateLocking(self.state_machine))]
217                         super().__init__(sm, nervlist)
218                 def handle_pins_event(self):
219                         if not self.pins().door_closed:
220                                 return StateMachine.StateLeaving(self.state_machine)
221                         if self.pins().door_locked:
222                                 return StateMachine.StateZu(self.state_machine)
223                         if self.pins().space_active:
224                                 return StateMachine.StateAuf(self.state_machine)
225         
226         class StateLeaving(State):
227                 def __init__(self, sm):
228                         nervlist = [(LEAVE_TIMEOUT, lambda: StateMachine.StateAboutToOpen(self.state_machine))]
229                         super().__init__(sm, nervlist)
230                 def handle_pins_event(self):
231                         if self.pins().door_closed:
232                                 return StateMachine.StateLocking(self.state_machine)
233                         if self.pins().door_locked:
234                                 return StateMachine.StateZu(self.state_machine)
235                         if self.pins().space_active:
236                                 return StateMachine.StateAuf(self.state_machine)
237         
238         def __init__(self, actor):
239                 self.actor = actor
240                 self.callback = ThreadFunction(self._callback, name="StateMachine")
241                 self.current_state = StateMachine.StateStart(self)
242                 self.pins = None
243                 self.old_pins = None
244         
245         def stop (self):
246                 self.callback.stop()
247         
248         def _callback(self, cmd, arg=None):
249                 # update pins
250                 if cmd == StateMachine.CMD_PINS:
251                         self.pins = arg
252                 # handle stuff
253                 newstate = self.current_state.handle_event(cmd,arg) # returns None or an instance of the new state
254                 self.old_pins = self.pins
255                 while newstate is not None:
256                         logger.debug("StateMachine: new state = %s" % newstate.__class__.__name__)
257                         self.current_state = newstate
258                         newstate = self.current_state.handle_event(StateMachine.CMD_PINS, self.pins)