本文整理汇总了Python中mycroft.messagebus.client.ws.WebsocketClient.run_forever方法的典型用法代码示例。如果您正苦于以下问题:Python WebsocketClient.run_forever方法的具体用法?Python WebsocketClient.run_forever怎么用?Python WebsocketClient.run_forever使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mycroft.messagebus.client.ws.WebsocketClient
的用法示例。
在下文中一共展示了WebsocketClient.run_forever方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import run_forever [as 别名]
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()
示例2: main
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import run_forever [as 别名]
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()
示例3: SkillContainer
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import run_forever [as 别名]
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()
示例4: __init__
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import run_forever [as 别名]
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()
示例5: SkillContainer
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import run_forever [as 别名]
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()
示例6: main
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import run_forever [as 别名]
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()
示例7: DevicePairingClient
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import run_forever [as 别名]
class DevicePairingClient(object):
def __init__(self, config=_config, pairing_code=None):
self.config = config
self.paired = False
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())
def on_registration(self, message):
# TODO: actually accept the configuration message and store it in
# identity
identity = self.identity_manager.get()
register_payload = message.metadata
if register_payload.get("device_id") == identity.device_id:
identity.token = register_payload.get('token')
identity.owner = register_payload.get('user')
self.identity_manager.update(identity)
self.ws_client.close()
self.paired = True
def send_device_info(self):
msg = Message("device_info",
metadata={
"pairing_code": self.pairing_code,
"device_id": self.identity.device_id
})
self.ws_client.emit(msg)
@staticmethod
def print_error(message):
print(repr(message))
def run(self):
self.ws_client.on('registration', self.on_registration)
self.ws_client.on('open', self.send_device_info)
self.ws_client.on('error', self.print_error)
self.ws_client.run_forever()
示例8: main
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import run_forever [as 别名]
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()
示例9: len
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import run_forever [as 别名]
from mycroft.messagebus.message import Message
if len(sys.argv) == 2:
messageToSend = sys.argv[1]
elif len(sys.argv) > 2:
messageToSend = " ".join(sys.argv[2:])
else:
filename = os.path.basename(__file__)
print filename
print "Simple command line interface to the messagebus."
print "Usage: messagebus_emit <utterance>\n"
print " where <utterance> is treated as if spoken to Mycroft."
print "Example: " + filename + " mycroft.wifi.start"
exit()
def onConnected(event=None):
print "Sending message...'" + messageToSend + "'"
messagebusClient.emit(Message(messageToSend))
messagebusClient.close()
exit()
# Establish a connection with the messagebus
messagebusClient = WebsocketClient()
messagebusClient.on('connected', onConnected)
# This will block until the client gets closed
messagebusClient.run_forever()
示例10: Enclosure
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import run_forever [as 别名]
#.........这里部分代码省略.........
self.ws.on('enclosure.mouth.events.activate',
self.__register_mouth_events)
self.ws.on('enclosure.mouth.events.deactivate',
self.__remove_mouth_events)
self.ws.on('enclosure.reset',
self.__reset)
self.__register_mouth_events()
def __register_mouth_events(self, event=None):
self.ws.on('recognizer_loop:record_begin', self.mouth.listen)
self.ws.on('recognizer_loop:record_end', self.mouth.reset)
self.ws.on('recognizer_loop:audio_output_start', self.mouth.talk)
self.ws.on('recognizer_loop:audio_output_end', self.mouth.reset)
def __remove_mouth_events(self, event=None):
self.ws.remove('recognizer_loop:record_begin', self.mouth.listen)
self.ws.remove('recognizer_loop:record_end', self.mouth.reset)
self.ws.remove('recognizer_loop:audio_output_start',
self.mouth.talk)
self.ws.remove('recognizer_loop:audio_output_end',
self.mouth.reset)
def __reset(self, event=None):
# Reset both the mouth and the eye elements to indicate the unit is
# ready for input.
self.writer.write("eyes.reset")
self.writer.write("mouth.reset")
def speak(self, text):
self.ws.emit(Message("speak", {'utterance': text}))
def run(self):
try:
self.ws.run_forever()
except Exception as e:
LOG.error("Error: {0}".format(e))
self.stop()
def check_for_response(self):
if not self.arduino_responded:
# There is nothing on the other end of the serial port
# close these serial-port readers and this process
self.writer.stop()
self.reader.stop()
self.serial.close()
self.ws.close()
def _handle_pairing_complete(self, Message):
"""
Handler for 'mycroft.paired', unmutes the mic after the pairing is
complete.
"""
self.ws.emit(Message("mycroft.mic.unmute"))
def _do_net_check(self):
# TODO: This should live in the derived Enclosure, e.g. Enclosure_Mark1
LOG.info("Checking internet connection")
if not connected(): # and self.conn_monitor is None:
if has_been_paired():
# TODO: Enclosure/localization
self.speak("This unit is not connected to the Internet. "
"Either plug in a network cable or hold the "
"button on top for two seconds, then select "
"wifi from the menu")
else:
# Begin the unit startup process, this is the first time it
示例11: __init__
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import run_forever [as 别名]
#.........这里部分代码省略.........
if connected:
LOG.warn("Mycroft is already connected to %s" % ssid)
else:
self.disconnect()
LOG.info("Connecting to: %s" % ssid)
nid = wpa(self.iface, 'add_network')
wpa(self.iface, 'set_network', nid, 'ssid', '"' + ssid + '"')
if event.data.__contains__("pass"):
psk = '"' + event.data.get("pass") + '"'
wpa(self.iface, 'set_network', nid, 'psk', psk)
else:
wpa(self.iface, 'set_network', nid, 'key_mgmt', 'NONE')
wpa(self.iface, 'enable', nid)
connected = self.get_connected(ssid)
if connected:
wpa(self.iface, 'save_config')
self.ws.emit(Message("mycroft.wifi.connected",
{'connected': connected}))
LOG.info("Connection status for %s = %s" % (ssid, connected))
if connected:
self.ws.emit(Message("speak", {
'utterance': "Thank you, I'm now connected to the "
"internet and ready for use"}))
# TODO: emit something that triggers a pairing check
def disconnect(self):
status = self.get_status()
nid = status.get("id")
if nid:
ssid = status.get("ssid")
wpa(self.iface, 'disable', nid)
LOG.info("Disconnecting %s id: %s" % (ssid, nid))
def get_status(self):
res = cli('wpa_cli', '-i', self.iface, 'status')
out = str(res.get("stdout"))
if out:
return dict(o.split("=") for o in out.split("\n")[:-1])
return {}
def get_connected(self, ssid, retry=5):
connected = self.is_connected(ssid)
while not connected and retry > 0:
sleep(2)
retry -= 1
connected = self.is_connected(ssid)
return connected
def is_connected(self, ssid, status=None):
status = status or self.get_status()
state = status.get("wpa_state")
return status.get("ssid") == ssid and state == "COMPLETED"
def stop(self, event=None):
LOG.info("Stopping access point...")
self._stop_connection_monitor()
self.ap.down()
if self.server:
self.server.server.shutdown()
self.server.server.server_close()
self.server.join()
self.server = None
LOG.info("Access point stopped!")
def _do_net_check(self):
# give system 5 seconds to resolve network or get plugged in
sleep(5)
LOG.info("Checking internet connection again")
if not connected() and self.conn_monitor is None:
# TODO: Enclosure/localization
self._speak_and_show(
"This device is not connected to the Internet. Either plug "
"in a network cable or hold the button on top for two "
"seconds, then select wifi from the menu", None)
def run(self):
try:
# When the system first boots up, check for a valid internet
# connection.
LOG.info("Checking internet connection")
if not connected():
LOG.info("No connection initially, waiting 20...")
self.net_check = threading.Thread(
target=self._do_net_check,
args={})
self.net_check.daemon = True
self.net_check.start()
else:
LOG.info("Connection found!")
self.ws.run_forever()
except Exception as e:
LOG.error("Error: {0}".format(e))
self.stop()
示例12: __init__
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import run_forever [as 别名]
class Enclosure:
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)
def run(self):
try:
self.bus.run_forever()
except Exception as e:
LOG.error("Error: {0}".format(e))
self.stop()
######################################################################
# GUI client API
def send(self, *args, **kwargs):
""" Send to all registered GUIs. """
for gui in self.GUIs.values():
if gui.socket:
gui.socket.send(*args, **kwargs)
else:
LOG.error('GUI connection {} has no socket!'.format(gui))
def on_gui_send_event(self, message):
""" Send an event to the GUIs. """
try:
data = {'type': 'mycroft.events.triggered',
'namespace': message.data.get('__from'),
'event_name': message.data.get('event_name'),
'params': message.data.get('params')}
self.send(data)
except Exception as e:
LOG.error('Could not send event ({})'.format(repr(e)))
def on_gui_set_value(self, message):
data = message.data
namespace = data.get("__from", "")
# Pass these values on to the GUI renderers
for key in data:
if key not in RESERVED_KEYS:
try:
self.set(namespace, key, data[key])
except Exception as e:
LOG.exception(repr(e))
def set(self, namespace, name, value):
""" Perform the send of the values to the connected GUIs. """
if namespace not in self.datastore:
self.datastore[namespace] = {}
if self.datastore[namespace].get(name) != value:
self.datastore[namespace][name] = value
# If the namespace is loaded send data to GUI
if namespace in [l.name for l in self.loaded]:
msg = {"type": "mycroft.session.set",
"namespace": namespace,
"data": {name: value}}
#.........这里部分代码省略.........
示例13: Enclosure
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import run_forever [as 别名]
#.........这里部分代码省略.........
self.ws.emit(Message("speak", {
'utterance': "This device is not connected to the Internet. "
"Either plug in a network cable or hold the "
"button on top for two seconds, then select "
"wifi from the menu"}))
else:
# enter wifi-setup mode automatically
self.ws.emit(Message("mycroft.wifi.start"))
def __init_serial(self):
try:
self.port = self.config.get("port")
self.rate = self.config.get("rate")
self.timeout = self.config.get("timeout")
self.serial = serial.serial_for_url(
url=self.port, baudrate=self.rate, timeout=self.timeout)
LOG.info("Connected to: %s rate: %s timeout: %s" %
(self.port, self.rate, self.timeout))
except:
LOG.error("Impossible to connect to serial port: " + self.port)
raise
def __register_events(self):
self.ws.on('enclosure.mouth.events.activate',
self.__register_mouth_events)
self.ws.on('enclosure.mouth.events.deactivate',
self.__remove_mouth_events)
self.ws.on('enclosure.reset',
self.__reset)
self.__register_mouth_events()
def __register_mouth_events(self, event=None):
self.ws.on('recognizer_loop:record_begin', self.mouth.listen)
self.ws.on('recognizer_loop:record_end', self.mouth.reset)
self.ws.on('recognizer_loop:audio_output_start', self.mouth.talk)
self.ws.on('recognizer_loop:audio_output_end', self.mouth.reset)
def __remove_mouth_events(self, event=None):
self.ws.remove('recognizer_loop:record_begin', self.mouth.listen)
self.ws.remove('recognizer_loop:record_end', self.mouth.reset)
self.ws.remove('recognizer_loop:audio_output_start',
self.mouth.talk)
self.ws.remove('recognizer_loop:audio_output_end',
self.mouth.reset)
def __reset(self, event=None):
# Reset both the mouth and the eye elements to indicate the unit is
# ready for input.
self.writer.write("eyes.reset")
self.writer.write("mouth.reset")
def speak(self, text):
self.ws.emit(Message("speak", {'utterance': text}))
def run(self):
try:
self.ws.run_forever()
except Exception as e:
LOG.error("Error: {0}".format(e))
self.stop()
def check_for_response(self):
if not self.arduino_responded:
# There is nothing on the other end of the serial port
# close these serial-port readers and this process
self.writer.stop()
self.reader.stop()
self.serial.close()
self.ws.close()
def _do_net_check(self):
# TODO: This should live in the derived Enclosure, e.g. Enclosure_Mark1
LOG.info("Checking internet connection")
if not connected(): # and self.conn_monitor is None:
if has_been_paired():
# TODO: Enclosure/localization
self.ws.emit(Message("speak", {
'utterance': "This unit is not connected to the Internet."
" Either plug in a network cable or hold the "
"button on top for two seconds, then select "
"wifi from the menu"
}))
else:
# Begin the unit startup process, this is the first time it
# is being run with factory defaults.
# TODO: This logic should be in Enclosure_Mark1
# TODO: Enclosure/localization
# Don't listen to mic during this out-of-box experience
self.ws.emit(Message("mycroft.mic.mute", None))
# Kick off wifi-setup automatically
self.ws.emit(Message("mycroft.wifi.start",
{'msg': "Hello I am Mycroft, your new "
"assistant. To assist you I need to be "
"connected to the internet. You can "
"either plug me in with a network cable,"
" or use wifi. To setup wifi ",
'allow_timeout': False}))
示例14: Enclosure
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import run_forever [as 别名]
class Enclosure(object):
"""
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.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
def start(self, event=None):
self.eyes = EnclosureEyes(self.ws, self.writer)
self.mouth = EnclosureMouth(self.ws, self.writer)
self.system = EnclosureArduino(self.ws, self.writer)
self.weather = EnclosureWeather(self.ws, self.writer)
self.__register_events()
self.__reset()
self.started = True
def __init_serial(self):
try:
self.port = self.config.get("port")
self.rate = self.config.get("rate")
self.timeout = self.config.get("timeout")
self.serial = serial.serial_for_url(
url=self.port, baudrate=self.rate, timeout=self.timeout)
LOG.info("Connected to: %s rate: %s timeout: %s" %
(self.port, self.rate, self.timeout))
except:
LOG.error("Impossible to connect to serial port: " + self.port)
raise
def __register_events(self):
self.ws.on('enclosure.mouth.events.activate',
self.__register_mouth_events)
self.ws.on('enclosure.mouth.events.deactivate',
self.__remove_mouth_events)
self.ws.on('enclosure.reset',
self.__reset)
self.__register_mouth_events()
def __register_mouth_events(self, event=None):
self.ws.on('recognizer_loop:record_begin', self.mouth.listen)
self.ws.on('recognizer_loop:record_end', self.mouth.reset)
self.ws.on('recognizer_loop:audio_output_start', self.mouth.talk)
self.ws.on('recognizer_loop:audio_output_end', self.mouth.reset)
def __remove_mouth_events(self, event=None):
self.ws.remove('recognizer_loop:record_begin', self.mouth.listen)
self.ws.remove('recognizer_loop:record_end', self.mouth.reset)
self.ws.remove('recognizer_loop:audio_output_start',
self.mouth.talk)
self.ws.remove('recognizer_loop:audio_output_end',
self.mouth.reset)
def __reset(self, event=None):
# Reset both the mouth and the eye elements to indicate the unit is
# ready for input.
self.writer.write("eyes.reset")
self.writer.write("mouth.reset")
def speak(self, text):
self.ws.emit(Message("speak", {'utterance': text}))
def run(self):
try:
self.ws.run_forever()
except Exception as e:
LOG.error("Error: {0}".format(e))
self.stop()
def stop(self):
if not self.started:
self.writer.stop()
self.reader.stop()
self.serial.close()
self.ws.close()
示例15: SkillContainer
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import run_forever [as 别名]
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()