def test_trivial_case(self): grammar = 'rulename = abc "def"\nabc = "abc"' rulename = 'rulename' edge = Edge('abc', 'abc') edge2 = Edge('def', 'def') final_edge = Edge('', FINAL_STATE) state = State('abc', edge2, is_automata=True) state2 = State('def', final_edge) start_state = State(START_STATE, edge) final_state = State(FINAL_STATE) states = [start_state, state, state2, final_state] expected = StateMachine(rulename, states) rulename = 'abc' sub_edge = Edge('abc', 'abc') sub_final_edge = Edge('', FINAL_STATE) sub_state = State('abc', sub_final_edge) sub_start_state = State(START_STATE, sub_edge) sub_final_state = State(FINAL_STATE) states = [sub_start_state, sub_state, sub_final_state] submachine = StateMachine(rulename, states) expected.register_automata(submachine) actual = choices_parser.parse_from_string(grammar) logger.debug(f'Actual: {actual}') logger.debug(f'Expected: {expected}') assert_state_machines_equal(actual, expected)
def test_sub_machines(self): machine = StateMachine(id_='a', states=[ State(START_STATE, Edge('', 'b')), State('b', Edge('a', FINAL_STATE), is_automata=True), State(FINAL_STATE, Edge('', START_STATE)) ]) submachine_b = StateMachine(id_='b', states=[ State(START_STATE, Edge('b', FINAL_STATE)), State(FINAL_STATE, Edge('', START_STATE)) ]) machine.register_automata(submachine_b) start_record = StateRecord('a', START_STATE, 0, 0) nested_start_record = StateRecord('b', START_STATE, 0, 1) submachine_record = StateRecord('a', 'b_internal', 0, 1, [nested_start_record]) b_record = StateRecord('a', 'b', 1, 2) state_records = [start_record, submachine_record, b_record] result = (True, state_records, 2) self.assertEqual(machine.accepts_partial('ba'), result)
def setUp(self): self.base_sm = StateMachine("test_state_machine", ["exit", "__preempted__"]) self.state1 = TestState("test1", ["s2"]) self.state2 = TestState("test2", ["s3"]) self.state3 = TestState("test3", ["exit"]) self.base_sm.add_state(self.state1, {"s2": "test2"}, initial=True) self.base_sm.add_state(self.state2, {"s3": "test3"}) self.base_sm.add_state(self.state3, {}) self.sms = [] self.sms.append(self.base_sm) for i in range(100): sm = StateMachine("test_state_machine" + str(i), ["exit"]) sm.add_state(self.sms[i], {}, initial=True) self.sms.append(sm) self.top_sm = self.sms[-1]
def bot(): replyStack = list() msg_in_json = request.get_json() msg_in_string = json.dumps(msg_in_json) replyToken = msg_in_json["events"][0]['replyToken'] userID = msg_in_json["events"][0]['source']['userId'] msgType = msg_in_json["events"][0]['message']['type'] if msgType != 'text': reply(replyToken, ['Only text is allowed.']) return 'OK', 200 sent = msg_in_json["events"][0]['message']['text'].lower().strip() if sent == 'reset': filebase.remove_user(userID) reply(replyToken, ['ลบข้อมูล State Machine บน firebase แล้ว']) return 'OK', 200 if sent in ['สวัสดี','สวัสดีจ้า','สวัสดีครับ','สวัสดีค่ะ','สวัสดีค้าบ','hello','hi','ทัก']: reply(replyToken, ['สวัสดีจ้า :)']) return 'OK', 200 state = StateMachine(push, token=userID) all_data = compute(sent) this_intention = all_data['intent'] this_information = all_data['frame'] state.get_input(this_intention, this_information) print("Intent:", this_intention) print("IR:", this_information) return 'OK', 200
def test_edge_traversal_order(self): machine = StateMachine(states=[ State(START_STATE, Edge('', 'a')), State('a', [Edge('a', 'a'), Edge('', FINAL_STATE)]), State(FINAL_STATE) ]) start_record = gen_test_state_record(START_STATE, 0, 0) a_record = gen_test_state_record('a', 0, 0) end_record = gen_test_state_record(FINAL_STATE, 0, 0) state_records = [start_record, a_record] result = (True, state_records, 0) self.assertEqual(machine.accepts_partial('aab'), result) start_record = gen_test_state_record(START_STATE, 0, 0) a_record = gen_test_state_record('a', 0, 1) a_record_2 = gen_test_state_record('a', 1, 1) state_records = [start_record, a_record, a_record_2] result = (True, state_records, 1) self.assertEqual(machine.accepts_partial('aab'), result) start_record = gen_test_state_record(START_STATE, 0, 0) a_record = gen_test_state_record('a', 0, 1) a_record_2 = gen_test_state_record('a', 1, 2) a_record_3 = gen_test_state_record('a', 2, 2) state_records = [start_record, a_record, a_record_2, a_record_3] result = (True, state_records, 2) self.assertEqual(machine.accepts_partial('aab'), result) self.assertEqual(machine.accepts_partial('aab'), (False, None, -1))
def test_parenthized_alternative_repeated_alternative_tokens_case(self): rulename = 'rulename' elements = 'abc / 2*("def" / "ghi")' edge = Edge('abc', 'abc') edge2 = Edge('def', 'def') edge3 = Edge('ghi', 'ghi') edge2_2 = Edge('def', 'def_2') edge3_2 = Edge('ghi', 'ghi_2') edge2_2 = Edge('def', 'def_2') edge2_e = Edge('def', 'def_2') edge3_2 = Edge('ghi', 'ghi_2') final_edge = Edge('', FINAL_STATE) state = State('abc', final_edge, is_automata=True) state2 = State('def', [edge2_2, edge3_2]) state3 = State('ghi', [edge2_2, edge3_2]) state2_2 = State('def_2', [edge2_2, edge3_2, final_edge]) state3_2 = State('ghi_2', [edge2_2, edge3_2, final_edge]) start_state = State(START_STATE, [edge, edge2, edge3]) final_state = State(FINAL_STATE) states = [ start_state, state, state2, state3, state2_2, state3_2, final_state ] expected = StateMachine(rulename, states) actual = choices_parser.parse_elements(rulename, elements) assert_state_machines_equal(actual, expected)
def __init__(self, name, state, conf): self._name = name # consensus module self._state = state self._log = Log() self._state_machine = StateMachine() self._server_list = conf.server_list self._total_nodes = conf.total_node self._commit_index = 0 self._current_term = 0 self._last_applied = 0 self._last_log_index = 0 self._last_log_term = None self._state.set_server(self) class ReadThread(threading.Thread): def run(thread): pass class WriteThread(threading.Thread): def run(thread): pass self.read_thread = ReadThread() self.write_thread = WriteThread() self.read_thread.daemon = True self.read_thread.start() self.write_thread.daemon = True self.write_thread.start()
def __init__(self): # getting access to elements in DroneVideo and FlightstatsReciever super(DroneMaster,self).__init__() # Seting up a timestamped folder inside Flight_Info that will have the pictures & log of this flight self.droneRecordPath= (expanduser("~")+"/drone_workspace/src/ardrone_lab/src/Flight_Info/" + datetime.datetime.now().strftime("%m-%d-%Y__%H:%M:%S, %A")+"_Flight"+"/") if not os.path.exists(self.droneRecordPath): os.makedirs(self.droneRecordPath) self.logger = Logger(self.droneRecordPath, "AR Drone Flight") self.logger.Start() self.settingsPath = expanduser("~")+"/drone_workspace/src/ardrone_lab/src/resources/calibrater_settings.txt" # initalizing the state machine that will handle which algorithms to run at which time; # the results of the algorithms will be used to control the drone self.stateMachine = StateMachine() #self.stateMachine = StateMachine((ReturnToColorDirective('orange'),30)) # drone starts without any machine loaded, so that it can be controlled using the keyboard self.currMachine = None # initalizing helper objects self.process = ProcessVideo() self.controller = BasicDroneController("TraceCircle") self.startTimer = time.clock() self.waitTime = 0 self.moveTime = 0
def test_chords(): state_machine = StateMachine() midi_client = MidiClient() state_machine.on_change_chord.append(midi_client.on_chord_change) sleep_time = 1 state_machine.set_current_chord(Notes.c, ChordTypes.major) midi_client.do_stroke() time.sleep(sleep_time) state_machine.set_current_chord(Notes.c, ChordTypes.minor) midi_client.do_stroke() time.sleep(sleep_time) state_machine.set_current_chord(Notes.c, ChordTypes.diminished) midi_client.do_stroke() time.sleep(sleep_time) state_machine.set_current_chord(Notes.c, ChordTypes.major_seventh) midi_client.do_stroke() time.sleep(sleep_time) state_machine.set_current_chord(Notes.c, ChordTypes.minor_seventh) midi_client.do_stroke() time.sleep(sleep_time) state_machine.set_current_chord(Notes.c, ChordTypes.dominant_seventh) midi_client.do_stroke() time.sleep(sleep_time) state_machine.set_current_chord(Notes.c, ChordTypes.suspended) midi_client.do_stroke() time.sleep(sleep_time) state_machine.set_current_chord(Notes.c, ChordTypes.augmented) midi_client.do_stroke() time.sleep(sleep_time) del midi_client
def test_continuation_works(self): machine = StateMachine(states=[ State(START_STATE, Edge('a', FINAL_STATE)), State(FINAL_STATE, Edge('', START_STATE)) ]) start_record = gen_test_state_record(START_STATE, 0, 1) state_records = [start_record] result = (True, state_records, 1) self.assertEqual(machine.accepts_partial('aaa'), result) end_record = gen_test_state_record(FINAL_STATE, 1, 1) start_record = gen_test_state_record(START_STATE, 0, 1) start_record2 = gen_test_state_record(START_STATE, 1, 2) state_records = [start_record, end_record, start_record2] result = (True, state_records, 2) self.assertEqual(machine.accepts_partial('aaa'), result) start_record = gen_test_state_record(START_STATE, 0, 1) end_record = gen_test_state_record(FINAL_STATE, 1, 1) start_record2 = gen_test_state_record(START_STATE, 1, 2) end_record2 = gen_test_state_record(FINAL_STATE, 2, 2) start_record3 = gen_test_state_record(START_STATE, 2, 3) state_records = [ start_record, end_record, start_record2, end_record2, start_record3 ] result = (True, state_records, 3) self.assertEqual(machine.accepts_partial('aaa'), result) self.assertEqual(machine.accepts_partial('aaa'), (False, None, -1))
def test_state_machine_init_method(): """Basic testing for the State Machine init method """ # Setup state_machine = StateMachine() # Setup def decision(): return 'state2' def decision2(): return 'state3' state1 = State(name="state1", routine_function=fun_routine, decision_function=decision, entry_function=fun_entry, exit_function=fun_exit, is_async=False) state2 = State(name="state2", routine_function=fun_routine, decision_function=decision2, entry_function=fun_entry, exit_function=fun_exit, is_async=False) state3 = State(name="state3", routine_function=fun_routine, decision_function=decision, is_async=False) state_machine.add_states(state3, state2, state1) state_machine.initial_state = "state1"
def test_undispach_event(self): sm_test = StateMachine() sm_test.sm['load'] = {1: print("test")} sm_test.inicia_tread() sm_test.on_event(event=1, args=None) sm_test.finaliza_tread() assert 1 == sm_test.events_queue.getLenth()
def setup_state_machine(self): # This is where we will initialize states, create a state machine, add # state transitions to the state machine, and start the state machine. hungup_state = HungUpState(self) recording_state = RecordingState(self) ending_state = EndingState(self) reviewing_state = ReviewingState(self) greeting_state = GreetingState(self) self.state_machine = StateMachine() self.state_machine.add_transition(recording_state, Event.DTMF_OCTOTHORPE, reviewing_state) self.state_machine.add_transition(recording_state, Event.HANGUP, hungup_state) self.state_machine.add_transition(recording_state, Event.DTMF_STAR, recording_state) self.state_machine.add_transition(reviewing_state, Event.HANGUP, hungup_state) self.state_machine.add_transition(reviewing_state, Event.DTMF_OCTOTHORPE, ending_state) self.state_machine.add_transition(reviewing_state, Event.DTMF_STAR, recording_state) self.state_machine.add_transition(greeting_state, Event.HANGUP, hungup_state) self.state_machine.add_transition(greeting_state, Event.PLAYBACK_COMPLETE, recording_state) self.state_machine.start(greeting_state)
def __init__(self, parent_window: Window) -> None: self.parent_window: Window = parent_window self.position: int = 0 self.state_machine: StateMachine = StateMachine() self.change_state: Callable[[str, any], None] = None self.key_handler: KeyHandler = KeyHandler() self.bind_keys()
def test_is_child_final_true(self): m = StateMachine() s = m.create_state('final', CompositeState) f = s.create_state('sfinal', FinalState) s.set_state(f) e = Event() self.assertTrue(guards.is_child_final(e, s))
def test_is_child_final_false(self): m = StateMachine() s = m.create_state('final', CompositeState) c = s.create_state('s') s.set_state(c) e = Event() self.assertFalse(guards.is_child_final(e, s))
def test_no_states(self): error = None try: StateMachine("test_state_machine", [])._run() except TransitionError as e: error = e assert error is not None
def __init__(self): # Setting the screen self.screen = pygame.display.set_mode( (settings.WINDOW_WIDTH, settings.WINDOW_HEIGHT)) pygame.display.set_caption('Bird') # Creating the virtual screen self.surface = pygame.Surface( (settings.VIRTUAL_WIDTH, settings.VIRTUAL_HEIGHT)) self.background_x = 0 self.ground_x = 0 self.clock = pygame.time.Clock() self.state_machine = StateMachine({ 'start': states.StartState, 'count': states.CountState, 'play': states.PlayState, 'score': states.ScoreState, }) self.state_machine.change('start') pygame.mixer.music.load('sounds/choco_birds_run.mp3') pygame.mixer.music.play(loops=-1) settings.GAME_SOUNDS['jump'].set_volume(0.5) settings.GAME_SOUNDS['death'].set_volume(0.5)
def test_continuation_with_internal_repetition(self): machine = StateMachine(states=[ State(START_STATE, Edge('', 'a')), State('a', [Edge('a', 'a'), Edge('', FINAL_STATE)]), State(FINAL_STATE) ]) start_record = gen_test_state_record(START_STATE, 0, 0) a_record = gen_test_state_record('a', 0, 0) state_records = [start_record, a_record] result = (True, state_records, 0) self.assertEqual(machine.accepts_partial('aab'), result) start_record = gen_test_state_record(START_STATE, 0, 0) a_record = gen_test_state_record('a', 0, 1) a_record_2 = gen_test_state_record('a', 1, 1) state_records = [start_record, a_record, a_record_2] result = (True, state_records, 1) self.assertEqual(machine.accepts_partial('aab'), result) start_record = gen_test_state_record(START_STATE, 0, 0) a_record = gen_test_state_record('a', 0, 1) a_record_2 = gen_test_state_record('a', 1, 2) a_record_3 = gen_test_state_record('a', 2, 2) state_records = [start_record, a_record, a_record_2, a_record_3] result = (True, state_records, 2) self.assertEqual(machine.accepts_partial('aab'), result) self.assertEqual(machine.accepts_partial('aab'), (False, None, -1))
async def run(robot: cozmo.robot.Robot): """ Causes the robot to play one-robot soccer. Args: robot: The robot to play soccer with. """ await initialize_robot(robot) # start streaming robot.camera.image_stream_enabled = True robot.camera.color_image_enabled = True robot.stateMachine = StateMachine(robot) await robot.stateMachine.changeState(goto_ball.HitBall(2.5)) await robot.set_head_angle(cozmo.util.degrees(robot.HEAD_ANGLE)).wait_for_completed() await robot.set_lift_height(0, 10000).wait_for_completed() while True: # Update the delta time since the last frame. current_time = time.time() robot.delta_time = current_time - robot.prev_time robot.prev_time = current_time await update_sensors(robot) if do_movement: await robot.stateMachine.update() await post_update(robot) if robot.gui: robot.gui.updated.set()
def __init__(self, id): self.id = id # unique id for this RaftServer self.state_machine = StateMachine() # Persistent state on a server. self.current_term = 0 self.voted_for = None # candidate_id that received vote # in current term self.log = Log() # Volatile state on a server. self.commit_index = 0 # index of highest log entry known # to be committed self.last_applied = 0 # index of highest log entry applied # to state machine # Volatile state on a leader. (Reinitialized after election.) # for each server, index of next log # entry to send to that server: self.next_index = [] # for each server, index of highest # log entry known to be replicated on server: self.match_index = [] self.leader_id = self.NO_LEADER self.num_votes = 0 # votes for this candidate self.state = self.State.FOLLOWER self.heartbeat_thread = None # for leader to assert authority self.candidate_thread = None # for candidate to grab votes self.election_timeout = 100 # random number for now
def setUp(self): chatbot = StateMachine('chatbot') active_state = chatbot.create_state('active', CompositeState) sleeping_state = chatbot.create_state('sleeping', State) chatbot.initial_state = active_state active_state.add_transition_to(sleeping_state, 'sunset') sleeping_state.add_transition_to(active_state, 'sunrise') happy_state = active_state.create_state('happy') sad_state = active_state.create_state('sad') happy_state.add_transition_to(sad_state, 'criticism') sad_state.add_transition_to(happy_state, 'praise') active_state.initial_state = happy_state active_state.initialise() chatbot.initialise() self.chatbot = chatbot self.active_state = active_state self.sleeping_state = sleeping_state self.happy_state = happy_state self.sad_state = sad_state self.sunrise = Event('sunrise') self.sunset = Event('sunset') self.criticism = Event('criticism') self.praise = Event('praise')
def test_notify_child(self): m = StateMachine() composite_state = m.create_state('composite', CompositeState) target_state = m.create_state('target') composite_state.add_transition_to(target_state, 'tick') substate_source = composite_state.create_state('substate1') substate_target = composite_state.create_state('substate2') substate_source.add_transition_to(substate_target, 'tick') substate_source.on_end = MagicMock() substate_target.on_start = MagicMock() composite_state.initial_state = substate_source composite_state.initialise() m.initial_state = composite_state m.initialise() # Test, expecting the composite state's machine to transition e = Event('tick') m.notify(e) # Verify self.assertEqual(composite_state, m.current_state) self.assertEqual(substate_target, composite_state.current_state) self.assertEqual(1, substate_source.on_end.call_count) self.assertEqual(1, substate_target.on_start.call_count)
def test_create_state(self): m = StateMachine() cs = CompositeState('composite', m) ss = cs.create_state('substate1') self.assertIsInstance(ss, State)
def setUp(self): self.sm = StateMachine("test_state_machine", ["exit", "__preempted__"]) self.state1 = TestStateLoop("test1", ["s2", "s3"]) self.state2 = TestStateLoop("test2", ["s1", "s1"]) self.state3 = TestStateLoop("test3", ["s1", "exit"]) self.sm.add_state(self.state1, {"s2": "test2", "s3": "test3"}, initial=True) self.sm.add_state(self.state2, {"s1": "test1"}) self.sm.add_state(self.state3, {"s1": "test1"})
def __init__(self, val): super().__init__(val) self.location = "Home" self.peeNeed = 5 self.cookingStew = False self.fsm = StateMachine(self) self.fsm.globalState = WifeGlobalState() self.fsm.currentState = WifeClean()
def test_is_final_state_using_subclass(self): class AnotherFinalState(FinalState): pass m = StateMachine() s = m.create_state('final', AnotherFinalState) e = Event() self.assertTrue(guards.is_final_state(e, s))
def __init__(self, escapable: bool = False): self.escapable: bool = escapable self.state_machine: StateMachine = StateMachine() self.position: int = 0 self.key_handler: KeyHandler = KeyHandler() self._caption: str = "" self.pyglet_window: pyglet.window.Window = None self.bind_keys()
def setUp(self): self.iterations_num = 3 self.sm = StateMachine("test_state_machine", ["exit", "__preempted__"]) self.state1 = TestState("test1", ["s2", "s3"], execute_iterations=self.iterations_num) self.state2 = TestState("test2", ["s3", "s1"], execute_iterations=self.iterations_num) self.state3 = TestState("test3", ["exit", "s1"], execute_iterations=self.iterations_num) self.sm.add_state(self.state1, {"s2": "test2", "s3": "test3"}, initial=True) self.sm.add_state(self.state2, {"s1": "test1", "s3": "test3"}) self.sm.add_state(self.state3, {"s2": "test2", "s1": "test1"})
def test_without_test_bank(self): state_machine = StateMachine() search = Mock() state_machine._search = search response = state_machine._handle(0, new_question_message) assert response is None search.get_search_results.assert_called_with(question)