コード例 #1
0
ファイル: main.py プロジェクト: insanemal/mycroft-core
def main():
    global client
    global loop
    client = WebsocketClient()
    device_index = config.get('speech_client').get('device_index')
    if device_index:
        device_index = int(device_index)
    loop = RecognizerLoop(device_index=device_index)
    loop.on('recognizer_loop:listening', handle_listening)
    loop.on('recognizer_loop:wakeword', handle_wakeword)
    loop.on('recognizer_loop:utterance', handle_utterance)
    loop.on('speak', handle_speak)
    client.on('speak', handle_speak)
    client.on('multi_utterance_intent_failure',
              handle_multi_utterance_intent_failure)
    client.on('recognizer_loop:sleep', handle_sleep)
    client.on('recognizer_loop:wake_up', handle_wake_up)
    event_thread = Thread(target=connect)
    event_thread.setDaemon(True)
    event_thread.start()
    try:
        loop.run()
    except KeyboardInterrupt, e:
        event_thread.exit()
        sys.exit()
コード例 #2
0
    def __init__(self, name=None, emitter=None, timeout=5, logger=None):
        """
           initialize emitter, register events, initialize internal variables

           args:
                name(str): name identifier
                emitter (WebsocketClient): mycroft messagebus websocket
                timeout (int): maximum seconds to wait for reply
                logger (logger) : custom logger if desired
        """
        if name is None:
            self.name = "QueryBackend"
        else:
            self.name = name
        if emitter is None:
            self.emitter = WebsocketClient()

            def connect():
                self.emitter.run_forever()

            ws_thread = Thread(target=connect)
            ws_thread.setDaemon(True)
            ws_thread.start()
        else:
            self.emitter = emitter
        self.timeout = timeout
        self.query = None
        if logger is None:
            self.logger = LOG
        else:
            self.logger = logger
        self.waiting_messages = []
        self.elapsed_time = 0
        self.config = Configuration.get().get(self.name, {})
        self.result = {}
コード例 #3
0
def main():
    global ws
    lock = Lock('skills')  # prevent multiple instances of this service

    # Connect this Skill management process to the websocket
    ws = WebsocketClient()
    ConfigurationManager.init(ws)

    ignore_logs = ConfigurationManager.instance().get("ignore_logs")

    # Listen for messages and echo them for logging
    def _echo(message):
        try:
            _message = json.loads(message)

            if _message.get("type") in ignore_logs:
                return

            if _message.get("type") == "registration":
                # do not log tokens from registration messages
                _message["data"]["token"] = None
            message = json.dumps(_message)
        except:
            pass
        LOG('SKILLS').debug(message)

    ws.on('message', _echo)
    ws.on('skill.converse.request', handle_converse_request)
    # Startup will be called after websocket is full live
    ws.once('open', _starting_up)
    ws.run_forever()
コード例 #4
0
def simple_cli():
    global bus
    global bSimple
    bSimple = True
    bus = WebsocketClient()  # Mycroft messagebus connection
    event_thread = Thread(target=connect)
    event_thread.setDaemon(True)
    event_thread.start()
    bus.on('speak', handle_speak)
    try:
        while True:
            # Sleep for a while so all the output that results
            # from the previous command finishes before we print.
            time.sleep(1.5)
            print("Input (Ctrl+C to quit):")
            line = sys.stdin.readline()
            bus.emit(Message("recognizer_loop:utterance",
                             {'utterances': [line.strip()]}))
    except KeyboardInterrupt as e:
        # User hit Ctrl+C to quit
        print("")
    except KeyboardInterrupt as e:
        LOG.exception(e)
        event_thread.exit()
        sys.exit()
コード例 #5
0
    def __init__(self):
        self.ws = WebsocketClient()

        Configuration.init(self.ws)

        global_config = Configuration.get()
        self.lang = global_config['lang']
        self.config = global_config.get("enclosure")

        self.__init_serial()
        self.reader = EnclosureReader(self.serial, self.ws, self.lang)
        self.writer = EnclosureWriter(self.serial, self.ws)

        # Prepare to receive message when the Arduino responds to the
        # following "system.version"
        self.ws.on("enclosure.started", self.on_arduino_responded)
        self.arduino_responded = False
        # Send a message to the Arduino across the serial line asking
        # for a reply with version info.
        self.writer.write("system.version")
        # Start a 5 second timer.  If the serial port hasn't received
        # any acknowledgement of the "system.version" within those
        # 5 seconds, assume there is nothing on the other end (e.g.
        # we aren't running a Mark 1 with an Arduino)
        Timer(5, self.check_for_response).start()

        # Notifications from mycroft-core
        self.ws.on("enclosure.notify.no_internet", self.on_no_internet)

        # initiates the web sockets on display manager
        # NOTE: this is a temporary place to initiate display manager sockets
        initiate_display_manager_ws()
コード例 #6
0
    def setUp(self):
        """
        This sets up for testing the message buss

        This requires starting the mycroft service and creating two
        WebsocketClient object to talk with eachother.  Not this is
        threaded and will require cleanup
        """
        # start the mycroft service. and get the pid of the script.
        self.pid = Popen(["python", "mycroft/messagebus/service/main.py"]).pid
        # delay to allow the service to start up.
        time.sleep(10)
        # Create the two web clients
        self.ws1 = WebsocketClient()
        self.ws2 = WebsocketClient()
        # init the flags for handler's
        self.handle1 = False
        self.handle2 = False
        # Start threads to handle websockets
        Thread(target=self.ws1.run_forever).start()
        Thread(target=self.ws2.run_forever).start()
        # Sleep to give the websockets to startup before adding handlers
        time.sleep(10)
        # Setup handlers for each of the messages.
        self.ws1.on('ws1.message', self.onHandle1)
        self.ws2.on('ws2.message', self.onHandle2)
コード例 #7
0
def listener():
    rospy.init_node('mycroft_skills')
    rospy.loginfo(rospy.get_caller_id() + " started")
    rospy.Subscriber("mycroft/utterance", String, handle_utterance)
    rospy.Subscriber("mycroft/remove_skill", String, handle_remove_skill)
    s = rospy.Service('mycroft/register_skill', MycroftService,
                      handle_register_skill)

    global bus
    reset_sigint_handler()
    # Create PID file, prevent multiple instancesof this service
    mycroft.lock.Lock('skills')
    # Connect this Skill management process to the Mycroft Messagebus
    bus = WebsocketClient()
    Configuration.init(bus)
    config = Configuration.get()
    # Set the active lang to match the configured one
    set_active_lang(config.get('lang', 'en-us'))

    bus.on('skill.manager.initialised', initialise_response_server)
    bus.on('message', create_echo_function('SKILLS'))
    # Startup will be called after the connection with the Messagebus is done
    bus.once('open', _starting_up)
    bus.on('skill.converse.request', check_working)

    create_daemon(bus.run_forever)
    wait_for_exit_signal()
    shutdown()

    rospy.spin()
