Merge branch 'master' of ralfj.de:saartuer
[saartuer.git] / statemachine.py
index 893287a53237351f7c290d8b3c07b1adb36f6e7c..a019eef83ad0054d6108b0d2c457365db92df319 100644 (file)
@@ -1,6 +1,6 @@
 from libtuer import ThreadFunction, logger, fire_and_forget
 from actor import Actor
-import os, random, time
+import os, random, time, threading
 
 # logger.{debug,info,warning,error,critical}
 
@@ -11,7 +11,7 @@ def play_sound (what):
                logger.error("StateMachine: Unable to list sound files in %s" % (SOUNDS_DIRECTORY+what))
                return
        soundfile = SOUNDS_DIRECTORY + what + '/' + random.choice(soundfiles)
-       fire_and_forget ([SOUNDS_PLAYER,soundfile], logger.error, "StateMachine: ")
+       fire_and_forget_cmd ([SOUNDS_PLAYER,soundfile], logger.error, "StateMachine: ")
 
 
 # StateUnlocking constants
@@ -22,14 +22,14 @@ OPEN_REPEAT_NUMBER = 3
 CLOSE_REPEAT_TIMEOUT = 7
 CLOSE_REPEAT_NUMBER = 3
 
+# StateFallback constants
+FALLBACK_LEAVE_DELAY_LOCK = 5 # seconds
+
 # StateAboutToOpen constants
 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")),\
        (10, lambda:play_sound("flipswitch")), (10, lambda:play_sound("flipswitch")), (0, lambda:logger.error("Space open but switch not flipped for 30 seconds")),\
-       (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"))]
-
-# StateAuf constants
-#  time that must pass between two bell_ringing events to buzz the door again (seconds)
-AUF_BELLBUZZ_REPEAT_TIME = 2
+       (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")),
+       (59*60, lambda:logger.critical("Space open but switch not flipped for one hour"))]
 
 # Timeout we wait after the switch was switched to "Closed", until we assume nobody will open the door and we just lock it
 # ALso the time we wait after the door was opend, till we assume something went wrong and start nerving
@@ -78,12 +78,16 @@ class StateMachine():
                        arg("200 okay: buzz executed")
                def handle_cmd_unlock_event(self,arg):
                        if arg is not None:
-                               arg("412 Precondition Failed: The current state (%s) cannot handle the OPEN event" % self.__class__.__name__)
+                               arg("412 Precondition Failed: The current state (%s) cannot handle the UNLOCK command. Try again later." % self.__class__.__name__)
                def handle_wakeup_event(self):
                        if self._nerver is not None:
                                return self._nerver.nerv()
+               def on_leave(self):
+                       pass
                def pins(self):
                        return self.state_machine.pins
+               def old_pins(self):
+                       return self.state_machine.old_pins
                def actor(self):
                        return self.state_machine.actor
                def handle_event(self,ev,arg): # don't override
@@ -98,98 +102,160 @@ class StateMachine():
                        else:
                                raise Exception("Unknown command number: %d" % ev)
        
+       class AbstractNonStartState(State):
+               def handle_pins_event(self):
+                       if self.pins().door_locked != (not self.pins().space_active):
+                               self.actor().act(Actor.CMD_RED_ON)
+                       else:
+                               self.actor().act(Actor.CMD_RED_OFF)
+                       return super().handle_pins_event()
+       
+       class AbstractLockedState(AbstractNonStartState):
+               '''A state with invariant "The space is locked", switching to StateAboutToOpen when the space becomes unlocked'''
+               def __init__(self, sm, nervlist = None):
+                       super().__init__(sm, nervlist)
+                       self.actor().act(Actor.CMD_GREEN_OFF)
+               def handle_pins_event(self):
+                       if not self.pins().door_locked:
+                               logger.info("Door unlocked, space is about to open")
+                               return StateMachine.StateAboutToOpen(self.state_machine)
+                       return super().handle_pins_event()
+       
+       class AbstractUnlockedState(AbstractNonStartState):
+               '''A state with invariant "The space is unlocked", switching to StateZu when the space becomes locked'''
+               def __init__(self, sm, nervlist = None):
+                       super().__init__(sm, nervlist)
+                       self.actor().act(Actor.CMD_GREEN_ON)
+               def handle_pins_event(self):
+                       if self.pins().door_locked:
+                               logger.info("Door locked, closing space")
+                               if self.pins().space_active:
+                                       logger.warning("StateMachine: door manually locked, but space switch is still on - going to StateZu")
+                                       play_sound("manual_lock")
+                               return StateMachine.StateZu(self.state_machine)
+                       return super().handle_pins_event()
+       
        class StateStart(State):
