From d61776afde64ed74e38b1ae1a13b25870c8c4f4a Mon Sep 17 00:00:00 2001 From: Gavin Ying Date: Thu, 12 Nov 2026 19:08:48 +0800 Subject: [PATCH] feat: restore v1 CSV configurations behind content detection --config accepts v1 CSV and WoT TM/TD JSON side by side; the format is detected from the content, not the filename. New --thing-model/--tm and --thing-description/--td flags assert the JSON document kind explicitly. The CSV loader keeps v1 row semantics (device/poll/ref rows, space-to- underscore point names, blank access defaulting to r, multiplicative scale, eight-bit bit-table groups) and feeds the same Device/Poller/Point engine as the WoT path. Usage mistakes (kind mismatch, --param with CSV, duplicate device names) exit 2 with one error line. --precision stays in the default auto rendering mode. --- README.md | 11 +- contrib/README.md | 7 +- docs/site/configure.rst | 55 +++++--- docs/site/csv-migration.rst | 22 +-- docs/site/index.rst | 5 +- docs/site/usage.rst | 5 +- docs/site/v1-compatibility.rst | 23 ++-- docs/validation.rst | 15 ++ examples/README.md | 3 +- modpoll/arg_parser.py | 31 ++++- modpoll/config_loader.py | 96 +++++++++++++ modpoll/csv_config.py | 243 +++++++++++++++++++++++++++++++++ modpoll/main.py | 5 +- modpoll/modbus_task.py | 27 +++- tests/test_cli_errors.py | 55 ++++++++ tests/test_csv_config.py | 125 +++++++++++++++++ tests/test_wot_config.py | 23 +++- 17 files changed, 690 insertions(+), 61 deletions(-) create mode 100644 modpoll/config_loader.py create mode 100644 modpoll/csv_config.py create mode 100644 tests/test_csv_config.py diff --git a/README.md b/README.md index 6090f68..2f3304a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -> **2.x development branch.** This checkout accepts WoT TM/TD JSON using profile 0.2. CSV remains supported on the 1.x `main` branch. Install the current preview with `uv tool install --prerelease allow 'modpoll[serial]==2.0.0a6'`; stable 1.x remains available with `uv tool install 'modpoll<2'`. For development, run `make install`, then prefix project commands with `uv run`. +> **2.x development branch.** This checkout accepts v1 CSV and WoT TM/TD JSON using profile 0.2; `--config` detects the format from the content. Install the current preview with `uv tool install --prerelease allow 'modpoll[serial]==2.0.0a6'`; stable 1.x remains available with `uv tool install 'modpoll<2'`. For development, run `make install`, then prefix project commands with `uv run`. # Modpoll - A New Command-line Tool for Modbus and MQTT @@ -92,9 +92,12 @@ The existing transport, polling, output and MQTT arguments remain available. See the [current profile](https://github.com/top-maker/modpoll-wot/blob/main/profile.md) for field mapping, access flags, byte order, multiplier semantics and supported limits; the [execution contract](https://github.com/top-maker/modpoll-wot/blob/main/CONTRACT.md) defines the profile 0.2-only input policy. -The configuration loader rejects CSV and reports invalid model fields before -polling. Each model describes one device; use multiple `--config` paths for -multiple devices. Give each model a unique `title`, which is the output device name. +The configuration loader detects the format from the content and reports invalid +model fields before polling. Each model describes one device; use multiple +`--config` paths for multiple devices. Give each model a unique `title`, which is +the output device name. Existing v1 CSV configurations load through the same +`--config` argument; use `--thing-model`/`--tm` or +`--thing-description`/`--td` to assert the JSON document kind explicitly. Physical RS485 polling has also been verified by the maintainer with an Eastron meter (2026-10-28). See [validation](docs/validation.rst) for the evidence scope and diff --git a/contrib/README.md b/contrib/README.md index 993ef9a..0681400 100644 --- a/contrib/README.md +++ b/contrib/README.md @@ -1,11 +1,12 @@ # Contributed device references This directory retains vendor register documentation and contributed mappings. -CSV files are v1 migration sources; modpoll 2.x accepts TM/TD JSON only. Use the +CSV files are v1 migration sources; modpoll 2.x loads them again through the +same `--config` content detection, and new configurations should still be +written as profile 0.2 Thing Models. Use the [migration guide and AI prompt](../docs/site/csv-migration.rst), then validate the new file with `modpoll-wot validate MODEL --profile` and compare known device -readings. This command requires the next shared package release or the candidate -source; the published `modpoll-wot==0.2.0a1` does not include it. +readings. The maintainer confirmed successful polling of an Eastron meter over physical RS485 on 2026-10-28. This is manual hardware evidence in addition to automated diff --git a/docs/site/configure.rst b/docs/site/configure.rst index 8f0e659..53324a7 100644 --- a/docs/site/configure.rst +++ b/docs/site/configure.rst @@ -1,25 +1,38 @@ -WoT TM/TD configuration -======================= +CSV and WoT TM/TD configuration +=============================== -The 2.x development branch accepts JSON configurations using WoT TM/TD 1.1. -Use the same ``--config`` argument for either format. A top-level ``@type`` -containing ``tm:ThingModel`` (a string or an array entry) selects TM validation; -otherwise the document is validated as TD. File extensions and URL suffixes do -not select the format. An invalid document fails its selected validation; the -loader does not retry it as the other format. This preview supports the fixed -``tm:ThingModel`` spelling, without resolving alternate JSON-LD aliases. +The 2.x development branch accepts both the v1 CSV configuration format and +JSON configurations using WoT TM/TD 1.1. ``--config`` takes either format and +detects it from the content, not the file name or URL suffix: a first +non-whitespace byte of ``{`` or ``[`` selects JSON; anything else is parsed as +v1 CSV. ``--thing-model``/``--tm`` and ``--thing-description``/``--td`` assert +the JSON document kind explicitly and reject content of the other kind (or a +CSV file) with a configuration error. -It rejects CSV input. The canonical ``examples/modsim.tm.json`` uses profile -0.2 standard property Forms and explicit acquisition blocks. The generated -``examples/modsim.generated.td.json`` binds that same 37-property model to local -TCP at port 5020. Current development source accepts only profile 0.2; older -profiles must be migrated. Details are in ``packages/modpoll-wot/profile.md``. +For JSON input, a top-level ``@type`` containing ``tm:ThingModel`` (a string or +an array entry) selects TM validation; otherwise the document is validated as +TD. An invalid document fails its selected validation; the loader does not +retry it as the other format. This preview supports the fixed ``tm:ThingModel`` +spelling, without resolving alternate JSON-LD aliases. + +The v1 CSV row format (``device``, ``poll`` and ``ref`` rows) keeps its original +semantics: point names replace ASCII spaces with underscores, a blank access +column defaults to ``r``, the scale column multiplies the decoded value, and +bit-table point addresses identify eight-bit groups. ``--unit-id`` overrides +the per-device ID column; ``--param`` placeholder bindings require a Thing +Model and are rejected for CSV. The canonical ``examples/modsim.csv`` produces +the same four blocks and 37 points as ``examples/modsim.tm.json``. Current +development source accepts only profile 0.2; older profiles must be migrated. +Details are in the `modpoll-wot profile documentation +`_. Each file describes one device. Its ``title`` is the output device name; ``--unit-id`` overrides the instance Unit ID (range 1–254). Without it, each file uses the Unit ID declared consistently in its Forms, falling back to 1. Different files can therefore address different Unit IDs in one process. -Multiple files may be supplied to ``--config``; titles must be unique. +Multiple files may be supplied per flag, and the three flags may be combined; +files load in ``--config``, ``--thing-model``, ``--thing-description`` order. +Device names must be unique across all files. The existing transport CLI arguments explicitly select the connection endpoint. A concrete TD's form Unit IDs, addresses and quantities must agree with the model. @@ -53,8 +66,9 @@ Migration from CSV * Preserve effective point names from legacy ``ref`` rows: the old loader replaced spaces with underscores. Unknown types or ambiguous fields require review. -The executable contract and test vectors live under -``packages/modpoll-wot``. Strings, bit selectors, four tables and all four +The executable contract and test vectors live in the +`modpoll-wot repository `_. Strings, +bit selectors, four tables and all four byte/word orders are represented by the contract. Model inheritance, optional members, URI templates, non-Modbus forms, and security schemes other than ``nosec`` are rejected in this preview subset. The interpreter records access flags; raw MQTT write commands retain the existing @@ -68,9 +82,10 @@ fixes and :doc:`csv-migration` for the reusable AI conversion prompt. Standard Form profile 0.2 ------------------------- -The shared package ``0.2.0a1`` introduces profile ``0.2`` with standard Form +The shared ``modpoll-wot`` package provides profile ``0.2`` with standard Form mappings and explicit blocks. The application uses the exact published package -version. See -``packages/modpoll-wot/profile.md`` for API details, parameter precedence, +version. See the +`profile documentation `_ +for API details, parameter precedence, necessary extensions and external Consumer limits. The source example is ``examples/modsim.tm.json``. Generated TDs are instance artifacts. diff --git a/docs/site/csv-migration.rst b/docs/site/csv-migration.rst index 68ddff0..758d936 100644 --- a/docs/site/csv-migration.rst +++ b/docs/site/csv-migration.rst @@ -1,10 +1,16 @@ Migrating CSV configurations ============================ -v1 remains available for existing CSV users. v2 accepts TM/TD JSON and provides -an offline validator; it does not load CSV or invoke an AI service at runtime. -Convert new configurations to profile 0.2 as described in -``packages/modpoll-wot/profile.md``. Current development source rejects profile +v2 loads v1 CSV configurations again: pass them to ``--config`` as before, and +the format is detected from the content. Existing v1 commands keep working +unchanged. Migrating to profile 0.2 remains the recommended path for new or +heavily edited configurations, because a Thing Model is validated offline, +carries access and unit metadata explicitly, and is what the ModioHub catalog +publishes. v2 does not invoke an AI service at runtime. +Convert configurations to profile 0.2 as described in the +`modpoll-wot profile documentation +`_. Current +development source rejects profile 0.1; migrate its member mapping into Forms and use physical bit addresses. Check the executable profile and bundled schemas before using a conversion. @@ -32,10 +38,10 @@ Migration procedure Review the report before using the file on a device. A successful schema check alone cannot certify a vendor register map. -Commands from the development checkout (the validation command uses the -candidate shared package; version 0.2.0a1 does not provide this subcommand):: +Commands from the development checkout (the pinned ``modpoll-wot`` dependency +provides the validation subcommand):: - PYTHONPATH=packages/modpoll-wot uv run python -m modpoll_wot validate meter.tm.json --profile + uv run python -m modpoll_wot validate meter.tm.json --profile uv run modpoll --once --config meter.tm.json --tcp HOST --tcp-port PORT --export data.json uv run modpoll --config first.tm.json second.tm.json --tcp HOST @@ -112,7 +118,7 @@ Review checklist * Access corrections and rejected source mistakes are explicit in the report. * All JSON files pass the offline profile validator; independent vectors and output comparisons pass. Unknown vendor facts remain unresolved, not guessed. -* No runtime CSV fallback, AI calls or device-library dependency is introduced. +* No AI calls or device-library dependency are introduced at conversion time. The authored ``examples/modsim.tm.json`` / ``modsim.generated.td.json`` pair and the independent vectors in the tests demonstrate the process. Migrating the entire diff --git a/docs/site/index.rst b/docs/site/index.rst index 5c277e7..c8cd688 100644 --- a/docs/site/index.rst +++ b/docs/site/index.rst @@ -3,8 +3,9 @@ Welcome to Modpoll's documentation! =================================== -This is the 2.x preview documentation. Choose `1.x / CSV `_ -or `2.x / TM/TD `_. +This is the 2.x preview documentation (CSV and TM/TD configurations). Choose +`1.x `_ +or `2.x `_. .. toctree:: :maxdepth: 2 diff --git a/docs/site/usage.rst b/docs/site/usage.rst index 87f310b..c61d77c 100644 --- a/docs/site/usage.rst +++ b/docs/site/usage.rst @@ -72,7 +72,10 @@ when that happens. The value is still written as asked for. Configuration File ------------------ -The configuration file (`--config`) is a WoT TM/TD JSON file that defines the devices, pollers, and references to be read. +The configuration file (`--config`) defines the devices, pollers, and points +to be read. It can be a WoT TM/TD JSON file or a v1 CSV file; the format is +detected from the content. Use `--thing-model`/`--tm` or +`--thing-description`/`--td` to assert the JSON document kind explicitly. For register references (i.e., Holding or Input registers) with a ``dtype`` of ``bool``, you can specify a single bit to be extracted from the 16-bit register. This is done by appending ``:bit`` to the address, where ``bit`` is an integer from 0 to 15. diff --git a/docs/site/v1-compatibility.rst b/docs/site/v1-compatibility.rst index 7d0c715..fe1506d 100644 --- a/docs/site/v1-compatibility.rst +++ b/docs/site/v1-compatibility.rst @@ -1,10 +1,13 @@ v1 compatibility and M3 acceptance =================================== -The v2 change replaces CSV loading with the executable TM/TD profile. The existing -transport, decoder, output and raw write paths remain. This table compares the -pinned v1 baseline ``0b42099`` with the v2 implementation; it is not a claim that -all WoT documents or every operating system has been validated. +The v2 change adds the executable TM/TD profile alongside the retained v1 CSV +loader. ``--config`` detects the format from the content; +``--thing-model``/``--thing-description`` assert the JSON document kind. The +existing transport, decoder, output and raw write paths remain. This table +compares the pinned v1 baseline ``0b42099`` with the v2 implementation; it is +not a claim that all WoT documents or every operating system has been +validated. .. list-table:: Capability and evidence :header-rows: 1 @@ -15,9 +18,11 @@ all WoT documents or every operating system has been validated. - Evidence / limit * - Existing CLI - Existing transport, rate, interval, output and MQTT arguments retained; - ``--unit-id`` adds an explicit override. - - ``test_framer_validation.py`` and existing CLI tests. No ``--model`` or - automatic connection from TD Forms is introduced. + ``--unit-id`` adds an explicit override. v1 CSV configurations load + through the same ``--config`` argument, detected from the content. + - ``test_framer_validation.py``, ``test_csv_config.py`` and existing CLI + tests. No automatic connection from TM Forms is introduced; a concrete + TD still supplies its endpoint. * - Multiple devices/configurations - One Thing per file; split an old multi-device CSV into several JSON files. Per-file Unit IDs and unique titles are retained. @@ -97,7 +102,9 @@ all WoT documents or every operating system has been validated. Current boundaries ------------------ -CSV runtime support is intentionally removed; use :doc:`csv-migration`. Strings +CSV runtime support is retained, so v1 configurations and commands keep +working; new configurations should still prefer profile 0.2 (see +:doc:`csv-migration`). Strings and bit arrays carrying meaningless numeric scales, invalid rw modes, unknown types and incomplete payload spans require review rather than silent conversion. Profile inheritance/templates/actions and new property-based writes are separate diff --git a/docs/validation.rst b/docs/validation.rst index cd3424f..7620030 100644 --- a/docs/validation.rst +++ b/docs/validation.rst @@ -136,3 +136,18 @@ The unified local Compose example was started in an isolated project and deliver template and duplicate Compose examples were removed; ``examples/modsim.csv`` remains as the explicit migration-test fixture. See ``examples/README.md`` for the current runnable example. + + +v1 CSV compatibility restoration +-------------------------------- + +On 2026-11-12 the v1 CSV loader was restored behind content detection: +``--config`` accepts v1 CSV and WoT TM/TD JSON side by side, and the new +``--thing-model``/``--thing-description`` flags assert the JSON document kind. +``make check`` passed and the offline suite passed 210 tests with 58 +integration tests deselected, including new CSV loader, kind-assertion and +CLI error tests. Against a local modsim process, ``modpoll --once --config +examples/modsim.csv`` and ``--config examples/modsim.tm.json`` exited 0 and +exported byte-identical snapshots of all 37 points; the CSV and TM poller +structures (four blocks, start addresses, quantities, endianness) match +exactly. ``--precision`` stays in the default ``auto`` rendering mode. diff --git a/examples/README.md b/examples/README.md index 322cf44..97e4650 100644 --- a/examples/README.md +++ b/examples/README.md @@ -4,7 +4,8 @@ explicit blocks and 37 properties. - `modsim.generated.td.json`: its generated local TCP instance for the same blocks and properties. -- `modsim.csv`: v1 migration and compatibility-test input. v2 does not load it. +- `modsim.csv`: the v1 CSV configuration; v2 loads it again through the same + `--config` content detection and produces the same 37 points as the TM. From the repository root, run the self-contained TCP/MQTT demonstration: diff --git a/modpoll/arg_parser.py b/modpoll/arg_parser.py index 4a75b89..5d7e8cc 100644 --- a/modpoll/arg_parser.py +++ b/modpoll/arg_parser.py @@ -25,12 +25,37 @@ def get_parser(): parser.add_argument( "-f", "--config", - required=True, + default=[], + help=( + "Local path or URL of a v1 CSV or WoT TM/TD JSON configuration. " + "The format is detected from the content, not the filename." + ), + nargs="+", + metavar="PATH_OR_URL", + ) + parser.add_argument( + "--thing-model", + "--tm", + dest="thing_model", + default=[], + help=( + "Local path or URL of a WoT Thing Model JSON configuration " + "(tm:ThingModel); asserts the document kind instead of detecting it" + ), + nargs="+", + metavar="PATH_OR_URL", + ) + parser.add_argument( + "--thing-description", + "--td", + dest="thing_description", + default=[], help=( - "Local path or URL of a WoT TM/TD JSON configuration. " - "Type is detected from content, not the filename. Required!" + "Local path or URL of a WoT Thing Description JSON configuration; " + "asserts the document kind instead of detecting it" ), nargs="+", + metavar="PATH_OR_URL", ) parser.add_argument( "--param", diff --git a/modpoll/config_loader.py b/modpoll/config_loader.py new file mode 100644 index 0000000..7357267 --- /dev/null +++ b/modpoll/config_loader.py @@ -0,0 +1,96 @@ +"""Detect the configuration format from content and load devices. + +``--config`` accepts the v1 CSV format and WoT TM/TD JSON side by side; the +format is detected from the content, not the file name or URL suffix. A first +non-whitespace byte of ``{`` or ``[`` selects JSON; anything else is parsed as +v1 CSV. ``--thing-model`` and ``--thing-description`` assert the JSON document +kind instead of relying on detection. +""" + +import requests +from modpoll_wot import AcquisitionError, loads_model +from modpoll_wot.loading import MAX_BYTES + +from .wot_config import create_devices + + +class ConfigUsageError(ValueError): + """A command-line usage mistake: one error line and exit code 2.""" + + +def load_devices( + location, + *, + kind=None, + timeout, + unit_id=None, + host=None, + port=None, + parameters=None, + logger=None, +): + """Load one configuration and return ``(devices, model)``. + + ``model`` is the instantiated WoT model for JSON input and ``None`` for + CSV. ``kind`` is the asserted document kind: ``"tm"``, ``"td"`` or ``None`` + to accept either. + """ + payload = _read_bytes(location, timeout=timeout) + if payload.lstrip()[:1] in (b"{", b"["): + try: + model = loads_model( + payload, + source=location, + kind=kind, + unit_id=unit_id, + host=host, + port=port, + parameters=parameters, + ) + except AcquisitionError as exc: + # The message is pinned with the exact modpoll-wot version. + if kind is not None and "document kind disagrees" in str(exc): + raise ConfigUsageError(str(exc)) from exc + raise + # Enforce application policy even with an older, exactly pinned wheel. + if model.profile_version != "0.2": + raise ValueError( + "unsupported executable profile; expected modpoll:version '0.2'" + ) + return create_devices(model), model + if kind is not None: + flag = "--thing-model" if kind == "tm" else "--thing-description" + raise ConfigUsageError( + f"{location}: {flag} expects a TM/TD JSON document, " + "but the content is not JSON" + ) + if parameters is not None: + raise ConfigUsageError( + f"{location}: --param requires a Thing Model; " + "CSV configurations have no placeholders" + ) + from .csv_config import parse_csv + + devices = parse_csv( + payload.decode("utf-8"), source=location, unit_id=unit_id, logger=logger + ) + return devices, None + + +def _read_bytes(location, *, timeout): + """Read a local path or URL with the shared 1 MiB configuration bound.""" + if location.startswith(("http://", "https://")): + with requests.get(location, timeout=timeout, stream=True) as response: + response.raise_for_status() + chunks, size = [], 0 + for chunk in response.iter_content(65536): + size += len(chunk) + if size > MAX_BYTES: + raise ValueError(f"{location}: configuration exceeds 1 MiB") + chunks.append(chunk) + return b"".join(chunks) + with open(location, "rb") as stream: + payload = stream.read(MAX_BYTES + 1) + if len(payload) > MAX_BYTES: + raise ValueError(f"{location}: configuration exceeds 1 MiB") + return payload diff --git a/modpoll/csv_config.py b/modpoll/csv_config.py new file mode 100644 index 0000000..91a4742 --- /dev/null +++ b/modpoll/csv_config.py @@ -0,0 +1,243 @@ +"""Load v1 CSV configurations into the shared polling engine. + +The v1 ``device``/``poll``/``ref`` row format is accepted again: ``--config`` +detects CSV versus WoT TM/TD JSON from the file content, and this module turns +CSV rows into the same Device, Poller and Point objects the WoT loader +produces, so both formats share one polling, output and export path. + +Row semantics follow v1: point names replace ASCII spaces with underscores, a +blank access column defaults to ``r``, and the scale column multiplies the +decoded value. Bit-table point addresses identify eight-bit groups, as the +documented v1 examples always did. +""" + +import csv +import io +import logging +import math + +DEVICE_COL_MIN = 3 +POLL_COL_MIN = 5 +REF_COL_MIN = 5 + +_FUNCTION_CODES = { + "coil": 1, + "discrete_input": 2, + "holding_register": 3, + "input_register": 4, +} + +_ENDIAN_VALUES = {"BE_BE", "BE_LE", "LE_BE", "LE_LE"} + + +def parse_csv(text, *, source, unit_id=None, logger=None): + """Parse v1 CSV rows into a device list. + + ``unit_id`` overrides the per-device ID column when given. Duplicate + device names abort the load; every other bad row is reported and skipped, + matching the v1 loader. + """ + from .modbus_task import Device, Point, Poller + + logger = logger or logging.getLogger(__name__) + device_list = [] + current_device = None + current_poller = None + duplicate_devices = [] + reader = csv.reader(io.StringIO(text)) + for line_number, row in enumerate(reader, start=1): + if not row or all(cell.strip() == "" for cell in row): + continue + try: + if "device" in row[0].lower(): + current_device, current_poller = None, None + if len(row) < DEVICE_COL_MIN: + logger.error( + "Config line %s: invalid device configuration", line_number + ) + continue + device_name = row[1].strip() + if any(device.name == device_name for device in device_list): + logger.error( + "Config line %s: duplicate device name %s", + line_number, + device_name, + ) + duplicate_devices.append((line_number, device_name)) + continue + try: + device_id = int(row[2], 0) + except ValueError: + logger.error( + "Config line %s: invalid device ID for %s", + line_number, + device_name, + ) + continue + if not 1 <= device_id <= 254: + logger.error( + "Config line %s: device ID out of range for %s", + line_number, + device_name, + ) + continue + current_device = Device(device_name, device_id) + device_list.append(current_device) + elif "poll" in row[0].lower(): + if not current_device: + logger.error("Config line %s: no device to add poller", line_number) + current_poller = None + continue + current_poller = _create_poller(row, current_device, logger) + if current_poller: + current_device.pollerList.append(current_poller) + else: + logger.error("Config line %s: poller ignored", line_number) + elif "ref" in row[0].lower(): + if not current_device or not current_poller: + logger.error( + "Config line %s: reference has no valid device/poller", + line_number, + ) + continue + point = _create_point(row, current_device, logger) + if point is None: + logger.error("Config line %s: reference ignored", line_number) + continue + if point.name in current_device.points: + logger.error( + "Config line %s: duplicate reference name %s", + line_number, + point.name, + ) + continue + if _validate_point(point, current_poller, logger): + if "r" in point.rw.lower(): + current_poller.add_readable_point(point) + current_device.add_point_mapping(point) + else: + logger.error( + "Config line %s: reference failed validation", line_number + ) + else: + logger.warning("Config line %s: unknown row type %r", line_number, row[0]) + except Exception as exc: + logger.error("Config line %s: invalid row %r: %s", line_number, row, exc) + if duplicate_devices: + details = ", ".join( + "%s (line %s)" % (name, line) for line, name in duplicate_devices + ) + from .config_loader import ConfigUsageError + + raise ConfigUsageError(f"Duplicate device names in {source}: {details}") + if unit_id is not None: + for device in device_list: + device.devid = unit_id + return device_list + + +def _create_poller(row, device, logger): + if len(row) < POLL_COL_MIN: + logger.error("Invalid poller configuration") + return None + function_code = _FUNCTION_CODES.get(row[1].lower()) + if function_code is None: + logger.warning("Unknown function code (%s) ignoring poller.", row[1]) + return None + try: + start_address = int(row[2], 0) + size = int(row[3], 0) + except ValueError: + logger.error("Invalid start address or size for poller") + return None + endian = row[4].upper() + if endian not in _ENDIAN_VALUES: + logger.error("Invalid endian setting: %s", endian) + return None + if not 0 <= start_address <= 65535: + logger.error("Invalid poller start address: %s", start_address) + return None + if not _validate_poller_size(function_code, size, logger): + return None + if start_address + size > 65536: + logger.error("Poller address range exceeds Modbus address space") + return None + from .modbus_task import Poller + + return Poller(device, function_code, start_address, size, endian) + + +def _validate_poller_size(function_code, size, logger): + if size <= 0: + logger.error("Poller size must be positive: %s", size) + return False + if function_code in (1, 2) and size > 2000: + logger.error( + f"Too many coils/discrete inputs (max. 2000): {size}. Ignoring poller." + ) + return False + if function_code in (3, 4) and size > 125: + logger.error(f"Too many registers (max. 125): {size}. Ignoring poller.") + return False + return True + + +def _create_point(row, device, logger): + if len(row) < REF_COL_MIN: + logger.error("Invalid reference configuration") + return None + ref_name = row[1].replace(" ", "_") + address = row[2] + dtype = row[3].lower() + rw = (row[4] or "r").lower() + if rw not in {"r", "w", "rw"}: + logger.error("Invalid read/write mode for reference %s", ref_name) + return None + unit = row[5] if len(row) > 5 and row[5] else None + try: + scale = float(row[6]) if len(row) > 6 and row[6] else None + if scale is not None and not math.isfinite(scale): + raise ValueError("scale must be finite") + except ValueError: + logger.error("Invalid scale for reference %s", ref_name) + return None + from .modbus_task import Point + + try: + return Point(device, ref_name, address, dtype, rw, unit, scale) + except ValueError as exc: + # Covers address format, bit selectors on non-bool types and + # unsupported dtypes from the shared width table. + logger.error("Invalid reference %s: %s", ref_name, exc) + return None + + +def _validate_point(point, poller, logger): + if poller.fc in (1, 2): + if point.bit is not None: + logger.warning( + "Bit selectors require a register poller: %s", point.name + ) + return False + group_count = math.ceil(poller.size / 8) + if not ( + poller.start_address + <= point.address + and point.address + point.bit_group_width - 1 + < poller.start_address + group_count + ): + logger.warning( + f"Reference {point.name} failed to pass sanity check, ignoring it." + ) + return False + return True + if not ( + poller.start_address + <= point.address + and point.address + point.point_width - 1 < poller.start_address + poller.size + ): + logger.warning( + f"Reference {point.name} failed to pass sanity check, ignoring it." + ) + return False + return True diff --git a/modpoll/main.py b/modpoll/main.py index 0963ab0..3dcb19f 100644 --- a/modpoll/main.py +++ b/modpoll/main.py @@ -146,7 +146,10 @@ def app(name="modpoll"): signal.signal(signal.SIGTERM, _signal_handler) # parse args - args = get_parser().parse_args() + parser = get_parser() + args = parser.parse_args() + if not (args.config or args.thing_model or args.thing_description): + parser.error("one of --config/--thing-model/--thing-description is required") print( f"\nModpoll v{__version__} - A New Command-line Tool for Modbus and MQTT\n", diff --git a/modpoll/modbus_task.py b/modpoll/modbus_task.py index 9ff02f5..2ddadcf 100644 --- a/modpoll/modbus_task.py +++ b/modpoll/modbus_task.py @@ -523,9 +523,11 @@ def __init__( instance_port: Optional[int] = None, instance_parameters=None, precision: Optional[int] = None, + config_kind: Optional[str] = None, ): self.modbus_client = modbus_client self.config_file = config_file + self.config_kind = config_kind self.unit_id = unit_id self.instance_host = instance_host self.instance_port = instance_port @@ -550,22 +552,27 @@ def __init__( ) def load_config(self) -> bool: - from .wot_config import create_devices, read_model + from .config_loader import ConfigUsageError, load_devices - self.logger.info(f"Loading WoT config from: {self.config_file}") + self.logger.info(f"Loading config from: {self.config_file}") try: - model = read_model( + self.deviceList, self.model = load_devices( self.config_file, + kind=self.config_kind, timeout=self.timeout, unit_id=self.unit_id, host=self.instance_host, port=self.instance_port, parameters=self.instance_parameters, + logger=self.logger, ) - self.deviceList = create_devices(model) - self.model = model + except ConfigUsageError: + raise except (ValueError, OSError, requests.RequestException) as exc: - self.logger.error("Invalid WoT configuration: %s", exc) + self.logger.error("Invalid configuration: %s", exc) + return False + if not self.deviceList: + self.logger.error("No device found in the config file. Skipping.") return False self.logger.info("Added %d device(s)", len(self.deviceList)) return True @@ -848,7 +855,12 @@ def setup_modbus_handlers(args, mqtt_handler: Optional[MqttHandler] = None): raise ValueError("TM parameters require the profile 0.2 interpreter") parameters = modpoll_wot.parse_parameters(args.param) try: - for config_file in args.config: + config_specs = ( + [(location, None) for location in args.config] + + [(location, "tm") for location in args.thing_model] + + [(location, "td") for location in args.thing_description] + ) + for config_file, config_kind in config_specs: current_handler = ModbusHandler( None, config_file, @@ -865,6 +877,7 @@ def setup_modbus_handlers(args, mqtt_handler: Optional[MqttHandler] = None): instance_port=args.tcp_port, instance_parameters=parameters, precision=parse_precision(getattr(args, "precision", None)), + config_kind=config_kind, ) if current_handler.load_config(): effective_args = copy.copy(args) diff --git a/tests/test_cli_errors.py b/tests/test_cli_errors.py index db1c549..6cca350 100644 --- a/tests/test_cli_errors.py +++ b/tests/test_cli_errors.py @@ -31,3 +31,58 @@ def test_configuration_errors_exit_2_without_a_traceback(args, message): assert result.returncode == 2 assert message in result.stderr + result.stdout assert "Traceback" not in result.stderr + result.stdout + + +def test_missing_configuration_exits_2(): + result = run("--once") + assert result.returncode == 2 + assert "one of --config/--thing-model/--thing-description is required" in ( + result.stderr + result.stdout + ) + assert "Traceback" not in result.stderr + result.stdout + + +@pytest.mark.parametrize( + "flag, config, extra", + [ + ("--tm", "examples/modsim.tm.json", []), + ("--thing-model", "examples/modsim.tm.json", []), + # A bound TD supplies its own TCP endpoint, so --udp exercises the + # unbound-TM guard instead of opening a connection. + ("--td", "examples/modsim.generated.td.json", ["--udp", "127.0.0.1"]), + ( + "--thing-description", + "examples/modsim.generated.td.json", + ["--udp", "127.0.0.1"], + ), + ], +) +def test_thing_model_and_description_flags_accept_json(flag, config, extra): + result = run(flag, config, "--once", *extra) + output = result.stderr + result.stdout + assert result.returncode == 2 + assert ( + "No communication method specified" in output or "unbound TM" in output + ), output + + +def test_thing_model_flag_rejects_csv_content(): + result = run("--tm", "examples/modsim.csv", "--tcp", "127.0.0.1", "--once") + assert result.returncode == 2 + assert "expects a TM/TD JSON document" in result.stderr + result.stdout + assert "Traceback" not in result.stderr + result.stdout + + +def test_csv_rejects_typed_parameters(): + result = run( + "--config", + "examples/modsim.csv", + "--param", + "GAIN=2", + "--tcp", + "127.0.0.1", + "--once", + ) + assert result.returncode == 2 + assert "--param requires a Thing Model" in result.stderr + result.stdout + assert "Traceback" not in result.stderr + result.stdout diff --git a/tests/test_csv_config.py b/tests/test_csv_config.py new file mode 100644 index 0000000..6bd5ad6 --- /dev/null +++ b/tests/test_csv_config.py @@ -0,0 +1,125 @@ +"""v1 CSV configuration loading and content-based format detection.""" + +from pathlib import Path + +import pytest + +from modpoll.config_loader import load_devices +from modpoll.csv_config import parse_csv + +ROOT = Path(__file__).resolve().parents[1] +MODSIM_CSV = ROOT / "examples/modsim.csv" +MODSIM_TM = ROOT / "examples/modsim.tm.json" +MODSIM_TD = ROOT / "examples/modsim.generated.td.json" + + +def test_modsim_csv_loads_with_v1_row_semantics(): + (device,), model = load_devices(str(MODSIM_CSV), timeout=1) + assert model is None + assert device.name == "modsim01" + assert device.devid == 1 + assert [(p.fc, p.start_address, p.size, p.endian) for p in device.pollerList] == [ + (1, 0, 16, "be_be"), + (2, 10000, 16, "be_be"), + (4, 30000, 20, "be_be"), + (3, 40000, 44, "be_be"), + ] + assert len(device.points) == 37 + scaled = device.points["input_reg10"] + assert scaled.address == 30010 + assert scaled.dtype == "uint32" + assert float(scaled.scale) == 0.001 + assert device.points["holding_reg19"].dtype == "string16" + assert device.points["coil01-08"].dtype == "bool8" + + +def test_csv_matches_tm_polling_structure(): + (csv_device,), _ = load_devices(str(MODSIM_CSV), timeout=1) + (tm_device,), _ = load_devices(str(MODSIM_TM), timeout=1) + csv_pollers = [ + (p.fc, p.start_address, p.size, p.endian) for p in csv_device.pollerList + ] + tm_pollers = [ + (p.fc, p.start_address, p.size, p.endian) for p in tm_device.pollerList + ] + assert csv_pollers == tm_pollers + assert set(csv_device.points) == set(tm_device.points) + for name, point in csv_device.points.items(): + tm_point = tm_device.points[name] + if tm_point.dtype == "bool" and name.startswith(("coil", "di")): + # Bit tables: v1 CSV names eight-bit groups, the TM names bits. + base = 0 if name.startswith("coil") else 10000 + assert (point.address - base) * 8 == tm_point.address - base + assert point.dtype == "bool8" + else: + assert (point.address, point.dtype) == (tm_point.address, tm_point.dtype) + assert point.unit == tm_point.unit + + +def test_point_names_replace_spaces_and_blank_access_defaults_to_read(): + text = "device,meter,1\npoll,holding_register,0,4,BE_BE\nref,my point,0,uint16,\n" + (device,) = parse_csv(text, source="") + assert "my_point" in device.points + assert device.points["my_point"].rw == "r" + assert device.points["my_point"] in device.pollerList[0].readablePoints + + +def test_csv_unit_id_override(): + (device,), _ = load_devices(str(MODSIM_CSV), timeout=1, unit_id=7) + assert device.devid == 7 + + +def test_duplicate_device_names_abort_the_load(): + text = "device,meter,1\ndevice,meter,2\n" + with pytest.raises(ValueError, match="Duplicate device names"): + parse_csv(text, source="") + + +def test_invalid_rows_are_reported_and_skipped(caplog): + text = "\n".join( + [ + "device,meter,1", + "poll,holding_register,0,2,BE_BE", + "ref,good,0,uint16,r", + "ref,bad-dtype,1,fancy16,r", + "poll,coil,0,8,BE_BE", + "ref,bit-on-coil,0:1,bool,r", + "ref,out-of-range,99,uint16,r", + "nonsense,row", + "", + ] + ) + with caplog.at_level("WARNING"): + (device,) = parse_csv(text, source="") + assert set(device.points) == {"good"} + assert "unsupported data type" in caplog.text + assert "Bit selectors require a register poller" in caplog.text + assert "unknown row type" in caplog.text + + +def test_format_is_detected_from_content_not_filename(tmp_path): + csv_named_json = tmp_path / "model.tm.json" + csv_named_json.write_text("device,meter,1\n") + devices, model = load_devices(str(csv_named_json), timeout=1) + assert model is None and devices[0].name == "meter" + + json_named_csv = tmp_path / "legacy.csv" + json_named_csv.write_text(MODSIM_TM.read_text()) + (_,), model = load_devices(str(json_named_csv), timeout=1) + assert model is not None + + +def test_thing_model_and_description_assert_the_document_kind(): + with pytest.raises(ValueError, match="document kind disagrees"): + load_devices(str(MODSIM_TD), kind="tm", timeout=1) + with pytest.raises(ValueError, match="document kind disagrees"): + load_devices(str(MODSIM_TM), kind="td", timeout=1) + with pytest.raises(ValueError, match="expects a TM/TD JSON document"): + load_devices(str(MODSIM_CSV), kind="tm", timeout=1) + (_,), model = load_devices(str(MODSIM_TM), kind="tm", timeout=1) + assert model is not None + + +def test_csv_rejects_typed_parameters(): + with pytest.raises(ValueError, match="--param requires a Thing Model"): + load_devices(str(MODSIM_CSV), timeout=1, parameters={"gain": 2}) diff --git a/tests/test_wot_config.py b/tests/test_wot_config.py index 27b94e4..045266d 100644 --- a/tests/test_wot_config.py +++ b/tests/test_wot_config.py @@ -10,15 +10,32 @@ from tests.wot_helpers import meter_model, write_meter -def test_csv_content_is_rejected_without_partial_device(tmp_path, caplog): +def test_csv_content_loads_as_v1_configuration(tmp_path): path = tmp_path / "old.csv" path.write_text( "device,meter,1\npoll,holding_register,0,1,BE_BE\nref,x,0,uint16,r\n" ) handler = ModbusHandler(object(), str(path)) - assert not handler.load_config() + assert handler.load_config() + assert [device.name for device in handler.deviceList] == ["meter"] + assert handler.model is None + + +def test_thing_model_flag_rejects_wrong_document_kind(tmp_path): + path = tmp_path / "model.td.json" + path.write_text( + json.dumps( + { + "@context": ["https://www.w3.org/2022/wot/td/v1.1"], + "@type": "tm:ThingDescription", + "title": "meter", + } + ) + ) + handler = ModbusHandler(object(), str(path), config_kind="tm") + with pytest.raises(ValueError, match="document kind disagrees"): + handler.load_config() assert handler.deviceList == [] - assert "Invalid WoT configuration" in caplog.text def test_url_model_loader_keeps_timeout_and_streams(monkeypatch):