コード例 #8
0
    def setUp(self):
        """
        This sets up for testing the message buss

        This requires starting the mycroft service and creating two
        WebsocketClient object to talk with eachother.  Not this is
        threaded and will require cleanup
        """
        # start the mycroft service. and get the pid of the script.
        self.pid = Popen(["python", "mycroft/messagebus/service/main.py"]).pid
        # delay to allow the service to start up.
        time.sleep(10)
        # Create the two web clients
        self.ws1 = WebsocketClient()
        self.ws2 = WebsocketClient()
        # init the flags for handler's
        self.handle1 = False
        self.handle2 = False
        # Start threads to handle websockets
        Thread(target=self.ws1.run_forever).start()
        Thread(target=self.ws2.run_forever).start()
        # Sleep to give the websockets to startup before adding handlers
        time.sleep(10)
        # Setup handlers for each of the messages.
        self.ws1.on('ws1.message', self.onHandle1)
        self.ws2.on('ws2.message', self.onHandle2)
コード例 #9
0
ファイル: container.py プロジェクト: wligtenberg/mycroft-core
    def __init__(self, args):
        parser = argparse.ArgumentParser()
        parser.add_argument("--dependency-dir", default="./lib")
        parser.add_argument("--messagebus-host",
                            default=messagebus_config.get("host"))
        parser.add_argument("--messagebus-port",
                            type=int,
                            default=messagebus_config.get("port"))
        parser.add_argument("--use-ssl", action='store_true', default=False)
        parser.add_argument("--enable-intent-skill",
                            action='store_true',
                            default=False)
        parser.add_argument("skill_directory",
                            default=os.path.dirname(__file__))

        parsed_args = parser.parse_args(args)
        if os.path.exists(parsed_args.dependency_dir):
            sys.path.append(parsed_args.dependency_dir)
        sys.path.append(parsed_args.skill_directory)

        self.skill_directory = parsed_args.skill_directory

        self.enable_intent_skill = parsed_args.enable_intent_skill

        self.client = WebsocketClient(host=parsed_args.messagebus_host,
                                      port=parsed_args.messagebus_port,
                                      ssl=parsed_args.use_ssl)
コード例 #10
0
    def __init__(self, name=None, emitter=None, logger=None):
        """
           initialize responder

           args:
                name(str): name identifier
                emitter (WebsocketClient): mycroft messagebus websocket
                logger (logger) : custom logger if desired
        """
        if name is None:
            self.name = "ResponderBackend"
        else:
            self.name = name
        if emitter is None:
            self.emitter = WebsocketClient()

            def connect():
                self.emitter.run_forever()
            ws_thread = Thread(target=connect)
            ws_thread.setDaemon(True)
            ws_thread.start()
        else:
            self.emitter = emitter
        self.response_type = "default.reply"
        if self.responder:
            self.responder.shutdown()
            self.responder = None
        self.callback = None
        if logger is None:
            self.logger = LOG
        else:
            self.logger = logger
        self.config = Configuration.get().get(self.name, {})
        self.events = []
コード例 #11
0
 def create_internal_emitter(self):
     # connect to mycroft internal websocket
     self.emitter = WebsocketClient()
     self.register_internal_messages()
     self.emitter_thread = Thread(target=self.connect_to_internal_emitter)
     self.emitter_thread.setDaemon(True)
     self.emitter_thread.start()
コード例 #12
0
ファイル: localstt.py プロジェクト: tjoen/local_listener
    def __init__(self,
                 hmm=None,
                 lm=None,
                 le_dict=None,
                 lang="en-us",
                 emitter=None,
                 debug=False):
        self.lang = lang
        self.decoder = None
        self.listening = False
        self.emitter = emitter
        self.event_thread = None
        self.async_thread = None
        # get hmm, already in mycroft
        self.hmm = MYCROFT_ROOT_PATH + '/mycroft/client/speech/recognizer/model/en-us/hmm/'
        # load wav config
        self.audioconfig = ConfigurationManager.get()
        self.reset_decoder()

        if not debug:
            ERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int, c_char_p,
                                           c_int, c_char_p)

            def py_error_handler(filename, line, function, err, fmt):
                ignores = [0, 2, 16, 77]
                if err not in ignores:
                    print err, fmt

            c_error_handler = ERROR_HANDLER_FUNC(py_error_handler)

            @contextmanager
            def noalsaerr():
                asound = cdll.LoadLibrary('libasound.so')
                asound.snd_lib_error_set_handler(c_error_handler)
                yield
                asound.snd_lib_error_set_handler(None)

            with noalsaerr():
                self.p = pyaudio.PyAudio()
        else:
            self.p = pyaudio.PyAudio()
        self.stream = self.p.open(format=pyaudio.paInt16,
                                  channels=1,
                                  rate=16000,
                                  input=True,
                                  frames_per_buffer=1024)

        if self.emitter is None:
            self.emitter = WebsocketClient()

            def connect():
                # Once the websocket has connected, just watch it for events
                self.emitter.run_forever()

            self.event_thread = Thread(target=connect)
            self.event_thread.setDaemon(True)
            self.event_thread.start()
            sleep(2)
コード例 #13
0
 def __init__(self):
     self.iface = pyw.winterfaces()[0]
     self.ap = AccessPoint(self.iface)
     self.server = None
     self.client = WebsocketClient()
     self.enclosure = EnclosureAPI(self.client)
     self.config = ConfigurationManager.get().get(self.NAME)
     self.init_events()
     self.first_setup()
コード例 #14
0
 def __init__(self):
     self.iface = pyw.winterfaces()[0]
     self.ap = AccessPoint(self.iface)
     self.server = None
     self.client = WebsocketClient()
     self.enclosure = EnclosureAPI(self.client)
     self.init_events()
     self.conn_monitor = None
     self.conn_monitor_stop = threading.Event()
コード例 #15
0
 def __init__(self):
     self.__init_serial()
     self.client = WebsocketClient()
     self.reader = EnclosureReader(self.serial, self.client)
     self.writer = EnclosureWriter(self.serial, self.client)
     self.eyes = EnclosureEyes(self.client, self.writer)
     self.mouth = EnclosureMouth(self.client, self.writer)
     self.system = EnclosureArduino(self.client, self.writer)
     self.__init_events()
コード例 #16
0
ファイル: client.py プロジェクト: insanemal/mycroft-core
 def __init__(self, config=_config, pairing_code=None):
     self.config = config
     self.ws_client = WebsocketClient(host=config.get("host"),
                                      port=config.get("port"),
                                      path=config.get("route"),
                                      ssl=str2bool(config.get("ssl")))
     self.identity_manager = IdentityManager()
     self.identity = self.identity_manager.identity
     self.pairing_code = pairing_code if pairing_code else generate_pairing_code()
