a18cb53c9f02004b61c262243dd06fc4943cd75f
[saartuer.git] / statemachine.py
1 8from 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")), (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 = 30
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                         (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 >= 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 arg is CMD_PINS:
91                                 self.handle_pins_event()
92                         elif arg is CMD_BUZZ:
93                                 self.handle_buzz_event(arg)
94                         elif arg is CMD_UNLOCK:
95                                 self.handle_cmd_unlock_event(arg)
96                         elif arg is CMD_WAKEUP:
97                                 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                         thepins = self.pins()
105                         for pin in thepins:
106                                 if pin is None:
107                                         return None
108                         if thepins.door_locked:
109                                 return StateZu(self.state_machine)
110                         else:
111                                 return StateAuf(self.state_machine)
112
113         class StateZu(State):
114                 def handle_pins_event(self):
115                         super().handle_pins_event()
116                         pins = self.pins()
117                         if not pins.door_locked:
118                                 return StateAboutToOpen(self.state_machine)
119                 def handle_cmd_unlock_event(self,callback):
120                         # intentionally not calling super() implementation
121                         return StateUnlocking(self.state_machine, callback)
122         
123         class StateUnlocking(State):
124                 def __init__(self,sm,callback=None):
125                         # construct a nervlist
126                         nervlist = [(OPEN_REPEAT_TIMEOUT, lambda: self.actor().act(Actor.CMD_UNLOCK)) for t in xrange(OPEN_REPEAT_NUMBER)]
127                         nervlist += [(OPEN_REPEAT_TIMEOUT, self.could_not_open)]
128                         super().__init__(sm,nervlist)
129                         self.callbacks=[callback]
130                         # TODO: can we send "202 processing: Trying to open the door" here? Are the callbacks multi-use?
131                         self.actor().act(Actor.CMD_UNLOCK)
132                 def notify(self, did_it_work):
133                         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))
134                         for cb in self.callbacks:
135                                 if cb is not None:
136                                         cb(s)
137                 def handle_pins_event(self):
138                         super().handle_pins_event()
139                         pins = self.pins()
140                         if not pins.door_locked:
141                                 self.notify(True)
142                                 return StateAboutToOpen(self.state_machine)
143                 def handle_cmd_unlock_event(self,callback):
144                         # intentionally not calling super() implementation
145                         # TODO: 202 notification also here if possible
146                         self.callbacks.append(callback)
147                 def could_not_open(self):
148                         logger.critical("Couldn't open door after %d tries. Going back to StateZu." % OPEN_REPEAT_NUMBER)
149                         self.notify(False)
150                         return StateZu(self.state_machine)
151         
152         class AbstractStateWhereOpeningIsRedundant(State):
153                 def handle_cmd_unlock_event(self, callback):
154                         # intentionally not calling super() implementation
155                         callback("299 redundant: Space seems to be already open. Still processing your request tough.")
156                         logger.info("Received OPEN command in StateAboutToOpen. This should not be necessary.")
157                         self.actor().act(Actor.CMD_UNLOCK)
158         
159         class StateAboutToOpen(AbstractStateWhereOpeningIsRedundant):
160                 def __init__(self, sm):
161                         super().__init__(sm, ABOUTOPEN_NERVLIST)
162                 def handle_pins_event(self):
163                         super().handle_pins_event()
164                         pins = self.pins()
165                         if pins.door_locked:
166                                 return StateZu(self.state_machine)
167                         elif pins.space_active:
168                                 return StateAuf(self.state_machine)
169         
170         class StateAuf(AbstractStateWhereOpeningIsRedundant):
171                 def __init__(self,sm):
172                         super().__init__(sm)
173                         self.last_buzzed = None
174                 def handle_pins_event(self):
175                         super().handle_pins_event()
176                         pins = self.pins()
177                         if pins.bell_ringing:
178                                 # TODO: use old_pins instead of a timer
179                                 now = time.time()
180                                 if self.last_buzzed is None or now-self.last_buzzed < AUF_BELLBUZZ_REPEAT_TIME:
181                                         logger.info("buzzing because of bell ringing in state auf")
182                                         self.actor().act(Actor.CMD_BUZZ)
183                                         self.last_buzzed = now
184                         if not pins.space_active:
185                                 logger.info("space switch off - starting leaving procedure")
186                                 return StateAboutToLeave(self.state_machine)
187                         if pins.door_locked:
188                                 logger.info("door manually locked, but space switch on - going to StateZu")
189                                 play_sound("manual_lock")
190                                 return StateZu(self.state_machine)
191         
192         class StateLocking(State):
193                 # TODO: share code with StateUnlocking
194                 def __init__(self,sm):
195                         # construct a nervlist
196                         nervlist = [(CLOSE_REPEAT_TIMEOUT, lambda: self.actor().act(Actor.CMD_LOCK)) for t in range(CLOSE_REPEAT_NUMBER)]
197                         nervlist += [(CLOSE_REPEAT_TIMEOUT, self.could_not_close)]
198                         super().__init__(sm, nervlist)
199                         if not pins.door_closed: # this should always be true, but just to be sure...
200                                 self.actor().act(Actor.CMD_LOCK)
201                 def handle_pins_event(self):
202                         pins = self.pins()
203                         if not pins.door_closed:
204                                 # TODO play a sound? This shouldn't happen, door was opened while we are locking
205                                 logger.warning("door manually opened during locking")
206                                 return StateAboutToOpen(self.state_machine)
207                         if pins.door_locked:
208                                 return SpaceZu(self.state_machine)
209                 def handle_cmd_unlock_event(self,callback):
210                         callback("409 conflict: The server is currently trying to lock the door. Try again later.")
211                 def could_not_close(self):
212                         logger.critical("Couldn't close door after %d tries. Going back to StateAboutToOpen." % CLOSE_REPEAT_NUMBER)
213                         return StateAboutToOpen(self.state_machine)
214         
215         class StateAboutToLeave(State):
216                 def __init__(self, sm):
217                         nervlist = [(LEAVE_TIMEOUT, lambda: StateLocking(self.state_machine))]
218                         super().__init__(sm, nervlist)
219                 def handle_pins_event(self):
220                         if not self.pins().door_closed:
221                                 return StateLeaving(self.state_machine)
222                         if self.pins().door_locked:
223                                 return StateZu(self.state_machine)
224         
225         class StateLeaving(State):
226                 def __init__(self, sm):
227                         nervlist = [(LEAVE_TIMEOUT, lambda: StateAboutToOpen(self.state_machine))]
228                         super().__init__(sm, nervlist)
229                 def handle_pins_event(self):
230                         if self.pins().door_closed:
231                                 return StateLocking(self.state_machine)
232                         if self.pins().door_locked:
233                                 return StateZu(self.state_machine)
234         
235         def __init__(self, actor):
236                 self.actor = actor
237                 self.callback = ThreadFunction(self._callback)
238                 self.current_state = StateStart(self)
239                 self.pins = None
240                 self.old_pins = None
241         
242         def stop (self):
243                 self.callback.stop()
244         
245         def _callback(self, cmd, arg=None):
246                 # update pins
247                 if cmd == StateMachine.CMD_PINS:
248                         self.pins = arg
249                 # handle stuff
250                 newstate = self.current_state.handle_event(cmd,arg) # returns None or an instance of the new state
251                 self.old_pins = self.pins
252                 while newstate is not None:
253                         logger.info("StateMachine: new state = %s" % newstate.__class__.__name__)
254                         self.current_state = newstate
255                         newstate = self.current_state.handle_event(StateMachine.CMD_PINS, self.pins)