service/ws.py
Go to the documentation of this file.
1 # Copyright 2017 Mycroft AI Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 #
15 import json
16 import sys
17 import traceback
18 
19 import tornado.websocket
20 from pyee import EventEmitter
21 
22 from mycroft.messagebus.message import Message
23 from mycroft.util.log import LOG
24 
25 
26 EventBusEmitter = EventEmitter()
27 
28 client_connections = []
29 
30 
31 class WebsocketEventHandler(tornado.websocket.WebSocketHandler):
32  def __init__(self, application, request, **kwargs):
33  tornado.websocket.WebSocketHandler.__init__(
34  self, application, request, **kwargs)
35  self.emitter = EventBusEmitter
36 
37  def on(self, event_name, handler):
38  self.emitter.on(event_name, handler)
39 
40  def on_message(self, message):
41  # LOG.debug(message)
42  try:
43  deserialized_message = Message.deserialize(message)
44  except Exception:
45  return
46 
47  try:
48  self.emitter.emit(deserialized_message.type, deserialized_message)
49  except Exception as e:
50  LOG.exception(e)
51  traceback.print_exc(file=sys.stdout)
52  pass
53 
54  for client in client_connections:
55  client.write_message(message)
56 
57  def open(self):
58  self.write_message(Message("connected").serialize())
59  client_connections.append(self)
60 
61  def on_close(self):
62  client_connections.remove(self)
63 
64  def emit(self, channel_message):
65  if (hasattr(channel_message, 'serialize') and
66  callable(getattr(channel_message, 'serialize'))):
67  self.write_message(channel_message.serialize())
68  else:
69  self.write_message(json.dumps(channel_message))
70 
71  def check_origin(self, origin):
72  return True
def __init__(self, application, request, kwargs)
Definition: service/ws.py:32


mycroft_ros
Author(s):
autogenerated on Mon Apr 26 2021 02:35:40