diff --git a/README.md b/README.md index 6090f68..6776b36 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,29 @@ meter (2026-10-28). See [validation](docs/validation.rst) for the evidence scope For a complete local simulator/MQTT demonstration, use the repository's [Docker Compose example](examples/README.md). +### Read a catalog product and write a verification report + +`--device /[@]` reads the baseline Thing Model of a product in the +[Open Modbus Catalog](https://github.com/top-maker/open-modbus-catalog) instead of a file. A branch or tag +(default `main`) is resolved to its commit, and the download is checked against the Git object id GitHub +reports for it. `--full-read` reads every point once: read-only, without retries and with a timeout of at +most 10 seconds, so a lost request is a result and not something to repeat. `--report FILE` also writes the +verification report (`-` prints it): + +```sh +modpoll --device advantech/adam-5017uh --tcp 192.168.1.20 --unit-id 3 --report report.json +``` + +The report records, per point, whether the read worked (`ok`, a Modbus `exception` with its code, +`no-response`, or `not-tested` when the answer could not be decoded) and your judgment of the value: +`--confirm POINT...` (or `all`) and `--reject POINT...` for values you compared with the device, otherwise +`unchecked`. `--chassis`, `--firmware` and `--configuration` add context. The report holds no address, Unit +ID, serial number or value; review it before sharing. It is checked with +[modpoll-wot](https://github.com/top-maker/modpoll-wot) (`modpoll-wot validate-report report.json --model +model.tm.json`), and `--export` still writes the snapshot of the same read. With `-f` for a local Thing +Model, add `--product /`; the report then names the model as local. The exit +code is 1 unless every point was read. + ### MQTT data and write behavior The local example above uses the `adam6024_raw` TD title for its default topics: diff --git a/modpoll/arg_parser.py b/modpoll/arg_parser.py index 4a75b89..21a0dad 100644 --- a/modpoll/arg_parser.py +++ b/modpoll/arg_parser.py @@ -25,12 +25,70 @@ def get_parser(): parser.add_argument( "-f", "--config", - required=True, + default=None, help=( "Local path or URL of a WoT TM/TD JSON configuration. " - "Type is detected from content, not the filename. Required!" + "Type is detected from content, not the filename. " + "Required unless --device is given." + ), + nargs="+", + ) + parser.add_argument( + "--device", + metavar="MANUFACTURER/MODEL[@COMMIT]", + help=( + "Read the baseline Thing Model of a product in the Open Modbus Catalog, " + "for example advantech/adam-5017uh, at a commit, tag or branch " + "(default: main). Use instead of -f." + ), + ) + parser.add_argument( + "--full-read", + action="store_true", + help=( + "Read every point of the model once, read-only and without retries, " + "and report which points could be read. Implies --once." + ), + ) + parser.add_argument( + "--report", + metavar="FILE", + help=( + "Write the verification report of a full read to FILE ('-' prints it). " + "It lists each point's result and carries no address, Unit ID, serial " + "number or value; review it before sharing. Implies --full-read." ), + ) + parser.add_argument( + "--product", + metavar="MANUFACTURER/MODEL", + help="Catalog product ID the report is for; needed with -f, taken from --device otherwise", + ) + parser.add_argument( + "--chassis", + metavar="MANUFACTURER/MODEL", + help="Chassis product ID, for the report", + ) + parser.add_argument( + "--firmware", help="Firmware version of the device, for the report" + ) + parser.add_argument( + "--configuration", + help="Short note on the device configuration, such as an input range, for the report", + ) + parser.add_argument( + "--confirm", nargs="+", + default=[], + metavar="POINT", + help="Points whose values you checked and found right ('all' for every point), for the report", + ) + parser.add_argument( + "--reject", + nargs="+", + default=[], + metavar="POINT", + help="Points whose values you checked and found wrong, for the report", ) parser.add_argument( "--param", diff --git a/modpoll/main.py b/modpoll/main.py index 0963ab0..3794408 100644 --- a/modpoll/main.py +++ b/modpoll/main.py @@ -14,7 +14,7 @@ snapshot_timestamp_conflicts, ) -from . import __version__ +from . import __version__, verification from .utils import set_threading_event, delay_thread, on_threading_event, get_utc_time @@ -128,6 +128,26 @@ def process_mqtt_command(topic, payload, retained, topic_pattern, handlers): return success +def _finish_full_read(args, handler): + """Summarize the full read and write its report; the result is whether every point was read.""" + try: + report = verification.build_report(handler, args) + if args.report: + verification.write_report(report, args.report) + except (ValueError, OSError, AcquisitionError) as exc: + logger.error("%s", exc) + logger.debug("Report error details", exc_info=True) + return False + print(f"\n{verification.summary(report)}", flush=True) + if args.report and args.report != "-": + print( + f"Report written to {args.report}. It has no addresses, Unit IDs, serial " + "numbers or values; review it before sharing.", + flush=True, + ) + return verification.is_full_read(report) + + def _signal_handler(signal_number, frame): if logger: logger.info(f"Exiting {sys.argv[0]}") @@ -158,6 +178,12 @@ def app(name="modpoll"): global logger logger = logging.getLogger(__name__) + try: + verification.validate_args(args) + except ValueError as exc: + logger.error("%s", exc) + sys.exit(2) + # setup mqtt if not args.mqtt_host: logger.info("No MQTT host specified, skip MQTT setup.") @@ -205,6 +231,7 @@ def app(name="modpoll"): try: # setup modbus tasks try: + verification.resolve_models(args) modbus_handlers = setup_modbus_handlers(args, mqtt_handler) except (ValueError, AcquisitionError) as exc: # A mistake in the command line or model is reported, not a stack. @@ -267,6 +294,10 @@ def app(name="modpoll"): timestamp=now if args.timestamp else None, ) cycle_success = export_success and cycle_success + if args.full_read and not on_threading_event(): + cycle_success = ( + _finish_full_read(args, modbus_handlers[0]) and cycle_success + ) if args.diagnostics_rate > 0 and ( last_diag is None or monotonic_now >= last_diag + args.diagnostics_rate ): diff --git a/modpoll/modbus_task.py b/modpoll/modbus_task.py index 9ff02f5..ab4a713 100644 --- a/modpoll/modbus_task.py +++ b/modpoll/modbus_task.py @@ -7,7 +7,7 @@ import tempfile from decimal import Decimal from pathlib import Path -from typing import List, Optional +from typing import List, Optional, Tuple import requests from prettytable import PrettyTable @@ -204,9 +204,12 @@ def __init__( self.readablePoints: List[Point] = [] self.disabled = False self.failcounter = 0 + # Why the last read of this group failed: ("exception", code) or ("no-response", None). + self.failure: Optional[Tuple[str, Optional[int]]] = None self.logger = logging.getLogger(__name__) def poll(self, master) -> bool: + self.failure = None try: result = None data = None @@ -336,10 +339,13 @@ def _call_read(method): self.update_statistics(decode_success) return decode_success except ModbusException: + self.failure = ("no-response", None) self.logger.error( f"Modbus exception: {self.device.name} {self.fc} {self.start_address} {self.size}" ) + if self.failure is None: + self.failure = _read_failure(result) self.update_statistics(False) for point in self.readablePoints: point.update_value(None) @@ -414,6 +420,14 @@ def update_statistics(self, success: bool): self.device.pollSuccess = False +def _read_failure(result): + """Classify a failed read: the device answered with an exception code, or did not answer.""" + code = getattr(result, "exception_code", None) + if isinstance(code, int) and 1 <= code <= 255: + return ("exception", code) + return ("no-response", None) + + def _multiplier(scale): """The float the engine computes with, and the exact decimal of it. @@ -523,6 +537,7 @@ def __init__( instance_port: Optional[int] = None, instance_parameters=None, precision: Optional[int] = None, + model_bytes: Optional[bytes] = None, ): self.modbus_client = modbus_client self.config_file = config_file @@ -530,6 +545,8 @@ def __init__( self.instance_host = instance_host self.instance_port = instance_port self.instance_parameters = instance_parameters + # The exact bytes of the model; given by the caller or read from the configuration location. + self.model_bytes = model_bytes self.model = None self.mqtt_handler = mqtt_handler self.timeout = timeout @@ -550,13 +567,16 @@ def __init__( ) def load_config(self) -> bool: - from .wot_config import create_devices, read_model + from .wot_config import create_devices, read_model, read_payload self.logger.info(f"Loading WoT config from: {self.config_file}") try: + if self.model_bytes is None: + self.model_bytes = read_payload(self.config_file, timeout=self.timeout) model = read_model( self.config_file, timeout=self.timeout, + payload=self.model_bytes, unit_id=self.unit_id, host=self.instance_host, port=self.instance_port, @@ -837,6 +857,8 @@ def get_device_list(self) -> List[Device]: def setup_modbus_handlers(args, mqtt_handler: Optional[MqttHandler] = None): + # ``args.model_payloads`` maps a configuration name to model bytes already in hand (--device). + models = getattr(args, "model_payloads", None) or {} modbus_handlers = [] current_handler = None device_names = set() @@ -865,6 +887,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)), + model_bytes=models.get(config_file), ) if current_handler.load_config(): effective_args = copy.copy(args) @@ -906,6 +929,11 @@ def _valid_write_address(address) -> bool: return type(address) is int and 0 <= address <= 65535 +def _read_options(args): + """A full read asks each group once: a lost request is a result, not something to repeat.""" + return {"retries": 0} if getattr(args, "full_read", False) else {} + + def _create_modbus_client(args): transport = _determine_transport(args) @@ -935,6 +963,7 @@ def _create_serial_client(args, port, framer): "parity": parity, "stopbits": 1, "timeout": args.timeout, + **_read_options(args), } if framer: client_args["framer"] = framer @@ -946,6 +975,7 @@ def _create_tcp_client(args, framer): "host": args.tcp, "port": 502 if args.tcp_port is None else args.tcp_port, "timeout": args.timeout, + **_read_options(args), } if framer: client_args["framer"] = framer diff --git a/modpoll/verification.py b/modpoll/verification.py new file mode 100644 index 0000000..15a029a --- /dev/null +++ b/modpoll/verification.py @@ -0,0 +1,274 @@ +"""Full read of a Thing Model on a real device and its verification report (POLL-02a). + +A full read executes the whole ``modpoll:acquisition`` plan once: read-only, no retries and a bounded timeout. The +result per point is recorded in a verification report whose format and validation belong to modpoll-wot. The report +holds no address, Unit ID, serial number or value; the user reviews it before anything leaves the machine. +""" + +import base64 +import hashlib +import json +import os +import re +import tempfile +from datetime import datetime, timezone +from importlib.metadata import version as package_version +from pathlib import Path + +import modpoll_wot +import requests + +from . import __version__ + +CATALOG_API = "https://api.github.com/repos/top-maker/open-modbus-catalog" +MAX_TIMEOUT = 10.0 +_SLUG = r"[a-z0-9]+(?:-[a-z0-9]+)*" +_DEVICE = re.compile(rf"^({_SLUG}/{_SLUG})(?:@([A-Za-z0-9][A-Za-z0-9._/-]{{0,99}}))?$") +_COMMIT = re.compile(r"^[0-9a-f]{40}$") + + +def parse_device(text): + """``manufacturer/model-number[@ref]`` as (product ID, ref); the ref is a commit, tag or branch.""" + match = _DEVICE.match(text) + if not match: + raise ValueError( + "--device must be /, optionally followed by @" + ) + return match.group(1), match.group(2) or "main" + + +def validate_args(args): + """Reject option combinations a full read cannot honour, before anything is connected.""" + args.full_read = args.full_read or bool(args.report) + if args.device and args.config: + raise ValueError("Use either --device or -f, not both") + if not args.device and not args.config: + raise ValueError("One of -f or --device is required") + if args.device: + parse_device(args.device) + if not args.full_read: + for option in ("confirm", "reject", "chassis", "firmware", "configuration"): + if getattr(args, option): + raise ValueError(f"--{option} needs --full-read or --report") + return + if args.mqtt_host: + raise ValueError("A full read does not publish to MQTT") + if args.udp: + raise ValueError("A full read supports Modbus TCP and RTU, not UDP") + if args.serial and args.framer == "ascii": + raise ValueError("A full read supports Modbus RTU, not Modbus ASCII") + if args.device is None and args.config and len(args.config) != 1: + raise ValueError("A full read reads one Thing Model") + if args.report and not (args.device or args.product): + raise ValueError( + "--report with -f needs --product /" + ) + if args.product and not _DEVICE.match(args.product): + raise ValueError("--product must be /") + if args.timeout > MAX_TIMEOUT: + raise ValueError(f"--timeout is at most {MAX_TIMEOUT:g} seconds in a full read") + if args.chassis and not _DEVICE.match(args.chassis): + raise ValueError("--chassis must be /") + args.once = True + args.daemon = False + + +def git_blob_sha1(payload): + """The id Git gives a file, so a download can be checked against the catalog repository.""" + return hashlib.sha1(b"blob %d\0" % len(payload) + payload).hexdigest() + + +def _github(path, *, timeout, **kwargs): + headers = {"User-Agent": f"modpoll/{__version__}", **kwargs.pop("headers", {})} + try: + response = requests.get( + f"{CATALOG_API}/{path}", headers=headers, timeout=timeout, **kwargs + ) + except requests.RequestException as exc: + raise ValueError(f"Could not reach the catalog on GitHub: {exc}") from exc + return response + + +def fetch_catalog_model(product, ref, *, timeout): + """The baseline Thing Model of a catalog product at a commit: (bytes, 40-character commit). + + A branch or tag is resolved to its commit first, so a report names the exact version that was read. The file + is checked against the Git blob id GitHub reports for it. + """ + commit = ref + if not _COMMIT.match(ref): + response = _github( + f"commits/{requests.utils.quote(ref, safe='')}", + timeout=timeout, + headers={"Accept": "application/vnd.github.sha"}, + ) + if response.status_code in (404, 422): + raise ValueError(f"The catalog has no commit, tag or branch {ref}") + _check_github(response) + commit = response.text.strip() + if not _COMMIT.match(commit): + raise ValueError("GitHub answered with an unexpected commit id") + response = _github( + f"contents/products/{product}/model.tm.json", + timeout=timeout, + params={"ref": commit}, + ) + if response.status_code == 404: + raise ValueError( + f"The catalog has no Thing Model for {product} at {commit[:7]}" + ) + _check_github(response) + entry = response.json() + if entry.get("encoding") != "base64" or "content" not in entry: + raise ValueError( + f"The catalog's Thing Model for {product} is too large to fetch" + ) + payload = base64.b64decode(entry["content"]) + if git_blob_sha1(payload) != entry.get("sha"): + raise ValueError( + f"The Thing Model for {product} does not match its Git object id" + ) + return payload, commit + + +def _check_github(response): + if ( + response.status_code == 403 + and response.headers.get("X-RateLimit-Remaining") == "0" + ): + raise ValueError( + "GitHub's anonymous request limit is used up; retry in an hour or use -f" + ) + if not response.ok: + raise ValueError(f"GitHub answered {response.status_code}") + + +def resolve_models(args): + """For ``--device``, fetch the model and name it as the configuration. + + The bytes go to ``args.model_payloads`` for the handler, and where they came from to ``args.model_source`` + for the report. + """ + if not args.device: + return + product, ref = parse_device(args.device) + payload, commit = fetch_catalog_model(product, ref, timeout=args.timeout) + label = f"{product}@{commit[:7]}" + args.config = [label] + args.product = product + args.model_payloads = {label: payload} + args.model_source = {"source": "catalog", "ref": commit} + + +def _transport(args): + return "rtu" if args.serial else "tcp" + + +def _points(handler): + """(property, poller or None) for every readable property of the model, in model order.""" + pollers = {} + for device in handler.get_device_list(): + for poller in device.pollerList: + for point in poller.readablePoints: + pollers[point.name] = poller + return pollers + + +def build_report(handler, args): + """The verification report of the read that just ran, checked against the model by modpoll-wot.""" + payload = handler.model_bytes + fingerprints = modpoll_wot.point_fingerprints(payload) + pollers = _points(handler) + points_by_name = { + point.name: point + for device in handler.get_device_list() + for point in device.points.values() + } + judged = ( + {name: "confirmed" for name in fingerprints} if "all" in args.confirm else {} + ) + judged.update({name: "confirmed" for name in args.confirm if name != "all"}) + judged.update({name: "rejected" for name in args.reject}) + unknown = sorted(set(judged) - set(fingerprints)) + if unknown: + raise ValueError(f"No readable point named {', '.join(unknown)}") + points = [] + for name, fingerprint in fingerprints.items(): + poller = pollers.get(name) + point = {"property": name, "fingerprint": fingerprint} + if poller is None: + point["read"] = "not-tested" + elif poller.failure is not None: + point["read"], code = poller.failure + if code is not None: + point["exceptionCode"] = code + elif points_by_name[name].valid_this_poll: + point["read"] = "ok" + else: + # The device answered but the answer could not be decoded as this point. + point["read"] = "not-tested" + read_ok = point["read"] == "ok" + if name in judged and not read_ok: + raise ValueError( + f"Point {name} was not read successfully, so it cannot be confirmed or rejected" + ) + point["expected"] = judged.get(name, "unchecked") if read_ok else "unchecked" + points.append(point) + environment = { + key: value + for key, value in ( + ("chassis", args.chassis), + ("firmware", args.firmware), + ("configuration", args.configuration), + ) + if value + } + report = { + "reportVersion": 3, + "product": args.product, + "model": { + "sha256": hashlib.sha256(payload).hexdigest(), + "fingerprint": modpoll_wot.model_fingerprint(payload), + **(getattr(args, "model_source", None) or {"source": "local"}), + }, + "tool": { + "name": "modpoll", + "version": __version__, + "interpreter": package_version("modpoll-wot"), + }, + "transport": _transport(args), + "date": datetime.now(timezone.utc).date().isoformat(), + **({"environment": environment} if environment else {}), + "points": points, + } + modpoll_wot.validate_report(report, model=payload) + return report + + +def is_full_read(report): + """Every point read successfully; the receiving service decides coverage again from the model.""" + return all(point["read"] == "ok" for point in report["points"]) + + +def write_report(report, target): + """Print the report for review, or write it atomically to a file; '-' means standard output.""" + text = json.dumps(report, indent=2) + "\n" + if target == "-": + print(text, end="") + return + path = Path(target) + fd, temporary = tempfile.mkstemp( + prefix=f".{path.name}.", suffix=".tmp", dir=path.parent + ) + try: + with os.fdopen(fd, "w", encoding="utf-8") as output: + output.write(text) + os.replace(temporary, path) + finally: + if os.path.exists(temporary): + os.unlink(temporary) + + +def summary(report): + ok = sum(point["read"] == "ok" for point in report["points"]) + return f"Full read: {ok} of {len(report['points'])} points read successfully." diff --git a/modpoll/wot_config.py b/modpoll/wot_config.py index 15b57de..9a54141 100644 --- a/modpoll/wot_config.py +++ b/modpoll/wot_config.py @@ -1,11 +1,12 @@ """Adapt validated WoT configuration to the existing Modpoll execution engine.""" -from modpoll_wot.loading import load_model, loads_model, MAX_BYTES +from modpoll_wot import AcquisitionError +from modpoll_wot.loading import loads_model, MAX_BYTES import requests -def read_model(location, *, timeout, unit_id, host=None, port=None, parameters=None): - instance = {"host": host, "port": port, "parameters": parameters} +def read_payload(location, *, timeout): + """The exact bytes of a configuration, from a file or an http(s) URL, at most 1 MiB.""" if location.startswith(("http://", "https://")): with requests.get(location, timeout=timeout, stream=True) as response: response.raise_for_status() @@ -15,11 +16,25 @@ def read_model(location, *, timeout, unit_id, host=None, port=None, parameters=N if size > MAX_BYTES: raise ValueError(f"{location}: configuration exceeds 1 MiB") chunks.append(chunk) - model = loads_model( - b"".join(chunks), source=location, unit_id=unit_id, **instance - ) - else: - model = load_model(location, unit_id=unit_id, **instance) + return b"".join(chunks) + try: + with open(location, "rb") as stream: + payload = stream.read(MAX_BYTES + 1) + except OSError as exc: + raise AcquisitionError(f"{location}: {exc}") from exc + if len(payload) > MAX_BYTES: + raise AcquisitionError(f"{location}: configuration exceeds 1 MiB") + return payload + + +def read_model( + location, *, timeout, unit_id, host=None, port=None, parameters=None, payload=None +): + """Load a model; ``payload`` are its bytes when the caller already has them.""" + instance = {"host": host, "port": port, "parameters": parameters} + if payload is None: + payload = read_payload(location, timeout=timeout) + model = loads_model(payload, source=location, unit_id=unit_id, **instance) # Enforce application policy even with an older, exactly pinned wheel. if model.profile_version != "0.2": raise ValueError( diff --git a/tests/test_verification.py b/tests/test_verification.py new file mode 100644 index 0000000..ae216ec --- /dev/null +++ b/tests/test_verification.py @@ -0,0 +1,346 @@ +"""Full read and verification report (POLL-02a): per-group outcomes, report content, catalog fetch and options.""" + +import base64 +import hashlib +import json +import sys +from argparse import Namespace + +import modpoll_wot +import pytest +from pymodbus.exceptions import ModbusIOException +from pymodbus.pdu import ExceptionResponse + +from modpoll import main, modbus_task, utils, verification +from modpoll.arg_parser import get_parser + +from .wot_helpers import meter_model, raw_form + + +@pytest.fixture(autouse=True) +def fresh_stop_event(): + """A finished run leaves the process-wide stop event set; each test starts a new run.""" + utils._thread_event.clear() + yield + utils._thread_event.clear() + + +PRODUCT = "acme/meter" +COMMIT = "0123456789abcdef0123456789abcdef01234567" + + +def three_group_model(): + """Points `ok1` and `ok2` in one group, `refused` and `silent` each in their own.""" + model = meter_model("meter") + model["properties"] = { + name: { + "type": "integer", + "readOnly": True, + "forms": [raw_form("uint16", address)], + } + for name, address in (("ok1", 0), ("ok2", 1), ("refused", 10), ("silent", 20)) + } + model["modpoll:acquisition"] = [ + { + "modv:entity": "HoldingRegister", + "modv:address": 0, + "modv:quantity": 2, + "modpoll:members": ["ok1", "ok2"], + }, + { + "modv:entity": "HoldingRegister", + "modv:address": 10, + "modv:quantity": 1, + "modpoll:members": ["refused"], + }, + { + "modv:entity": "HoldingRegister", + "modv:address": 20, + "modv:quantity": 1, + "modpoll:members": ["silent"], + }, + ] + return model + + +class Answer: + def __init__(self, registers): + self.registers = registers + + def isError(self): + return False + + +class FakeClient: + """A device that answers address 0, refuses address 10 with exception 2 and ignores address 20.""" + + def __init__(self, refuse=True, ignore=True): + self.refuse, self.ignore, self.requests = refuse, ignore, [] + + def connect(self): + return True + + def close(self): + pass + + def read_holding_registers(self, address, count, device_id): + self.requests.append((address, count, device_id)) + if address == 10 and self.refuse: + return ExceptionResponse(3, 2) + if address == 20 and self.ignore: + return ModbusIOException("no response") + return Answer(list(range(100, 100 + count))) + + +def run_app(monkeypatch, argv, client): + monkeypatch.setattr(modbus_task, "_create_modbus_client", lambda args: client) + monkeypatch.setattr(sys, "argv", ["modpoll", "--interval", "0", *argv]) + monkeypatch.setattr(main, "logger", None) + main.app() + + +def write_model(tmp_path, model): + path = tmp_path / "meter.tm.json" + path.write_text(json.dumps(model)) + return path + + +def test_full_read_records_each_group_and_never_retries(monkeypatch, tmp_path, capsys): + path = write_model(tmp_path, three_group_model()) + report_path = tmp_path / "report.json" + client = FakeClient() + with pytest.raises(SystemExit) as exit_info: + run_app( + monkeypatch, + [ + "-f", + str(path), + "--tcp", + "192.0.2.10", + "--unit-id", + "7", + "--report", + str(report_path), + "--product", + PRODUCT, + "--confirm", + "ok1", + "--reject", + "ok2", + "--firmware", + "1.2", + "--configuration", + "range 0-10 V", + ], + client, + ) + assert exit_info.value.code == 1 + report = json.loads(report_path.read_text()) + assert [ + (p["property"], p["read"], p.get("exceptionCode"), p["expected"]) + for p in report["points"] + ] == [ + ("ok1", "ok", None, "confirmed"), + ("ok2", "ok", None, "rejected"), + ("refused", "exception", 2, "unchecked"), + ("silent", "no-response", None, "unchecked"), + ] + assert report["model"]["source"] == "local" and "ref" not in report["model"] + assert report["product"] == PRODUCT and report["transport"] == "tcp" + assert report["environment"] == {"firmware": "1.2", "configuration": "range 0-10 V"} + assert report["tool"]["name"] == "modpoll" + modpoll_wot.validate_report(report, model=path.read_bytes()) + # Nothing that identifies the device or what it answered is in the file. + text = report_path.read_text() + assert all( + secret not in text for secret in ("192.0.2.10", '"unitId"', "100", "101") + ) + assert [request[0] for request in client.requests] == [0, 10, 20] + assert "Full read: 2 of 4 points read successfully." in capsys.readouterr().out + + +def test_full_read_of_a_healthy_device_succeeds_and_exports_a_snapshot( + monkeypatch, tmp_path +): + path = write_model(tmp_path, three_group_model()) + report_path, snapshot = tmp_path / "report.json", tmp_path / "snapshot.json" + run_app( + monkeypatch, + [ + "-f", + str(path), + "--tcp", + "192.0.2.10", + "--report", + str(report_path), + "--product", + PRODUCT, + "--export", + str(snapshot), + "--confirm", + "all", + ], + FakeClient(refuse=False, ignore=False), + ) + report = json.loads(report_path.read_text()) + assert {p["read"] for p in report["points"]} == {"ok"} and { + p["expected"] for p in report["points"] + } == {"confirmed"} + assert json.loads(snapshot.read_text())["meter"]["ok1"] == 100 + + +def test_report_goes_to_standard_output_with_dash(monkeypatch, tmp_path, capsys): + path = write_model(tmp_path, three_group_model()) + run_app( + monkeypatch, + ["-f", str(path), "--tcp", "x", "--report", "-", "--product", PRODUCT], + FakeClient(False, False), + ) + out = capsys.readouterr().out + assert json.loads(out[out.index("{") : out.rindex("}") + 1])["reportVersion"] == 3 + + +def test_a_point_that_was_not_read_cannot_be_judged(monkeypatch, tmp_path): + path = write_model(tmp_path, three_group_model()) + with pytest.raises(SystemExit) as exit_info: + run_app( + monkeypatch, + [ + "-f", + str(path), + "--tcp", + "x", + "--report", + str(tmp_path / "r.json"), + "--product", + PRODUCT, + "--confirm", + "refused", + ], + FakeClient(), + ) + assert exit_info.value.code == 1 + assert not (tmp_path / "r.json").exists() + + +@pytest.mark.parametrize( + "argv, message", + [ + (["--device", PRODUCT, "-f", "x.json"], "either --device or -f"), + ([], "One of -f or --device is required"), + (["--device", "Bad/Id"], "--device must be"), + (["-f", "x.json", "--report", "r.json", "--tcp", "x"], "needs --product"), + ( + ["-f", "x.json", "--full-read", "--tcp", "x", "--timeout", "30"], + "at most 10", + ), + (["-f", "x.json", "--full-read", "--udp", "x"], "not UDP"), + ( + ["-f", "x.json", "--full-read", "--rtu", "p", "--framer", "ascii"], + "not Modbus ASCII", + ), + (["-f", "x.json", "--full-read", "--tcp", "x", "--mqtt-host", "h"], "MQTT"), + (["-f", "x.json", "--confirm", "all", "--tcp", "x"], "needs --full-read"), + ], +) +def test_option_combinations_are_refused(argv, message, monkeypatch, caplog): + monkeypatch.setattr(sys, "argv", ["modpoll", *argv]) + monkeypatch.setattr(main, "logger", None) + with pytest.raises(SystemExit) as exit_info: + main.app() + assert exit_info.value.code == 2 + assert message in caplog.text + + +def test_full_read_asks_each_group_once(): + args = get_parser().parse_args(["-f", "x", "--tcp", "h", "--full-read"]) + assert modbus_task._read_options(args) == {"retries": 0} + assert ( + modbus_task._read_options(get_parser().parse_args(["-f", "x", "--tcp", "h"])) + == {} + ) + + +class Response: + def __init__(self, status=200, text="", body=None, headers=None): + self.status_code, self.text, self._body, self.headers = ( + status, + text, + body, + headers or {}, + ) + self.ok = status < 400 + + def json(self): + return self._body + + +def catalog_stub(monkeypatch, payload, *, commit=COMMIT, blob=None): + calls = [] + entry = { + "encoding": "base64", + "content": base64.encodebytes(payload).decode(), + "sha": blob or verification.git_blob_sha1(payload), + } + + def get(url, headers=None, timeout=None, params=None): + calls.append((url, params)) + if "/commits/" in url: + return ( + Response(text=commit + "\n") + if url.endswith("/main") or url.endswith("/v1") + else Response(404) + ) + return Response(body=entry) if "products/acme/meter/" in url else Response(404) + + monkeypatch.setattr(verification.requests, "get", get) + return calls + + +def test_a_branch_is_resolved_to_the_commit_the_report_names(monkeypatch, tmp_path): + payload = json.dumps(three_group_model()).encode() + calls = catalog_stub(monkeypatch, payload) + report_path = tmp_path / "report.json" + run_app( + monkeypatch, + ["--device", PRODUCT, "--tcp", "x", "--report", str(report_path)], + FakeClient(False, False), + ) + report = json.loads(report_path.read_text()) + assert report["product"] == PRODUCT + assert report["model"] == { + "sha256": hashlib.sha256(payload).hexdigest(), + "fingerprint": modpoll_wot.model_fingerprint(payload), + "source": "catalog", + "ref": COMMIT, + } + assert calls[-1][1] == {"ref": COMMIT} + + +def test_a_commit_is_used_as_given_and_a_download_is_checked(monkeypatch): + payload = b'{"title": "x"}' + calls = catalog_stub(monkeypatch, payload) + assert verification.fetch_catalog_model(PRODUCT, COMMIT, timeout=1) == ( + payload, + COMMIT, + ) + assert len(calls) == 1 + catalog_stub(monkeypatch, payload, blob="0" * 40) + with pytest.raises(ValueError, match="Git object id"): + verification.fetch_catalog_model(PRODUCT, COMMIT, timeout=1) + catalog_stub(monkeypatch, payload) + with pytest.raises(ValueError, match="no commit, tag or branch nope"): + verification.fetch_catalog_model(PRODUCT, "nope", timeout=1) + with pytest.raises(ValueError, match="no Thing Model for acme/other"): + verification.fetch_catalog_model("acme/other", COMMIT, timeout=1) + + +def test_device_syntax(): + assert verification.parse_device("advantech/adam-5017uh") == ( + "advantech/adam-5017uh", + "main", + ) + assert verification.parse_device(f"a/b@{COMMIT}") == ("a/b", COMMIT) + for bad in ("adam", "A/B", "a/b@", "a/b/c"): + with pytest.raises(ValueError): + verification.parse_device(bad)