コード例 #17
0
ファイル: enclosure.py プロジェクト: Cliabhach/mycroft-core
class Enclosure:
    """
    Serves as a communication interface between Arduino and Mycroft Core.

    ``Enclosure`` initializes and aggregates all enclosures implementation.

    E.g. ``EnclosureEyes``, ``EnclosureMouth`` and ``EnclosureArduino``

    It also listens to the basis events in order to perform those core actions
    on the unit.

    E.g. Start and Stop talk animation
    """

    def __init__(self):
        self.__init_serial()
        self.client = WebsocketClient()
        self.reader = EnclosureReader(self.serial, self.client)
        self.writer = EnclosureWriter(self.serial, self.client)
        self.eyes = EnclosureEyes(self.client, self.writer)
        self.mouth = EnclosureMouth(self.client, self.writer)
        self.system = EnclosureArduino(self.client, self.writer)
        self.__init_events()

    def __init_serial(self):
        try:
            self.config = ConfigurationManager.get_config().get("enclosure")
            self.port = self.config.get("port")
            self.rate = int(self.config.get("rate"))
            self.timeout = int(self.config.get("timeout"))
            self.serial = serial.serial_for_url(
                url=self.port, baudrate=self.rate, timeout=self.timeout)
            LOGGER.info(
                "Connected to: " + self.port + " rate: " + str(self.rate) +
                " timeout: " + str(self.timeout))
        except:
            LOGGER.error(
                "It is not possible to connect to serial port: " + self.port)
            raise

    def __init_events(self):
        self.client.on('recognizer_loop:listening', self.mouth.listen)
        self.client.on('recognizer_loop:audio_output_start', self.mouth.talk)
        self.client.on('recognizer_loop:audio_output_end', self.mouth.reset)
        self.client.on('recognizer_loop:wakeword', self.eyes.blink)

    def run(self):
        try:
            self.client.run_forever()
        except Exception as e:
            LOGGER.error("Client error: {0}".format(e))
            self.stop()

    def stop(self):
        self.writer.stop()
        self.reader.stop()
        self.serial.close()
コード例 #18
0
class Enclosure:
    """
    Serves as a communication interface between Arduino and Mycroft Core.

    ``Enclosure`` initializes and aggregates all enclosures implementation.

    E.g. ``EnclosureEyes``, ``EnclosureMouth`` and ``EnclosureArduino``

    It also listens to the basis events in order to perform those core actions
    on the unit.

    E.g. Start and Stop talk animation
    """
    def __init__(self):
        self.__init_serial()
        self.client = WebsocketClient()
        self.reader = EnclosureReader(self.serial, self.client)
        self.writer = EnclosureWriter(self.serial, self.client)
        self.eyes = EnclosureEyes(self.client, self.writer)
        self.mouth = EnclosureMouth(self.client, self.writer)
        self.system = EnclosureArduino(self.client, self.writer)
        self.__init_events()

    def __init_serial(self):
        try:
            self.config = ConfigurationManager.get_config().get("enclosure")
            self.port = self.config.get("port")
            self.rate = int(self.config.get("rate"))
            self.timeout = int(self.config.get("timeout"))
            self.serial = serial.serial_for_url(url=self.port,
                                                baudrate=self.rate,
                                                timeout=self.timeout)
            LOGGER.info("Connected to: " + self.port + " rate: " +
                        str(self.rate) + " timeout: " + str(self.timeout))
        except:
            LOGGER.error("It is not possible to connect to serial port: " +
                         self.port)
            raise

    def __init_events(self):
        self.client.on('recognizer_loop:listening', self.mouth.listen)
        self.client.on('recognizer_loop:audio_output_start', self.mouth.talk)
        self.client.on('recognizer_loop:audio_output_end', self.mouth.reset)
        self.client.on('recognizer_loop:wakeword', self.eyes.blink)

    def run(self):
        try:
            self.client.run_forever()
        except Exception as e:
            LOGGER.error("Client error: {0}".format(e))
            self.stop()

    def stop(self):
        self.writer.stop()
        self.reader.stop()
        self.serial.close()
コード例 #19
0
ファイル: main.py プロジェクト: Acidburn0zzz/mycroft-core
def main():
    global client
    global loop
    client = WebsocketClient()
    device_index = config.get('speech_client').get('device_index')
    if device_index:
        device_index = int(device_index)
    loop = RecognizerLoop(device_index=device_index)
    loop.on('recognizer_loop:utterance', handle_utterance)
    loop.on('recognizer_loop:record_begin', handle_record_begin)
    loop.on('recognizer_loop:wakeword', handle_wakeword)
    loop.on('recognizer_loop:record_end', handle_record_end)
    loop.on('speak', handle_speak)
    client.on('speak', handle_speak)
    client.on(
        'multi_utterance_intent_failure',
        handle_multi_utterance_intent_failure)
    client.on('recognizer_loop:sleep', handle_sleep)
    client.on('recognizer_loop:wake_up', handle_wake_up)
    event_thread = Thread(target=connect)
    event_thread.setDaemon(True)
    event_thread.start()
    try:
        loop.run()
    except KeyboardInterrupt, e:
        logger.exception(e)
        event_thread.exit()
        sys.exit()
コード例 #20
0
ファイル: enclosure.py プロジェクト: tornadozou/mycroft-core
    def __init__(self):
        resetSelf = False
        try:
            self.config = ConfigurationManager.get().get("enclosure")

            platform = self.config.get('platform')
            if platform is None:
                # Use the serial port to check if this is a Mycroft
                # Mark 1 unit.
                platform = self.detect_platform()
                if platform == 'unknown':
                    # Since this is a semi-permanent detection, be
                    # certain!  Sometimes noise on the serial line
                    # causes a faulty mis-detection on a real
                    # Mycroft Mark 1
                    platform = self.detect_platform()

                ConfigurationManager.set('enclosure', 'platform', platform)

                # After a platform detection, the system is usually
                # already active, so the message from the loop
                # has already gone by on the messagebus.  So self reset.
                resetSelf = True
        except Exception as e:
            self.disconnect()
            raise Exception("Exception: Unable to determine platform\n" +
                            str(e))

        LOGGER.info("Platform = '" + platform + "'")
        if platform == "mycroft_mark_1":
            # We are a mycroft_mark_1 unit, start up the
            # enclosure client to communicate over the
            # serial port
            self.__init_serial()
        else:
            self.disconnect()
            raise Exception("Exception: Not a Mycroft Mark 1, shutting down")

        self.client = WebsocketClient()
        self.reader = EnclosureReader(self.serial, self.client)
        self.writer = EnclosureWriter(self.serial, self.client)

        # Create helpers to handle the various parts of the enclosure
        self.eyes = EnclosureEyes(self.client, self.writer)
        self.mouth = EnclosureMouth(self.client, self.writer)
        self.system = EnclosureArduino(self.client, self.writer)

        # TODO: Remove EnclosureWeather once the Skill can send images
        #       directly to the EnclosureAPI.
        self.weather = EnclosureWeather(self.client, self.writer)
        self.__register_events()

        if resetSelf:
            self.__handle_reset(None)
コード例 #21
0
 def __init__(self):
     self.ws = WebsocketClient()
     ConfigurationManager.init(self.ws)
     self.config = ConfigurationManager.get().get("enclosure")
     self.__init_serial()
     self.reader = EnclosureReader(self.serial, self.ws)
     self.writer = EnclosureWriter(self.serial, self.ws)
     self.writer.write("system.version")
     self.ws.on("enclosure.start", self.start)
     self.started = False
     Timer(5, self.stop).start()  # WHY? This at least
