Skip to content

Commit

Permalink
messagebus module duplicate code removal
Browse files Browse the repository at this point in the history
  • Loading branch information
JarbasAl committed Nov 18, 2022
1 parent e6a0c0b commit 81bb7cd
Show file tree
Hide file tree
Showing 7 changed files with 7 additions and 188 deletions.
46 changes: 1 addition & 45 deletions mycroft/messagebus/client/client.py
Original file line number Diff line number Diff line change
@@ -1,50 +1,6 @@
# Copyright 2019 Mycroft AI Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from ovos_bus_client.client import MessageBusClient as _MessageBusClient
from ovos_bus_client.client.client import MessageBusClient, echo
from ovos_bus_client.client import MessageWaiter

from mycroft.messagebus.load_config import load_message_bus_config
import mycroft.util.process_utils


class MessageBusClient(_MessageBusClient):
# minimize reading of the .conf
_config_cache = None

def __init__(self, host=None, port=None, route=None, ssl=None, cache=False):
config_overrides = dict(host=host, port=port, route=route, ssl=ssl)
if cache and self._config_cache:
config = self._config_cache
else:
config = load_message_bus_config(**config_overrides)
if cache:
MessageBusClient._config_cache = config
super().__init__(config.host, config.port, config.route, config.ssl)


def echo():
message_bus_client = MessageBusClient()

def repeat_utterance(message):
message.msg_type = 'speak'
message_bus_client.emit(message)

message_bus_client.on('message', mycroft.util.process_utils.create_echo_function(None))
message_bus_client.on('recognizer_loop:utterance', repeat_utterance)
message_bus_client.run_forever()


if __name__ == "__main__":
Expand Down
54 changes: 1 addition & 53 deletions mycroft/messagebus/load_config.py
Original file line number Diff line number Diff line change
@@ -1,53 +1 @@
# Copyright 2019 Mycroft AI Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Message bus configuration loader.
The message bus event handler and client use basically the same configuration.
This code is re-used in both to load config values.
"""
from collections import namedtuple

from ovos_config.config import Configuration
from mycroft.util.log import LOG

MessageBusConfig = namedtuple(
'MessageBusConfig',
['host', 'port', 'route', 'ssl']
)


def load_message_bus_config(**overrides):
"""Load the bits of device configuration needed to run the message bus."""
LOG.info('Loading message bus configs')
config = Configuration()

try:
websocket_configs = config['websocket']
except KeyError as ke:
LOG.error('No websocket configs found ({})'.format(repr(ke)))
raise
else:
mb_config = MessageBusConfig(
host=overrides.get('host') or websocket_configs.get('host'),
port=overrides.get('port') or websocket_configs.get('port'),
route=overrides.get('route') or websocket_configs.get('route'),
ssl=overrides.get('ssl') or config.get('ssl')
)
if not all([mb_config.host, mb_config.port, mb_config.route]):
error_msg = 'Missing one or more websocket configs'
LOG.error(error_msg)
raise ValueError(error_msg)

return mb_config
from ovos_bus_client.conf import load_message_bus_config, client_from_config, MessageBusConfig
42 changes: 1 addition & 41 deletions mycroft/messagebus/message.py
Original file line number Diff line number Diff line change
@@ -1,41 +1 @@
# Copyright 2017 Mycroft AI Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import re

from mycroft.util.parse import normalize
from ovos_bus_client.message import dig_for_message
import ovos_bus_client


class Message(ovos_bus_client.Message):
"""Mycroft specific Message class."""

def utterance_remainder(self):
"""
For intents get the portion not consumed by Adapt.
For example: if they say 'Turn on the family room light' and there are
entity matches for "turn on" and "light", then it will leave behind
" the family room " which is then normalized to "family room".
Returns:
str: Leftover words or None if not an utterance.
"""
utt = normalize(self.data.get("utterance", ""))
if utt and "__tags__" in self.data:
for token in self.data["__tags__"]:
# Substitute only whole words matching the token
utt = re.sub(r'\b' + token.get("key", "") + r"\b", "", utt)
return normalize(utt)
from ovos_bus_client.message import dig_for_message, Message
2 changes: 1 addition & 1 deletion mycroft/messagebus/send.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import sys
import json

from mycroft.messagebus.send_func import send
from ovos_bus_client.send_func import send


def main():
Expand Down
47 changes: 1 addition & 46 deletions mycroft/messagebus/send_func.py
Original file line number Diff line number Diff line change
@@ -1,46 +1 @@
# Copyright 2019 Mycroft AI Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from websocket import create_connection

from ovos_config.config import Configuration
from mycroft.messagebus.client import MessageBusClient
from mycroft.messagebus.message import Message


def send(message_to_send, data_to_send=None):
"""Send a single message over the websocket.
Args:
message_to_send (str): Message to send
data_to_send (dict): data structure to go along with the
message, defaults to empty dict.
"""
data_to_send = data_to_send or {}

# Calculate the standard Mycroft messagebus websocket address
config = Configuration()
config = config.get("websocket")
url = MessageBusClient.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(message_to_send, data_to_send).serialize()
ws.send(packet)
ws.close()
from ovos_bus_client.send_func import send
2 changes: 1 addition & 1 deletion requirements/minimal.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ mycroft-messagebus-client~=0.9,!=0.9.2,!=0.9.3
combo-lock~=0.2
ovos-utils~=0.0, >=0.0.26
ovos-plugin-manager~=0.0, >=0.0.20a1
ovos-bus-client~=0.0, >=0.0.1
ovos-bus-client~=0.0, >=0.0.2
ovos-config~=0.0,>=0.0.5
python-dateutil~=2.6
ovos-lingua-franca==0.4.6a1
Expand Down
2 changes: 1 addition & 1 deletion requirements/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ combo-lock~=0.2
PyYAML~=5.4
watchdog

ovos-bus-client~=0.0, >=0.0.1
ovos-bus-client~=0.0, >=0.0.2
ovos_backend_client~=0.0, >=0.0.5
ovos-config~=0.0,>=0.0.5a5
ovos-utils~=0.0, >=0.0.26
Expand Down

0 comments on commit 81bb7cd

Please sign in to comment.