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