from time import time class WindowBlind(object): def __init__(self, tu, td, outUp, outDown): self.idle = BlindIdle(outUp, outDown) self.moveUp = BlindMoving(tu, outUp, outDown) self.moveDown = BlindMoving(td, outDown, outUp) self.idle.enter() self.__state = self.idle def run(self): nextstate = self.__state.next(self) if nextstate != self.__state: nextstate.enter() self.__state = nextstate self.__state.run() def up(self): self.__state.setNextState(self.moveUp) def down(self): self.__state.setNextState(self.moveDown) class BlindState(object): def enter(self): self.lastChange = time() self.nextState = self self.running = True class BlindMoving(BlindState): def __init__(self, timeout, outOn, outOff): self.timeout, self.outOn, self.outOff = timeout, outOn, outOff def run(self): self.outOn.on() self.outOff.off() def next(self, statemachine): return self if self.running and time() - self.lastChange <= self.timeout else statemachine.idle def setNextState(self, state): self.running = False class BlindIdle(BlindState): def __init__(self, outUp, outDown): self.outUp, self.outDown = outUp, outDown def run(self): self.outUp.off() self.outDown.off() def next(self, statemachine): return self if time() - self.lastChange <= .5 else self.nextState def setNextState(self, state): self.nextState = state