update diargam for "open" in about-to-open
[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 # StateAboutToOpen constants
22 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")),\
23         (20, lambda:play_sound("flipswitch")), (30, lambda:play_sound("flipswitch")), (30, lambda:Logger.error("Space open but switch not flipped for 30 seconds")),\
24         (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"))]
25
26 # StateAuf constants
27 #  time that must pass between two bell_ringing events to buzz the door again (seconds)
28 AUF_BELLBUZZ_REPEAT_TIME = 2
29
30 # play_sound constants
31 SOUNDS_DIRECTORY = "/opt/tuer/sounds/"
32 SOUNDS_PLAYER = "/usr/bin/mplayer"
33
34
35 class StateMachine():
36         # commands you can send
37         CMD_PINS = 0
38         CMD_BUZZ = 1
39         CMD_OPEN = 2
40         CMD_WAKEUP = 3
41         CMD_LAST = 4
42         
43         class State():
44                 def __init__(self, state_machine):
45                         self.state_machine = state_machine
46                         self.time_entered = time.time()
47                         self.theDict = None
48                         self.last_wakeup = self.time_entered
49                 def handle_pins_event(self):
50                         pass # one needn't implement this
51                 def handle_buzz_event(self,arg): # this shouldn't be overwritten
52                         self.actor.act(Actor.CMD_BUZZ)
53                         arg("200 okay: buzz executed")
54                 def handle_open_event(self,arg):
55                         if arg is not None:
56                                 arg("412 Precondition Failed: The current state (%s) cannot handle the OPEN event" % self.__class__.__name__)
57                 def handle_wakeup_event(self):
58                         self.last_wakeup = time.time()
59                 def pins(self):
60                         return self.state_machine.pins
61                 def actor(self):
62                         return self.state_machine.actor
63                 def handle_event(self,ev,arg): # don't override
64                         if arg is CMD_PINS:
65                                 self.handle_pins_event()
66                         elif arg is CMD_BUZZ:
67                                 self.handle_buzz_event(arg)
68                         elif arg is CMD_OPEN:
69                                 self.handle_open_event(arg)
70                         elif arg is CMD_WAKEUP:
71                                 self.handle_wakeup_event()
72                         else:
73                                 raise Exception("Unknown command number: %d" % ev)
74         
75         class StateStart(State):
76                 def handle_pins_event(self):
77                         super().handle_pins_event()
78                         thepins = self.pins()
79                         for pin in thepins:
80                                 if pin is None:
81                                         return None
82                         if thepins.door_locked:
83                                 return StateZu
84                         else:
85                                 return StateAuf
86
87         class StateZu(State):
88                 def handle_pins_event(self):
89                         super().handle_pins_event()
90                         pins = self.pins()
91                         if not pins.door_locked:
92                                 return StateAboutToOpen(self.state_machine)
93                 def handle_open_event(self,callback):
94                         # intentionally not calling super() implementation
95                         return StateOpening(callback,self.state_machine)
96         
97         class StateOpening(State):
98                 def __init__(self,callback,sm):
99                         super().__init__(self,sm)
100                         self.callbacks=[callback]
101                         # FIXME: can we send "202 processing: Trying to open the door" here? Are the callbacks multi-use?
102                         self.tries = 0
103                         self.actor().act(Actor.CMD_OPEN)
104                 def notify(self, did_it_work):
105                         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))
106                         for cb in self.callbacks:
107                                 if cb is not None:
108                                         cb(s)
109                 def handle_pins_event(self):
110                         super().handle_pins_event()
111                         pins = self.pins()
112                         if not pins.door_locked:
113                                 self.notify(True)
114                                 return StateAboutToOpen(self.state_machine)
115                 def handle_open_event(self,callback):
116                         # intentionally not calling super() implementation
117                         # FIXME: 202 notification also here if possible
118                         self.callbacks.append(callback)
119                 def handle_wakeup_event(self):
120                         super().handle_wakeup_event()
121                         over = time.time() - self.time_entered
122                         nexttry = (self.tries+1) * OPEN_REPEAT_TIMEOUT
123                         if over > nexttry:
124                                 if self.tries < OPEN_REPEAT_NUMBER:
125                                         self.actor().act(Actor.CMD_OPEN)
126                                         self.tries += 1
127                                 else:
128                                         logger.critical("Couldn't open door after %d tries. Going back to StateZu." % OPEN_REPEAT_NUMBER)
129                                         self.notify(False)
130                                         return StateZu(self.state_machine)
131         
132         class AbstractStateWhereOpeningIsRedundant(State):
133                 def handle_open_event(self, callback):
134                         # intentionally not calling super() implementation
135                         callback("299 redundant: Space seems to be already open. Still processing your request tough.")
136                         logger.warning("Received OPEN command in StateAboutToOpen. This should not be necessary.")
137                         self.actor().act(Actor.CMD_OPEN)
138         
139         class StateAboutToOpen(AbstractStateWhereOpeningIsRedundant):
140                 def handle_pins_event(self):
141                         super().handle_pins_event()
142                         pins = self.pins()
143                         if pins.door_locked:
144                                 return StateZu(self.state_machine)
145                         elif pins.space_active:
146                                 return StateAuf(self.state_machine)
147                 def handle_wakeup_event(self):
148                         super().handle_wakeup_event()
149                         now = time.time()
150                         lasttime = self.last_wakeup - self.time_entered
151                         thistime = now - self.time_entered
152                         for (t,f) in filter(lambda (t,f): t<=thistime and t>lasttime, ABOUTOPEN_NERVLIST):
153                                 ret = f();
154                                 if ret is not None:
155                                         return ret
156         
157         class StateAuf(AbstractStateWhereOpeningIsRedundant):
158                 def __init__(self,sm):
159                         super().__init__(sm)
160                         self.last_buzzed = None
161                 def handle_pins_event(self):
162                         super().handle_pins_event()
163                         pins = self.pins()
164                         if pins.bell_ringing:
165                                 now = time.time()
166                                 if self.last_buzzed is None or now-self.last_buzzed < AUF_BELLBUZZ_REPEAT_TIME:
167                                         logger.info("buzzing because of bell ringing in state auf")
168                                         self.actor().act(Actor.CMD_BUZZ)
169                                         self.last_buzzed = now
170                         if not pins.space_active:
171                                 logger.info("space switch off - starting leaving procedure")
172                                 return StateAboutToLeave(self.state_machine)
173                         if pins.door_locked:
174                                 logger.error("door manually locked, but space switch on - going to StateZu")
175                                 play_sound("manual_lock")
176                                 return StateZu(self.state_machine)
177                 # handle_wakeup_event intentionally not overwritten
178         
179         class StateClosing(State):
180                 #TODO Ralf/Conny
181                 pass
182         
183         class StateAboutToLeave(State):
184                 #TODO Ralf
185                 pass
186         
187         class StateLeaving(State):
188                 #TODO Ralf
189                 pass
190         
191         def __init__(self, actor):
192                 self.actor = actor
193                 self.callback = ThreadFunction(self._callback)
194                 self.current_state = StateStart(self)
195                 self.pins = None
196                 self.old_pins = None
197         
198         def stop (self):
199                 self.callback.stop()
200         
201         def _callback(self, cmd, arg=None):
202                 # update pins
203                 if cmd == StateMachine.CMD_PINS:
204                         self.pins = arg
205                 # handle stuff
206                 newstate = self.current_state.handle_event(cmd,arg) # returns None or an instance of the new state
207                 self.old_pins = self.pins # FIXME not used?
208                 while newstate is not None:
209                         logger.info("StateMachine: new state = %s" % newstate.__class__.__name__)
210                         self.current_state = newstate
211                         newstate = self.current_state.handle_event(StateMachine.CMD_PINS, self.pins)