### Start Docker Compose integration test environment Source: https://github.com/allangood/rtlamr2mqtt/blob/main/README.md Starts the Docker Compose setup with Mosquitto and rtlamr2mqtt using mock rtl_tcp/rtlamr scripts. Run from the rtlamr2mqtt-addon directory. ```bash cd rtlamr2mqtt-addon docker compose up --build ``` -------------------------------- ### Test ManagedProcess start with ready pattern and timeout Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/plans/2026-03-26-async-subprocess-refactor.md Test cases for ManagedProcess.start() covering a successful start with a ready pattern and a timeout when the pattern never appears. Uses a mock script directory and a temporary slow script. ```python import asyncio import os import pytest from process_manager import ManagedProcess @pytest.fixture def mock_script_dir(): return os.path.join(os.path.dirname(__file__), '..', 'mock') class TestManagedProcessStart: async def test_start_with_ready_pattern(self, mock_script_dir): proc = ManagedProcess( name='rtl_tcp', command=[os.path.join(mock_script_dir, 'rtl_tcp')], ready_pattern='listening...', ready_timeout=10.0, ) result = await proc.start() assert result is True assert proc.is_alive is True await proc.stop() async def test_start_timeout(self, tmp_path): # Script that never prints the ready pattern script = tmp_path / 'slow.sh' script.write_text('#!/bin/bash\nwhile true; do sleep 1; done\n') script.chmod(0o755) proc = ManagedProcess( name='slow', command=[str(script)], ready_pattern='READY', ready_timeout=1.0, ) result = await proc.start() assert result is False assert proc.is_alive is False ``` -------------------------------- ### Set up virtual environment and run tests Source: https://github.com/allangood/rtlamr2mqtt/blob/main/README.md Run these commands from the rtlamr2mqtt-addon directory to create a Python virtual environment, install development dependencies, and execute the test suite with pytest. ```bash cd rtlamr2mqtt-addon python3 -m venv .venv .venv/bin/pip install -r requirements-dev.txt .venv/bin/pytest tests/ -v ``` -------------------------------- ### Dockerfile.mock for testing Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/plans/2026-03-26-async-subprocess-refactor.md Mock Dockerfile that sets RTLAMR2MQTT_USE_MOCK=1 and copies mock binaries. It installs coreutils (removes expect) and uses the same Python entrypoint. ```dockerfile # syntax=docker/dockerfile:1 FROM python:3.13-slim ENV VIRTUAL_ENV=/opt/venv ENV PATH="$VIRTUAL_ENV/bin:$PATH" ENV RTLAMR2MQTT_USE_MOCK=1 COPY mock/ /usr/bin/ COPY requirements.txt /tmp RUN apt-get update && \ apt-get install -o Dpkg::Options::="--force-confnew" -y \ libusb-1.0-0 \ coreutils && \ python3 -m venv $VIRTUAL_ENV && \ pip install -r /tmp/requirements.txt && \ rm -rf /usr/share/doc /tmp/requirements.txt COPY ./app/ $VIRTUAL_ENV/app/ STOPSIGNAL SIGTERM ENTRYPOINT ["python", "/opt/venv/app/rtlamr2mqtt.py"] ``` -------------------------------- ### Run rtlamr2mqtt with Docker (Standalone) Source: https://github.com/allangood/rtlamr2mqtt/blob/main/README.md Starts the rtlamr2mqtt container with a read-only configuration file mounted at /etc/rtlamr2mqtt.yaml and USB device access. The container restarts unless stopped. ```bash docker run --name rtlamr2mqtt \ -v /path/to/rtlamr2mqtt.yaml:/etc/rtlamr2mqtt.yaml:ro \ --device /dev/bus/usb:/dev/bus/usb \ --restart unless-stopped \ allangood/rtlamr2mqtt ``` -------------------------------- ### Set up dev environment and run tests/build Source: https://github.com/allangood/rtlamr2mqtt/blob/main/CLAUDE.md Run from the rtlamr2mqtt-addon/ directory. Sets up a Python virtual environment, installs dev requirements, runs tests (optionally filtered by file or name), lints the app code, builds the standalone Docker image, and runs an integration test with mock RTL-SDR hardware. The final docker exec command subscribes to the rtlamr/# and homeassistant/# MQTT topics to verify output. ```bash # Set up dev environment python3 -m venv .venv .venv/bin/pip install -r requirements-dev.txt # Run all tests .venv/bin/pytest # Run a single test file .venv/bin/pytest tests/test_process_manager.py -v # Run a single test by name .venv/bin/pytest tests/test_config.py -v -k "test_load_standalone" # Lint .venv/bin/pylint --rcfile=.pylint app/ # Build Docker image (standalone mode) docker build -t rtlamr2mqtt . # Integration test with mock RTL-SDR hardware docker compose up --build # In another terminal, subscribe to verify output: docker exec rtlamr2mqtt-addon-mosquitto-1 mosquitto_sub -t 'rtlamr/#' -t 'homeassistant/#' -v ``` -------------------------------- ### Rewrite rtlamr2mqtt.py main entry point Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/plans/2026-03-26-async-subprocess-refactor.md Full replacement for rtlamr2mqtt.py, the main entry point. Sets up logging, loads config, handles signals, starts rtl_tcp and rtlamr as managed processes, and exits on critical failures. ```python #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ rtlamr2mqtt - A Home Assistant add-on for RTLAMR https://github.com/allangood/rtlamr2mqtt/blob/main/LICENSE This add-on uses the code from: - https://github.com/bemasher/rtlamr - https://git.osmocom.org/rtl-sdr """ import asyncio import os import sys import signal import logging from shutil import which import helpers.config as cnf import helpers.buildcmd as cmd import helpers.usb_utils as usbutil import helpers.info as i from process_manager import ManagedProcess from meter_reader import MeterReader from mqtt_publisher import MQTTPublisher # Logging verbosity map VERBOSITY_MAP = { 'none': logging.CRITICAL + 1, 'error': logging.ERROR, 'warning': logging.WARNING, 'info': logging.INFO, 'debug': logging.DEBUG, } logger = logging.getLogger('rtlamr2mqtt') def setup_logging(verbosity: str): """Configure logging with the given verbosity level.""" logging.basicConfig( format='[%(asctime)s] %(levelname)s: %(message)s', level=VERBOSITY_MAP.get(verbosity, logging.INFO), ) logger.setLevel(VERBOSITY_MAP.get(verbosity, logging.INFO)) def load_and_validate_config(): """Load config, set up logging, return config dict or exit.""" if len(sys.argv) == 2: config_path = os.path.join(os.path.dirname(__file__), sys.argv[1]) else: config_path = None status, msg, config = cnf.load_config(config_path) if status != 'success': # Use basic logging since we don't have config yet logging.basicConfig(format='[%(asctime)s] %(levelname)s: %(message)s') logger.critical(msg) sys.exit(1) setup_logging(config['general']['verbosity']) logger.info('Starting rtlamr2mqtt %s', i.version()) logger.info(msg) return config async def main(): """Main async entry point.""" config = load_and_validate_config() shutdown_event = asyncio.Event() reading_queue = asyncio.Queue(maxsize=100) # Signal handlers loop = asyncio.get_event_loop() for sig in (signal.SIGTERM, signal.SIGINT): loop.add_signal_handler(sig, shutdown_event.set) # Determine if rtl_tcp is remote rtltcp_host = config['general']['rtltcp_host'] is_remote = rtltcp_host.split(':')[0] not in ['127.0.0.1', 'localhost'] # USB setup (sync, before async work) if not is_remote and 'RTLAMR2MQTT_USE_MOCK' not in os.environ: device_index = config['general']['device_id'] devices = usbutil.find_rtl_sdr_devices() if device_index >= len(devices): if len(devices) == 0: logger.critical('No RTL-SDR devices found') else: logger.critical('Device index %d out of range (found %d devices)', device_index, len(devices)) sys.exit(1) logger.info('Found %d RTL-SDR device(s), using index %d', len(devices), device_index) # Build commands rtltcp_cmd = None if not is_remote: rtltcp_args = cmd.build_rtltcp_args(config) rtltcp_bin = which('rtl_tcp') if rtltcp_bin and rtltcp_args is not None: rtltcp_cmd = [rtltcp_bin] + rtltcp_args rtlamr_args = cmd.build_rtlamr_args(config) rtlamr_bin = which('rtlamr') if not rtlamr_bin: logger.critical('rtlamr binary not found in PATH') sys.exit(1) rtlamr_cmd = [rtlamr_bin] + rtlamr_args # Create managed processes rtltcp_proc = ManagedProcess( name='rtl_tcp', command=rtltcp_cmd or ['echo', 'remote'], ready_pattern='listening...', ready_timeout=30.0, ) rtlamr_proc = ManagedProcess( name='rtlamr', command=rtlamr_cmd, ready_pattern='GainCount:', ready_timeout=30.0, ) # Start rtl_tcp if local if not is_remote: if not await rtltcp_proc.start_with_retry(): logger.critical('Failed to start rtl_tcp') sys.exit(1) # Tickle rtl_tcp to wake it up usbutil.tickle_rtl_tcp(rtltcp_host) # Start rtlamr if not await rtlamr_proc.start_with_retry(): logger.critical('Failed to start rtlamr') if not is_remote: await rtltcp_proc.stop() sys.exit(1) ``` -------------------------------- ### Main orchestration function Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/specs/2026-03-26-async-subprocess-refactor-design.md Async main function that loads config, sets up USB, creates managed processes for rtl_tcp and rtlamr, sets up signal handlers, starts rtl_tcp if local, runs meter_reader and mqtt_publisher tasks in a TaskGroup, and cleans up by stopping processes. Uses shutdown_event for cooperative cancellation and bounded queue. ```python async def main(): config = load_config() shutdown_event = asyncio.Event() reading_queue = asyncio.Queue(maxsize=100) # USB setup (sync, before async loop) setup_usb(config) # Create managed processes rtltcp = ManagedProcess("rtl_tcp", ..., ready_pattern="listening...") rtlamr = ManagedProcess("rtlamr", ..., ready_pattern="GainCount:") # Signal handlers loop = asyncio.get_event_loop() for sig in (SIGTERM, SIGINT): loop.add_signal_handler(sig, shutdown_event.set) # Start rtl_tcp (if local) if not is_remote: await rtltcp.start_with_retry() # Run tasks async with asyncio.TaskGroup() as tg: tg.create_task(meter_reader(rtlamr, rtltcp, config, reading_queue, shutdown_event)) tg.create_task(mqtt_publisher(config, reading_queue, shutdown_event)) # Cleanup await rtlamr.stop() await rtltcp.stop() ``` -------------------------------- ### Complete rtlamr2mqtt.yaml configuration example Source: https://github.com/allangood/rtlamr2mqtt/blob/main/README.md Full YAML configuration for standalone (non-HA add-on) operation. Includes general settings (sleep_for, verbosity, device_id, rtltcp_host, listen_mode), MQTT broker settings (host, port, TLS, topics), optional custom rtl_tcp/rtlamr parameters, and a meters list with one meter definition. Required when running standalone. ```yaml general: # Seconds to sleep after all meters are read. 0 = continuous reading. sleep_for: 60 # Log verbosity: debug, info, warning, error, critical, none verbosity: info # RTL-SDR device index (0 = first device). Use if you have multiple SDR dongles. # device_id: 0 # RTL_TCP server address. Default: local server at 127.0.0.1:1234 # Set to a remote address to use an external rtl_tcp instance. # rtltcp_host: "192.168.1.100:1234" # Enable to log all received meters without MQTT. Useful for finding your meter ID. # listen_mode: false mqtt: # MQTT broker connection (not needed when running as HA add-on) host: 127.0.0.1 port: 1883 # user: myuser # password: mypassword # TLS settings tls_enabled: false # tls_insecure: false # tls_ca: "/path/to/ca.crt" # tls_cert: "/path/to/client.crt" # tls_keyfile: "/path/to/client.key" # MQTT topics ha_autodiscovery_topic: homeassistant ha_status_topic: homeassistant/status base_topic: rtlamr # How often (seconds) to re-publish HA discovery payloads. Keeps entities alive after broker restarts. # discovery_interval: 300 # Optional: pass extra arguments to rtl_tcp or rtlamr # custom_parameters: # rtltcp: "-s 2048000" # rtlamr: "-unique=true" # Meter definitions (required) meters: - id: 12345678 protocol: scm+ # scm, scm+, idm, netidm, r900, r900bcd name: my_water_meter format: "######.###" # Each '#' is a digit unit_of_measurement: "m3" icon: mdi:water device_class: water # water, gas, energy, power, current, none state_class: total_increasing # measurement, total, total_increasing # expire_after: 3600 # Seconds before sensor becomes unavailable # force_update: true # Send updates even if value unchanged # manufacturer: "Badger Meter" # Shown in HA device info # model: "ORION SE" # Shown in HA device info ``` -------------------------------- ### Install dev dependencies and verify pytest Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/plans/2026-03-26-async-subprocess-refactor.md Install dev dependencies and verify pytest runs. Expected output is "no tests ran" with exit code 0 or 5. ```bash cd /home/user/allangood/rtlamr2mqtt/rtlamr2mqtt-addon && pip install -r requirements-dev.txt && pytest --co -q ``` -------------------------------- ### Dockerfile for rtlamr2mqtt addon Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/plans/2026-03-26-async-subprocess-refactor.md Production Dockerfile that builds rtlamr and rtl-sdr from source, then creates a Python 3.13 slim image with a virtual environment. It installs coreutils (removes expect) and sets the entrypoint to the main script. ```dockerfile # syntax=docker/dockerfile:1 FROM golang:1.24 AS go-builder WORKDIR /go/src/app RUN go install github.com/bemasher/rtlamr@latest \ && apt-get update \ && apt-get install -y libusb-1.0-0-dev build-essential git cmake \ && git clone https://git.osmocom.org/rtl-sdr.git \ && cd rtl-sdr \ && mkdir build && cd build \ && cmake .. -DDETACH_KERNEL_DRIVER=ON -DENABLE_ZEROCOPY=ON -Wno-dev \ && make \ && make install FROM python:3.13-slim ENV VIRTUAL_ENV=/opt/venv RUN python3 -m venv $VIRTUAL_ENV ENV PATH="$VIRTUAL_ENV/bin:$PATH" COPY --from=go-builder /usr/local/lib/librtl* /lib/ COPY --from=go-builder /go/bin/rtlamr* /usr/bin/ COPY --from=go-builder /usr/local/bin/rtl* /usr/bin/ COPY requirements.txt /tmp COPY ./app/ $VIRTUAL_ENV/app/ RUN apt-get update \ && apt-get install -o Dpkg::Options::="--force-confnew" -y \ libusb-1.0-0 \ coreutils \ && apt-get --purge autoremove -y \ && apt-get clean \ && find /var/lib/apt/lists/ -type f -delete \ && pip install -r /tmp/requirements.txt \ && rm -rf /usr/share/doc /tmp/requirements.txt STOPSIGNAL SIGTERM ENTRYPOINT ["python", "/opt/venv/app/rtlamr2mqtt.py"] ``` -------------------------------- ### Home Assistant Add-On: Enable Listen Mode Source: https://github.com/allangood/rtlamr2mqtt/blob/main/README.md Set general.listen_mode to true in the add-on configuration to run without meter filtering and without MQTT publishing. Leave the meters list empty or remove it entirely. Start the add-on and check the Log tab for 'New meter' lines. ```yaml general: listen_mode: true ``` -------------------------------- ### Add-on configuration YAML Source: https://github.com/allangood/rtlamr2mqtt/blob/main/rtlamr2mqtt-addon/DOCS.md Full configuration example for the rtlamr2mqtt add-on. Includes general settings (sleep_for, verbosity, device_id), MQTT broker settings (host, port, TLS), and meter definitions with protocol, format, and HA attributes. Note that the old version and new device_id setting are incompatible. ```yaml general: # Sleep for this amount of seconds before each reading # If this value is 0, it means we will never stop reading sleep_for: 0 # Verbose output. It can be: debug, info, warning, error, none verbosity: debug # if you have multiple RTL devices, set the device id to use with this instance. # Get the ID running the lsusb command. If not specified, the first device will be used. # Example: # device_id: '001:010' # RTL_TCP host and port to connect. Default, use the internal server # If you want to use a remote rtl_tcp server, set the host and port here # rtltcp_host: "172.17.0.4:1234" mqtt: # Broker host. This is optional. # If not specified, it will query supervisor ###host: localhost # Broker port. This is optional. # If not specified, it will query supervisor ###port: 1883 # Username. This is optional. # If not specified, it will query supervisor ###user: test # Password. This is optional. # If not specified, it will query supervisor ###password: testpassword # Use TLS with MQTT? tls_enabled: false # TLS insecure. Must be true for self-signed certificates. Defaults to False tls_insecure: true # Path to CA certificate to use. Mandatory if tls_enabled = true tls_ca: "/etc/ssl/certs/ca-certificates.crt" # Path to certificate file to use. Optional tls_cert: "/etc/ssl/my_self_signed_cert.crt" # Certificate key file to use. Optional tls_keyfile: "/etc/ssl/my_self_signed_cert_key.key" # Which topic for the auto discover to use? ha_autodiscovery_topic: homeassistant # Home Assistant status topic ha_status_topic: homeassistant/status # Base topic to send status and state information # i.e.: status = /status base_topic: "rtlamr" # Optional section # If you need to pass parameters to rtl_tcp or rtlamr # custom_parameters: # rtltcp: "-s 2048000 -f 912600155" # rtlamr: "" # Mandatory section: Meters definition # You can define multiple meters # Check here for more info: # https://www.home-assistant.io/integrations/sensor.mqtt meters: # Meter ID - id: 33333333 # Protocol: scm, scm+, idm, netidm, r900 and r900bcd protocol: scm+ # A nice name to show on HA name: my_water_meter # How to format the number of your meter. Each '#' is a digit format: "######.###" # Unit of measurement to show on HA unit_of_measurement: "m³" # Icon to show on HA icon: mdi:gauge # device_class on HA device_class: water # HA state_class. It can be measurement|total|total_increasing # state_class: total_increasing # If set, it defines the number of seconds after the sensor’s state expires, # if it’s not updated. After expiry, the sensor’s state becomes unavailable. # expire_after: 0 # Sends update events even if the value hasn’t changed. # Useful if you want to have meaningful value graphs in history. # force_update: true - id: 22222222 # Protocol: scm, scm+, idm, netidm, r900 and r900bcd protocol: r900 # A nice name to show on HA name: my_energy_meter # How to format the number of your meter. Each '#' is a digit format: "######.###" # Unit of measurement to show on HA unit_of_measurement: "KWh" # Icon to show on HA icon: mdi:gauge # device_class on HA device_class: energy ``` -------------------------------- ### Test start exits early Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/plans/2026-03-26-async-subprocess-refactor.md Test that ManagedProcess.start() returns False when the process exits before becoming ready. Uses a temporary shell script that prints an error and exits with code 1. ```python async def test_start_process_exits_early(self, tmp_path): script = tmp_path / 'fail.sh' script.write_text('#!/bin/bash\necho "error"\nexit 1\n') script.chmod(0o755) proc = ManagedProcess( name='fail', command=[str(script)], ready_pattern='READY', ready_timeout=5.0, ) result = await proc.start() assert result is False ``` -------------------------------- ### Python logging verbosity map and logger setup Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/specs/2026-03-26-async-subprocess-refactor-design.md Replaces the numeric LOG_LEVEL global with a mapping from verbosity strings to logging levels and configures the 'rtlamr2mqtt' logger. Use this to enable standard Python logging calls like logger.info() and logger.debug() instead of 'if LOG_LEVEL >= 3:' checks. ```python VERBOSITY_MAP = { 'none': logging.CRITICAL + 1, 'error': logging.ERROR, 'warning': logging.WARNING, 'info': logging.INFO, 'debug': logging.DEBUG, } logger = logging.getLogger('rtlamr2mqtt') logger.setLevel(VERBOSITY_MAP[config['general']['verbosity']]) ``` -------------------------------- ### Test ManagedProcess restart Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/plans/2026-03-26-async-subprocess-refactor.md Test that ManagedProcess.restart() stops the running process and starts it again, returning True and leaving the process alive. ```python class TestManagedProcessRestart: async def test_restart(self, mock_script_dir): proc = ManagedProcess( name='rtl_tcp', command=[os.path.join(mock_script_dir, 'rtl_tcp')], ready_pattern='listening...', ready_timeout=10.0, ) await proc.start() assert proc.is_alive is True result = await proc.restart() assert result is True assert proc.is_alive is True await proc.stop() ``` -------------------------------- ### Run MQTT publisher tests Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/plans/2026-03-26-async-subprocess-refactor.md Run the test suite for the MQTT publisher. Expected to fail with ModuleNotFoundError: No module named 'mqtt_publisher' before implementation. ```bash cd /home/user/allangood/rtlamr2mqtt/rtlamr2mqtt-addon && pytest tests/test_mqtt_publisher.py -v ``` -------------------------------- ### Test ManagedProcess stop behavior Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/plans/2026-03-26-async-subprocess-refactor.md Tests for ManagedProcess.stop(): verifies that stopping a running process sets is_alive to False, and that calling stop() on a process that was never started does not raise an exception. ```python class TestManagedProcessStop: async def test_stop_terminates(self, mock_script_dir): proc = ManagedProcess( name='rtl_tcp', command=[os.path.join(mock_script_dir, 'rtl_tcp')], ready_pattern='listening...', ready_timeout=10.0, ) await proc.start() await proc.stop() assert proc.is_alive is False async def test_stop_when_not_started(self): proc = ManagedProcess( name='test', command=['echo', 'hello'], ready_pattern='hello', ready_timeout=5.0, ) # Should not raise await proc.stop() ``` -------------------------------- ### Async main with TaskGroup orchestration Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/plans/2026-03-26-async-subprocess-refactor.md Main entry point that creates MeterReader and MQTTPublisher, runs them concurrently with asyncio.TaskGroup, and cleans up by stopping the rtlamr and rtltcp processes. The except* clause logs non-cancelled task errors. ```python # Create reader and publisher reader = MeterReader( config=config, rtlamr=rtlamr_proc, rtltcp=rtltcp_proc, reading_queue=reading_queue, shutdown_event=shutdown_event, is_remote=is_remote, ) publisher = MQTTPublisher( config=config, reading_queue=reading_queue, shutdown_event=shutdown_event, ) # Run reader and publisher concurrently try: async with asyncio.TaskGroup() as tg: tg.create_task(reader.run()) tg.create_task(publisher.run()) except* Exception as eg: for exc in eg.exceptions: if not isinstance(exc, asyncio.CancelledError): logger.error('Task error: %s', exc) # Cleanup logger.info('Shutting down...') await rtlamr_proc.stop() if not is_remote: await rtltcp_proc.stop() logger.info('Goodbye!') if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### ProcessManager class for async subprocess management Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/plans/2026-03-26-async-subprocess-refactor.md Defines the ProcessManager class with methods to start, stop, restart, and retry a subprocess. It waits for a ready pattern in stdout, uses stdbuf for line-buffered output, and sends SIGTERM then SIGKILL on stop. ```python def __init__( self, name: str, command: list[str], ready_pattern: str, ready_timeout: float = 30.0, max_retries: int = 5, backoff: list[float] | None = None, ): self.name = name self.command = command self.ready_pattern = ready_pattern self.ready_timeout = ready_timeout self.max_retries = max_retries self.backoff = backoff if backoff is not None else [2, 5, 10, 20, 30] self._process: asyncio.subprocess.Process | None = None @property def is_alive(self) -> bool: return self._process is not None and self._process.returncode is None async def start(self) -> bool: """ Start the process and wait for the ready pattern in stdout. Returns True if the process started and is ready, False otherwise. """ if self.is_alive: await self.stop() # Prepend stdbuf for line-buffered output if available full_command = list(self.command) stdbuf_path = which('stdbuf') if stdbuf_path: full_command = [stdbuf_path, '-oL'] + full_command logger.info('Starting %s: %s', self.name, ' '.join(full_command)) try: self._process = await asyncio.create_subprocess_exec( *full_command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT, start_new_session=True, ) except Exception as e: logger.error('Failed to launch %s: %s', self.name, e) self._process = None return False # Wait for ready pattern with timeout try: ready = await asyncio.wait_for( self._wait_for_ready(), timeout=self.ready_timeout, ) if ready: logger.info('%s is ready', self.name) return ready except asyncio.TimeoutError: logger.error('%s did not become ready within %.1fs', self.name, self.ready_timeout) await self.stop() return False async def _wait_for_ready(self) -> bool: """ Read stdout lines until the ready pattern is found or the process exits. """ while True: if self._process.stdout is None: return False line_bytes = await self._process.stdout.readline() if not line_bytes: # EOF — process exited logger.error('%s exited before becoming ready (exit code: %s)', self.name, self._process.returncode) return False line = line_bytes.decode('utf-8', errors='replace').strip() if line: logger.debug('%s: %s', self.name, line) if self.ready_pattern in line: return True async def stop(self): """ Stop the process. Sends SIGTERM, waits 2 seconds, then SIGKILL. """ if self._process is None: return if self._process.returncode is not None: # Already exited self._process = None return logger.info('Stopping %s (pid %d)', self.name, self._process.pid) try: self._process.send_signal(signal.SIGTERM) try: await asyncio.wait_for(self._process.wait(), timeout=2.0) except asyncio.TimeoutError: logger.warning('%s did not exit after SIGTERM, sending SIGKILL', self.name) self._process.kill() await self._process.wait() except ProcessLookupError: pass # Already dead logger.info('%s stopped', self.name) self._process = None async def restart(self) -> bool: """ Stop then start the process. """ await self.stop() return await self.start() async def start_with_retry(self) -> bool: """ Try to start the process, retrying with backoff on failure. Returns True if the process started successfully, False if all retries exhausted. """ if await self.start(): return True for attempt in range(self.max_retries): delay = self.backoff[min(attempt, len(self.backoff) - 1)] logger.warning( '%s failed to start, retry %d/%d in %.1fs', self.name, attempt + 1, self.max_retries, delay, ) await asyncio.sleep(delay) if await self.start(): return True logger.error('%s failed to start after %d retries', self.name, self.max_retries) return False ``` -------------------------------- ### Run tests for config module Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/plans/2026-03-26-async-subprocess-refactor.md Run the test suite for the configuration module. Expected output is that all tests pass. ```bash cd /home/user/allangood/rtlamr2mqtt/rtlamr2mqtt-addon && pytest tests/test_config.py -v ``` -------------------------------- ### ManagedProcess class definition Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/specs/2026-03-26-async-subprocess-refactor-design.md Defines the generic async subprocess wrapper with constructor parameters and async methods. Includes start, stop, restart, start_with_retry, read_line, wait_for_exit, and is_alive property. Uses asyncio.create_subprocess_exec and asyncio.wait_for for readiness detection, SIGTERM/SIGKILL for stop, and backoff retry. ```python class ManagedProcess: def __init__( self, name: str, # "rtl_tcp" or "rtlamr" command: list[str], # full command with args ready_pattern: str, # stdout string indicating readiness ready_timeout: float, # seconds to wait for ready pattern max_retries: int = 5, backoff: list[float] = [2, 5, 10, 20, 30], ) async def start(self) -> bool async def stop(self) async def restart(self) -> bool async def start_with_retry(self) -> bool async def read_line(self) -> str | None async def wait_for_exit(self) @property def is_alive(self) -> bool ``` -------------------------------- ### Docker/Standalone: Minimal Listen Mode Config Source: https://github.com/allangood/rtlamr2mqtt/blob/main/README.md Minimal YAML configuration for standalone use. listen_mode is enabled and verbosity is set to info. The mqtt host is still required but no connection is made. ```yaml general: listen_mode: true verbosity: info mqtt: host: 127.0.0.1 # still required for standalone, but no connection is made ``` -------------------------------- ### Run buildcmd tests Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/plans/2026-03-26-async-subprocess-refactor.md Runs the new buildcmd tests. Expected to fail due to current set() deduplication, sdl_devices bug, and bus:address logic. ```bash cd /home/user/allangood/rtlamr2mqtt/rtlamr2mqtt-addon && pytest tests/test_buildcmd.py -v ``` -------------------------------- ### Run tests to verify they fail Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/plans/2026-03-26-async-subprocess-refactor.md Command to run the test suite for usb_utils. Expected: tests referencing get_device_by_index fail because the function does not exist yet; others may pass. ```bash cd /home/user/allangood/rtlamr2mqtt/rtlamr2mqtt-addon && pytest tests/test_usb_utils.py -v ``` -------------------------------- ### Docker/Standalone: Run Container and Watch Logs Source: https://github.com/allangood/rtlamr2mqtt/blob/main/README.md Command to run the rtlamr2mqtt container with the listen mode config. Mounts the config file read-only and passes the USB device. After finding the meter ID, update the config and set listen_mode to false. ```bash docker run --rm \ -v /path/to/listen.yaml:/etc/rtlamr2mqtt.yaml:ro \ --device /dev/bus/usb:/dev/bus/usb \ allangood/rtlamr2mqtt ``` -------------------------------- ### Rewrite helpers/usb_utils.py - test_usb_utils.py Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/plans/2026-03-26-async-subprocess-refactor.md Test suite for helpers/usb_utils.py covering load_id_file, find_rtl_sdr_devices, get_device_by_index, and tickle_rtl_tcp. Uses unittest.mock patches to simulate USB and socket behavior. The get_device_by_index tests are expected to fail until that function is implemented. ```python import os import pytest from unittest.mock import patch, MagicMock from helpers.usb_utils import load_id_file, find_rtl_sdr_devices, get_device_by_index, tickle_rtl_tcp class TestLoadIdFile: def test_loads_valid_ids(self): sdl_file = os.path.join(os.path.dirname(__file__), '..', 'app', 'helpers', 'sdl_ids.txt') ids = load_id_file(sdl_file) assert len(ids) > 0 assert '0bda:2838' in ids def test_ignores_comments(self): sdl_file = os.path.join(os.path.dirname(__file__), '..', 'app', 'helpers', 'sdl_ids.txt') ids = load_id_file(sdl_file) for device_id in ids: assert not device_id.startswith('#') class TestFindRtlSdrDevices: @patch('helpers.usb_utils.usb.core.find') def test_finds_matching_device(self, mock_find): mock_dev = MagicMock() mock_dev.idVendor = 0x0bda mock_dev.idProduct = 0x2838 mock_find.return_value = [mock_dev] devices = find_rtl_sdr_devices() assert len(devices) == 1 @patch('helpers.usb_utils.usb.core.find') def test_no_devices(self, mock_find): mock_find.return_value = [] devices = find_rtl_sdr_devices() assert len(devices) == 0 @patch('helpers.usb_utils.usb.core.find') def test_ignores_non_rtlsdr(self, mock_find): mock_dev = MagicMock() mock_dev.idVendor = 0xFFFF mock_dev.idProduct = 0xFFFF mock_find.return_value = [mock_dev] devices = find_rtl_sdr_devices() assert len(devices) == 0 class TestGetDeviceByIndex: @patch('helpers.usb_utils.usb.core.find') def test_get_first_device(self, mock_find): mock_dev = MagicMock() mock_dev.idVendor = 0x0bda mock_dev.idProduct = 0x2838 mock_find.return_value = [mock_dev] device = get_device_by_index(0) assert device is mock_dev @patch('helpers.usb_utils.usb.core.find') def test_index_out_of_range(self, mock_find): mock_dev = MagicMock() mock_dev.idVendor = 0x0bda mock_dev.idProduct = 0x2838 mock_find.return_value = [mock_dev] device = get_device_by_index(5) assert device is None @patch('helpers.usb_utils.usb.core.find') def test_no_devices(self, mock_find): mock_find.return_value = [] device = get_device_by_index(0) assert device is None class TestTickleRtlTcp: @patch('helpers.usb_utils.socket.socket') def test_tickle_sends_commands(self, mock_socket_class): mock_conn = MagicMock() mock_socket_class.return_value = mock_conn tickle_rtl_tcp('127.0.0.1:1234') mock_conn.connect.assert_called_once() assert mock_conn.send.call_count == 2 mock_conn.close.assert_called_once() @patch('helpers.usb_utils.socket.socket') def test_tickle_handles_connection_error(self, mock_socket_class): mock_conn = MagicMock() mock_conn.connect.side_effect = ConnectionRefusedError("refused") mock_socket_class.return_value = mock_conn # Should not raise tickle_rtl_tcp('127.0.0.1:1234') mock_conn.close.assert_called_once() ``` -------------------------------- ### Create requirements-dev.txt Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/plans/2026-03-26-async-subprocess-refactor.md Create rtlamr2mqtt-addon/requirements-dev.txt with the base requirements and pytest dependencies. ```text -r requirements.txt pytest>=8.0 pytest-asyncio>=0.23 ``` -------------------------------- ### Rewrite helpers/config.py with load_config and get_mqtt_info_from_supervisor Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/plans/2026-03-26-async-subprocess-refactor.md Rewritten helpers/config.py for the rtlamr2mqtt addon. It loads configuration from JSON/YAML files, falls back to Supervisor API for MQTT settings when no host is configured, and returns a (status, message, config_dict) tuple. Requires the SUPERVISOR_TOKEN environment variable for Supervisor API access. ```python """ Helper functions for loading configuration files """ import os import requests from json import load from yaml import safe_load def get_mqtt_info_from_supervisor(mqtt_config): """ Get MQTT broker information from the Supervisor API. """ token = os.getenv("SUPERVISOR_TOKEN") if token is None: return mqtt_config api_url = 'http://supervisor/services/mqtt' headers = { "Authorization": f"Bearer {token}", "Content-Type": "application/json", } try: resp = requests.get(api_url, headers=headers, timeout=10) resp.raise_for_status() data = resp.json()['data'] mqtt_config['host'] = data.get('host') mqtt_config['port'] = data.get('port') mqtt_config['user'] = data.get('username', None) mqtt_config['password'] = data.get('password', None) mqtt_config['tls_enabled'] = data.get('ssl', False) except Exception: return mqtt_config return mqtt_config def load_config(config_path=None): """ Load the configuration file. Returns a tuple of (status, message, config_dict). """ # Search for config file in default locations if no path given search_paths = [ '/data/options.json', '/data/options.js', '/data/options.yaml', '/data/options.yml', '/etc/rtlamr2mqtt.yaml', ] if config_path is None: for path in search_paths: if os.path.isfile(path) and os.access(path, os.R_OK): config_path = path break if config_path is None: return ('error', 'No config file found.', None) if not os.path.isfile(config_path): return ('error', 'Config file not found.', None) if not os.access(config_path, os.R_OK): return ('error', 'Config file not readable.', None) file_extension = os.path.splitext(config_path)[1] if file_extension in ['.json', '.js']: with open(config_path, 'r', encoding='utf-8') as file: config = load(file) elif file_extension in ['.yaml', '.yml']: with open(config_path, 'r', encoding='utf-8') as file: config = safe_load(file) else: return ('error', 'Config file format not supported.', None) if 'meters' not in config: return ('error', 'No meters section found in config file.', None) # Parse sections with defaults general = config.get('general') or {} mqtt = config.get('mqtt') or {} custom_parameters = config.get('custom_parameters') or {} # General section general['sleep_for'] = int(general.get('sleep_for', 0)) general['verbosity'] = str(general.get('verbosity', 'info')) general['device_id'] = int(general.get('device_id', 0)) general['rtltcp_host'] = str(general.get('rtltcp_host', '127.0.0.1:1234')) # MQTT section mqtt['host'] = mqtt.get('host', None) if mqtt['host'] is None: mqtt = get_mqtt_info_from_supervisor(mqtt) else: mqtt['port'] = int(mqtt.get('port', 1883)) mqtt['user'] = mqtt.get('user', None) mqtt['password'] = mqtt.get('password', None) mqtt['tls_enabled'] = bool(mqtt.get('tls_enabled', False)) if mqtt.get('host') is None: return ('error', 'No MQTT broker information found.', None) mqtt['tls_insecure'] = bool(mqtt.get('tls_insecure', False)) mqtt['tls_ca'] = mqtt.get('tls_ca', None) mqtt['tls_cert'] = mqtt.get('tls_cert', None) mqtt['tls_keyfile'] = mqtt.get('tls_keyfile', None) mqtt['base_topic'] = str(mqtt.get('base_topic', 'rtlamr')) mqtt['ha_status_topic'] = str(mqtt.get('ha_status_topic', 'homeassistant/status')) mqtt['ha_autodiscovery_topic'] = mqtt.get('ha_autodiscovery_topic', 'homeassistant') # Custom parameters section custom_parameters['rtltcp'] = str(custom_parameters.get('rtltcp', '-s 2048000')) custom_parameters['rtlamr'] = str(custom_parameters.get('rtlamr', '-unique=true')) # Convert meters list to dict keyed by ID meters = {} meters_allowed_keys = [ 'id', 'protocol', 'name', 'format', 'unit_of_measurement', 'icon', 'device_class', 'state_class', 'expire_after', 'force_update', 'manufacturer', 'model', ] for m in config['meters']: m['state_class'] = m.get('state_class', 'total_increasing') meters[str(m['id'])] = {key: value for key, value in m.items() if key in meters_allowed_keys} return ('success', 'Config loaded successfully', { 'general': general, 'mqtt': mqtt, 'custom_parameters': custom_parameters, 'meters': meters, }) ``` -------------------------------- ### Commit MQTT publisher changes Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/plans/2026-03-26-async-subprocess-refactor.md Stage and commit the new MQTT publisher implementation and its tests. ```bash git add rtlamr2mqtt-addon/app/mqtt_publisher.py rtlamr2mqtt-addon/tests/test_mqtt_publisher.py git commit -m "feat: add async MQTTPublisher with aiomqtt, discovery, and reconnection" ``` -------------------------------- ### Commit test infrastructure Source: https://github.com/allangood/rtlamr2mqtt/blob/main/docs/superpowers/plans/2026-03-26-async-subprocess-refactor.md Commit the new test infrastructure and dependency files. ```bash git add rtlamr2mqtt-addon/requirements.txt rtlamr2mqtt-addon/requirements-dev.txt rtlamr2mqtt-addon/pytest.ini rtlamr2mqtt-addon/tests/conftest.py git commit -m "chore: set up test infrastructure and update dependencies" ```