コード例 #22
0
ファイル: container.py プロジェクト: teotikalki/mycroft-core
    def __init_client(self, params):
        config = ConfigurationManager.get().get("messagebus_client")

        if not params.host:
            params.host = config.get('host')
        if not params.port:
            params.port = config.get('port')

        self.client = WebsocketClient(host=params.host,
                                      port=params.port,
                                      ssl=params.use_ssl)
コード例 #23
0
ファイル: __init__.py プロジェクト: tomh05/teddy-ruxpi
 def __init__(self):
     self.ws = WebsocketClient()
     ConfigurationManager.init(self.ws)
     self.config = ConfigurationManager.get().get("enclosure")
     self.__init_serial()
     self.reader = EnclosureReader(self.serial, self.ws)
     self.writer = EnclosureWriter(self.serial, self.ws)
     self.writer.write("system.version")
     self.ws.on("enclosure.start", self.start)
     self.started = False
     Timer(5, self.reconnect).start(
     )  # WHY? This at least needs an explaination, this is non-obvious behavior
コード例 #24
0
def main():
    global skill_response, wait_response, port, lang
    wait_response = True
    skill_response = ""

    global ws
    ws = WebsocketClient()
    event_thread = Thread(target=connect)
    event_thread.setDaemon(True)
    event_thread.start()

    ws.on('speak', handle_speak)

    import tornado.options

    tornado.options.parse_command_line()
    config = ConfigurationManager.get().get("websocket")
    lang = ConfigurationManager.get().get("lang")

    port = "9090"
    url = ("http://" + str(ip) + ":" + str(port))
    print("*********************************************************")
    print("*   JCASOFT - Mycroft Web Cliento ")
    print("*")
    print("*   Access from web browser " + url)
    print("*********************************************************")

    routes = [
        tornado.web.url(r"/", MainHandler, name="main"),
        tornado.web.url(r"/static/(.*)", tornado.web.StaticFileHandler,
                        {'path': './'}),
        tornado.web.url(r"/ws", WebSocketHandler)
    ]

    settings = {
        "debug": True,
        "template_path": os.path.join(os.path.dirname(__file__), "templates"),
        "static_path": os.path.join(os.path.dirname(__file__), "static"),
    }

    application = tornado.web.Application(routes, **settings)
    httpServer = tornado.httpserver.HTTPServer(application)
    tornado.options.parse_command_line()
    httpServer.listen(port)

    try:
        tornado.ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        logger.exception(e)
        event_thread.exit()
        tornado.ioloop.IOLoop.instance().stop()
        sys.exit()
コード例 #25
0
    def __init__(self):
        self.ws = WebsocketClient()
        self.ws.on("open", self.on_ws_open)

        ConfigurationManager.init(self.ws)
        self.config = ConfigurationManager.instance().get("enclosure")
        self.__init_serial()
        self.reader = EnclosureReader(self.serial, self.ws)
        self.writer = EnclosureWriter(self.serial, self.ws)

        # initiates the web sockets on display manager
        # NOTE: this is a temporary place to initiate display manager sockets
        initiate_display_manager_ws()
コード例 #26
0
def main():
    global skill_response, wait_response, port, lang
    wait_response = True
    skill_response = ""

    global ws
    ws = WebsocketClient()
    event_thread = Thread(target=connect)
    event_thread.setDaemon(True)
    event_thread.start()

    ws.on('speak', handle_speak)

    import tornado.options

    tornado.options.parse_command_line()
    config = ConfigurationManager.get().get("websocket")
    lang = ConfigurationManager.get().get("lang")

    host = config.get("host")
    port = config.get("port")
    route = config.get("route")
    validate_param(host, "websocket.host")
    validate_param(port, "websocket.port")
    validate_param(route, "websocket.route")


    url = "http://" + str(ip)+":"+str(port)
    print "*********************************************************"
    print "*   Access from web browser " + url
    print "*********************************************************"

    routes = [
        (route, WebsocketEventHandler),
	tornado.web.url(r"/", MainHandler, name="main"),
	tornado.web.url(r"/static/(.*)", tornado.web.StaticFileHandler, {'path':  './'}),
	tornado.web.url(r"/ws", WebSocketHandler)
    ]

    settings = {
        "debug": True,
        "template_path": os.path.join(os.path.dirname(__file__), "templates"),
        "static_path": os.path.join(os.path.dirname(__file__), "static"),
    }
    

    application = tornado.web.Application(routes, **settings)
    httpServer = tornado.httpserver.HTTPServer(application)
    tornado.options.parse_command_line()
    httpServer.listen(port)
    tornado.ioloop.IOLoop.instance().start()
コード例 #27
0
def main():
    global ws
    global config
    ws = WebsocketClient()
    ConfigurationManager.init(ws)
    config = ConfigurationManager.get()
    speech.init(ws)

    # Setup control of pulse audio
    setup_pulseaudio_handlers(config.get('Audio').get('pulseaudio'))

    def echo(message):
        try:
            _message = json.loads(message)
            if 'mycroft.audio.service' not in _message.get('type'):
                return
            message = json.dumps(_message)
        except:
            pass
        LOG.debug(message)

    LOG.info("Staring Audio Services")
    ws.on('message', echo)
    ws.once('open', load_services_callback)
    try:
        ws.run_forever()
    except KeyboardInterrupt, e:
        LOG.exception(e)
        speech.shutdown()
        sys.exit()
コード例 #28
0
    def __init_client(self, params):
        config = ConfigurationManager.get().get("websocket")

        if not params.host:
            params.host = config.get('host')
        if not params.port:
            params.port = config.get('port')

        self.ws = WebsocketClient(host=params.host,
                                  port=params.port,
                                  ssl=params.use_ssl)

        # Connect configuration manager to message bus to receive updates
        ConfigurationManager.init(self.ws)
コード例 #29
0
class SkillContainer(object):
    def __init__(self, args):
        parser = argparse.ArgumentParser()
        parser.add_argument("--dependency-dir", default="./lib")
        parser.add_argument("--messagebus-host", default=messagebus_config.get("host"))
        parser.add_argument("--messagebus-port", type=int, default=messagebus_config.get("port"))
        parser.add_argument("--use-ssl", action='store_true', default=False)
        parser.add_argument("--enable-intent-skill", action='store_true', default=False)
        parser.add_argument("skill_directory", default=os.path.dirname(__file__))

        parsed_args = parser.parse_args(args)
        if os.path.exists(parsed_args.dependency_dir):
            sys.path.append(parsed_args.dependency_dir)

        self.skill_directory = parsed_args.skill_directory
        self.enable_intent_skill = parsed_args.enable_intent_skill

        self.client = WebsocketClient(host=parsed_args.messagebus_host,
                                      port=parsed_args.messagebus_port,
                                      ssl=parsed_args.use_ssl)

    def try_load_skill(self):
        if self.enable_intent_skill:
            intent_skill = create_intent_skill()
            intent_skill.bind(self.client)
            intent_skill.initialize()
        skill_descriptor = create_skill_descriptor(self.skill_directory)
        load_skill(skill_descriptor, self.client)

    def run(self):
        self.client.on('message', logger.debug)
        self.client.on('open', self.try_load_skill)
        self.client.on('error', logger.error)
        self.client.run_forever()
