예제 #1
0
 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')
예제 #2
0
    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')
예제 #3
0
 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')
예제 #4
0
    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  # 用户临时口令
예제 #5
0
파일: machine.py 프로젝트: sina33/asef
 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
예제 #6
0
    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)
예제 #7
0
 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')
예제 #8
0
파일: wholeshow.py 프로젝트: linas/HEAD
    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)
예제 #9
0
    def __init__(self):
        # Wait for service to set initial params
        rospy.wait_for_service('/current/attention/set_parameters')
        rospy.wait_for_service('/current/animations/set_parameters')
        # Current state config
        self.state_config = None
        self.config = None
        self.starting = True
        # Current TTS mode: chatbot_responses - auto, web_sresponses - operator
        self.current_tts_mode = "chatbot_responses"
        # Controls states_timeouts
        self._state_timer = None
        # ROS Topics and services
        self.robot_name = rospy.get_param('/robot_name')
        # ROS publishers
        self.topics = {
            'running_performance':
            rospy.Publisher('/running_performance', String, queue_size=1),
            'chatbot_speech':
            rospy.Publisher('/{}/chatbot_speech'.format(self.robot_name),
                            ChatMessage,
                            queue_size=10),
            'soma_pub':
            rospy.Publisher('/blender_api/set_soma_state',
                            SomaState,
                            queue_size=10),
            'state_pub':
            rospy.Publisher('/current_state', String, latch=True),
        }
        # ROS Subscribers
        self.subscribers = {
            'speech':
            rospy.Subscriber('/{}/speech'.format(self.robot_name), ChatMessage,
                             self.speech_cb),
            'running_performance':
            rospy.Subscriber('/performances/running_performance', String,
                             self.performance_cb),
            'performance_events':
            rospy.Subscriber('/performances/events', PerformanceEvent,
                             self.performance_events_cb),
            'speech_events':
            rospy.Subscriber('/{}/speech_events'.format(self.robot_name),
                             String, self.speech_events_cb),
            'chat_events':
            rospy.Subscriber('/{}/chat_events'.format(self.robot_name), String,
                             self.chat_events_cb),
            'state_switch':
            rospy.Subscriber('/state_switch', String, self.state_callback),
            'tts_mux':
            rospy.Subscriber('/{}/tts_mux/selected'.format(self.robot_name),
                             String, self.tts_mux_cb)
        }
        # ROS Services
        # Wait for all services to become available
        rospy.wait_for_service('/blender_api/set_param')
        rospy.wait_for_service('/performances/current')
        # All services required.
        self.services = {
            'performance_runner':
            rospy.ServiceProxy('/performances/run_full_performance',
                               srv.RunByName),
            'blender_param':
            rospy.ServiceProxy('/blender_api/set_param', SetParam),
        }
        # Configure clients
        self.clients = {
            'attention':
            dynamic_reconfigure.client.Client('/current/attention',
                                              timeout=0.1),
            'animation':
            dynamic_reconfigure.client.Client('/current/animations',
                                              timeout=0.1),
        }
        # robot properties
        self.props = {
            'disable_attention': None,
            'disable_animations': None,
            'disable_blinking': None,
            'disable_saccades': None,
            'disable_keepalive': None,
        }

        self._before_presentation = ''
        self._current_performance = None
        # State server mostly used for checking current states settings
        self.state_server = Server(StateConfig,
                                   self.state_config_callback,
                                   namespace='/current/state_settings')
        # Machine starts
        HierarchicalMachine.__init__(
            self,
            states=STATES,
            transitions=TRANSITIONS,
            initial='idle',
            ignore_invalid_triggers=True,
            after_state_change=self.state_changed,
            before_state_change=self.on_before_state_change)
        # Main param server
        self.server = Server(StatesConfig,
                             self.config_callback,
                             namespace='/behavior/behavior_settings')
        self.faces_db_file = None
        self.known_faces = {}
        self.faces_last_update = time.time()
        # Faces last seen database:
        try:
            assemblies = rospy.get_param('/assemblies')
            assembly = assemblies[0] if self.robot_name in assemblies[
                0] else assemblies[1]
            self.faces_db_file = os.path.join(assembly, 'known_faces.yaml')
            with open(self.faces_db_file, 'r') as stream:
                try:
                    self.known_faces = yaml.load(stream)
                except yaml.YAMLError as exc:
                    logger.warn(exc)
        except Exception as e:
            logger.error("Cant load the known faces {}".format(e))
        rospy.Subscriber('/{}/perception/state'.format(self.robot_name), State,
                         self.perception_state_cb)