class ATMStateMachine(StateMachine): """ This class is strongly protects the condition of the atm device. Prevent unauthorized requests from being made arbitrarily. """ ## State ready = State('Ready', initial=True) card_inserted = State('CardInserted') pin_checked = State('PinChecked') account_selected = State('AccountSelected') error = State('Error') ## Action insert_card = ready.to(card_inserted) check_pin_number = card_inserted.to(pin_checked) get_account_list = pin_checked.to(pin_checked) select_account = pin_checked.to(account_selected) check_balance = account_selected.to(account_selected) deposit = account_selected.to(account_selected) withdraw = account_selected.to(account_selected) finish = card_inserted.to(ready) | pin_checked.to( ready) | account_selected.to(ready) need_fix = ready.to(error)
class BMSChargeStateMachine(StateMachine): idle = State("Idle", initial=True)#, value=1) bulk_chg = State("ConstCurChg")#, value=2) absorb_chg = State("ConstVoltChg")#, value=3) float_chg = State("FloatChg")#, value=4) canceled = State("CancelChg")#, value=5) bulk = idle.to(bulk_chg) absorb = bulk_chg.to(absorb_chg) floating = absorb_chg.to(float_chg) rebulk = bulk_chg.from_(absorb_chg, float_chg) cancel = canceled.from_(bulk_chg, absorb_chg, float_chg) # canceled is the final state and cannot be cycled back to idle # create a new state machine to restart the charge cycle cycle = bulk | absorb | floating def on_enter_idle(self): if (getattr(self.model, "on_enter_idle", None) != None): self.model.on_enter_idle() def on_enter_bulk_chg(self): if (getattr(self.model, "on_enter_bulk_chg", None) != None): self.model.on_enter_bulk_chg() def on_enter_absorb_chg(self): if (getattr(self.model, "on_enter_absorb_chg", None) != None): self.model.on_enter_absorb_chg() def on_enter_float_chg(self): if (getattr(self.model, "on_enter_float_chg", None) != None): self.model.on_enter_float_chg()
class StartUpMachine(StateMachine): user_id = None not_started = State("Not started", initial=True) entering_login = State("Entering login") entering_city = State("Entering city") entering_oo = State("Entering OO") entering_school = State("Entering school") reset = not_started.from_(entering_login, entering_city, entering_oo, entering_school, not_started) sent_start = entering_login.from_(not_started) sent_login = entering_city.from_(entering_login) sent_city = entering_oo.from_(entering_city) sent_oo = entering_school.from_(entering_oo) cycle = sent_start | sent_login | sent_oo | sent_city @staticmethod def from_user_id(user_id): q = Query() try: p = db.db.search(q.user_id == user_id)[0]["start_value"] except IndexError: p = None m = StartUpMachine(start_value=p) m.user_id = user_id return m def save(self): q = Query() db.db.upsert({ "user_id": self.user_id, "start_value": self.model.state }, q.user_id == self.user_id)
class MissionStateMachine(StateMachine): # Defined States in the Mission State Machine init = State('init', initial=True) stageOne = State('stageOne') stageTwo = State('stageTwo') stageThree = State('stageThree') # Defined Transitions initEnd = init.to(stageOne) triggerOne = stageOne.to(stageTwo) triggerTwo = stageTwo.to(stageThree) # Executed when entering stages def on_enter_stageOne(self): print(":::: STAGE ONE ENTERED :::: ") def on_enter_stageTwo(self): print(":::: STAGE TWO ENTERED :::: ") def on_enter_stageThree(self): print(":::: STAGE THREE ENTERED :::: ") # Executed when exiting stages def on_exit_stageOne(self): print("S1:Transition to Stage 2") def on_exit_stageTwo(self): print("S2:Transition to Stage 3") def on_exit_stageThree(self): print(":::: SYSTEM SHUTDOWN :::: ")
def test_transition(self): sm = StateMachine() sm.add(State('online', is_starting_state=True)) sm.add(State('offline')) sm.add(Transition('online', ['offline'])) sm.transition_to('offline')
class CampaignMachine(StateMachine): "A workflow machine" draft = State('Draft', initial=True) producing = State('Being produced') add_job = draft.to(draft) | producing.to(producing) produce = draft.to(producing)
class PingPongMachine(StateMachine): # States. playerA = State('PlayerA', initial=True) playerB = State('PlayerB') # Transitions. #pingpong = playerA.to(playerB) #pingpong = playerB.to(playerA) pingpongA = playerA.to(playerB) pingpongB = playerB.to(playerA) def on_enter_playerA(self): print('Enter playerA.') def on_exit_playerA(self): print('Exit playerA.') def on_enter_playerB(self): print('Enter playerB.') def on_exit_playerB(self): print('Exit playerB.') def on_pingpongA(self): print('Pingpong.') def on_pingpongB(self): print('Pingpong.')
class PlayerState(statemachine.StateMachine): from statemachine import State unconnected = State('Unconnected', initial=True) connected = State('Connected') won = State('Won') lost = State('Lost') connect = unconnected.to(connected) win = connected.to(won) lose = connected.to(lost) def on_connect(self): logging.info("Player {}: PlayerState:connect".format(self.model.uuid)) # FIXME: Hardwired grid size used here! # FIXME: Hardwired player 'UUID' used here! if self.model.is_starting_player: starting_player_id = self.model.uuid else: starting_player_id = "someone else" self.model.sock.send( "GAME-READY 3 3 {}\n".format(starting_player_id).encode()) def on_win(self): logging.info("Player {}: PlayerState:win".format(self.model.uuid)) self.model.write("GAME-WON {}".format(self.model.uuid)) def on_lose(self): logging.info("Player {}: PlayerState:lose".format(self.model.uuid)) self.model.write("GAME-WON {}".format("FIXME-THE-OTHER-PLAYER-WON"))
class UpperMachine(StateMachine): start = State('Start', initial=True) loading = State('Loading') welding = State('Welding') unloading = State('Unloading') end = State('End') Start = start.to(loading) LtoW = loading.to(welding) WtoU = welding.to(unloading) UtoL = unloading.to(end) Reset = end.to(start) def on_enter_loading(self): B.process() def on_enter_welding(self): C.welding_process() def on_enter_unloading(self): print("Unloading") D.unloading_process() def on_enter_end(self): print("fe")
def __loadOwnFormat(self, path): print("Start loading own format...") file = open(path, mode='r') fileContent = file.readlines() file.close() stateList = [] transitionList = [] marker = 0 for item in fileContent: # skip comments if "#" in item: marker = marker + 1 continue pass # add states to the list if marker == 1: state = State() state.setName(item[:-1]) stateList.append(state) pass # add transitions to list if marker == 2: transition = self.__decodeTransitionFromLine(item, stateList) transitionList.append(transition) pass pass return stateList, transitionList pass
class ApprovalMachine(StateMachine): "A workflow" requested = State('Requested', initial=True) accepted = State('Accepted') rejected = State('Rejected') validate = requested.to(accepted, rejected)
def test_hooks_order(self): result = [] def hook(s): def h(): result.append(s) return h sm = StateMachine() sm.add( State('online', is_starting_state=True, will_exit=hook('onwex'), exited=hook('onex'))) sm.add(State('offline', will_enter=hook('ofwen'), entered=hook('ofen'))) sm.add( Transition('online', ['offline'], before=hook('tb'), after=hook('ta'))) sm.transition_to('offline') assert result == ['tb', 'onwex', 'ofwen', 'onex', 'ofen', 'ta']
class ApprovalMachine(StateMachine): "A workflow machine" requested = State('Requested', initial=True) accepted = State('Accepted') rejected = State('Rejected') completed = State('Completed') @requested.to(accepted, rejected) def validate(self, *args, **kwargs): if self.model.is_ok(): self.model.accepted_at = current_time return self.model, self.accepted else: self.model.rejected_at = current_time return self.model, self.rejected @accepted.to(completed) def complete(self): self.model.completed_at = current_time @requested.to(requested) def update(self, **kwargs): for k, v in kwargs.items(): setattr(self.model, k, v) return self.model @rejected.to(requested) def retry(self): self.model.rejected_at = None return self.model
class BrokenTrafficLightMachine(StateMachine): "A broken traffic light machine" green = State('Green', initial=True) yellow = State('Yellow') blue = State('Blue') # This state is unreachable cycle = green.to(yellow) | yellow.to(green)
class CampaignMachine(StateMachine): "A workflow machine" draft = State('Draft', initial=True) producing = State('Being produced') closed = State('Closed') abort = draft.to(closed) | producing.to(closed) | closed.to(closed)
class TrafficLightMachineStateEvents(StateMachine): "A traffic light machine" green = State('Green', initial=True) yellow = State('Yellow') red = State('Red') cycle = green.to(yellow) | yellow.to(red) | red.to(green) def on_enter_state(self, state): event_mock.on_enter_state(state) def on_exit_state(self, state): event_mock.on_exit_state(state) def on_enter_green(self): event_mock.on_enter_green() def on_exit_green(self): event_mock.on_exit_green() def on_enter_yellow(self): event_mock.on_enter_yellow() def on_exit_yellow(self): event_mock.on_exit_yellow() def on_enter_red(self): event_mock.on_enter_red() def on_exit_red(self): event_mock.on_exit_red()
class MovingMachine(StateMachine): walking = State('Walking', initial=True) enraged = State('Enraged') attack = State('Attack') moving = idle.to(move) stop = moving.to(idle)
class TrafficLightMachine(StateMachine): green = State(TrafficLightColor.green.value) yellow = State(TrafficLightColor.yellow.value) red = State(TrafficLightColor.red.value, initial=True) slowdown = green.to(yellow) stop = yellow.to(red) wait = red.to(yellow) go = yellow.to(green) def __print_current_state(self): print(f"Текущее состояние {self.current_state}") def running(self): while True: if self.is_yellow: self.stop() self.__print_current_state() time.sleep(7) self.wait() self.__print_current_state() time.sleep(2) self.go() self.__print_current_state() time.sleep(2) self.slowdown() self.__print_current_state() time.sleep(1)
class BombermanSM(StateMachine): walk = State('walk', initial=True) bomb = State('bomb') finish = State('finish') # Idle is detection state walkToBomb = walk.to(bomb) bombToWalk = bomb.to(walk) walkToFinish = walk.to(finish)
def __init__(self, pin_number): super().__init__() self.add(State('high')) self.add(State('low', is_starting_state=True)) self.add(Transition('high', ['low'], after=lambda: self._change_low)) self.add(Transition('low', ['high'], after=lambda: self._change_high)) self.pin_number = pin_number
class Bezpieczenstwo(StateMachine): Praca = State('Praca ukladu', initial=True) Przypal = State('Zadzialanie zabezpieczen') Powrot = State('Powrot do procesu') # =============================================Przejscia======================================================= Awaria = Praca.to(Przypal) Safety_OK = Przypal.to(Powrot) Praca_procesu = Powrot.to(Praca)
class ShadowState(StateMachine, Observable): """Provides states and their transitions for the ShadowBot class""" alive: State = State("Alive") dead: State = State("Dead", initial=True) revive: Callable = dead.to(alive) kill: Callable = alive.to(dead)
class TrafficLightMachine(StateMachine): green = State('Green', initial=True) yellow = State('Yellow') red = State('Red') slowdown = green.to(yellow) stop = yellow.to(red) go = red.to(green)
class CampaignMachine(StateMachine): draft = State('Draft', initial=True) producing = State('Being produced') closed = State('Closed', initial=True) # Should raise an Exception when instantiated add_job = draft.to(draft) | producing.to(producing) produce = draft.to(producing) deliver = producing.to(closed)
class CampaignMachineWithKeys(StateMachine): draft = State('Draft', initial=True, value=1) producing = State('Being produced', value=2) closed = State('Closed', value=3) add_job = draft.to(draft) | producing.to(producing) produce = draft.to(producing) deliver = producing.to(closed)
class CampaignMachine(StateMachine): draft = State('Draft', initial=True) producing = State('Being produced') closed = State('Closed') add_job = draft.to(draft) | producing.to(producing) produce = draft.to(producing) deliver = producing.to(closed)
def test_add_Transition(self): sm = StateMachine() sm.add(State('f')) sm.add(State('t')) t = Transition('f', ['t']) sm.add(t) assert sm.transitions == {'f': t}
class BPMStateMachine(StateMachine): pdSendsBPM = State('pdSendsBPM', initial=True) tapTempo = State('taptempo') programBPM = State('programBPM') tapped = pdSendsBPM.to(tapTempo) tapStopped = tapTempo.to(programBPM) go = programBPM.to(pdSendsBPM)
def test_transitions_arent_two_way(self): sm = StateMachine() sm.add(State('online', is_starting_state=True)) sm.add(State('offline')) sm.add(Transition('offline', ['online'])) assert not sm.can_transition_to('offline')
class ReverseTrafficLightMachine(StateMachine): "A traffic light machine" green = State('Green', initial=True) yellow = State('Yellow') red = State('Red') stop = red.from_(yellow, green, red) cycle = green.from_(red) | yellow.from_(green) | red.from_( yellow) | red.from_.itself()
def __init__(self, manager): State.__init__(self, manager) self.sprite = Sprite() self.sprite.image = Surface((0, 0)) self.sprite.rect = Rect(0, 0, 1, options.height) self.sprite.mask = Mask((1, options.height)) self.sprite.mask.fill() self.STATE_NUMBER = manager.DEACTIVATED
def __init__(self, manager, target, sprite_filename): """manager is the base Cannon object target is the player's sprite """ State.__init__(self, manager) self.sprite = ASprite(sprite_filename, 0) self.target = target self.STATE_NUMBER = manager.STANDBY
def __init__(self, manager, position, sprite_filename, speed): """manager is the base Cannon object position is the sprite's initial rect.center coordinate """ State.__init__(self, manager) self.sprite = ASprite(sprite_filename, speed) self.sprite.rect.center = position self.direction = vector.EAST self.STATE_NUMBER = manager.FIRING
def __init__(self, manager, position, direction, sprite_sheet, height, width, delay, speed): """manager is the base EnemyBase object position is the rect.center coordinates (taken from the spinning state) direction is a vector """ State.__init__(self, manager) self.sprite = AnimatedFacingSprite(sprite_sheet, height, width, delay, speed) self.sprite.rect.center = position self.direction = direction self.STATE_NUMBER = manager.SHOOTING self.IS_FOLLOWABLE = False
def __init__(self, manager, sprite_filename, speed, top, bottom, avg_transition): """manager is the root EnemyBase object top, bottom are the boundaries of movement (rect.top <= top, etc) """ State.__init__(self, manager) self.sprite = ASprite(sprite_filename, speed) self.sprite.rect.topright = (options.width, top) self.top = top self.bottom = bottom self.current_dir = vector.SOUTH self.transition_probability = 1.0 / (avg_transition * options.max_framerate) self.STATE_NUMBER = manager.MOVING self.IS_FOLLOWABLE = True
def __init__(self, manager, position, target, sprite_sheet, height, width, delay, targ_time, shoot_time): """manager is the root EnemyBase object position is the sprite's rect.center coordinates (taken from the moving state) sprite_sheet, etc are AnimatedFacingSprite args targ_time is the frame (from start) when target direction is taken shoot_time is the frame (from start) when spinner becomes shooter and begins movement """ State.__init__(self, manager) self.sprite = AnimatedFacingSprite(sprite_sheet, height, width, delay, 0) self.sprite.rect.center = position self.target = target self.targ_time = targ_time self.shoot_time = shoot_time self.tick = 0 self.STATE_NUMBER = manager.SPINNING self.IS_FOLLOWABLE = False
def movesTo(self, new): return True if new == State2 else State.movesTo(self, new) class State2(State):
def __init__(self, cat): State.__init__(self, "roaming") self.cat = cat
def __init__(self, parent, name, next_state): State.__init__(self, parent, name) self.next_state = next_state self.blocks = ()
from twisted.internet.endpoints import TCP4ClientEndpoint from txzmq import ZmqFactory, ZmqEndpoint, ZmqREPConnection, ZmqEndpointType, ZmqPubConnection from statemachine import StateMachine, State from incoming import MESSAGE_PARSERS, MESSAGE_NAMES, FieldCount, Done from config import Config from inspect import isgeneratorfunction import logging log = logging.getLogger(__name__) # States for TWS protocol state machine. Disconnected = State('Disconnected') Connecting = State('Connecting') WaitingForMessageID = State('WaitingForMessageID') WaitingForGenerator = State('WaitingForGenerator', 'generator fieldcount cumfieldcount') Connecting.fieldcount = 2 WaitingForMessageID.fieldcount = 2 class IBTWSProtocol(StateMachine, LineOnlyReceiver): delimiter = '\0' CLIENT_VERSION = 59 states = { Disconnected, Connecting, WaitingForMessageID, WaitingForGenerator }
def movesTo(self, new): State.movesTo(self, new) State1.movesTo = {State2: State1.advance}
def __init__(self, cat): State.__init__(self, "eating") self.cat = cat
def __init__(self, parent, name, success_state): State.__init__(self, parent, name) self.success_state = success_state self.fixed_up_top_key = None
# INIT 2 check_deps.checkroot() # Initialise the ddrescue xfer log name ddrescue.set_ddrlog(OPTIONS) # device size in sectors DEVSIZE = helpers.get_device_size(OPTIONS.device) USED = parse_args.check_used(OPTIONS) manualY = False # If MetaRescue is interrupted, resume will assume all clones were a success partinfo = helpers.getpartinfo(OPTIONS.device) # Start ddrescueview if required if hasattr(OPTIONS, 'noshow') and OPTIONS.noshow == False: ddrescue.start_viewer(OPTIONS) # STATES MetaClone = State('Transfer Clonable Metadata', "partinfo = clone.clonemeta(OPTIONS, DEVSIZE, partinfo)") StartBtrace = State('Btrace', "btrace.start_bgproc(OPTIONS.device, DEVSIZE); BTRACE_POLL_COUNT = 0") AddStartEnd = State('Mark Start & End 1Mi Used', "btrace.add_used_extent(start=0, size=2048); " + "btrace.add_used_extent(size=2048, next=DEVSIZE)") PTRead = State('Auto TestDisk', "ptable = pt.PartitionTable(testdisk.get_list(OPTIONS.device), OPTIONS, DEVSIZE)") PTAskUser = State('Manual TestDisk?', "manualY = testdisk.question_manual(ptable)") PTManual = State('Manual TestDisk', "testdiskrunning = testdisk.manual(OPTIONS)") PTReadTDLog = State('Read TestDisk Log', "ptable.read_testdisk(testdisk.get_log(OPTIONS))") PTManualRpt = State('Repeat Manual TestDisk', "repeatY = testdisk.question_manual(ptable)")
def __init__(self, cat): State.__init__(self, "runningToPot") self.cat = cat