コード例 #30
0
def main():
    global ws
    ws = WebsocketClient()
    tts.init(ws)
    if '--quiet' in sys.argv:
        ws.on('speak', handle_quiet)
    else:
        ws.on('speak', handle_speak)
    event_thread = Thread(target=connect)
    event_thread.setDaemon(True)
    event_thread.start()
    try:
        while True:
            # TODO: Change this mechanism
            # Sleep for a while so all the output that results
            # from the previous command finishes before we print.
            time.sleep(1.5)
            print("Input (Ctrl+C to quit):")
            line = sys.stdin.readline()
            ws.emit(
                Message("recognizer_loop:utterance",
                        {'utterances': [line.strip()]}))
    except KeyboardInterrupt, e:
        # User hit Ctrl+C to quit
        print("")
コード例 #31
0
ファイル: main.py プロジェクト: zero-direwolf/mycroft-core
def main():
    global ws
    global config
    global pulse
    ws = WebsocketClient()
    ConfigurationManager.init(ws)
    config = ConfigurationManager.get()
    speech.init(ws)

    # Setup control of pulse audio
    if pulsectl and config.get('Audio').get('pulseaudio') == 'mute':
        pulse = pulsectl.Pulse('Mycroft-audio-service')
    else:
        pulse = None

    def echo(message):
        try:
            _message = json.loads(message)

            if 'mycroft.audio.service' in _message.get('type'):
                return
            message = json.dumps(_message)
        except:
            pass
        logger.debug(message)

    logger.info("Staring Audio Services")
    ws.on('message', echo)
    ws.once('open', load_services_callback)
    try:
        ws.run_forever()
    except KeyboardInterrupt, e:
        logger.exception(e)
        speech.shutdown()
        sys.exit()
コード例 #32
0
def main():
    global ws
    lock = Lock('skills')  # prevent multiple instances of this service

    # Connect this Skill management process to the websocket
    ws = WebsocketClient()
    ConfigurationManager.init(ws)

    ignore_logs = ConfigurationManager.instance().get("ignore_logs")

    # Listen for messages and echo them for logging
    def _echo(message):
        try:
            _message = json.loads(message)

            if _message.get("type") in ignore_logs:
                return

            if _message.get("type") == "registration":
                # do not log tokens from registration messages
                _message["data"]["token"] = None
            message = json.dumps(_message)
        except:
            pass
        logger.debug(message)

    ws.on('message', _echo)

    # Kick off loading of skills
    ws.once('open', _load_skills)
    ws.run_forever()
コード例 #33
0
def connect_to_messagebus():
    global bus
    bus = WebsocketClient()  # Mycroft messagebus connection

    event_thread = Thread(target=connect)
    event_thread.setDaemon(True)
    event_thread.start()
コード例 #34
0
ファイル: __main__.py プロジェクト: Dark5ide/mycroft-core
def main():
    global bus
    reset_sigint_handler()
    # Create PID file, prevent multiple instancesof this service
    mycroft.lock.Lock('skills')
    # Connect this Skill management process to the Mycroft Messagebus
    bus = WebsocketClient()
    Configuration.init(bus)

    bus.on('message', create_echo_function('SKILLS'))
    # Startup will be called after the connection with the Messagebus is done
    bus.once('open', _starting_up)

    create_daemon(bus.run_forever)
    wait_for_exit_signal()
    shutdown()
コード例 #35
0
ファイル: container.py プロジェクト: Cliabhach/mycroft-core
    def __init__(self, args):
        parser = argparse.ArgumentParser()
        parser.add_argument("--dependency-dir", default="./lib")
        parser.add_argument(
            "--messagebus-host", default=messagebus_config.get("host"))
        parser.add_argument(
            "--messagebus-port", type=int,
            default=messagebus_config.get("port"))
        parser.add_argument("--use-ssl", action='store_true', default=False)
        parser.add_argument(
            "--enable-intent-skill", action='store_true', default=False)
        parser.add_argument(
            "skill_directory", default=os.path.dirname(__file__))

        parsed_args = parser.parse_args(args)
        if os.path.exists(parsed_args.dependency_dir):
            sys.path.append(parsed_args.dependency_dir)
        sys.path.append(parsed_args.skill_directory)

        self.skill_directory = parsed_args.skill_directory

        self.enable_intent_skill = parsed_args.enable_intent_skill

        self.client = WebsocketClient(host=parsed_args.messagebus_host,
                                      port=parsed_args.messagebus_port,
                                      ssl=parsed_args.use_ssl)
コード例 #36
0
ファイル: cli.py プロジェクト: BK-University/mycroft-core
def main():
    global client
    client = WebsocketClient()
    if not '--quiet' in sys.argv:
        client.on('speak', handle_speak)
    event_thread = Thread(target=connect)
    event_thread.setDaemon(True)
    event_thread.start()
    try:
        while True:
            print("Input:")
            line = sys.stdin.readline()
            client.emit(Message("recognizer_loop:utterance", metadata={'utterances': [line.strip()]}))
    except KeyboardInterrupt, e:
        event_thread.exit()
        sys.exit()
コード例 #37
0
ファイル: main.py プロジェクト: hungnt1/core
def main():
    """ Main function. Run when file is invoked. """
    reset_sigint_handler()
    ws = WebsocketClient()
    Configuration.init(ws)
    speech.init(ws)

    LOG.info("Starting Audio Services")
    ws.on('message', create_echo_function('AUDIO', ['mycroft.audio.service']))
    audio = AudioService(ws)  # Connect audio service instance to message bus
    create_daemon(ws.run_forever)

    wait_for_exit_signal()

    speech.shutdown()
    audio.shutdown()
コード例 #38
0
ファイル: container.py プロジェクト: teotikalki/mycroft-core
class SkillContainer(object):
    def __init__(self, args):
        params = self.__build_params(args)

        if params.config:
            ConfigurationManager.load_local([params.config])

        if exists(params.lib) and isdir(params.lib):
            sys.path.append(params.lib)

        sys.path.append(params.dir)
        self.dir = params.dir

        self.enable_intent_skill = params.enable_intent_skill

        self.__init_client(params)

    @staticmethod
    def __build_params(args):
        parser = argparse.ArgumentParser()
        parser.add_argument("--config", default="./mycroft.ini")
        parser.add_argument("--dir", default=dirname(__file__))
        parser.add_argument("--lib", default="./lib")
        parser.add_argument("--host", default=None)
        parser.add_argument("--port", default=None)
        parser.add_argument("--use-ssl", action='store_true', default=False)
        parser.add_argument("--enable-intent-skill",
                            action='store_true',
                            default=False)
        return parser.parse_args(args)

    def __init_client(self, params):
        config = ConfigurationManager.get().get("messagebus_client")

        if not params.host:
            params.host = config.get('host')
        if not params.port:
            params.port = config.get('port')

        self.client = WebsocketClient(host=params.host,
                                      port=params.port,
                                      ssl=params.use_ssl)

    def try_load_skill(self):
        if self.enable_intent_skill:
            intent_skill = create_intent_skill()
            intent_skill.bind(self.client)
            intent_skill.initialize()
        skill_descriptor = create_skill_descriptor(self.dir)
        load_skill(skill_descriptor, self.client)

    def run(self):
        self.client.on('message', logger.debug)
        self.client.on('open', self.try_load_skill)
        self.client.on('error', logger.error)
        self.client.run_forever()
