import socket
import threading
import json
import time
from collections import deque
import logging
# Configure logging for the library
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(threadName)s - %(levelname)s - %(message)s')
class UdpStateListener:
"""
Robot Framework custom library to listen to multiple UDP streams,
store their latest states, and provide them to Robot tests.
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL' # Or 'SUITE' if you need separate instances per suite
def __init__(self):
self._listeners = {} # {channel_name: {'socket': sock, 'thread': thread, 'stop_event': event, 'latest_state': {}, 'last_update_time': 0}}
self._state_lock = threading.Lock() # To ensure thread-safe access to latest_state
def start_listening(self, channel_1_ip, channel_1_port, channel_2_ip, channel_2_port):
"""
Starts listening on two UDP channels in separate threads.
Expects JSON formatted UDP messages.
"""
logging.info(f"Starting UDP listeners for Channel 1: {channel_1_ip}:{channel_1_port} and Channel 2: {channel_2_ip}:{channel_2_port}")
self._start_single_listener("channel_1", channel_1_ip, int(channel_1_port))
self._start_single_listener("channel_2", channel_2_ip, int(channel_2_port))
logging.info("All UDP listeners started.")
def _start_single_listener(self, channel_name, ip, port):
"""Internal method to start a single listener thread."""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((ip, port))
sock.settimeout(1.0) # Timeout for recvfrom to allow thread to check stop_event
logging.info(f"Socket bound for {channel_name} on {ip}:{port}")
stop_event = threading.Event()
thread = threading.Thread(
target=self._listen_thread,
args=(channel_name, sock, stop_event),
name=f"UDP_Listener_{channel_name}"
)
thread.daemon = True # Allow main program to exit even if threads are running
thread.start()
self._listeners[channel_name] = {
'socket': sock,
'thread': thread,
'stop_event': stop_event,
'latest_state': {},
'last_update_time': 0
}
logging.info(f"Thread for {channel_name} started.")
except Exception as e:
logging.error(f"Failed to start listener for {channel_name} on {ip}:{port}: {e}")
raise RuntimeError(f"Failed to start UDP listener for {channel_name}: {e}")
def _listen_thread(self, channel_name, sock, stop_event):
"""Target function for each UDP listening thread."""
logging.info(f"Listening thread for {channel_name} started.")
while not stop_event.is_set():
try:
data, addr = sock.recvfrom(4096) # Buffer size
decoded_data = data.decode('utf-8')
try:
state = json.loads(decoded_data)
with self._state_lock:
self._listeners[channel_name]['latest_state'] = state
self._listeners[channel_name]['last_update_time'] = time.time()
# logging.debug(f"Received from {channel_name}: {state}") # Too verbose for regular use
except json.JSONDecodeError:
logging.warning(f"Could not decode JSON from {channel_name}: {decoded_data}")
except Exception as e:
logging.error(f"Error processing data from {channel_name}: {e} Data: {decoded_data}")
except socket.timeout:
# Timeout occurred, loop back to check stop_event
pass
except Exception as e:
logging.error(f"Socket error for {channel_name}: {e}")
# Decide if you want to stop the thread on persistent errors or try to recover
time.sleep(1) # Prevent busy loop on continuous errors
logging.info(f"Listening thread for {channel_name} stopped.")
sock.close()
logging.info(f"Socket for {channel_name} closed.")
def get_latest_state(self, channel_name):
"""
Returns the most recently received state for a given channel.
"""
if channel_name not in self._listeners:
raise ValueError(f"Unknown channel: {channel_name}. Available: {list(self._listeners.keys())}")
with self._state_lock:
# Return a copy to prevent external modification
return self._listeners[channel_name]['latest_state'].copy()
def get_last_update_time(self, channel_name):
"""
Returns the timestamp of the last state update for a given channel.
"""
if channel_name not in self._listeners:
raise ValueError(f"Unknown channel: {channel_name}")
with self._state_lock:
return self._listeners[channel_name]['last_update_time']
def stop_listening(self):
"""
Signals all listening threads to stop and waits for them to terminate.
"""
logging.info("Stopping all UDP listeners...")
for channel_name, listener_info in self._listeners.items():
listener_info['stop_event'].set()
# It's good practice to join the threads, but for daemon threads,
# it might not be strictly necessary if main program exits.
# However, for graceful shutdown, it's better.
listener_info['thread'].join(timeout=5) # Give it some time to finish
if listener_info['thread'].is_alive():
logging.warning(f"Thread for {channel_name} did not stop gracefully.")
self._listeners.clear()
logging.info("All UDP listeners stopped and resources released.")
def get_channel_names(self):
"""Returns a list of configured channel names."""
return list(self._listeners.keys())
# Example of a keyword for direct use in Robot Framework
def assert_channel_is_active(self, channel_name, timeout_seconds=5):
"""
Asserts that the specified UDP channel has updated its state within the timeout.
"""
current_time = time.time()
last_update = self.get_last_update_time(channel_name)
if (current_time - last_update) > float(timeout_seconds):
raise AssertionError(f"Channel '{channel_name}' has not updated its state in the last {timeout_seconds} seconds. Last update: {last_update} ({(current_time - last_update):.2f}s ago).")
logging.info(f"Channel '{channel_name}' is active. Last update was {(current_time - last_update):.2f}s ago.")