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