+               def __init__(self, sm, nervlist = None, fallback=False):
+                       super().__init__(sm, nervlist)
+                       self.fallback = fallback
                def handle_pins_event(self):
-                       super().handle_pins_event()
                        pins = self.pins()
-                       if pins.door_locked is None or pins.door_closed is None or pins.space_active is None or pins.bell_ringing is None:
-                               return None # wait till we have all sensors non-None
-                       if pins.door_locked:
-                               return StateMachine.StateZu(self.state_machine)
-                       else:
-                               return StateMachine.StateAuf(self.state_machine)
+                       if not (pins.door_locked is None or pins.door_closed is None or pins.space_active is None or pins.bell_ringing is None):
+                               if self.fallback:
+                                       logger.info("Going to StateFallback because running in fallback mode")
+                                       return StateMachine.StateFallback(self.state_machine)
+                               if pins.door_locked:
+                                       logger.info("All sensors got a value, switching to a proper state: Space is closed")
+                                       return StateMachine.StateZu(self.state_machine)
+                               else:
+                                       logger.info("All sensors got a value, switching to a proper state: Space is (about to) open")
+                                       return StateMachine.StateAboutToOpen(self.state_machine)
+                       return super().handle_pins_event()
        
-       class StateZu(State):
+       class StateFallback(State):
+               def __init__(self, sm, nervlist = None):
+                       super().__init__(sm, nervlist)
+                       self._last_blink_time = time.time()
+                       self._red_state = False
                def handle_pins_event(self):
-                       super().handle_pins_event()
                        pins = self.pins()
-                       if not pins.door_locked:
-                               return StateMachine.StateAboutToOpen(self.state_machine)
+                       # buzz if open and bell rang
+                       if pins.space_active and pins.bell_ringing and not self.old_pins().bell_ringing:
+                               logger.info("StateFallback: Space switch on and door bell rung => buzzing")
+                               self.actor().act(Actor.CMD_BUZZ)
+                       # set green LED according to space switch
+                       if pins.space_active:
+                               self.actor().act(Actor.CMD_GREEN_ON)
+                       else:
+                               self.actor().act(Actor.CMD_GREEN_OFF)
+                       # primitive leaving procedure if space switch turned off
+                       if not pins.space_active and self.old_pins().space_active:
+                               def _close_after_time():
+                                       time.sleep(FALLBACK_LEAVE_DELAY_LOCK)
+                                       self.actor().act(Actor.CMD_LOCK)
+                               fire_and_forget(_close_after_time)
+                       # not calling superclass because we want to stay in fallback mode
+               def handle_wakeup_event(self):
+                       # blink red LED
+                       now = time.time()
+                       if self._red_state:
+                               self.actor().act(Actor.CMD_RED_OFF)
+                               self._red_state = False
+                       else:
+                               self.actor().act(Actor.CMD_RED_ON)
+                               self._red_state = True
+                       self._last_blink_time = now
+               def handle_cmd_unlock_event(self,arg):
+                       if arg is not None:
+                               arg("298 Fallback Okay: Trying to unlock the door. The System is in fallback mode, success information is not available.")
+                       self.actor().act(Actor.CMD_UNLOCK)
+       
+       class StateZu(AbstractLockedState):
                def handle_cmd_unlock_event(self,callback):
-                       # intentionally not calling super() implementation
                        return StateMachine.StateUnlocking(self.state_machine, callback)
+               def handle_pins_event(self):
+                       if not self.old_pins().space_active and self.pins().space_active: # first thing to check: edge detection
+                               logger.info("Space toggled to active while it was closed - unlocking the door")
+                               return StateMachine.StateUnlocking(self.state_machine)
+                       return super().handle_pins_event()
        
-       class StateUnlocking(State):
+       class StateUnlocking(AbstractLockedState):
                def __init__(self,sm,callback=None):
                        # construct a nervlist
                        nervlist = [(OPEN_REPEAT_TIMEOUT, lambda: self.actor().act(Actor.CMD_UNLOCK)) for t in range(OPEN_REPEAT_NUMBER)]
                        nervlist += [(OPEN_REPEAT_TIMEOUT, self.could_not_open)]
                        super().__init__(sm,nervlist)
                        self.callbacks=[callback]
