Skip to content

Commit

Permalink
add hidden msgs and add capability to send random msgs from the client
Browse files Browse the repository at this point in the history
  • Loading branch information
Georgios Hadjiharalambous committed Oct 2, 2024
1 parent 78e60ac commit cd2b2a4
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
2.0.1
2.0.2
33 changes: 33 additions & 0 deletions speechmatics/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
# including a hex dump of every message being sent. Setting the websockets
# logger at INFO level specifically prevents this spam.
logging.getLogger("websockets.protocol").setLevel(logging.INFO)
HIDDEN_MSG_PREFIX = "Hidden_"


class WebsocketClient:
Expand Down Expand Up @@ -275,6 +276,28 @@ async def _consumer_handler(self):
raise ex
self._consumer(message)

async def _send_message(self, msg):
"""
Sends a message to the server. A dict/json like object is expected as the msg param.
"""
if self.session_running:
assert self.websocket
try:
await self.websocket.send(json.dumps(msg))
except TypeError as ex:
LOGGER.info(
f"Cannot send this type of object {msg=} as a message. Exception occured:%s",
repr(ex),
)
return
except websockets.exceptions.ConnectionClosedOK:
# Can occur if a timeout has closed the connection.
LOGGER.info("Cannot send from a closed websocket.")
return
except websockets.exceptions.ConnectionClosedError:
LOGGER.info("Disconnected while sending a message().")
return

async def _producer_handler(self, stream, audio_chunk_size):
"""
Controls the producer loop for sending messages to the server.
Expand Down Expand Up @@ -344,6 +367,11 @@ def add_event_handler(self, event_name, event_handler):
:raises ValueError: If the given event name is not valid.
"""
if (
event_name.startswith(HIDDEN_MSG_PREFIX)
and event_name not in self.event_handlers
):
self.event_handlers[event_name] = []
if event_name == "all":
for name in self.event_handlers.keys():
self.event_handlers[name].append(event_handler)
Expand Down Expand Up @@ -377,6 +405,11 @@ def add_middleware(self, event_name, middleware):
:raises ValueError: If the given event name is not valid.
"""
if (
event_name.startswith(HIDDEN_MSG_PREFIX)
and event_name not in self.middlewares
):
self.middlewares[event_name] = []
if event_name == "all":
for name in self.middlewares.keys():
self.middlewares[name].append(middleware)
Expand Down

0 comments on commit cd2b2a4

Please sign in to comment.