333285869f514af727d4a38d8cda9478f0462e45
[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 # StateOpening constants
18 OPEN_REPEAT_TIMEOUT = 8
19 OPEN_REPEAT_NUMBER = 3
20
21 # StateClosing 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 StateMachine():
43         # commands you can send
44         CMD_PINS = 0
45         CMD_BUZZ = 1
46         CMD_OPEN = 2
47         CMD_WAKEUP = 3
48         CMD_LAST = 4
49         
50         class State():
51                 def __init__(self, state_machine):
52                         self.state_machine = state_machine
53                         self.time_entered = time.time()
54                         self.theDict = None
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):
62                         if arg is not None:
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()
66                 def pins(self):
67                         return self.state_machine.pins
68                 def actor(self):
69                         return self.state_machine.actor
70                 def handle_event(self,ev,arg): # don't override
71                         if arg is CMD_PINS:
72                                 self.handle_pins_event()
73                         elif arg is CMD_BUZZ:
74                                 self.handle_buzz_event(arg)
75                         elif arg is CMD_OPEN:
76                                 self.handle_open_event(arg)
77                         elif arg is CMD_WAKEUP:
78                                 self.handle_wakeup_event()
79                         else:
80                                 raise Exception("Unknown command number: %d" % ev)
81         
82         class StateStart(State):
83                 def handle_pins_event(self):
84                         super().handle_pins_event()
85                         thepins = self.pins()
86                         for pin in thepins:
87                                 if pin is None:
88                                         return None
89                         if thepins.door_locked:
90                                 return StateZu
91                         else:
92                                 return StateAuf
93
94         class StateZu(State):
95                 def handle_pins_event(self):
96                         super().handle_pins_event()
97                         pins = self.pins()
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)
103         
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?
109                         self.tries = 0
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:
114                                 if cb is not None:
115                                         cb(s)
116                 def handle_pins_event(self):
117                         super().handle_pins_event()
118                         pins = self.pins()
119                         if not pins.door_locked:
120                                 self.notify(True)
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
130                         if over > nexttry:
131                                 if self.tries < OPEN_REPEAT_NUMBER:
132                                         self.actor().act(Actor.CMD_OPEN)
133                                         self.tries += 1
134                                 else:
135                                         logger.critical("Couldn't open door after %d tries. Going back to StateZu." % OPEN_REPEAT_NUMBER)
136                                         self.notify(False)
137                                         return StateZu(self.state_machine)
138         
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)
145         
146         class StateAboutToOpen(AbstractStateWhereOpeningIsRedundant):
147                 def handle_pins_event(self):
148                         super().handle_pins_event()
149                         pins = self.pins()
150                         if pins.door_locked:
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()
156                         now = time.time()
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):
160                                 ret = f();
161                                 if ret is not None:
162                                         return ret
163         
164         class StateAuf(AbstractStateWhereOpeningIsRedundant):
165                 def __init__(self,sm):
166                         super().__init__(sm)
167                         self.last_buzzed = None
168                 def handle_pins_event(self):
169                         super().handle_pins_event()
170                         pins = self.pins()
171                         if pins.bell_ringing:
172                                 now = time.time()
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)
180                         if pins.door_locked:
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
185         
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):
190                         super().__init__(sm)
191                         self.callbacks=[]
192                         # FIXME: can we send "202 processing: Trying to close the door" here? Are the callbacks multi-use?
193                         self.tries = 0
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:
199                                 if cb is not None:
200                                         cb(s)
201                 def handle_pins_event(self):
202                         pins = self.pins()
203                         if not pins.door_locked:
204                                 self.notify(True)
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
211                         if over > nexttry:
212                                 if self.tries < CLOSE_REPEAT_NUMBER:
213                                         self.actor().act(Actor.CMD_CLOSE)
214                                         self.tries += 1
215                                 else:
216                                         logger.critical("Couldn't close door after %d tries. Going back to StateAboutToOpen." % CLOSE_REPEAT_NUMBER)
217                                         self.notify(False)
218                                         return StateAboutToOpen(self.state_machine)
219         
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)
230         
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)
241         
242         def __init__(self, actor):
243                 self.actor = actor
244                 self.callback = ThreadFunction(self._callback)
245                 self.current_state = StateStart(self)
246                 self.pins = None
247                 self.old_pins = None
248         
249         def stop (self):
250                 self.callback.stop()
251         
252         def _callback(self, cmd, arg=None):
253                 # update pins
254                 if cmd == StateMachine.CMD_PINS:
255                         self.pins = arg
256                 # handle stuff
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)