-                       # TODO: can we send "202 processing: Trying to open the door" here? Are the callbacks multi-use?
+                       # TODO: can we send "202 processing: Trying to unlock the door" here? Are the callbacks multi-use?
                        self.actor().act(Actor.CMD_UNLOCK)
                def notify(self, did_it_work):
-                       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))
+                       s = "200 okay: door unlocked" if did_it_work else ("500 internal server error: Couldn't unlock door with %d tries à %f seconds" % (OPEN_REPEAT_NUMBER,OPEN_REPEAT_TIMEOUT))
                        for cb in self.callbacks:
                                if cb is not None:
                                        cb(s)
-               def handle_pins_event(self):
-                       super().handle_pins_event()
-                       pins = self.pins()
-                       if not pins.door_locked:
-                               self.notify(True)
-                               return StateMachine.StateAboutToOpen(self.state_machine)
+               def on_leave(self):
+                       self.notify(not self.pins().door_locked)
                def handle_cmd_unlock_event(self,callback):
-                       # intentionally not calling super() implementation
                        # TODO: 202 notification also here if possible
                        self.callbacks.append(callback)
                def could_not_open(self):
-                       logger.critical("Couldn't open door after %d tries. Going back to StateZu." % OPEN_REPEAT_NUMBER)
-                       self.notify(False)
+                       logger.critical("StateMachine: Couldn't open door after %d tries. Going back to StateZu." % OPEN_REPEAT_NUMBER)
                        return StateMachine.StateZu(self.state_machine)
        
-       class AbstractStateWhereOpeningIsRedundant(State):
+       class AbstractStateWhereUnlockingIsRedundant(AbstractUnlockedState):
                def handle_cmd_unlock_event(self, callback):
-                       # intentionally not calling super() implementation
                        callback("299 redundant: Space seems to be already open. Still processing your request tough.")
-                       logger.info("Received OPEN command in StateAboutToOpen. This should not be necessary.")
+                       logger.info("StateMachine: Received UNLOCK command in %s. This should not be necessary." % self.__class__.__name__)
                        self.actor().act(Actor.CMD_UNLOCK)
        
-       class StateAboutToOpen(AbstractStateWhereOpeningIsRedundant):
+       class StateAboutToOpen(AbstractStateWhereUnlockingIsRedundant):
                def __init__(self, sm):
                        super().__init__(sm, ABOUTOPEN_NERVLIST)
                def handle_pins_event(self):
-                       super().handle_pins_event()
                        pins = self.pins()
-                       if pins.door_locked:
-                               return StateMachine.StateZu(self.state_machine)
-                       elif pins.space_active:
+                       if pins.space_active:
+                               logger.info("Space activated, opening procedure completed")
                                return StateMachine.StateAuf(self.state_machine)
+                       return super().handle_pins_event()
        
-       class StateAuf(AbstractStateWhereOpeningIsRedundant):
+       class StateAuf(AbstractStateWhereUnlockingIsRedundant):
                def __init__(self,sm):
-                       super().__init__(sm)
+                       nervlist = [(24*60*60, lambda: logger.critical("Space is now open for 24h. Is everything all right?"))]
+                       super().__init__(sm, nervlist)
                        self.last_buzzed = None
                def handle_pins_event(self):
-                       super().handle_pins_event()
                        pins = self.pins()
-                       if pins.bell_ringing:
-                               # TODO: use old_pins instead of a timer
-                               now = time.time()
-                               if self.last_buzzed is None or now-self.last_buzzed < AUF_BELLBUZZ_REPEAT_TIME:
-                                       logger.info("buzzing because of bell ringing in state auf")
-                                       self.actor().act(Actor.CMD_BUZZ)
-                                       self.last_buzzed = now
+                       if pins.bell_ringing and not self.old_pins().bell_ringing: # first thing to check: edge detection
+                               # someone just pressed the bell
+                               logger.info("StateMachine: buzzing because of bell ringing in StateAuf")
+                               self.actor().act(Actor.CMD_BUZZ)
                        if not pins.space_active:
-                               logger.info("space switch off - starting leaving procedure")
+                               logger.info("StateMachine: space switch turned off - starting leaving procedure")
                                return StateMachine.StateAboutToLeave(self.state_machine)