コード例 #39
0
ファイル: __main__.py プロジェクト: Dark5ide/mycroft-core
def main():
    """ Main function. Run when file is invoked. """
    reset_sigint_handler()
    check_for_signal("isSpeaking")
    bus = WebsocketClient()  # Connect to the Mycroft Messagebus
    Configuration.init(bus)
    speech.init(bus)

    LOG.info("Starting Audio Services")
    bus.on('message', create_echo_function('AUDIO', ['mycroft.audio.service']))
    audio = AudioService(bus)  # Connect audio service instance to message bus
    create_daemon(bus.run_forever)

    wait_for_exit_signal()

    speech.shutdown()
    audio.shutdown()
コード例 #40
0
ファイル: main.py プロジェクト: Wolfgange3311999/mycroft-core
def main():
    global ws
    lock = Lock('skills')  # prevent multiple instances of this service

    # Connect this Skill management process to the websocket
    ws = WebsocketClient()
    ConfigurationManager.init(ws)

    ignore_logs = ConfigurationManager.instance().get("ignore_logs")

    # Listen for messages and echo them for logging
    def _echo(message):
        try:
            _message = json.loads(message)

            if _message.get("type") in ignore_logs:
                return

            if _message.get("type") == "registration":
                # do not log tokens from registration messages
                _message["data"]["token"] = None
            message = json.dumps(_message)
        except:
            pass
        logger.debug(message)

    ws.on('message', _echo)

    # Startup will be called after websocket is full live
    ws.once('open', _starting_up)
    ws.run_forever()
コード例 #41
0
ファイル: main.py プロジェクト: antlarr/mycroft-core
def main():
    global ws
    global config
    ws = WebsocketClient()
    Configuration.init(ws)
    config = Configuration.get()
    speech.init(ws)

    # Setup control of pulse audio
    setup_pulseaudio_handlers(config.get('Audio').get('pulseaudio'))

    def echo(message):
        try:
            _message = json.loads(message)
            if 'mycroft.audio.service' not in _message.get('type'):
                return
            message = json.dumps(_message)
        except:
            pass
        LOG.debug(message)

    LOG.info("Staring Audio Services")
    ws.on('message', echo)
    ws.once('open', load_services_callback)
    try:
        ws.run_forever()
    except KeyboardInterrupt, e:
        LOG.exception(e)
        speech.shutdown()
        sys.exit()
コード例 #42
0
class SkillContainer(object):
    def __init__(self, args):
        params = self.__build_params(args)

        if params.config:
            ConfigurationManager.load_local([params.config])

        if exists(params.lib) and isdir(params.lib):
            sys.path.append(params.lib)

        sys.path.append(params.dir)
        self.dir = params.dir

        self.enable_intent_skill = params.enable_intent_skill

        self.__init_client(params)

    @staticmethod
    def __build_params(args):
        parser = argparse.ArgumentParser()
        parser.add_argument("--config", default="./mycroft.ini")
        parser.add_argument("dir", nargs='?', default=dirname(__file__))
        parser.add_argument("--lib", default="./lib")
        parser.add_argument("--host", default=None)
        parser.add_argument("--port", default=None)
        parser.add_argument("--use-ssl", action='store_true', default=False)
        parser.add_argument("--enable-intent-skill", action='store_true',
                            default=False)
        return parser.parse_args(args)

    def __init_client(self, params):
        config = ConfigurationManager.get().get("messagebus_client")

        if not params.host:
            params.host = config.get('host')
        if not params.port:
            params.port = config.get('port')

        self.client = WebsocketClient(host=params.host,
                                      port=params.port,
                                      ssl=params.use_ssl)

    def try_load_skill(self):
        if self.enable_intent_skill:
            intent_skill = create_intent_skill()
            intent_skill.bind(self.client)
            intent_skill.initialize()
        skill_descriptor = create_skill_descriptor(self.dir)
        load_skill(skill_descriptor, self.client)

    def run(self):
        self.client.on('message', logger.debug)
        self.client.on('open', self.try_load_skill)
        self.client.on('error', logger.error)
        self.client.run_forever()
コード例 #43
0
ファイル: __init__.py プロジェクト: aatchison/mycroft-core
def stop_speaking(ws=None):
    from mycroft.messagebus.client.ws import WebsocketClient
    from mycroft.messagebus.message import Message

    if ws is None:
        ws = WebsocketClient()
    # TODO: Less hacky approach to this once Audio Manager is implemented
    # Skills should only be able to stop speech they've initiated

    create_signal('stoppingTTS')
    ws.emit(Message('mycroft.audio.speech.stop'))

    # Block until stopped
    while check_for_signal("isSpeaking", -1):
        time.sleep(0.25)

    # This consumes the signal
    check_for_signal('stoppingTTS')
コード例 #44
0
ファイル: enclosure.py プロジェクト: khellan/mycroft-core
 def __init__(self):
     self.__init_serial()
     self.client = WebsocketClient()
     self.reader = EnclosureReader(self.serial, self.client)
     self.writer = EnclosureWriter(self.serial, self.client)
     self.eyes = EnclosureEyes(self.client, self.writer)
     self.mouth = EnclosureMouth(self.client, self.writer)
     self.system = EnclosureArduino(self.client, self.writer)
     self.__register_events()
コード例 #45
0
ファイル: main.py プロジェクト: Holly-Buteau/mycroft-core
 def __init__(self):
     self.iface = pyw.winterfaces()[0]
     self.ap = AccessPoint(self.iface)
     self.server = None
     self.ws = WebsocketClient()
     self.enclosure = EnclosureAPI(self.ws)
     self.init_events()
     self.conn_monitor = None
     self.conn_monitor_stop = threading.Event()
     self.starting = False
コード例 #46
0
ファイル: main.py プロジェクト: antlarr/mycroft-core
def simple_cli():
    global ws
    ws = WebsocketClient()
    event_thread = Thread(target=connect)
    event_thread.setDaemon(True)
    event_thread.start()
    try:
        while True:
            # Sleep for a while so all the output that results
            # from the previous command finishes before we print.
            time.sleep(1.5)
            print("Input (Ctrl+C to quit):")
            line = sys.stdin.readline()
            ws.emit(
                Message("recognizer_loop:utterance",
                        {'utterances': [line.strip()]}))
    except KeyboardInterrupt, e:
        # User hit Ctrl+C to quit
        print("")
コード例 #47
0
ファイル: container.py プロジェクト: jasonehines/mycroft-core
    def __init_client(self, params):
        config = ConfigurationManager.get().get("websocket")

        if not params.host:
            params.host = config.get('host')
        if not params.port:
            params.port = config.get('port')

        self.ws = WebsocketClient(host=params.host,
                                  port=params.port,
                                  ssl=params.use_ssl)
