def create_statemachine(self, state_machine_model): NestedState.separator = ':' states = [{ 'name': 'base', 'children': ['inactive', 'preparing', 'committed'] }] transitions = [['unavailable', 'base', 'base:inactive'], ['task_created', 'base:inactive', 'base:preparing'], ['commit', 'base:preparing', 'base:committed'], ['no_commit', 'base:committed', 'base:preparing'], ['completed', 'base:committed', 'base:inactive'], ['failed', 'base:committed', 'base:inactive'], ['default', 'base:inactive', 'base:inactive'], ['default', 'base:committed', 'base:committed'], ['default', 'base', 'base']] statemachine = Machine(model=state_machine_model, states=states, transitions=transitions, initial='base', ignore_invalid_triggers=True) statemachine.on_enter('base:inactive', 'INACTIVE') statemachine.on_enter('base:preparing', 'PREPARING') statemachine.on_enter('base:committed', 'COMMITTED') return statemachine
class ConnectionStateMachine: """HSMS Connection state machine.""" def __init__(self, callbacks=None): """ Initialize the hsms connection state machine. :param callbacks: callbacks for the state machine """ self.callbacks = {} self.states = [ STATE_NOT_CONNECTED, { 'name': STATE_CONNECTED, 'on_enter': self._on_enter_CONNECTED, 'on_exit': self._on_exit_CONNECTED, 'children': [ STATE_NOT_SELECTED, { 'name': STATE_SELECTED, 'on_enter': self._on_enter_CONNECTED_SELECTED } ] } ] # transition 1 self.machine = Machine(model=self, states=self.states, initial=STATE_NOT_CONNECTED, auto_transitions=False) if callbacks: self.callbacks = callbacks self.machine.add_transition( 'connect', STATE_NOT_CONNECTED, STATE_CONNECTED_NOT_SELECTED) # transition 2 self.machine.add_transition('disconnect', STATE_CONNECTED, STATE_NOT_CONNECTED) # transition 3 self.machine.add_transition('select', STATE_CONNECTED_NOT_SELECTED, STATE_CONNECTED_SELECTED) # transition 4 self.machine.add_transition( 'deselect', STATE_CONNECTED_SELECTED, STATE_CONNECTED_NOT_SELECTED) # transition 5 self.machine.add_transition('timeoutT7', STATE_CONNECTED_NOT_SELECTED, STATE_NOT_CONNECTED) # transition 6 def _on_enter_CONNECTED(self): if "on_enter_CONNECTED" in self.callbacks: self.callbacks["on_enter_CONNECTED"]() def _on_exit_CONNECTED(self): if "on_exit_CONNECTED" in self.callbacks: self.callbacks["on_exit_CONNECTED"]() def _on_enter_CONNECTED_SELECTED(self): if "on_enter_CONNECTED_SELECTED" in self.callbacks: self.callbacks["on_enter_CONNECTED_SELECTED"]()
def a2(): NestedState.separator = '↦' # 配置状态分隔符, 嵌套的状态会自动加上这个符号 states = [ 'A', # 状态 A 'B', # 状态 B { 'name': 'C', # 状态 C 'children':[ '1', '2', # 状态 C↦1 C↦2 { 'name': '3', # 状态 C↦3 'children': [ 'a', 'b', 'c' # 状态 C↦3↦a C↦3↦b C↦3↦c ] } ] } ] transitions = [ # 状态转移表 ['reset', 'C', 'A'], ['reset', 'C↦2', 'C'] # overwriting parent reset ] # we rely on auto transitions machine = Machine(states=states, transitions=transitions, initial='A') machine.to_B() # exit state A, enter state B machine.to_C() # exit B, enter C machine.to_C.s3.a() # enter C↦a; enter C↦3↦a; # 状态为数字, 前面加上 s 字母 print(machine.state) # if __name__ == "__main__": # a2()
def __init__(self, num_edges): self.max_edges = num_edges # stops seeking after finding this many edges self.reset_edge_count() self.ch = CliffHandler() self.states = [ 'idle', 'edge_finding', { 'name': 'clearing', 'children': self.ch, 'remap': { 'done': 'cleared' } }, { 'name': 'cleared', 'on_enter': 'check_if_done' }, 'final_move', 'mission_complete' ] Machine.__init__(self, states=self.states, initial='idle') self.add_transition('start', 'idle', 'edge_finding', before=['reset_edge_count']) self.add_transition('at_cliff', 'edge_finding', 'clearing', before=['increment_edge_count'], after='to_clearing_angle_finding') self.add_transition('at_goal', 'final_move', 'mission_complete')
def test_wrong_nesting(self): correct = ['A', {'name': 'B', 'children': self.stuff.machine}] wrong_type = ['A', {'name': 'B', 'children': self.stuff}] siblings = ['A', {'name': 'B', 'children': ['1', self.stuff.machine]}] collision = ['A', {'name': 'B', 'children': ['A', self.stuff.machine]}] m = Machine(None, states=correct) if State.separator in '_': m.to_B_C_3_a() else: m.to_B.C.s3.a() with self.assertRaises(ValueError): m = Machine(None, states=wrong_type) with self.assertRaises(ValueError): m = Machine(None, states=collision) m = Machine(None, states=siblings) if State.separator in '_': m.to_B_1() m.to_B_A() else: m.to_B.s1() m.to_B.A()
def test_blueprint_simple(self): states = ['A', 'B', 'C', 'D'] # Define with list of dictionaries transitions = [{ 'trigger': 'walk', 'source': 'A', 'dest': 'B' }, { 'trigger': 'run', 'source': 'B', 'dest': 'C' }, { 'trigger': 'sprint', 'source': 'C', 'dest': 'D' }] m = Machine(states=states, transitions=transitions, before_state_change='before_state_change', after_state_change='after_state_change', initial='A') self.assertEqual(len(m.blueprints['states']), 4) self.assertEqual(m.blueprints['states'][3], 'D') self.assertEqual(len(m.blueprints['transitions']), 3) self.assertEqual(m.blueprints['transitions'][2]['trigger'], 'sprint') m.add_transition('fly', 'D', 'A') self.assertEqual(len(m.blueprints['transitions']), 4) self.assertEqual(m.blueprints['transitions'][3]['source'], 'D')
def a1(): states = [ 'standing', # 站立 'walking', # 不行 { 'name': 'caffeinated', # 精神抖擞 'initial': 'dithering', 'children':[ 'dithering', # 抖动 'running', # 跑 ] } ] transitions = [ ['walk', 'standing', 'walking'], # 走 : 站立->步行 ['stop', 'walking', 'standing'], # 停 : 步行->站立 ['drink', "standing", 'caffeinated'], # 喝 : *->精神抖擞 ['walk', ['caffeinated', 'caffeinated_dithering'], 'caffeinated_running'], # 走 : ['relax', 'caffeinated', 'standing'], # 放松 : ] machine = Machine(states=states, transitions=transitions, initial='standing', ignore_invalid_triggers=True) # machine.walk() # Walking now # machine.stop() # let's stop for a moment machine.drink() # coffee time print(machine.state)
def test_blueprint_nested(self): c1 = NestedState('C_1', parent='C') c2 = NestedState('C_2', parent='C') c3 = NestedState('C_3', parent='C') c = NestedState('C', children=[c1, c2, c3]) states = ['A', {'name': 'B', 'on_enter': 'chirp', 'children': ['1', '2', '3']}, c, 'D'] # Define with list of dictionaries transitions = [ {'trigger': 'walk', 'source': 'A', 'dest': 'B','before': 'before_state_change', 'after': 'after_state_change' }, {'trigger': 'run', 'source': 'B', 'dest': 'C'}, {'trigger': 'sprint', 'source': 'C', 'dest': 'D'} ] m = Machine(states=states, transitions=transitions, before_state_change='before_state_change', after_state_change='after_state_change', initial='A') m.before_state_change = MagicMock() m.after_state_change = MagicMock() self.assertEqual(len(m.blueprints['states']), 4) self.assertEqual(m.blueprints['states'][3], 'D') self.assertEqual(len(m.blueprints['transitions']), 3) # transition 'walk' before should contain two calls of the same method self.assertEqual(len(m.blueprints['transitions'][0]['before']), 2) self.assertEqual(len(m.blueprints['transitions'][0]['after']), 2) self.assertEqual(len(m.blueprints['transitions'][1]['before']), 1) self.assertEqual(m.blueprints['transitions'][2]['trigger'], 'sprint') m.add_transition('fly', 'D', 'A') self.assertEqual(len(m.blueprints['transitions']), 4) self.assertEqual(m.blueprints['transitions'][3]['source'], 'D')
def __init__(self): self.nested = Nested(self) self.states = ['t1', {'name': 't2', 'children': self.nested}] Machine.__init__(self, states=self.states, initial='t1') self.add_transition(trigger='print_top', source='*', dest='=', after=self.print_msg) self.add_transition(trigger='goto_t2', source='*', dest='t2_n1')
def __init__(self): self.states = [{ 'name': 'angle_finding', 'on_enter': self.save_start_pose, 'on_exit': self.save_end_pose }, 'aligning', 'backing', 'spinning', 'done'] Machine.__init__(self, states=self.states, initial='angle_finding') self.add_transition('at_cliff', 'angle_finding', 'aligning') self.add_transition('at_goal', 'aligning', 'backing') self.add_transition('at_goal', 'backing', 'spinning') self.add_transition('at_goal', 'spinning', 'done') self.add_transition('at_goal', 'angle_finding', 'backing') self.add_transition('at_cliff', 'aligning', 'backing')
def test_blueprint_nested(self): c1 = NestedState('C_1', parent='C') c2 = NestedState('C_2', parent='C') c3 = NestedState('C_3', parent='C') c = NestedState('C', children=[c1, c2, c3]) states = [ 'A', { 'name': 'B', 'on_enter': 'chirp', 'children': ['1', '2', '3'] }, c, 'D' ] # Define with list of dictionaries transitions = [{ 'trigger': 'walk', 'source': 'A', 'dest': 'B', 'before': 'before_state_change', 'after': 'after_state_change' }, { 'trigger': 'run', 'source': 'B', 'dest': 'C' }, { 'trigger': 'sprint', 'source': 'C', 'dest': 'D' }] m = Machine(states=states, transitions=transitions, before_state_change='before_state_change', after_state_change='after_state_change', initial='A') m.before_state_change = MagicMock() m.after_state_change = MagicMock() self.assertEqual(len(m.blueprints['states']), 4) self.assertEqual(m.blueprints['states'][3], 'D') self.assertEqual(len(m.blueprints['transitions']), 3) # transition 'walk' before should contain two calls of the same method self.assertEqual(len(m.blueprints['transitions'][0]['before']), 2) self.assertEqual(len(m.blueprints['transitions'][0]['after']), 2) self.assertEqual(len(m.blueprints['transitions'][1]['before']), 1) self.assertEqual(m.blueprints['transitions'][2]['trigger'], 'sprint') m.add_transition('fly', 'D', 'A') self.assertEqual(len(m.blueprints['transitions']), 4) self.assertEqual(m.blueprints['transitions'][3]['source'], 'D')
def __init__ (self, name): annotator.__init__(self, name) self.machine = Machine(model=self, states=HFSA15._states, initial='waiting') self.machine.add_transition('start_analysis', 'waiting', 'searching_for_first_spondeus_secondF', after='_search_second') self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_secondF', 'searching_for_first_spondeus_firstF', unless=[self._found_first], after='_search_first') self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_secondF', 'searching_for_second_spondeus_firstF', conditions=[self._found_first], after='_search_first') self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_firstF', 'found_two_spondees', conditions=[self._found_second]) self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_firstF', 'searching_for_second_spondeus_fourthF', unless=[self._found_second], after='_search_fourth') self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_firstF', 'searching_for_first_spondeus_fourthF', unless=[self._found_first], after='_search_fourth') self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_firstF', 'searching_for_second_spondeus_fourthF', conditions=[self._found_first], after='_search_fourth') self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_fourthF', 'found_two_spondees', conditions=[self._found_second]) self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_fourthF', 'searching_for_second_spondeus_thirdF', unless=[self._found_second], after='_search_third') self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_fourthF', 'searching_for_first_spondeus_thirdF', unless=[self._found_first], after='_search_third') self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_fourthF', 'searching_for_second_spondeus_thirdF', conditions=[self._found_first], after='_search_third') self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_thirdF', 'found_two_spondees', conditions=[self._found_second]) self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_thirdF', 'searching_for_second_spondeus_fifthF', unless=[self._found_second], after='_search_fifth') self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_thirdF', 'no_spondeus_found', unless=[self._found_first]) self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_thirdF', 'searching_for_second_spondeus_fifthF', conditions=[self._found_first], after='_search_fifth') self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_fifthF', 'found_two_spondees', conditions=[self._found_second]) #deal with implausible spondeus positions self.machine.add_transition('search_spondeus', 'found_two_spondees', 'no_spondeus_found') self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_fifthF', 'no_spondeus_found', unless=[self._found_second]) self.machine.add_transition('not_found', 'no_spondeus_found', 'fallback') self.machine.add_transition('verified', 'fallback', 'correction', unless=[self._is_successful]) self.machine.add_transition('verified', 'fallback', 'success', conditions=[self._is_successful]) self.machine.add_transition('verified', 'found_two_spondees', 'success', conditions=[self._is_successful]) self.machine.add_transition('verified', 'found_two_spondees', 'correction', unless=[self._is_successful]) self.machine.add_transition('corrected', 'correction', 'success', conditions=[self._is_successful]) self.machine.add_transition('corrected', 'correction', 'failure', unless=[self._is_successful])
def test_blueprint_simple(self): states = ['A', 'B', 'C', 'D'] # Define with list of dictionaries transitions = [ {'trigger': 'walk', 'source': 'A', 'dest': 'B'}, {'trigger': 'run', 'source': 'B', 'dest': 'C'}, {'trigger': 'sprint', 'source': 'C', 'dest': 'D'} ] m = Machine(states=states, transitions=transitions, before_state_change='before_state_change', after_state_change='after_state_change', initial='A') self.assertEqual(len(m.blueprints['states']), 4) self.assertEqual(m.blueprints['states'][3], 'D') self.assertEqual(len(m.blueprints['transitions']), 3) self.assertEqual(m.blueprints['transitions'][2]['trigger'], 'sprint') m.add_transition('fly', 'D', 'A') self.assertEqual(len(m.blueprints['transitions']), 4) self.assertEqual(m.blueprints['transitions'][3]['source'], 'D')
class SimpleFSA(annotator): _states = [ {'name': 'waiting', 'on_enter': '_reset_positions'}, {'name': 'analysing'}, {'name': 'finished'} ] def __init__(self, name): annotator.__init__(self, name) self.machine = Machine(model=self, states=SimpleFSA._states, initial='waiting') self.machine.add_transition(trigger='start_analysis', source='waiting', dest='analysing', after='_analyse') self.machine.add_transition('corrected', 'analysing', 'finished') def verify(self, line): return annotator._verify_string(self, line) def _analyse(self): annotator._correct(self)
class ConnectionStateMachine(object): states = [ "NOT_CONNECTED", { 'name': 'CONNECTED', 'children': ['NOT_SELECTED', 'SELECTED'] } ] def __init__(self, callbacks=None): self.machine = Machine(model=self, states=ConnectionStateMachine.states, initial='NOT_CONNECTED', auto_transitions=False, queued=True) # transition 1 if callbacks is None: self.callbacks = {} else: self.callbacks = callbacks self.machine.add_transition('connect', 'NOT_CONNECTED', 'CONNECTED_NOT_SELECTED') # transition 2 self.machine.add_transition('disconnect', 'CONNECTED', 'NOT_CONNECTED') # transition 3 self.machine.add_transition('select', 'CONNECTED_NOT_SELECTED', 'CONNECTED_SELECTED') # transition 4 self.machine.add_transition('deselect', 'CONNECTED_SELECTED', 'CONNECTED_NOT_SELECTED') # transition 5 self.machine.add_transition('timeoutT7', 'CONNECTED_NOT_SELECTED', 'NOT_CONNECTED') # transition 6 def on_enter_CONNECTED(self): if "on_enter_CONNECTED" in self.callbacks: self.callbacks["on_enter_CONNECTED"]() def on_exit_CONNECTED(self): if "on_exit_CONNECTED" in self.callbacks: self.callbacks["on_exit_CONNECTED"]() def on_enter_CONNECTED_SELECTED(self): if "on_enter_CONNECTED_SELECTED" in self.callbacks: self.callbacks["on_enter_CONNECTED_SELECTED"]()
def __init__(self, server_uri: tuple = None, ssl_mode=False, cert_path=CERT_PATH): """ 客户端初始化 :param server_uri: 服务器地址 :param ssl_mode: 是否使用SSL :param cert_path: 服务器证书路径 """ # 状态机初始化 Machine.__init__(self, states=STATES, transitions=TRANSITIONS, initial="INIT", send_event=True, **extra_args) self.__machine_init() # socket初始化 self.raw_sock = socket.create_connection(server_uri) self.work_sock = None if ssl_mode: print('使用SSL模式加密传输') self.context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) self.context.load_verify_locations(cert_path) self.work_sock = self.context.wrap_socket( self.raw_sock, server_hostname=server_uri[0]) else: print('不使用SSL') self.work_sock = self.raw_sock # 其他参数 self.file_sock = None # 传输文件专用 socket # 下载文件专用监听socket # self.down_listen_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # self.down_listen_sock.bind((SERVER_HOST, SERVER_DATA_PORT)) # self.down_conn_sock = None # 下载文件连接socket self.token = None # 用户临时口令
def __init__(self): NestedState.separator = '>' states = ['Main', {'name': 'Profile', 'children': ['Gender', 'Age']}, {'name': 'Test1', 'children': [str(i) for i in range(1, 11)]}, 'Result1', {'name': 'Test2', 'children': ['1', '2', {'name': '3', 'children': [str(i) for i in range(1, 8)]}]}, 'Result2' 'Wait', 'Admin' ] transitions = [ ['profile', 'Main', 'Profile>Gender'], ['next_q', 'Profile>Gender', 'Profile>Age'], ['test1', 'Main', 'Test1>1'], ['result1', 'Test1>10', 'Result1'], ['test2', 'Main', 'Test2>1'], ['result2', 'Test2>3>7', 'Result2'], ['reset', '*', 'Main'], ['admin', '*', 'Admin'] ] HierarchicalMachine.__init__(self, states=states, transitions=transitions, initial='Main') # before_state_change='before_transition', # after_state_change='after_transition') st_list = list(['Test1>{0}'.format(i) for i in range(1, 11)]) st_list.append('Result1') self.add_ordered_transitions(trigger='next_q', states=st_list, loop=False) st_list = list(['Test2>3>{0}'.format(i) for i in range(1, 8)]) st_list.append('Result2') self.add_ordered_transitions(trigger='next_q', states=st_list, loop=False) self.add_ordered_transitions(trigger='next_part', states=['Test2>1', 'Test2>2', 'Test2>3>1'], loop=False) self.t2_dream_category = int() self.t2_dream_subject = int() self.add_transition(trigger='wait', source='*', dest='Wait', before='before_wait', conditions=['proceed']) self.previous_state = 'Main' self.is_waiting = False self.wait_interrupted = False
def __init__(self, name): annotator.__init__(self, name) self.machine = Machine(model=self, states=HFSA16._states, initial='waiting') self.machine.add_transition(trigger='start_analysis', source='waiting', dest='searching_for_spondeus_secondF', after='_search_second') self.machine.add_transition('found_spondeus', 'searching_for_spondeus_secondF', 'spondeus_found') self.machine.add_transition('not_found', 'searching_for_spondeus_secondF', 'searching_for_spondeus_firstF', after='_search_first') self.machine.add_transition('found_spondeus', 'searching_for_spondeus_firstF', 'spondeus_found') self.machine.add_transition('not_found', 'searching_for_spondeus_firstF', 'searching_for_spondeus_fourthF', after='_search_fourth') self.machine.add_transition('found_spondeus', 'searching_for_spondeus_fourthF', 'spondeus_found') self.machine.add_transition('not_found', 'searching_for_spondeus_fourthF', 'searching_for_spondeus_thirdF', after='_search_third') self.machine.add_transition('found_spondeus', 'searching_for_spondeus_thirdF', 'spondeus_found') self.machine.add_transition('not_found', 'searching_for_spondeus_thirdF', 'searching_for_spondeus_fifthF', after='_search_fifth') self.machine.add_transition('found_spondeus', 'searching_for_spondeus_fifthF', 'spondeus_found') self.machine.add_transition('not_found', 'searching_for_spondeus_fifthF', 'no_spondeus_found') self.machine.add_transition('not_found', 'no_spondeus_found', 'fallback') self.machine.add_transition('verified', 'fallback', 'correction', unless=[self._is_successful]) self.machine.add_transition('verified', 'fallback', 'success', conditions=[self._is_successful]) self.machine.add_transition('verified', 'spondeus_found', 'success', conditions=[self._is_successful]) self.machine.add_transition('verified', 'spondeus_found', 'correction', unless=[self._is_successful]) self.machine.add_transition('corrected', 'correction', 'success', conditions=[self._is_successful]) self.machine.add_transition('corrected', 'correction', 'failure', unless=[self._is_successful])
def __init__(self, callbacks=None): self.machine = Machine(model=self, states=ConnectionStateMachine.states, initial='NOT_CONNECTED', auto_transitions=False, queued=True) # transition 1 if callbacks is None: self.callbacks = {} else: self.callbacks = callbacks self.machine.add_transition('connect', 'NOT_CONNECTED', 'CONNECTED_NOT_SELECTED') # transition 2 self.machine.add_transition('disconnect', 'CONNECTED', 'NOT_CONNECTED') # transition 3 self.machine.add_transition('select', 'CONNECTED_NOT_SELECTED', 'CONNECTED_SELECTED') # transition 4 self.machine.add_transition('deselect', 'CONNECTED_SELECTED', 'CONNECTED_NOT_SELECTED') # transition 5 self.machine.add_transition('timeoutT7', 'CONNECTED_NOT_SELECTED', 'NOT_CONNECTED') # transition 6
def __init__(self): rospy.wait_for_service('/performances/reload_properties') # States for wholeshow states = [{'name': 'sleeping', 'children': ['shutting']}, {'name': 'interacting', 'children': ['nonverbal']}, 'performing', 'opencog', 'analysis'] HierarchicalMachine.__init__(self, states=states, initial='interacting') # Transitions self.add_transition('wake_up', 'sleeping', 'interacting') # Transitions self.add_transition('perform', 'interacting', 'performing') self.add_transition('interact', 'performing', 'interacting') self.add_transition('start_opencog', 'interacting', 'opencog') self.add_transition('shut', 'sleeping', 'sleeping_shutting') self.add_transition('be_quiet', 'interacting', 'interacting_nonverbal') self.add_transition('start_talking', 'interacting_nonverbal', 'interacting') # States handling self.on_enter_sleeping("start_sleeping") self.on_exit_sleeping("stop_sleeping") self.on_enter_interacting("start_interacting") self.on_exit_interacting("stop_interacting") self.on_enter_sleeping_shutting("system_shutdown") # ROS Handling rospy.init_node('WholeShow') self.btree_pub = rospy.Publisher("/behavior_switch", String, queue_size=5) self.btree_sub = rospy.Subscriber("/behavior_switch", String, self.btree_cb) self.soma_pub = rospy.Publisher('/blender_api/set_soma_state', SomaState, queue_size=10) self.look_pub = rospy.Publisher('/blender_api/set_face_target', Target, queue_size=10) self.gaze_pub = rospy.Publisher('/blender_api/set_gaze_target', Target, queue_size=10) self.performance_runner = rospy.ServiceProxy('/performances/run_full_performance', srv.RunByName) # Wholeshow starts with behavior enabled, unless set otherwise rospy.set_param("/behavior_enabled", rospy.get_param("/behavior_enabled", True)) # Start sleeping. Wait for Blender to load rospy.wait_for_service('/blender_api/set_param') rospy.wait_for_service('/performances/current') self.blender_param = rospy.ServiceProxy('/blender_api/set_param', SetParam) time.sleep(2) self.sleeping = rospy.get_param('start_sleeping', False) if self.sleeping: t = threading.Timer(1, self.to_sleeping) t.start() # Performance id as key and keyword array as value self.performances_keywords = {} # Parse on load. # TODO make sure we reload those once performances are saved. self.after_performance = False # Speech handler. Receives all speech input, and forwards to chatbot if its not a command input, # or chat is enabled self.speech_sub = rospy.Subscriber('speech', ChatMessage, self.speech_cb) self.speech_pub = rospy.Publisher('chatbot_speech', ChatMessage, queue_size=10) # Sleep self.performance_events = rospy.Subscriber('/performances/events', Event, self.performances_cb) # Dynamic reconfigure self.config = {} self.cfg_srv = Server(WholeshowConfig, self.config_cb) # Behavior was paused entering into state self.behavior_paused = False # Chatbot was paused entering the state self.chatbot_paused = False self.sleeping = rospy.get_param('start_sleeping', False) # Preferred speech source self.speech_provider = rospy.get_param("active_stt", 'cloudspeech') self.speech_provider_active = False rospy.Subscriber('{}/status'.format(self.speech_provider), Bool, self.stt_status_cb)
class HFSA16(annotator): _states = [ {'name': 'waiting', 'on_enter': '_reset_positions'}, {'name': 'searching_for_spondeus', 'children': ['secondF', 'firstF', 'fourthF', 'thirdF', 'fifthF']}, {'name': 'spondeus_found', 'on_enter': '_verify_output'}, {'name': 'no_spondeus_found', 'on_enter': '_make_spondeus'}, {'name': 'fallback', 'on_enter': '_search_whole'}, {'name': 'correction', 'on_enter': '_correct'}, 'success', 'failure' ] def __init__(self, name): annotator.__init__(self, name) self.machine = Machine(model=self, states=HFSA16._states, initial='waiting') self.machine.add_transition(trigger='start_analysis', source='waiting', dest='searching_for_spondeus_secondF', after='_search_second') self.machine.add_transition('found_spondeus', 'searching_for_spondeus_secondF', 'spondeus_found') self.machine.add_transition('not_found', 'searching_for_spondeus_secondF', 'searching_for_spondeus_firstF', after='_search_first') self.machine.add_transition('found_spondeus', 'searching_for_spondeus_firstF', 'spondeus_found') self.machine.add_transition('not_found', 'searching_for_spondeus_firstF', 'searching_for_spondeus_fourthF', after='_search_fourth') self.machine.add_transition('found_spondeus', 'searching_for_spondeus_fourthF', 'spondeus_found') self.machine.add_transition('not_found', 'searching_for_spondeus_fourthF', 'searching_for_spondeus_thirdF', after='_search_third') self.machine.add_transition('found_spondeus', 'searching_for_spondeus_thirdF', 'spondeus_found') self.machine.add_transition('not_found', 'searching_for_spondeus_thirdF', 'searching_for_spondeus_fifthF', after='_search_fifth') self.machine.add_transition('found_spondeus', 'searching_for_spondeus_fifthF', 'spondeus_found') self.machine.add_transition('not_found', 'searching_for_spondeus_fifthF', 'no_spondeus_found') self.machine.add_transition('not_found', 'no_spondeus_found', 'fallback') self.machine.add_transition('verified', 'fallback', 'correction', unless=[self._is_successful]) self.machine.add_transition('verified', 'fallback', 'success', conditions=[self._is_successful]) self.machine.add_transition('verified', 'spondeus_found', 'success', conditions=[self._is_successful]) self.machine.add_transition('verified', 'spondeus_found', 'correction', unless=[self._is_successful]) self.machine.add_transition('corrected', 'correction', 'success', conditions=[self._is_successful]) self.machine.add_transition('corrected', 'correction', 'failure', unless=[self._is_successful]) def _search_second(self): fourth = self._search_long(4) fifth = self._search_long(5) if fourth and fifth: self.verse.scansion = '-** -- -** -** -** -X' self.found_spondeus() elif fourth: self.positions.append(4) self.not_found() elif fifth: self.positions.append(5) self.not_found() else: self.not_found() def _search_first(self): if self._search_long(2): self.verse.scansion = '-- -** -** -** -** -X' self.found_spondeus() else: self.not_found() def _search_fourth(self): tenth = self._search_long(10) eleventh = self._search_long(11) if tenth and eleventh: self.verse.scansion = '-** -** -** -- -** -X' self.found_spondeus() elif tenth: self.positions.append(10) self.not_found() elif eleventh: self.positions.append(11) self.not_found() else: self.not_found() def _search_third(self): seventh = self._search_long(7) eigth = self._search_long(8) if seventh and eigth: self.verse.scansion = '-** -** -- -** -** -X' self.found_spondeus() elif seventh: self.positions.append(7) self.not_found() elif eigth: self.positions.append(8) self.not_found() else: self.not_found() def _search_fifth(self): thirteenth = self._search_long(13) fourteenth = self._search_long(14) if thirteenth and fourteenth: self.verse.scansion = '-** -** -** -** -- -X' self.found_spondeus() elif thirteenth: self.positions.append(13) self.not_found() elif fourteenth: self.positions.append(14) self.not_found() else: self.not_found() def _make_spondeus(self): annotator._make_spondeus(self, 14)
def create_statemachine(self, state_machine_model): NestedState.separator = ':' states = [{ 'name': 'base', 'children': ['not_ready', 'ready', 'active', 'fail', 'processing'] }] transitions = [['start', 'base', 'base:not_ready'], ['unavailable', 'base', 'base:not_ready'], ['deactivate', 'base', 'base:not_ready'], ['activate', 'base:not_ready', 'base:active'], ['idle', 'base:not_ready', 'base:ready'], ['ready', 'base:ready', 'base:active'], ['activate', 'base:ready', 'base:active'], ['idle', 'base:active', 'base:ready'], ['not_ready', 'base:active', 'base:ready'], ['failure', 'base:active', 'base:fail'], ['active', 'base:active', 'base:processing'], ['idle', 'base:processing', 'base:fail'], ['ready', 'base:processing', 'base:fail'], ['not_ready', 'base:processing', 'base:fail'], ['active', 'base:processing', 'base:fail'], ['activate', 'base:processing', 'base:fail'], ['fail', 'base:processing', 'base:fail'], ['idle', 'base:fail', 'base:ready'], ['ready', 'base:fail', 'base:ready'], ['not_ready', 'base:fail', 'base:ready'], ['active', 'base:fail', 'base:ready'], ['activate', 'base:fail', 'base:ready'], ['failure', 'base:fail', 'base:ready'], ['complete', 'base:fail', 'base:ready'], { 'trigger': 'complete', 'source': 'base:processing', 'dest': 'base:not_ready', 'after': 'COMPLETE' }, ['default', 'base:processing', 'base:fail'], ['default', 'base:fail', 'base:ready'], ['default', 'base:not_ready', 'base:not_ready'], ['default', 'base:ready', 'base:ready'], ['default', 'base:active', 'base:active'], ['reset', '*', 'base:not_ready']] statemachine = Machine(model=state_machine_model, states=states, transitions=transitions, initial='base', ignore_invalid_triggers=True) statemachine.on_enter('base:ready', 'READY') statemachine.on_enter('base:active', 'ACTIVE') statemachine.on_enter('base:not_ready', 'NOT_READY') statemachine.on_enter('base:fail', 'FAILURE') statemachine.on_exit('base:fail', 'complete_failed') statemachine.on_enter('base:processing', 'PROCESSING') return statemachine
class HFSA15(annotator): _states = [ {'name': 'waiting', 'on_enter': '_reset_positions'}, {'name': 'searching_for_first_spondeus', 'children': ['secondF', 'firstF', 'fourthF', 'thirdF']}, {'name': 'searching_for_second_spondeus', 'children': ['firstF', 'fourthF', 'thirdF', 'fifthF']}, {'name': 'no_spondeus_found', 'on_enter': '_make_spondeus'}, {'name': 'found_two_spondees', 'on_enter': '_make_scansion'}, {'name': 'fallback', 'on_enter': '_search_whole'}, {'name': 'correction', 'on_enter': '_correct'}, 'success', 'failure' ] def __init__ (self, name): annotator.__init__(self, name) self.machine = Machine(model=self, states=HFSA15._states, initial='waiting') self.machine.add_transition('start_analysis', 'waiting', 'searching_for_first_spondeus_secondF', after='_search_second') self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_secondF', 'searching_for_first_spondeus_firstF', unless=[self._found_first], after='_search_first') self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_secondF', 'searching_for_second_spondeus_firstF', conditions=[self._found_first], after='_search_first') self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_firstF', 'found_two_spondees', conditions=[self._found_second]) self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_firstF', 'searching_for_second_spondeus_fourthF', unless=[self._found_second], after='_search_fourth') self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_firstF', 'searching_for_first_spondeus_fourthF', unless=[self._found_first], after='_search_fourth') self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_firstF', 'searching_for_second_spondeus_fourthF', conditions=[self._found_first], after='_search_fourth') self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_fourthF', 'found_two_spondees', conditions=[self._found_second]) self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_fourthF', 'searching_for_second_spondeus_thirdF', unless=[self._found_second], after='_search_third') self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_fourthF', 'searching_for_first_spondeus_thirdF', unless=[self._found_first], after='_search_third') self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_fourthF', 'searching_for_second_spondeus_thirdF', conditions=[self._found_first], after='_search_third') self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_thirdF', 'found_two_spondees', conditions=[self._found_second]) self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_thirdF', 'searching_for_second_spondeus_fifthF', unless=[self._found_second], after='_search_fifth') self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_thirdF', 'no_spondeus_found', unless=[self._found_first]) self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_thirdF', 'searching_for_second_spondeus_fifthF', conditions=[self._found_first], after='_search_fifth') self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_fifthF', 'found_two_spondees', conditions=[self._found_second]) #deal with implausible spondeus positions self.machine.add_transition('search_spondeus', 'found_two_spondees', 'no_spondeus_found') self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_fifthF', 'no_spondeus_found', unless=[self._found_second]) self.machine.add_transition('not_found', 'no_spondeus_found', 'fallback') self.machine.add_transition('verified', 'fallback', 'correction', unless=[self._is_successful]) self.machine.add_transition('verified', 'fallback', 'success', conditions=[self._is_successful]) self.machine.add_transition('verified', 'found_two_spondees', 'success', conditions=[self._is_successful]) self.machine.add_transition('verified', 'found_two_spondees', 'correction', unless=[self._is_successful]) self.machine.add_transition('corrected', 'correction', 'success', conditions=[self._is_successful]) self.machine.add_transition('corrected', 'correction', 'failure', unless=[self._is_successful]) def _search_second(self): third = self._search_long(3) fourth = self._search_long(4) fifth = self._search_long(5) if third and fourth: self.positions.append(3) self.positions.append(4) self._set_found() elif fourth and fifth: self.positions.append(4) self.positions.append(5) self._set_found() else: if third: self.positions.append(3) if fourth: self.positions.append(4) if fifth: self.positions.append(5) self.search_spondeus() def _search_first(self): first = self._search_long(1) second = self._search_long(2) if first and second: self.positions.append(1) self.positions.append(2) self._set_found() elif first: self.positions.append(1) elif second: self.positions.append(2) self.search_spondeus() def _search_fourth(self): ninth = self._search_long(9) tenth = self._search_long(10) eleventh = self._search_long(11) if tenth and eleventh: self.positions.append(10) self.positions.append(11) self._set_found() elif ninth and tenth: self.positions.append(9) self.positions.append(10) self._set_found() else: if ninth: self.positions.append(9) if tenth: self.positions.append(10) if eleventh: self.positions.append(11) self.search_spondeus() def _search_third(self): sixth = self._search_long(6) seventh = self._search_long(7) eigth = self._search_long(8) if seventh and eigth: self.positions.append(7) self.positions.append(8) self._set_found() elif sixth and seventh: self.positions.append(6) self.positions.append(7) self._set_found() else: if sixth: self.positions.append(6) if seventh: self.positions.append(7) if eigth: self.positions.append(8) self.search_spondeus() def _search_fifth(self): twelfth = self._search_long(12) thirteenth = self._search_long(13) if twelfth and thirteenth: self.positions.append(12) self.positions.append(13) self._set_found() elif twelfth: self.positions.append(12) elif thirteenth: self.positions.append(13) self.search_spondeus() def _make_scansion(self): if 2 in self.positions: self.verse.scansion = '-- ' if 4 in self.positions: self.verse.scansion+= '-- -** -** -** -X' self._verify_output() elif 7 in self.positions: self.verse.scansion+= '-** -- -** -** -X' self._verify_output() elif 10 in self.positions: self.verse.scansion+= '-** -** -- -** -X' self._verify_output() elif 13 in self.positions: self.verse.scansion+= '-** -** -** -- -X' self._verify_output() else: self.search_spondeus() elif 5 in self.positions: self.verse.scansion = '-** -- ' if 7 in self.positions: self.verse.scansion+= '-- -** -** -X' self._verify_output() elif 10 in self.positions: self.verse.scansion+= '-** -- -** -X' self._verify_output() elif 13 in self.positions: self.verse.scansion+= '-** -** -- -X' self._verify_output() else: self.search_spondeus() elif 8 in self.positions: self.verse.scansion = '-** -** -- ' if 10 in self.positions: self.verse.scansion+= '-- -** -X' self._verify_output() elif 13 in self.positions: self.verse.scansion+= '-** -- -X' self._verify_output() else: self.search_spondeus() elif 11 in self.positions: self.verse.scansion = '-** -** -** -- -- -X' self._verify_output() else: self.search_spondeus() def _make_spondeus(self): annotator._make_spondeus(self, 13)
def test_blueprint_initial_false(self): child = Machine(states=['A', 'B'], initial='A') parent = Machine(states=['a', 'b', {'name': 'c', 'children': child, 'initial': False}]) parent.to_c() self.assertEqual(parent.state, 'c')
def test_blueprint_reuse(self): states = ['1', '2', '3'] transitions = [ { 'trigger': 'increase', 'source': '1', 'dest': '2' }, { 'trigger': 'increase', 'source': '2', 'dest': '3' }, { 'trigger': 'decrease', 'source': '3', 'dest': '2' }, { 'trigger': 'decrease', 'source': '1', 'dest': '1' }, { 'trigger': 'reset', 'source': '*', 'dest': '1' }, ] counter = Machine(states=states, transitions=transitions, before_state_change='check', after_state_change='clear', initial='1') new_states = ['A', 'B', {'name': 'C', 'children': counter}] new_transitions = [ { 'trigger': 'forward', 'source': 'A', 'dest': 'B' }, { 'trigger': 'forward', 'source': 'B', 'dest': 'C%s1' % State.separator }, { 'trigger': 'backward', 'source': 'C', 'dest': 'B' }, { 'trigger': 'backward', 'source': 'B', 'dest': 'A' }, { 'trigger': 'calc', 'source': '*', 'dest': 'C' }, ] walker = Machine(states=new_states, transitions=new_transitions, before_state_change='watch', after_state_change='look_back', initial='A') walker.watch = lambda: 'walk' walker.look_back = lambda: 'look_back' walker.check = lambda: 'check' walker.clear = lambda: 'clear' with self.assertRaises(MachineError): walker.increase() self.assertEqual(walker.state, 'A') walker.forward() walker.forward() self.assertEqual(walker.state, 'C%s1' % State.separator) walker.increase() self.assertEqual(walker.state, 'C%s2' % State.separator) walker.reset() self.assertEqual(walker.state, 'C%s1' % State.separator) walker.to_A() self.assertEqual(walker.state, 'A') walker.calc() self.assertEqual(walker.state, 'C')
def create_statemachine(self, state_machine_model): NestedState.separator = ':' states = [{ 'name': 'base', 'children': [ 'activated', { 'name': 'operational', 'children': [ 'loading', 'cycle_start', 'unloading', 'idle', 'in_transition' ] }, { 'name': 'disabled', 'children': ['fault', 'not_ready'] } ] }] transitions = [ ['start', 'base', 'base:disabled'], ['cnc_controller_mode_automatic', 'base', 'base:activated'], ['reset_cnc', 'base', 'base:activated'], ['enable', 'base', 'base:activated'], ['disable', 'base', 'base:activated'], ['cnc_controller_mode_manual', 'base', 'base:activated'], [ 'cnc_controller_mode_manual_data_input', 'base', 'base:activated' ], [ 'cnc_controller_mode_automatic', 'base:disabled', 'base:activated' ], ['robot_material_load_ready', 'base:disabled', 'base:activated'], ['robot_material_unload_ready', 'base:disabled', 'base:activated'], [ 'default', 'base:operational:cycle_start', 'base:operational:cycle_start' ], { 'trigger': 'complete', 'source': 'base:operational:loading', 'dest': 'base:operational:cycle_start', 'before': 'LOADED' }, [ 'complete', 'base:operational:in_transition', 'base:operational:loading' ], { 'trigger': 'complete', 'source': 'base:operational:unloading', 'dest': 'base:operational:in_transition', 'before': 'UNLOADED' }, ['fault', 'base', 'base:disabled:fault'], ['robot_system_fault', 'base', 'base:disabled:fault'], ['default', 'base:disabled:fault', 'base:disabled:fault'], ['faulted', 'base:activated', 'base:disabled:fault'], [ 'cnc_fault', 'base:operational:cycle_start', 'base:disabled:fault' ], ['start', 'base:disabled', 'base:disabled:not_ready'], ['default', 'base:disabled:not_ready', 'base:disabled:not_ready'], ['default', 'base:disabled', 'base:disabled:not_ready'], ['still_not_ready', 'base:activated', 'base:disabled:not_ready'], ['loading', 'base:operational', 'base:operational:loading'], [ 'default', 'base:operational:loading', 'base:operational:loading' ], ['unloading', 'base:operational', 'base:operational:unloading'], [ 'default', 'base:operational:unloading', 'base:operational:unloading' ], [ 'cnc_execution_ready', 'base:operational:cycle_start', 'base:operational:unloading' ], ['failed', 'base:operational:loading', 'base:operational:idle'], ['failed', 'base:operational:unloading', 'base:operational:idle'], ['start', 'base:operational', 'base:operational:idle'], { 'trigger': 'robot_material_unload_ready', 'source': 'base:operational:idle', 'dest': 'base:operational', 'after': 'EXITING_IDLE' }, { 'trigger': 'robot_material_load_ready', 'source': 'base:operational:idle', 'dest': 'base:operational', 'after': 'EXITING_IDLE' }, ['default', 'base:operational:idle', 'base:operational:idle'], ['make_operational', 'base:activated', 'base:operational'] ] statemachine = Machine(model=state_machine_model, states=states, transitions=transitions, initial='base', ignore_invalid_triggers=True) statemachine.on_enter('base:disabled', 'CNC_NOT_READY') statemachine.on_enter('base:disabled:not_ready', 'CNC_NOT_READY') statemachine.on_enter('base:disabled:fault', 'CNC_NOT_READY') statemachine.on_enter('base:activated', 'ACTIVATE') statemachine.on_enter('base:operational', 'OPERATIONAL') statemachine.on_enter('base:operational:idle', 'IDLE') statemachine.on_enter('base:operational:cycle_start', 'CYCLING') statemachine.on_enter('base:operational:loading', 'LOADING') statemachine.on_enter('base:operational:unloading', 'UNLOADING') statemachine.on_enter('base:operational:in_transition', 'IN_TRANSITION') statemachine.on_exit('base:operational:in_transition', 'EXIT_TRANSITION') return statemachine
from states import states import time import threading from ulity import china_time, send_email # # Set up logging; The basic log level will be DEBUG # import logging # logging.basicConfig(level=logging.DEBUG) # # Set transitions' log level to INFO; DEBUG messages will be omitted # logging.getLogger('transitions').setLevel(logging.INFO) threadLock = threading.Lock() threads = [] hpg = HPG() machine = Machine(hpg, states=states, initial='initial') #### machine.add_transition('connect_chrome', 'initial', 'connectedChrome', conditions='connectChrome') ##### machine.add_transition('CheckLogin', '*', 'loginHPG', conditions='check_login') machine.add_transition('QuereTask', '*', 'quereedTask', conditions='queue_task') machine.add_transition('ReceiveTask',
def create_statemachine(self, state_machine_model): NestedState.separator = ':' states = [{ 'name': 'base', 'children': [ 'inactive', 'preparing', 'committing', 'committed', 'complete', 'fail' ] }, 'removed'] transitions = [['create', 'base', 'base:inactive'], ['activated', 'base:inactive', 'base:preparing'], ['failure', 'base:inactive', 'base:fail'], ['quorum', 'base:preparing', 'base:committing'], ['all_commit', 'base:committing', 'base:committed'], ['no_commit', 'base:committing', 'base:preparing'], ['success', 'base:committed', 'base:complete'], ['failure', 'base:committed', 'base:fail'], ['default', 'base:complete', 'removed'], ['default', 'base:fail', 'removed'], ['default', 'base:inactive', 'base:inactive'], ['default', 'base:committed', 'base:committed']] statemachine = Machine(model=state_machine_model, states=states, transitions=transitions, initial='base', ignore_invalid_triggers=True) statemachine.on_enter('base:inactive', 'INACTIVE') statemachine.on_enter('base:committing', 'COMMITTING') statemachine.on_enter('base:committed', 'COMMITTED') statemachine.on_enter('base:complete', 'COMPLETE') statemachine.on_enter('base:fail', 'FAIL') return statemachine
] transitions = [ ['slowdown', 'green', 'yellow'], ['stop', 'yellow', 'red'], ['go', 'red', 'green'], ['throw_rock', '*', 'broken'], ['evening', 'broken', 'broken_buzzing'], ['day', ['broken_sparking', 'broken_buzzing'], 'broken'], # Since you have to specify a transition, and a specific # state to pop to, this is not a push/pop # at all, simply nested states. ['pop_broken', 'broken', 'green'] ] machine = Machine(t, states=states, transitions=transitions, initial='green') # Transitioning from multiple states via the same trigger - pity can't specify this in the transitions structure machine.add_transition('powersurge', 'broken', 'broken_buzzing') machine.add_transition('powersurge', 'broken_buzzing', 'broken_sparking') print(t.state) assert t.state == 'green' print(machine.get_state(t.state)) t.slowdown() t.stop() print(t.state) assert t.state == 'red' # same test as in state-demo2-stack
def test_blueprint_reuse(self): states = ['1', '2', '3'] transitions = [ {'trigger': 'increase', 'source': '1', 'dest': '2'}, {'trigger': 'increase', 'source': '2', 'dest': '3'}, {'trigger': 'decrease', 'source': '3', 'dest': '2'}, {'trigger': 'decrease', 'source': '1', 'dest': '1'}, {'trigger': 'reset', 'source': '*', 'dest': '1'}, ] counter = Machine(states=states, transitions=transitions, before_state_change='check', after_state_change='clear', initial='1') new_states = ['A', 'B', {'name':'C', 'children': counter}] new_transitions = [ {'trigger': 'forward', 'source': 'A', 'dest': 'B'}, {'trigger': 'forward', 'source': 'B', 'dest': 'C'}, {'trigger': 'backward', 'source': 'C', 'dest': 'B'}, {'trigger': 'backward', 'source': 'B', 'dest': 'A'}, {'trigger': 'calc', 'source': '*', 'dest': 'C'}, ] walker = Machine(states=new_states, transitions=new_transitions, before_state_change='watch', after_state_change='look_back', initial='A') walker.watch = lambda: 'walk' walker.look_back = lambda: 'look_back' walker.check = lambda: 'check' walker.clear = lambda: 'clear' with self.assertRaises(MachineError): walker.increase() self.assertEqual(walker.state, 'A') walker.forward() walker.forward() self.assertEqual(walker.state, 'C_1') walker.increase() self.assertEqual(walker.state, 'C_2') walker.reset() self.assertEqual(walker.state, 'C_1') walker.to_A() self.assertEqual(walker.state, 'A') walker.calc() self.assertEqual(walker.state, 'C_1')
def __init__(self): rospy.wait_for_service('/performances/reload_properties') # States for wholeshow states = [{ 'name': 'sleeping', 'children': ['shutting'] }, { 'name': 'interacting', 'children': ['nonverbal'] }, 'performing', 'opencog', 'analysis'] HierarchicalMachine.__init__(self, states=states, initial='interacting') # Transitions self.add_transition('wake_up', 'sleeping', 'interacting') # Transitions self.add_transition('perform', 'interacting', 'performing') self.add_transition('interact', 'performing', 'interacting') self.add_transition('start_opencog', 'interacting', 'opencog') self.add_transition('shut', 'sleeping', 'sleeping_shutting') self.add_transition('be_quiet', 'interacting', 'interacting_nonverbal') self.add_transition('start_talking', 'interacting_nonverbal', 'interacting') # States handling self.on_enter_sleeping("start_sleeping") self.on_exit_sleeping("stop_sleeping") self.on_enter_interacting("start_interacting") self.on_exit_interacting("stop_interacting") self.on_enter_sleeping_shutting("system_shutdown") # ROS Handling rospy.init_node('WholeShow') self.btree_pub = rospy.Publisher("/behavior_switch", String, queue_size=5) self.btree_sub = rospy.Subscriber("/behavior_switch", String, self.btree_cb) self.soma_pub = rospy.Publisher('/blender_api/set_soma_state', SomaState, queue_size=10) self.look_pub = rospy.Publisher('/blender_api/set_face_target', Target, queue_size=10) self.gaze_pub = rospy.Publisher('/blender_api/set_gaze_target', Target, queue_size=10) self.performance_runner = rospy.ServiceProxy( '/performances/run_full_performance', srv.RunByName) # Wholeshow starts with behavior enabled, unless set otherwise rospy.set_param("/behavior_enabled", rospy.get_param("/behavior_enabled", True)) # Start sleeping. Wait for Blender to load rospy.wait_for_service('/blender_api/set_param') rospy.wait_for_service('/performances/current') self.blender_param = rospy.ServiceProxy('/blender_api/set_param', SetParam) time.sleep(2) self.sleeping = rospy.get_param('start_sleeping', False) if self.sleeping: t = threading.Timer(1, self.to_sleeping) t.start() # Performance id as key and keyword array as value self.performances_keywords = {} # Parse on load. # TODO make sure we reload those once performances are saved. self.after_performance = False # Speech handler. Receives all speech input, and forwards to chatbot if its not a command input, # or chat is enabled self.speech_sub = rospy.Subscriber('speech', ChatMessage, self.speech_cb) self.speech_pub = rospy.Publisher('chatbot_speech', ChatMessage, queue_size=10) # Sleep self.performance_events = rospy.Subscriber('/performances/events', Event, self.performances_cb) # Dynamic reconfigure self.config = {} self.cfg_srv = Server(WholeshowConfig, self.config_cb) # Behavior was paused entering into state self.behavior_paused = False # Chatbot was paused entering the state self.chatbot_paused = False self.sleeping = rospy.get_param('start_sleeping', False) # Preferred speech source self.speech_provider = rospy.get_param("active_stt", 'cloudspeech') self.speech_provider_active = False rospy.Subscriber('{}/status'.format(self.speech_provider), Bool, self.stt_status_cb)
def __init__(self, name): annotator.__init__(self, name) self.machine = Machine(model=self, states=SimpleFSA._states, initial='waiting') self.machine.add_transition(trigger='start_analysis', source='waiting', dest='analysing', after='_analyse') self.machine.add_transition('corrected', 'analysing', 'finished')
def __init__(self, top): self.top = top self.states = ['n1', {'name': 'n2', 'on_enter': self.print_msg}] Machine.__init__(self, states=self.states, initial='n1') self.add_transition(trigger='goto_n2', source='*', dest='n2')
def test_blueprint_remap(self): states = ['1', '2', '3', 'finished'] transitions = [{ 'trigger': 'increase', 'source': '1', 'dest': '2' }, { 'trigger': 'increase', 'source': '2', 'dest': '3' }, { 'trigger': 'decrease', 'source': '3', 'dest': '2' }, { 'trigger': 'decrease', 'source': '1', 'dest': '1' }, { 'trigger': 'reset', 'source': '*', 'dest': '1' }, { 'trigger': 'done', 'source': '3', 'dest': 'finished' }] counter = Machine(states=states, transitions=transitions, initial='1') new_states = [ 'A', 'B', { 'name': 'C', 'children': [ counter, { 'name': 'X', 'children': ['will', 'be', 'filtered', 'out'] } ], 'remap': { 'finished': 'A', 'X': 'A' } } ] new_transitions = [ { 'trigger': 'forward', 'source': 'A', 'dest': 'B' }, { 'trigger': 'forward', 'source': 'B', 'dest': 'C%s1' % State.separator }, { 'trigger': 'backward', 'source': 'C', 'dest': 'B' }, { 'trigger': 'backward', 'source': 'B', 'dest': 'A' }, { 'trigger': 'calc', 'source': '*', 'dest': 'C%s1' % State.separator }, ] walker = Machine(states=new_states, transitions=new_transitions, before_state_change='watch', after_state_change='look_back', initial='A') walker.watch = lambda: 'walk' walker.look_back = lambda: 'look_back' counter.increase() counter.increase() counter.done() self.assertEqual(counter.state, 'finished') with self.assertRaises(MachineError): walker.increase() self.assertEqual(walker.state, 'A') walker.forward() walker.forward() self.assertEqual(walker.state, 'C%s1' % State.separator) walker.increase() self.assertEqual(walker.state, 'C%s2' % State.separator) walker.reset() self.assertEqual(walker.state, 'C%s1' % State.separator) walker.to_A() self.assertEqual(walker.state, 'A') walker.calc() self.assertEqual(walker.state, 'C%s1' % State.separator) walker.increase() walker.increase() walker.done() self.assertEqual(walker.state, 'A') self.assertFalse('C.finished' in walker.states)
class HFSA14(annotator): _states = [ {'name': 'waiting', 'on_enter': '_reset_positions'}, {'name': 'searching_for_first_spondeus', 'children': ['secondF', 'firstF', 'fourthF']}, {'name': 'searching_for_second_spondeus', 'children': ['firstF', 'fourthF', 'thirdF']}, {'name': 'searching_for_third_spondeus', 'children': ['fourthF', 'thirdF', 'fifthF']}, {'name': 'no_spondeus_found', 'on_enter': '_make_spondeus'}, {'name': 'found_three_spondees', 'on_enter': '_make_scansion'}, {'name': 'fallback', 'on_enter': '_search_whole'}, {'name': 'correction', 'on_enter': '_correct'}, 'success', 'failure' ] def __init__ (self, name): annotator.__init__(self, name) self.machine = Machine(model=self, states=HFSA14._states, initial='waiting') self.machine.add_transition('start_analysis', 'waiting', 'searching_for_first_spondeus_secondF', after='_search_second') self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_secondF', 'searching_for_first_spondeus_firstF', unless=[self._found_first], after='_search_first') self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_firstF', 'searching_for_first_spondeus_fourthF', unless=[self._found_first], after='_search_fourth') self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_fourthF', 'no_spondeus_found', unless=[self._found_first]) self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_secondF', 'searching_for_second_spondeus_firstF', conditions=[self._found_first], after='_search_first') self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_firstF', 'searching_for_second_spondeus_fourthF', unless=[self._found_second], after='_search_fourth') self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_fourthF', 'searching_for_second_spondeus_thirdF', unless=[self._found_second], after='_search_third') self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_thirdF', 'no_spondeus_found', unless=[self._found_second]) self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_secondF', 'searching_for_second_spondeus_firstF', conditions=[self._found_first], after='_search_first') self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_firstF', 'searching_for_second_spondeus_fourthF', conditions=[self._found_first], after='_search_fourth') self.machine.add_transition('search_spondeus', 'searching_for_first_spondeus_fourthF', 'searching_for_second_spondeus_thirdF', conditions=[self._found_first], after='_search_third') self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_thirdF', 'searching_for_third_spondeus_fifthF', conditions=[self._found_second], after='_search_fifth') self.machine.add_transition('search_spondeus', 'searching_for_third_spondeus_fifthF', 'no_spondeus_found', unless=[self._found_third]) self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_firstF', 'searching_for_third_spondeus_fourthF', conditions=[self._found_second], after='_search_fourth') self.machine.add_transition('search_spondeus', 'searching_for_third_spondeus_fourthF', 'searching_for_third_spondeus_thirdF', unless=[self._found_third], after='_search_third') self.machine.add_transition('search_spondeus', 'searching_for_third_spondeus_thirdF', 'searching_for_third_spondeus_fifthF', unless=[self._found_third], after='_search_fifth') self.machine.add_transition('search_spondeus', 'searching_for_second_spondeus_fourthF', 'searching_for_third_spondeus_thirdF', conditions=[self._found_second], after='_search_third') self.machine.add_transition('search_spondeus', 'searching_for_third_spondeus_fifthF', 'found_three_spondees', conditions=[self._found_third]) self.machine.add_transition('search_spondeus', 'searching_for_third_spondeus_fourthF', 'found_three_spondees', conditions=[self._found_third]) self.machine.add_transition('search_spondeus', 'searching_for_third_spondeus_thirdF', 'found_three_spondees', conditions=[self._found_third]) self.machine.add_transition('search_spondeus', 'found_three_spondees', 'no_spondeus_found') self.machine.add_transition('not_found', 'no_spondeus_found', 'fallback') self.machine.add_transition('verified', 'fallback', 'correction', unless=[self._is_successful]) self.machine.add_transition('verified', 'fallback', 'success', conditions=[self._is_successful]) self.machine.add_transition('verified', 'found_three_spondees', 'success', conditions=[self._is_successful]) self.machine.add_transition('verified', 'found_three_spondees', 'correction', unless=[self._is_successful]) self.machine.add_transition('corrected', 'correction', 'success', conditions=[self._is_successful]) self.machine.add_transition('corrected', 'correction', 'failure', unless=[self._is_successful]) def _search_second(self): third = self._search_long(3) fourth = self._search_long(4) fifth = self._search_long(5) if third and fourth: self.positions.append(3) self.positions.append(4) self._set_found() elif fourth and fifth: self.positions.append(4) self.positions.append(5) self._set_found() else: if third: self.positions.append(3) if fourth: self.positions.append(4) if fifth: self.positions.append(5) self.search_spondeus() def _search_first(self): first = self._search_long(1) second = self._search_long(2) if first and second: self.positions.append(1) self.positions.append(2) self._set_found() elif first: self.positions.append(1) elif second: self.positions.append(2) self.search_spondeus() def _search_fourth(self): eigth = self._search_long(8) ninth = self._search_long(9) tenth = self._search_long(10) if eigth and ninth: self.positions.append(8) self.positions.append(9) self._set_found() elif ninth and tenth: self.positions.append(9) self.positions.append(10) self._set_found() else: if eigth: self.positions.append(8) if ninth: self.positions.append(9) if tenth: self.positions.append(10) self.search_spondeus() def _search_third(self): sixth = self._search_long(6) seventh = self._search_long(7) eigth = self._search_long(8) if seventh and eigth: self.positions.append(7) self.positions.append(8) self._set_found() elif sixth and seventh: self.positions.append(6) self.positions.append(7) self._set_found() else: if sixth: self.positions.append(6) if seventh: self.positions.append(7) if eigth: self.positions.append(8) self.search_spondeus() def _search_fifth(self): eleventh = self._search_long(11) twelfth = self._search_long(12) if eleventh and twelfth: self.positions.append(11) self.positions.append(12) self._set_found() elif eleventh: self.positions.append(11) elif twelfth: self.positions.append(12) self.search_spondeus() def _make_scansion(self): for x in range(1,13): if x not in self.positions: self.questions.append(x) #nr. 30 if 8 in self.questions and 9 in self.questions and 11 in self.questions and 12 in self.questions: self.verse.scansion = '-- -- -- -** -** -X' self._verify_output() #nr. 31 elif 6 in self.questions and 7 in self.questions and 11 in self.questions and 12 in self.questions: self.verse.scansion = '-- -- -** -- -** -X' self._verify_output() #nr. 32 elif 6 in self.questions and 7 in self.questions and 9 in self.questions and 10 in self.questions: self.verse.scansion = '-- -- -** -** -- -X' self._verify_output() #nr. 33 elif 2 in self.questions and 3 in self.questions and 11 in self.questions and 12 in self.questions: self.verse.scansion = '-** -- -- -- -** -X' self._verify_output() #nr. 34 elif 2 in self.questions and 3 in self.questions and 9 in self.questions and 10 in self.questions: self.verse.scansion = '-** -- -- -** -- -X' self._verify_output() #nr. 35 elif 2 in self.questions and 3 in self.questions and 7 in self.questions and 8 in self.questions: self.verse.scansion = '-** -- -** -- -- -X' self._verify_output() #nr. 36 elif 2 in self.questions and 3 in self.questions and 5 in self.questions and 6 in self.questions: self.verse.scansion = '-** -** -- -- -- -X' self._verify_output() #nr. 37 elif 4 in self.questions and 5 in self.questions and 11 in self.questions and 12 in self.questions: self.verse.scansion = '-- -** -- -- -** -X' self._verify_output() #nr. 38 elif 4 in self.questions and 5 in self.questions and 9 in self.questions and 10 in self.questions: self.verse.scansion = '-- -** -- -** -- -X' self._verify_output() #nr. 39 elif 4 in self.questions and 5 in self.questions and 7 in self.questions and 8 in self.questions: self.verse.scansion = '-- -** -** -- -- -X' self._verify_output() else: self.search_spondeus() def _make_spondeus(self): annotator._make_spondeus(self, 12)
['walk', 'caffeinated_dithering', 'caffeinated_running'], ['relax', 'caffeinated', 'standing'] ] # states = ['standing', 'walking', # {'name': 'caffeinated', 'children':['dithering', 'running']}] # transitions = [ # ['walk', 'standing', 'walking'], # ['stop', 'walking', 'standing'], # ['drink', '*', 'caffeinated'], # ['walk', ['caffeinated', 'caffeinated_dithering'], 'caffeinated_running'], # ['relax', 'caffeinated', 'standing'] # ] machine = Machine(states=states, transitions=transitions, initial='standing', ignore_invalid_triggers=True) machine.walk() # Walking now machine.stop() # let's stop for a moment machine.drink() # coffee time print(machine.state) machine.walk() # we have to go faster print(machine.state) machine.stop() # can't stop moving! print(machine.state) machine.relax() # leave nested state print(machine.state) # phew, what a ride
def test_blueprint_remap(self): states = ['1', '2', '3', 'finished'] transitions = [ {'trigger': 'increase', 'source': '1', 'dest': '2'}, {'trigger': 'increase', 'source': '2', 'dest': '3'}, {'trigger': 'decrease', 'source': '3', 'dest': '2'}, {'trigger': 'decrease', 'source': '1', 'dest': '1'}, {'trigger': 'reset', 'source': '*', 'dest': '1'}, {'trigger': 'done', 'source': '3', 'dest': 'finished'} ] counter = Machine(states=states, transitions=transitions, initial='1') new_states = ['A', 'B', {'name': 'C', 'children': [counter, {'name': 'X', 'children': ['will', 'be', 'filtered', 'out']}], 'remap': {'finished': 'A', 'X': 'A'}}] new_transitions = [ {'trigger': 'forward', 'source': 'A', 'dest': 'B'}, {'trigger': 'forward', 'source': 'B', 'dest': 'C%s1' % State.separator}, {'trigger': 'backward', 'source': 'C', 'dest': 'B'}, {'trigger': 'backward', 'source': 'B', 'dest': 'A'}, {'trigger': 'calc', 'source': '*', 'dest': 'C%s1' % State.separator}, ] walker = Machine(states=new_states, transitions=new_transitions, before_state_change='watch', after_state_change='look_back', initial='A') walker.watch = lambda: 'walk' walker.look_back = lambda: 'look_back' counter.increase() counter.increase() counter.done() self.assertEqual(counter.state, 'finished') with self.assertRaises(MachineError): walker.increase() self.assertEqual(walker.state, 'A') walker.forward() walker.forward() self.assertEqual(walker.state, 'C%s1' % State.separator) walker.increase() self.assertEqual(walker.state, 'C%s2' % State.separator) walker.reset() self.assertEqual(walker.state, 'C%s1' % State.separator) walker.to_A() self.assertEqual(walker.state, 'A') walker.calc() self.assertEqual(walker.state, 'C%s1' % State.separator) walker.increase() walker.increase() walker.done() self.assertEqual(walker.state, 'A') self.assertFalse('C.finished' in walker.states)