本文整理汇总了Python中mycroft.messagebus.client.ws.WebsocketClient.emit方法的典型用法代码示例。如果您正苦于以下问题:Python WebsocketClient.emit方法的具体用法?Python WebsocketClient.emit怎么用?Python WebsocketClient.emit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mycroft.messagebus.client.ws.WebsocketClient
的用法示例。
在下文中一共展示了WebsocketClient.emit方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: simple_cli
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import emit [as 别名]
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()
示例2: main
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import emit [as 别名]
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()
示例3: stop_speaking
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import emit [as 别名]
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')
示例4: DevicePairingClient
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import emit [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()
示例5: simple_cli
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import emit [as 别名]
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("")
示例6: catchInput
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import emit [as 别名]
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()
示例7: __init__
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import emit [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.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:
#.........这里部分代码省略.........
示例8: TestMessagebusMethods
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import emit [as 别名]
class TestMessagebusMethods(unittest.TestCase):
"""This class is for testing the messsagebus.
It currently only tests send and receive. The tests could include
more.
"""
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
# 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()
# Setup handlers for each of the messages.
self.ws1.on('ws1.message', self.onHandle1)
self.ws2.on('ws2.message', self.onHandle2)
def onHandle1(self, event):
"""This is the handler for ws1.message
This for now simply sets a flag to true when received.
Args:
event(Message): this is the message received
"""
self.handle1 = True
def onHandle2(self, event):
"""This is the handler for ws2.message
This for now simply sets a flag to true when received.
Args:
event(Message): this is the message received
"""
self.handle2 = True
def tearDown(self):
"""This is the clean up for the tests
This will close the websockets ending the threads then kill the
mycroft service that was started in setUp.
"""
self.ws1.close()
self.ws2.close()
retcode = call(["kill", "-9", str(self.pid)])
def test_ClientServer(self):
"""This is the test to send a message from each of the websockets
to the other.
"""
# Send the messages
self.ws2.emit(Message('ws1.message'))
self.ws1.emit(Message('ws2.message'))
# allow time for messages to be processed
time.sleep(0.2)
# Check that both of the handlers were called.
self.assertTrue(self.handle1)
self.assertTrue(self.handle2)
示例9: gui_main
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import emit [as 别名]
def gui_main(stdscr):
global scr
global ws
global line
global log_line_lr_scroll
global longest_visible_line
global find_str
global last_key
scr = stdscr
init_screen()
ws = WebsocketClient()
ws.on('speak', handle_speak)
ws.on('message', handle_message)
event_thread = Thread(target=connect)
event_thread.setDaemon(True)
event_thread.start()
history = []
hist_idx = -1 # index, from the bottom
try:
input = ""
while True:
draw_screen()
c = scr.getch()
# Convert VT100 ESC codes generated by some terminals
if c == 27:
c1 = scr.getch()
c2 = scr.getch()
if c1 == 79 and c2 == 120:
c = curses.KEY_UP
elif c1 == 79 and c2 == 116:
c = curses.KEY_LEFT
elif c1 == 79 and c2 == 114:
c = curses.KEY_DOWN
elif c1 == 79 and c2 == 118:
c = curses.KEY_RIGHT
elif c1 == 79 and c2 == 121:
c = curses.KEY_PPAGE # aka PgUp
elif c1 == 79 and c2 == 115:
c = curses.KEY_NPAGE # aka PgDn
elif c1 == 79 and c2 == 119:
c = curses.KEY_HOME
elif c1 == 79 and c2 == 113:
c = curses.KEY_END
else:
c = c2
last_key = str(c)+",ESC+"+str(c1)+"+"+str(c2)
else:
last_key = str(c)
if c == curses.KEY_ENTER or c == 10 or c == 13:
# ENTER sends the typed line to be processed by Mycroft
if line == "":
continue
if line[:1] == ":":
# Lines typed like ":help" are 'commands'
if handle_cmd(line[1:]) == 1:
break
else:
# Treat this as an utterance
history.append(line)
chat.append(line)
ws.emit(Message("recognizer_loop:utterance",
{'utterances': [line.strip()],
'lang': 'en-us'}))
hist_idx = -1
line = ""
elif c == 16 or c == 545: # Ctrl+P or Ctrl+Left (Previous)
# Move up the history stack
hist_idx = clamp(hist_idx + 1, -1, len(history) - 1)
if hist_idx >= 0:
line = history[len(history) - hist_idx - 1]
else:
line = ""
elif c == 14 or c == 560: # Ctrl+N or Ctrl+Right (Next)
# Move down the history stack
hist_idx = clamp(hist_idx - 1, -1, len(history) - 1)
if hist_idx >= 0:
line = history[len(history) - hist_idx - 1]
else:
line = ""
elif c == curses.KEY_LEFT:
# scroll long log lines left
log_line_lr_scroll += curses.COLS // 4
elif c == curses.KEY_RIGHT:
# scroll long log lines right
log_line_lr_scroll -= curses.COLS // 4
if log_line_lr_scroll < 0:
log_line_lr_scroll = 0
elif c == curses.KEY_HOME:
# HOME scrolls log lines all the way to the start
log_line_lr_scroll = longest_visible_line
elif c == curses.KEY_END:
# END scrolls log lines all the way to the end
log_line_lr_scroll = 0
#.........这里部分代码省略.........
示例10: Enclosure
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import emit [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
"""
_last_internet_notification = 0
def __init__(self):
self.ws = WebsocketClient()
self.ws.on("open", self.on_ws_open)
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)
# initiates the web sockets on display manager
# NOTE: this is a temporary place to initiate display manager sockets
initiate_display_manager_ws()
def on_ws_open(self, event=None):
# Mark 1 auto-detection:
#
# 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)
def on_arduino_responded(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.arduino_responded = True
# verify internet connection and prompt user on bootup if needed
if not connected():
# We delay this for several seconds to ensure that the other
# clients are up and connected to the messagebus in order to
# receive the "speak". This was sometimes happening too
# quickly and the user wasn't notified what to do.
Timer(5, self._do_net_check).start()
Timer(60, self._hack_check_for_duplicates).start()
def on_no_internet(self, event=None):
if connected():
# One last check to see if connection was established
return
if time.time() - Enclosure._last_internet_notification < 30:
# don't bother the user with multiple notifications with 30 secs
return
Enclosure._last_internet_notification = time.time()
# TODO: This should go into EnclosureMark1 subclass of Enclosure.
if has_been_paired():
# Handle the translation within that code.
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('system.wifi.setup', {'lang': self.lang}))
def __init_serial(self):
try:
self.port = self.config.get("port")
self.rate = self.config.get("rate")
self.timeout = self.config.get("timeout")
#.........这里部分代码省略.........
示例11: __init__
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import emit [as 别名]
class WiFi:
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
def init_events(self):
'''
Register handlers for various websocket events used
to communicate with outside systems.
'''
# This event is generated by an outside mechanism. On a
# Mark 1 unit this comes from the Enclosure's WIFI menu
# item being selected.
self.ws.on('mycroft.wifi.start', self.start)
# Similar to the above. Resets to factory defaults
self.ws.on('mycroft.wifi.reset', self.reset)
# Similar to the above. Enable/disable SSH
self.ws.on('mycroft.enable.ssh', self.ssh_enable)
self.ws.on('mycroft.disable.ssh', self.ssh_disable)
# These events are generated by Javascript in the captive
# portal.
self.ws.on('mycroft.wifi.stop', self.stop)
self.ws.on('mycroft.wifi.scan', self.scan)
self.ws.on('mycroft.wifi.connect', self.connect)
def start(self, event=None):
'''
Fire up the MYCROFT access point for the user to connect to
with a phone or computer.
'''
if self.starting:
return
self.starting = True
LOG.info("Starting access point...")
self.intro_msg = ""
if event and event.data.get("msg"):
self.intro_msg = event.data.get("msg")
self.allow_timeout = True
if event and event.data.get("allow_timeout"):
self.allow_timeout = event.data.get("allow_timeout")
# Fire up our access point
self.ap.up()
if not self.server:
LOG.info("Creating web server...")
self.server = WebServer(self.ap.ip, 80)
LOG.info("Starting web server...")
self.server.start()
LOG.info("Created web server.")
LOG.info("Access point started!\n%s" % self.ap.__dict__)
self._start_connection_monitor()
def _connection_prompt(self, intro):
while self.ap.password is None or self.ap.password == "":
sleep(1) # give it time to load
# Speak the connection instructions and show the password on screen
passwordSpelled = ", ".join(self.ap.password)
self._speak_and_show(intro +
" Use your mobile device or computer to connect "
"to the wifi network 'MYCROFT'. Then enter the "
"password " + passwordSpelled,
self.ap.password)
def _speak_and_show(self, speak, show):
''' Communicate with the user throughout the process '''
self.ws.emit(Message("speak", {'utterance': speak}))
if show is None:
return
wait_while_speaking()
self.enclosure.mouth_text(show)
def _start_connection_monitor(self):
LOG.info("Starting monitor thread...\n")
if self.conn_monitor is not None:
LOG.info("Killing old thread...\n")
self.conn_monitor_stop.set()
self.conn_monitor_stop.wait()
self.conn_monitor = threading.Thread(
target=self._do_connection_monitor,
args={})
self.conn_monitor.daemon = True
self.conn_monitor.start()
LOG.info("Monitor thread setup complete.\n")
#.........这里部分代码省略.........
示例12: __init__
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import emit [as 别名]
#.........这里部分代码省略.........
"position": index,
"items_number": 1
})
# Remove namespace from loaded namespaces
self.loaded.pop(index)
def remove_pages(self, namespace, pages):
""" Remove the listed pages from the provided namespace.
Args:
namespace (str): The namespace to modify
pages (list): List of page names (str) to delete
"""
try:
index = self.__find_namespace(namespace)
if index is None:
return
else:
# Remove any pages that doesn't exist in the namespace
pages = [p for p in pages if p in self.loaded[index].pages]
# Make sure to remove pages from the back
indexes = [self.loaded[index].pages.index(p) for p in pages]
indexes = sorted(indexes)
indexes.reverse()
for page_index in indexes:
self.__remove_page(namespace, page_index)
except Exception as e:
LOG.exception(repr(e))
######################################################################
# GUI client socket
#
# The basic mechanism is:
# 1) GUI client announces itself on the main messagebus
# 2) Mycroft prepares a port for a socket connection to this GUI
# 3) The port is announced over the messagebus
# 4) The GUI connects on the socket
# 5) Connection persists for graphical interaction indefinitely
#
# If the connection is lost, it must be renegotiated and restarted.
def on_gui_client_connected(self, message):
# GUI has announced presence
LOG.debug("on_gui_client_connected")
gui_id = message.data.get("gui_id")
# Spin up a new communication socket for this GUI
if gui_id in self.GUIs:
# TODO: Close it?
pass
self.GUIs[gui_id] = GUIConnection(gui_id, self.global_config,
self.callback_disconnect, self)
LOG.debug("Heard announcement from gui_id: {}".format(gui_id))
# Announce connection, the GUI should connect on it soon
self.bus.emit(Message("mycroft.gui.port",
{"port": self.GUIs[gui_id].port,
"gui_id": gui_id}))
def callback_disconnect(self, gui_id):
LOG.info("Disconnecting!")
# TODO: Whatever is needed to kill the websocket instance
LOG.info(self.GUIs.keys())
LOG.info('deleting: {}'.format(gui_id))
if gui_id in self.GUIs:
del self.GUIs[gui_id]
else:
LOG.warning('ID doesn\'t exist')
def register_gui_handlers(self):
# TODO: Register handlers for standard (Mark 1) events
# self.bus.on('enclosure.eyes.on', self.on)
# self.bus.on('enclosure.eyes.off', self.off)
# self.bus.on('enclosure.eyes.blink', self.blink)
# self.bus.on('enclosure.eyes.narrow', self.narrow)
# self.bus.on('enclosure.eyes.look', self.look)
# self.bus.on('enclosure.eyes.color', self.color)
# self.bus.on('enclosure.eyes.level', self.brightness)
# self.bus.on('enclosure.eyes.volume', self.volume)
# self.bus.on('enclosure.eyes.spin', self.spin)
# self.bus.on('enclosure.eyes.timedspin', self.timed_spin)
# self.bus.on('enclosure.eyes.reset', self.reset)
# self.bus.on('enclosure.eyes.setpixel', self.set_pixel)
# self.bus.on('enclosure.eyes.fill', self.fill)
# self.bus.on('enclosure.mouth.reset', self.reset)
# self.bus.on('enclosure.mouth.talk', self.talk)
# self.bus.on('enclosure.mouth.think', self.think)
# self.bus.on('enclosure.mouth.listen', self.listen)
# self.bus.on('enclosure.mouth.smile', self.smile)
# self.bus.on('enclosure.mouth.viseme', self.viseme)
# self.bus.on('enclosure.mouth.text', self.text)
# self.bus.on('enclosure.mouth.display', self.display)
# self.bus.on('enclosure.mouth.display_image', self.display_image)
# self.bus.on('enclosure.weather.display', self.display_weather)
# self.bus.on('recognizer_loop:record_begin', self.mouth.listen)
# self.bus.on('recognizer_loop:record_end', self.mouth.reset)
# self.bus.on('recognizer_loop:audio_output_start', self.mouth.talk)
# self.bus.on('recognizer_loop:audio_output_end', self.mouth.reset)
pass
示例13: gui_main
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import emit [as 别名]
#.........这里部分代码省略.........
last_key = "ESC"
else:
if code < 33:
last_key = str(code)
else:
last_key = str(code)
if code == 27: # Hitting ESC twice clears the entry line
hist_idx = -1
line = ""
elif c == curses.KEY_RESIZE:
# Generated by Curses when window/screen has been resized
y, x = scr.getmaxyx()
curses.resizeterm(y, x)
# resizeterm() causes another curses.KEY_RESIZE, so
# we need to capture that to prevent a loop of resizes
c = scr.get_wch()
elif screen_mode == SCR_HELP:
# in Help mode, any key goes to next page
show_next_help()
continue
elif c == '\n' or code == 10 or code == 13 or code == 343:
# ENTER sends the typed line to be processed by Mycroft
if line == "":
continue
if line[:1] == ":":
# Lines typed like ":help" are 'commands'
if handle_cmd(line[1:]) == 1:
break
else:
# Treat this as an utterance
bus.emit(Message("recognizer_loop:utterance",
{'utterances': [line.strip()],
'lang': 'en-us'}))
hist_idx = -1
line = ""
elif code == 16 or code == 545: # Ctrl+P or Ctrl+Left (Previous)
# Move up the history stack
hist_idx = clamp(hist_idx + 1, -1, len(history) - 1)
if hist_idx >= 0:
line = history[len(history) - hist_idx - 1]
else:
line = ""
elif code == 14 or code == 560: # Ctrl+N or Ctrl+Right (Next)
# Move down the history stack
hist_idx = clamp(hist_idx - 1, -1, len(history) - 1)
if hist_idx >= 0:
line = history[len(history) - hist_idx - 1]
else:
line = ""
elif c == curses.KEY_LEFT:
# scroll long log lines left
log_line_lr_scroll += curses.COLS // 4
elif c == curses.KEY_RIGHT:
# scroll long log lines right
log_line_lr_scroll -= curses.COLS // 4
if log_line_lr_scroll < 0:
log_line_lr_scroll = 0
elif c == curses.KEY_HOME:
# HOME scrolls log lines all the way to the start
log_line_lr_scroll = longest_visible_line
elif c == curses.KEY_END:
# END scrolls log lines all the way to the end
log_line_lr_scroll = 0
示例14: Enclosure
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import emit [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
"""
_last_internet_notification = 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)
def on_arduino_responded(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.arduino_responded = True
# verify internet connection and prompt user on bootup if needed
if not connected():
# We delay this for several seconds to ensure that the other
# clients are up and connected to the messagebus in order to
# receive the "speak". This was sometimes happening too
# quickly and the user wasn't notified what to do.
Timer(5, self._do_net_check).start()
def on_no_internet(self, event=None):
if connected():
# One last check to see if connection was established
return
if time.time()-Enclosure._last_internet_notification < 30:
# don't bother the user with multiple notifications with 30 secs
return
Enclosure._last_internet_notification = time.time()
# TODO: This should go into EnclosureMark1 subclass of Enclosure.
if has_been_paired():
# Handle the translation within that code.
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',
#.........这里部分代码省略.........
示例15: Enclosure
# 需要导入模块: from mycroft.messagebus.client.ws import WebsocketClient [as 别名]
# 或者: from mycroft.messagebus.client.ws.WebsocketClient import emit [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()