コード例 #48
0
ファイル: __init__.py プロジェクト: forslund/mycroft-core
 def __init__(self):
     self.ws = WebsocketClient()
     ConfigurationManager.init(self.ws)
     self.config = ConfigurationManager.get().get("enclosure")
     self.__init_serial()
     self.reader = EnclosureReader(self.serial, self.ws)
     self.writer = EnclosureWriter(self.serial, self.ws)
     self.writer.write("system.version")
     self.ws.on("enclosure.start", self.start)
     self.started = False
     Timer(5, self.stop).start()     # WHY? This at least needs an explaination, this is non-obvious behavior
コード例 #49
0
ファイル: __init__.py プロジェクト: aatchison/mycroft-core
    def __init__(self):
        self.ws = WebsocketClient()
        self.ws.on("open", self.on_ws_open)

        ConfigurationManager.init(self.ws)
        self.config = ConfigurationManager.instance().get("enclosure")
        self.__init_serial()
        self.reader = EnclosureReader(self.serial, self.ws)
        self.writer = EnclosureWriter(self.serial, self.ws)

        # initiates the web sockets on display manager
        # NOTE: this is a temporary place to initiate display manager sockets
        initiate_display_manager_ws()
コード例 #50
0
ファイル: container.py プロジェクト: Ceda-EI/mycroft-core
    def __init_client(self, params):
        config = Configuration.get().get("websocket")

        if not params.host:
            params.host = config.get('host')
        if not params.port:
            params.port = config.get('port')

        self.ws = WebsocketClient(host=params.host,
                                  port=params.port,
                                  ssl=params.use_ssl)

        # Connect configuration manager to message bus to receive updates
        Configuration.init(self.ws)
コード例 #51
0
def catchInput(queryInput):
	bus = dbus.SessionBus()
	remote_object = bus.get_object("org.gnome.Shell","/com/mycroftaignome/MycroftGnomeResult")  
	getText = remote_object.sendQuery(guioutputstring,dbus_interface = "com.mycroftaignome.MycroftAiGnomeBox")	
	print getText	
 	global client
	client = WebsocketClient()
	client.on('speak', handle_speak)
	event_thread = Thread(target=connect)
	event_thread.setDaemon(True)
	event_thread.start()
	try:
		while True:
		
       			print("Input:")
      	 		queryInput= object.sendQuery(guioutputstring,dbus_interface = "com.mycroftaignome.MycroftAiGnomeBox")
      			client.emit(
      		          Message("recognizer_loop:utterance",
      		                  metadata={'utterances': [queryInput]}))
			break
    	except KeyboardInterrupt, e:
        	logger.exception(e)
        	event_thread.exit()
		sys.exit()		
コード例 #52
0
ファイル: base.py プロジェクト: MycroftAI/mycroft-core
    def __init__(self):
        # Establish Enclosure's websocket connection to the messagebus
        self.bus = WebsocketClient()

        # Load full config
        Configuration.init(self.bus)
        config = Configuration.get()

        self.lang = config['lang']
        self.config = config.get("enclosure")
        self.global_config = config

        # This datastore holds the data associated with the GUI provider. Data
        # is stored in Namespaces, so you can have:
        # self.datastore["namespace"]["name"] = value
        # Typically the namespace is a meaningless identifier, but there is a
        # special "SYSTEM" namespace.
        self.datastore = {}

        # self.loaded is a list, each element consists of a namespace named
        # tuple.
        # The namespace namedtuple has the properties "name" and "pages"
        # The name contains the namespace name as a string and pages is a
        # mutable list of loaded pages.
        #
        # [Namespace name, [List of loaded qml pages]]
        # [
        # ["SKILL_NAME", ["page1.qml, "page2.qml", ... , "pageN.qml"]
        # [...]
        # ]
        self.loaded = []  # list of lists in order.
        self.explicit_move = True  # Set to true to send reorder commands

        # Listen for new GUI clients to announce themselves on the main bus
        self.GUIs = {}      # GUIs, either local or remote
        self.active_namespaces = []
        self.bus.on("mycroft.gui.connected", self.on_gui_client_connected)
        self.register_gui_handlers()

        # First send any data:
        self.bus.on("gui.value.set", self.on_gui_set_value)
        self.bus.on("gui.page.show", self.on_gui_show_page)
        self.bus.on("gui.page.delete", self.on_gui_delete_page)
        self.bus.on("gui.clear.namespace", self.on_gui_delete_namespace)
        self.bus.on("gui.event.send", self.on_gui_send_event)
コード例 #53
0
ファイル: main.py プロジェクト: Alphacodeclub/mycroft-core
def main():
    global client
    client = WebsocketClient()

    def echo(message):
        try:
            _message = json.loads(message)

            if _message.get("message_type") == "registration":
                # do not log tokens from registration messages
                _message["metadata"]["token"] = None
            message = json.dumps(_message)
        except:
            pass
        logger.debug(message)

    client.on('message', echo)
    client.once('open', load_skills_callback)
    client.run_forever()
コード例 #54
0
ファイル: main.py プロジェクト: forslund/mycroft-core
def main():
    global ws
    ws = WebsocketClient()
    ConfigurationManager.init(ws)

    def echo(message):
        try:
            _message = json.loads(message)

            if _message.get("type") == "registration":
                # do not log tokens from registration messages
                _message["data"]["token"] = None
            message = json.dumps(_message)
        except:
            pass
        logger.debug(message)

    ws.on('message', echo)
    ws.once('open', load_skills_callback)
    ws.run_forever()
コード例 #55
0
ファイル: send.py プロジェクト: Ceda-EI/mycroft-core
def send(messageToSend, dataToSend=None):
    """
        Send a single message over the websocket.

        Args:
            messageToSend (str):    Message to send
            dataToSend (dict):      data structure to go along with the
                                    message, defaults to empty dict.
    """
    dataToSend = dataToSend or {}

    # Calculate the standard Mycroft messagebus websocket address
    config = ConfigurationManager.get().get("websocket")
    url = WebsocketClient.build_url(config.get("host"),
                                    config.get("port"),
                                    config.get("route"),
                                    config.get("ssl"))

    # Send the provided message/data
    ws = create_connection(url)
    packet = Message(messageToSend, dataToSend).serialize()
    ws.send(packet)
    ws.close()
コード例 #56
0
def init_display_manager_bus_connection():
    """ Connects the display manager to the messagebus """
    LOG.info("Connecting display manager to messagebus")

    # Should remove needs to be an object so it can be referenced in functions
    # [https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference]
    display_manager = DisplayManager()
    should_remove = [True]

    def check_flag(flag):
        if flag[0] is True:
            display_manager.remove_active()

    def set_delay(event=None):
        should_remove[0] = True
        Timer(2, check_flag, [should_remove]).start()

    def set_remove_flag(event=None):
        should_remove[0] = False

    def connect():
        bus.run_forever()

    def remove_wake_word():
        data = _read_data()
        if "active_skill" in data and data["active_skill"] == "wakeword":
            display_manager.remove_active()

    def set_wakeword_skill(event=None):
        display_manager.set_active("wakeword")
        Timer(10, remove_wake_word).start()

    bus = WebsocketClient()
    bus.on('recognizer_loop:audio_output_end', set_delay)
    bus.on('recognizer_loop:audio_output_start', set_remove_flag)
    bus.on('recognizer_loop:record_begin', set_wakeword_skill)

    event_thread = Thread(target=connect)
    event_thread.setDaemon(True)
    event_thread.start()
