From c4ff75f44c0575394e2998c89813c2219210cfb8 Mon Sep 17 00:00:00 2001 From: Kevin Barnard Date: Thu, 12 Oct 2023 13:16:34 -0700 Subject: [PATCH] Implements #7 --- lcm_websocket_server/app.py | 9 ++++++++- lcm_websocket_server/lcmpubsub.py | 24 +++++++++++++++++++++--- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/lcm_websocket_server/app.py b/lcm_websocket_server/app.py index 4688299..5362e58 100644 --- a/lcm_websocket_server/app.py +++ b/lcm_websocket_server/app.py @@ -15,6 +15,7 @@ import asyncio import queue from signal import SIGINT, SIGTERM +from urllib.parse import unquote from websockets import serve @@ -44,8 +45,14 @@ async def republish_lcm(websocket, path): ip, port = websocket.remote_address[:2] logger.info(f"Client connected from {ip}:{port} at {path}") + # Extract channel regex + channel_regex = unquote(path.lstrip('/')) + if not channel_regex: # empty path -> subscribe to all channels + channel_regex = '.*' + # Create an LCM observer for this client - observer = LCMObserver() + observer = LCMObserver(channel_regex=channel_regex) + logger.debug(f"Created LCM observer with channel regex {channel_regex}") # Subscribe the observer to the LCM republisher lcm_republisher.subscribe(observer) diff --git a/lcm_websocket_server/lcmpubsub.py b/lcm_websocket_server/lcmpubsub.py index eb92049..837edc4 100644 --- a/lcm_websocket_server/lcmpubsub.py +++ b/lcm_websocket_server/lcmpubsub.py @@ -5,6 +5,7 @@ import lcm import queue +import re from threading import Thread from lcm_websocket_server.log import get_logger @@ -15,12 +16,28 @@ class LCMObserver: """ Observer for an LCMObservable. Puts received events in a thread-safe queue. """ - def __init__(self): + def __init__(self, channel_regex: str = ".*"): self._queue = queue.Queue() + self._channel_regex = channel_regex + def match(self, channel: str) -> bool: + """ + Check if the observer matches a given channel. + + Args: + channel: Channel name + + Returns: + True if the observer matches the channel, False otherwise. + """ + try: + return re.fullmatch(self._channel_regex, channel) is not None + except: + return False + def handle(self, event): """ - Handles an LCM event. + Handle an LCM event. """ self._queue.put(event) @@ -91,4 +108,5 @@ def _handler(self, channel, data): data: The LCM data """ for subscriber in self._subscribers: - subscriber.handle((channel, data)) \ No newline at end of file + if subscriber.match(channel): + subscriber.handle((channel, data)) \ No newline at end of file