-                       if pins.door_locked:
-                               logger.info("door manually locked, but space switch on - going to StateZu")
-                               play_sound("manual_lock")
-                               return StateMachine.StateZu(self.state_machine)
+                       return super().handle_pins_event()
        
-       class StateLocking(State):
-               # TODO: share code with StateUnlocking
+       class StateLocking(AbstractUnlockedState):
                def __init__(self,sm):
                        # construct a nervlist
                        nervlist = [(CLOSE_REPEAT_TIMEOUT, lambda: self.actor().act(Actor.CMD_LOCK)) for t in range(CLOSE_REPEAT_NUMBER)]
@@ -201,46 +267,48 @@ class StateMachine():
                        pins = self.pins()
                        if not pins.door_closed:
                                # TODO play a sound? This shouldn't happen, door was opened while we are locking
-                               logger.warning("door manually opened during locking")
+                               logger.warning("StateMachine: door manually opened during locking")
                                return StateMachine.StateAboutToOpen(self.state_machine)
-                       if pins.door_locked:
-                               return StateMachine.StateZu(self.state_machine)
+                       # TODO do anything here if the switch is activated now?
+                       return super().handle_pins_event()
                def handle_cmd_unlock_event(self,callback):
-                       callback("409 conflict: The server is currently trying to lock the door. Try again later.")
+                       callback("409 conflict: The sphinx is currently trying to lock the door. Try again later.")
                def could_not_close(self):
-                       logger.critical("Couldn't close door after %d tries. Going back to StateAboutToOpen." % CLOSE_REPEAT_NUMBER)
+                       logger.critical("StateMachine: Couldn't close door after %d tries. Going back to StateAboutToOpen." % CLOSE_REPEAT_NUMBER)
                        return StateMachine.StateAboutToOpen(self.state_machine)
        
-       class StateAboutToLeave(State):
+       class StateAboutToLeave(AbstractUnlockedState):
                def __init__(self, sm):
                        nervlist = [(LEAVE_TIMEOUT, lambda: StateMachine.StateLocking(self.state_machine))]
                        super().__init__(sm, nervlist)
                def handle_pins_event(self):
                        if not self.pins().door_closed:
                                return StateMachine.StateLeaving(self.state_machine)
-                       if self.pins().door_locked:
-                               return StateMachine.StateZu(self.state_machine)
                        if self.pins().space_active:
+                               logger.info("Space re-activated, cancelling leaving procedure")
                                return StateMachine.StateAuf(self.state_machine)
+                       return super().handle_pins_event()
        
-       class StateLeaving(State):
+       class StateLeaving(AbstractUnlockedState):
                def __init__(self, sm):
                        nervlist = [(LEAVE_TIMEOUT, lambda: StateMachine.StateAboutToOpen(self.state_machine))]
                        super().__init__(sm, nervlist)
                def handle_pins_event(self):
                        if self.pins().door_closed:
+                               logger.info("The space was left, locking the door")
                                return StateMachine.StateLocking(self.state_machine)
-                       if self.pins().door_locked:
-                               return StateMachine.StateZu(self.state_machine)
                        if self.pins().space_active:
+                               logger.info("Space re-activated, cancelling leaving procedure")
                                return StateMachine.StateAuf(self.state_machine)
+                       return super().handle_pins_event()
        
-       def __init__(self, actor):
+       def __init__(self, actor, waker, fallback = False):
                self.actor = actor
                self.callback = ThreadFunction(self._callback, name="StateMachine")
-               self.current_state = StateMachine.StateStart(self)
+               self.current_state = StateMachine.StateStart(self, fallback=fallback)
                self.pins = None
                self.old_pins = None
+               waker.register(lambda: self.callback(StateMachine.CMD_WAKEUP), 1.0) # wake up every second
        
        def stop (self):
                self.callback.stop()
@@ -253,6 +321,8 @@ class StateMachine():
                newstate = self.current_state.handle_event(cmd,arg) # returns None or an instance of the new state
                self.old_pins = self.pins
                while newstate is not None:
-                       logger.debug("StateMachine: new state = %s" % newstate.__class__.__name__)
+                       assert isinstance(newstate, StateMachine.State), "I should get a state"
+                       self.current_state.on_leave()
+                       logger.debug("StateMachine: Doing state transition %s -> %s" % (self.current_state.__class__.__name__, newstate.__class__.__name__))
                        self.current_state = newstate
                        newstate = self.current_state.handle_event(StateMachine.CMD_PINS, self.pins)