pyledriver/stateMachine.py

361 lines
12 KiB
Python
Raw Normal View History

2017-06-11 04:27:03 -04:00
'''
Controls and manages state of the alarm system. The design follows a reactor-
like model (similar to twisted) except the statemachine itself is passive (eg it
does not run/block on its own thread waiting for events). Instead the
StateMachine object holds the current status as well as the logic to move
between states, while child threads (listeners) deliver signals to the state
machine in response to external events. The state machine itself does not "wait"
but rather its selectState method could be called within any child thread (hence
the lock) which also means the entry/exit functions of each state are run within
the signal-originating child thread.
'''
2016-12-30 02:51:56 -05:00
import RPi.GPIO as GPIO
import time, logging, enum, os
2017-06-11 18:45:23 -04:00
from threading import Lock, Event
2016-12-30 02:51:56 -05:00
from functools import partial
from collections import namedtuple
from exceptionThreading import ExceptionThread
from config import stateFile
from sensors import startDoorSensor, startMotionSensor
2017-05-31 00:41:42 -04:00
from gmail import intruderAlert
2016-12-30 02:51:56 -05:00
from listeners import KeypadListener, PipeListener
from blinkenLights import Blinkenlights
from soundLib import SoundLib
from webInterface import startWebInterface
2017-06-03 01:28:57 -04:00
from stream import Camera, FileDump
2016-12-30 02:51:56 -05:00
logger = logging.getLogger(__name__)
class _SIGNALS(enum.Enum):
2017-06-11 04:27:03 -04:00
'''
Valid signals the statemachine can recieve. The consequence of each signal
depends on the current state
'''
2017-06-08 01:43:14 -04:00
ARM = enum.auto()
INSTANT_ARM = enum.auto()
2017-06-17 01:28:44 -04:00
LOCK = enum.auto()
INSTANT_LOCK = enum.auto()
2017-06-08 01:43:14 -04:00
DISARM = enum.auto()
TIMOUT = enum.auto()
TRIGGER = enum.auto()
class _CountdownTimer(ExceptionThread):
'''
Launches thread which self terminates after some time (given in seconds).
Termination triggers some action (a function). Optionally, a sound can be
assigned to each 'tick'
'''
def __init__(self, countdownSeconds, action, sound=None):
self._stopper = Event()
def countdown():
for i in range(countdownSeconds, 0, -1):
if self._stopper.isSet():
return None
if sound and i < countdownSeconds:
sound.play()
time.sleep(1)
action()
super().__init__(target=countdown, daemon=True)
self.start()
def stop(self):
self._stopper.set()
def __del__(self):
self.stop()
def _resetUSBDevice(device):
'''
Resets a USB device using the de/reauthorization method. This is really
crude but works beautifully
'''
devpath = os.path.join('/sys/bus/usb/devices/' + device + '/authorized')
with open(devpath, 'w') as f:
f.write('0')
with open(devpath, 'w') as f:
f.write('1')
logger.debug('Reset USB device: %s', devpath)
2016-12-30 02:51:56 -05:00
class _State:
2017-06-11 04:27:03 -04:00
'''
Represents one discrete status of the system. Each state has a set of entry
and exit functions and optionaly has sound that can play upon state entry.
States link to other states via the addTransition function, which links
another state with a signal. In this way, many states can be linked together
in a network.
There is currently nothing stopping multiple states from sharing the same
name...try not to be an idiot. This mostly matters in equality tests, which
only compares the name
'''
2017-06-10 01:18:36 -04:00
def __init__(self, name, entryCallbacks=[], exitCallbacks=[], sound=None):
2016-12-30 02:51:56 -05:00
self.name = name
self.entryCallbacks = entryCallbacks
self.exitCallbacks = exitCallbacks
2017-06-10 01:13:51 -04:00
self._transTbl = {}
2016-12-30 02:51:56 -05:00
2017-06-10 01:18:36 -04:00
self._sound = sound
2016-12-30 02:51:56 -05:00
def entry(self):
2017-05-30 02:11:15 -04:00
logger.info('entering ' + self.name)
2017-06-10 01:18:36 -04:00
if self._sound:
self._sound.play()
2016-12-30 02:51:56 -05:00
for c in self.entryCallbacks:
c()
def exit(self):
2017-05-30 02:11:15 -04:00
logger.info('exiting ' + self.name)
2017-06-10 01:18:36 -04:00
if self._sound:
self._sound.stop()
2016-12-30 02:51:56 -05:00
for c in self.exitCallbacks:
c()
def next(self, signal):
if signal in _SIGNALS:
2017-06-10 01:13:51 -04:00
return self if signal not in self._transTbl else self._transTbl[signal]
2017-06-08 01:43:14 -04:00
else:
raise Exception('Illegal signal')
2017-06-10 01:13:51 -04:00
def addTransition(self, signal, state):
2017-06-10 02:15:16 -04:00
self._transTbl[signal] = state
2016-12-30 02:51:56 -05:00
def __str__(self):
return self.name
def __eq__(self, other):
return self.name == other
class StateMachine:
2017-06-11 04:27:03 -04:00
'''
Manager for states. This is intended to be used as a context manager (eg
"with" statement) for brevity...and because there should only be one.
Init is responsible for setting up all objects (including child threads) as
well as contructing the state network. Each thread functions as some kind of
listener (or supports one) that wait for an event to happen.
Note we distinguish between "managed" and "non-managed" objects; the former
need to be started/stopped to ensure things get cleaned. Managed objects are
added to the managed list with _addManaged, which also returns a ref to the
object for other uses.
Upon opening the context, all threads are started. Note that not all threads
are managed; some are started and forgotten, as these require no cleanup.
Managed threads are started with _startManaged and stopped with _stopManaged
upon closing the context. This system has the added benefit of not trying to
stop an object that has not been initialized, as it cannot appear in the
managed list otherwise
During steady-state operation, the receiver for signals that make things
happen is selectState, intended to be called from any of the state machine's
child threads. This calls the current state's "next" method and sets the
result as the new current state. Note the lock because it could be called by
any number of listeners simultaneously
'''
def __init__(self):
self._lock = Lock()
self._managed = []
self.soundLib = self._addManaged(SoundLib())
self.fileDump = self._addManaged(FileDump())
self._addManaged(Camera())
2016-12-30 02:51:56 -05:00
# add signals to self to avoid calling partial every time
for sig in _SIGNALS:
2017-06-10 01:56:42 -04:00
setattr(self, sig.name, partial(self.selectState, sig))
2017-06-08 01:02:31 -04:00
secretTable = {
'dynamoHum': self.DISARM,
'zombyWoof': self.ARM,
2017-06-17 01:28:44 -04:00
'imTheSlime': self.INSTANT_ARM,
'fiftyFifty': self.LOCK,
'dentalFloss': self.INSTANT_LOCK
2017-06-08 01:02:31 -04:00
}
def secretCallback(secret, logger):
if secret in secretTable:
secretTable[secret]()
logger.debug('Secret pipe listener received: \"%s\"', secret)
elif logger:
logger.debug('Secret pipe listener received invalid secret')
self._addManaged(PipeListener(callback=secretCallback, name= 'secret'))
2017-06-08 01:02:31 -04:00
self._addManaged(KeypadListener(stateMachine=self, callbackDisarm=self.DISARM,
callbackArm=self.ARM, passwd='5918462'))
2017-06-08 01:02:31 -04:00
2016-12-30 02:51:56 -05:00
def startTimer(t, sound):
self._timer = _CountdownTimer(t, self.TIMOUT, sound)
2016-12-30 02:51:56 -05:00
def stopTimer():
if self._timer.is_alive():
self._timer.stop()
self._timer = None
2017-06-03 19:11:06 -04:00
LED = self._addManaged(Blinkenlights(17))
blinkingLED = partial(LED.setBlink, True)
2017-06-08 02:15:50 -04:00
sfx = self.soundLib.soundEffects
2017-06-03 19:11:06 -04:00
stateObjs = [
_State(
2016-12-30 02:51:56 -05:00
name = 'disarmed',
entryCallbacks = [partial(LED.setBlink, False)],
2017-06-10 01:18:36 -04:00
sound = sfx['disarmed']
2016-12-30 02:51:56 -05:00
),
_State(
2017-06-08 02:15:50 -04:00
name = 'disarmedCountdown',
2017-06-10 01:18:36 -04:00
entryCallbacks = [blinkingLED, partial(startTimer, 30, sfx['disarmedCountdown'])],
exitCallbacks = [stopTimer],
sound = sfx['disarmedCountdown']
2016-12-30 02:51:56 -05:00
),
_State(
2017-06-08 02:15:50 -04:00
name = 'armed',
2017-06-10 01:18:36 -04:00
entryCallbacks = [blinkingLED],
sound = sfx['armed']
2016-12-30 02:51:56 -05:00
),
2017-06-17 01:28:44 -04:00
_State(
name = 'lockedCountdown',
entryCallbacks = [blinkingLED, partial(startTimer, 30, sfx['disarmedCountdown'])],
exitCallbacks = [stopTimer],
sound = sfx['disarmedCountdown']
),
_State(
name = 'locked',
entryCallbacks = [blinkingLED],
sound = sfx['armed']
),
_State(
2016-12-30 02:51:56 -05:00
name = 'armedCountdown',
2017-06-10 01:18:36 -04:00
entryCallbacks = [blinkingLED, partial(startTimer, 30, sfx['armedCountdown'])],
exitCallbacks = [stopTimer],
sound = sfx['armedCountdown']
2016-12-30 02:51:56 -05:00
),
_State(
2016-12-30 02:51:56 -05:00
name = 'triggered',
2017-06-10 01:18:36 -04:00
entryCallbacks = [blinkingLED, intruderAlert],
sound = sfx['triggered']
2016-12-30 02:51:56 -05:00
)
2017-06-03 19:11:06 -04:00
]
2017-06-10 01:56:42 -04:00
self.states = st = namedtuple('States', [obj.name for obj in stateObjs])(*stateObjs)
2016-12-30 02:51:56 -05:00
st.disarmed.addTransition( _SIGNALS.ARM, st.disarmedCountdown)
st.disarmed.addTransition( _SIGNALS.INSTANT_ARM, st.armed)
2017-06-17 01:28:44 -04:00
st.disarmed.addTransition( _SIGNALS.LOCK, st.lockedCountdown)
st.disarmed.addTransition( _SIGNALS.INSTANT_LOCK, st.locked)
2016-12-30 02:51:56 -05:00
st.disarmedCountdown.addTransition( _SIGNALS.DISARM, st.disarmed)
st.disarmedCountdown.addTransition( _SIGNALS.TIMOUT, st.armed)
st.disarmedCountdown.addTransition( _SIGNALS.INSTANT_ARM, st.armed)
2017-06-17 01:28:44 -04:00
st.disarmedCountdown.addTransition( _SIGNALS.LOCK, st.lockedCountdown)
st.disarmedCountdown.addTransition( _SIGNALS.INSTANT_LOCK, st.locked)
2017-06-10 01:13:51 -04:00
st.armed.addTransition( _SIGNALS.DISARM, st.disarmed)
st.armed.addTransition( _SIGNALS.TRIGGER, st.armedCountdown)
2017-06-17 01:28:44 -04:00
st.armed.addTransition( _SIGNALS.LOCK, st.lockedCountdown)
st.armed.addTransition( _SIGNALS.INSTANT_LOCK, st.locked)
st.lockedCountdown.addTransition( _SIGNALS.DISARM, st.disarmed)
st.lockedCountdown.addTransition( _SIGNALS.TIMOUT, st.locked)
st.lockedCountdown.addTransition( _SIGNALS.INSTANT_LOCK, st.locked)
st.lockedCountdown.addTransition( _SIGNALS.ARM, st.disarmedCountdown)
st.lockedCountdown.addTransition( _SIGNALS.INSTANT_ARM, st.armed)
st.locked.addTransition( _SIGNALS.DISARM, st.disarmed)
st.locked.addTransition( _SIGNALS.TRIGGER, st.armedCountdown)
st.locked.addTransition( _SIGNALS.ARM, st.disarmedCountdown)
st.locked.addTransition( _SIGNALS.INSTANT_ARM, st.armed)
2017-06-10 01:13:51 -04:00
st.armedCountdown.addTransition( _SIGNALS.DISARM, st.disarmed)
st.armedCountdown.addTransition( _SIGNALS.TIMOUT, st.triggered)
st.armedCountdown.addTransition( _SIGNALS.ARM, st.armed)
st.armedCountdown.addTransition( _SIGNALS.INSTANT_ARM, st.armed)
2017-06-17 01:28:44 -04:00
st.armedCountdown.addTransition( _SIGNALS.LOCK, st.locked)
st.armedCountdown.addTransition( _SIGNALS.INSTANT_LOCK, st.locked)
2017-06-10 01:13:51 -04:00
st.triggered.addTransition( _SIGNALS.DISARM, st.disarmed)
st.triggered.addTransition( _SIGNALS.ARM, st.armed)
st.triggered.addTransition( _SIGNALS.INSTANT_ARM, st.armed)
2017-06-17 01:28:44 -04:00
st.triggered.addTransition( _SIGNALS.LOCK, st.locked)
st.triggered.addTransition( _SIGNALS.INSTANT_LOCK, st.locked)
2017-06-10 01:13:51 -04:00
self.currentState = getattr(self.states, stateFile['state'])
2016-12-30 02:51:56 -05:00
def __enter__(self):
_resetUSBDevice('1-1')
2017-06-11 04:27:03 -04:00
# start all managed threads (we retain ref to these to stop them later)
self._startManaged()
2017-06-17 01:28:44 -04:00
activeSensorStates = (self.states.armed, self.states.armedCountdown, self.states.triggered)
def sensorAction(location, logger):
2017-06-17 01:28:44 -04:00
cst = self.currentState
level = logging.INFO if cst in activeSensorStates else logging.DEBUG
logger.log(level, 'detected motion: ' + location)
2017-06-17 01:28:44 -04:00
if cst == self.states.armed:
self.selectState(_SIGNALS.TRIGGER)
def videoAction(location, logger, pin):
sensorAction(location, logger)
2017-06-17 01:28:44 -04:00
cst = self.currentState
if cst in activeSensorStates:
self.fileDump.addInitiator(pin)
2017-06-17 01:28:44 -04:00
while GPIO.input(pin) and cst in activeSensorStates:
time.sleep(0.1)
self.fileDump.removeInitiator(pin)
2017-06-17 01:28:44 -04:00
activeDoorStates = activeSensorStates + (self.states.locked,)
2016-12-30 02:51:56 -05:00
def doorAction(closed, logger):
self.soundLib.soundEffects['door'].play()
2017-06-17 01:28:44 -04:00
cst = self.currentState
level = logging.INFO if cst in activeDoorStates else logging.DEBUG
entry = 'door closed' if closed else 'door opened'
logger.log(level, entry)
2017-06-17 01:28:44 -04:00
if not closed and cst == self.states.armed or cst == self.states.locked:
self.selectState(_SIGNALS.TRIGGER)
2017-06-11 04:27:03 -04:00
# start non-managed threads (we forget about these because they can exit with no cleanup)
startMotionSensor(5, 'Nate\'s room', sensorAction)
startMotionSensor(19, 'front door', sensorAction)
startMotionSensor(26, 'Laura\'s room', sensorAction)
startMotionSensor(6, 'deck window', partial(videoAction, pin=6))
startMotionSensor(13, 'kitchen bar', partial(videoAction, pin=13))
startDoorSensor(22, doorAction)
startWebInterface(self)
self.currentState.entry()
2017-06-10 01:13:51 -04:00
def __exit__(self, exception_type, exception_value, traceback):
self._stopManaged()
2016-12-30 02:51:56 -05:00
def selectState(self, signal):
with self._lock:
2016-12-30 02:51:56 -05:00
nextState = self.currentState.next(signal)
if nextState != self.currentState:
self.currentState.exit()
self.currentState = nextState
self.currentState.entry()
stateFile['state'] = self.currentState.name
def _addManaged(self, obj):
self._managed.append(obj)
return obj
def _startManaged(self):
for m in self._managed:
m.start()
def _stopManaged(self):
for m in self._managed:
m.stop()