コード例 #57
0
    def __init__(self):
        self.ws = WebsocketClient()
        ConfigurationManager.init(self.ws)
        self.config = ConfigurationManager.instance().get("enclosure")
        self.__init_serial()
        self.reader = EnclosureReader(self.serial, self.ws)
        self.writer = EnclosureWriter(self.serial, self.ws)

        # Send a message to the Arduino across the serial line asking
        # for a reply with version info.
        self.writer.write("system.version")
        # When the Arduino responds, it will generate this message
        self.ws.on("enclosure.started", self.on_arduino_responded)

        self.arduino_responded = False

        # Start a 5 second timer.  If the serial port hasn't received
        # any acknowledgement of the "system.version" within those
        # 5 seconds, assume there is nothing on the other end (e.g.
        # we aren't running a Mark 1 with an Arduino)
        Timer(5, self.check_for_response).start()

        # Notifications from mycroft-core
        self.ws.on("enclosure.notify.no_internet", self.on_no_internet)
コード例 #58
0
ファイル: enclosure.py プロジェクト: bisaysavath/mycroft-core
class Enclosure:
    """
    Serves as a communication interface between Arduino and Mycroft Core.

    ``Enclosure`` initializes and aggregates all enclosures implementation.

    E.g. ``EnclosureEyes``, ``EnclosureMouth`` and ``EnclosureArduino``

    It also listens to the basis events in order to perform those core actions
    on the unit.

    E.g. Start and Stop talk animation
    """

    def __init__(self):
        self.__init_serial()
        self.client = WebsocketClient()
        self.reader = EnclosureReader(self.serial, self.client)
        self.writer = EnclosureWriter(self.serial, self.client)
        self.eyes = EnclosureEyes(self.client, self.writer)
        self.mouth = EnclosureMouth(self.client, self.writer)
        self.system = EnclosureArduino(self.client, self.writer)
        self.weather = EnclosureWeather(self.client, self.writer)
        self.__register_events()

    def setup(self):
        must_upload = self.config.get('must_upload')
        if must_upload is not None and str2bool(must_upload):
            ConfigurationManager.set('enclosure', 'must_upload', False)
            time.sleep(5)
            self.client.emit(Message("speak", metadata={
                'utterance': "I am currently uploading to the arduino."}))
            self.client.emit(Message("speak", metadata={
                'utterance': "I will be finished in just a moment."}))
            self.upload_hex()
            self.client.emit(Message("speak", metadata={
                'utterance': "Arduino programing complete."}))

        must_start_test = self.config.get('must_start_test')
        if must_start_test is not None and str2bool(must_start_test):
            ConfigurationManager.set('enclosure', 'must_start_test', False)
            time.sleep(0.5)  # Ensure arduino has booted
            self.client.emit(Message("speak", metadata={
                'utterance': "Begining hardware self test."}))
            self.writer.write("test.begin")

    @staticmethod
    def upload_hex():
        old_path = os.getcwd()
        try:
            os.chdir('/opt/enclosure/')
            subprocess.check_call('./upload.sh')
        finally:
            os.chdir(old_path)

    def __init_serial(self):
        try:
            self.config = ConfigurationManager.get().get("enclosure")
            self.port = self.config.get("port")
            self.rate = int(self.config.get("rate"))
            self.timeout = int(self.config.get("timeout"))
            self.serial = serial.serial_for_url(
                url=self.port, baudrate=self.rate, timeout=self.timeout)
            LOGGER.info(
                "Connected to: " + self.port + " rate: " + str(self.rate) +
                " timeout: " + str(self.timeout))
        except:
            LOGGER.error(
                "It is not possible to connect to serial port: " + self.port)
            raise

    def __register_events(self):
        self.client.on('mycroft.paired', self.__update_events)
        self.client.on('enclosure.mouth.listeners', self.__mouth_listeners)
        self.__register_mouth_events()

    def __mouth_listeners(self, event=None):
        if event and event.metadata:
            active = event.metadata['active']
            if active:
                self.__register_mouth_events()
            else:
                self.__remove_mouth_events()

    def __register_mouth_events(self):
        self.client.on('recognizer_loop:record_begin', self.mouth.listen)
        self.client.on('recognizer_loop:record_end', self.mouth.reset)
        self.client.on('recognizer_loop:audio_output_start', self.mouth.talk)
        self.client.on('recognizer_loop:audio_output_end', self.mouth.reset)

    def __remove_mouth_events(self):
        self.client.remove('recognizer_loop:record_begin', self.mouth.listen)
        self.client.remove('recognizer_loop:record_end', self.mouth.reset)
        self.client.remove('recognizer_loop:audio_output_start',
                           self.mouth.talk)
        self.client.remove('recognizer_loop:audio_output_end',
                           self.mouth.reset)

    def __update_events(self, event=None):
        if event and event.metadata:
            if event.metadata.get('paired', False):
                self.__register_mouth_events()
            else:
                self.__remove_mouth_events()

    def run(self):
        try:
            self.client.run_forever()
        except Exception as e:
            LOGGER.error("Client error: {0}".format(e))
            self.stop()

    def stop(self):
        self.writer.stop()
        self.reader.stop()
        self.serial.close()
コード例 #59
0
ファイル: container.py プロジェクト: Ceda-EI/mycroft-core
class SkillContainer(object):
    def __init__(self, args):
        params = self.__build_params(args)

        if params.config:
            Configuration.get([params.config])

        if exists(params.lib) and isdir(params.lib):
            sys.path.append(params.lib)

        sys.path.append(params.dir)
        self.dir = params.dir

        self.enable_intent = params.enable_intent

        self.__init_client(params)

    @staticmethod
    def __build_params(args):
        parser = argparse.ArgumentParser()
        parser.add_argument("--config", default="./mycroft.conf")
        parser.add_argument("dir", nargs='?', default=dirname(__file__))
        parser.add_argument("--lib", default="./lib")
        parser.add_argument("--host", default=None)
        parser.add_argument("--port", default=None)
        parser.add_argument("--use-ssl", action='store_true', default=False)
        parser.add_argument("--enable-intent", action='store_true',
                            default=False)
        return parser.parse_args(args)

    def __init_client(self, params):
        config = Configuration.get().get("websocket")

        if not params.host:
            params.host = config.get('host')
        if not params.port:
            params.port = config.get('port')

        self.ws = WebsocketClient(host=params.host,
                                  port=params.port,
                                  ssl=params.use_ssl)

        # Connect configuration manager to message bus to receive updates
        Configuration.init(self.ws)

    def load_skill(self):
        if self.enable_intent:
            IntentService(self.ws)

        skill_descriptor = create_skill_descriptor(self.dir)
        self.skill = load_skill(skill_descriptor, self.ws, hash(self.dir))

    def run(self):
        try:
            self.ws.on('message', LOG.debug)
            self.ws.on('open', self.load_skill)
            self.ws.on('error', LOG.error)
            self.ws.run_forever()
        except Exception as e:
            LOG.error("Error: {0}".format(e))
            self.stop()

    def stop(self):
        if self.skill:
            self.skill.shutdown()