From 770806fbcd0955196edac14c5b71d8ce9180a791 Mon Sep 17 00:00:00 2001 From: Gavin Ying Date: Sat, 14 Nov 2026 19:30:29 +0800 Subject: [PATCH] feat(modpoll): report failures as the device answered, write report schema 5 and identify the product before an upload (POLL-06) --- packages/modpoll/README.md | 20 +- packages/modpoll/docs/preview-notes.md | 19 ++ packages/modpoll/modpoll/arg_parser.py | 3 +- packages/modpoll/modpoll/main.py | 137 +++++++++-- packages/modpoll/modpoll/modbus_task.py | 5 + packages/modpoll/modpoll/verification.py | 202 +++++++++++++++- packages/modpoll/tests/conftest.py | 19 ++ packages/modpoll/tests/test_login.py | 14 +- packages/modpoll/tests/test_verification.py | 251 +++++++++++++++++++- 9 files changed, 617 insertions(+), 53 deletions(-) diff --git a/packages/modpoll/README.md b/packages/modpoll/README.md index 4fd8bf2..f7aac30 100644 --- a/packages/modpoll/README.md +++ b/packages/modpoll/README.md @@ -120,8 +120,24 @@ The report records, per point, whether the read worked (`ok`, a Modbus `exceptio ID, serial number or value; review it before sharing. It is checked with [modpoll-wot](https://github.com/top-maker/modpoll/tree/v2/packages/modpoll-wot) (`modpoll-wot validate-report report.json --model model.tm.json`), and `--export` still writes the snapshot of the same read. ModioHub resolves the product -from the model fingerprint, so you never name the product. The exit -code is 1 unless every point was read. +from the model fingerprint; when it does not know the model, modpoll names the product whose baseline +Thing Model holds all of the report's points, or lets you choose one from the matched products or a search, +and otherwise prints a prefilled catalog request. A point whose DataSchema declares `const` (an identity +point, such as a meter code) is compared with the value read, and the report records only `match` or +`mismatch`. + +When a read fails, modpoll lists each failed group as the device answered it, without guessing why: + +```text +Group 3 of 8 (holding registers 40-59): exception code 02 (illegal data address). +Group 5 of 8 (input registers 0-59): no response. +Groups 6-8 of 8: not tried. +Not a full read: 21 of 44 points read. +``` + +Only a full read whose identity points match can be uploaded; any other report is saved for your own checks +or a catalog request, and `--upload` refuses it without contacting ModioHub. The exit code is 1 unless the +report can be uploaded. ### Sign in to ModioHub, read a Workspace Thing Model and upload the report diff --git a/packages/modpoll/docs/preview-notes.md b/packages/modpoll/docs/preview-notes.md index 3d43e47..a900674 100644 --- a/packages/modpoll/docs/preview-notes.md +++ b/packages/modpoll/docs/preview-notes.md @@ -1,3 +1,22 @@ +# Modpoll 2.0.0a13 preview (unreleased) + +Modpoll 2.0.0a13 writes verification report schema 5 (modpoll-wot with `identity_constants`): + +- A failed read lists each failed group as the device answered it (data table, addresses, exception code and + its Modbus name, or no response), each point whose answer could not be decoded, and the groups not tried. + modpoll does not guess why and does not change the configuration. +- Only a full read whose identity points match can be uploaded. The `Continue?` question is gone: a report + with failures is saved and not offered for upload, and `--upload FILE` refuses it, or a schema 3 or 4 + report, without contacting ModioHub. +- Points whose DataSchema declares `const` are compared with the value read; the report records `match` or + `mismatch`, never the value. +- Before an upload, a model ModioHub does not know is matched by its point fingerprints: a report whose points + all belong to one baseline gets that product, other matches or a search are offered interactively, and + otherwise a prefilled catalog request is printed. A Workspace model's report names its product. +- Refusals from ModioHub are explained by their code (`not-full-read`, `identity-mismatch`, + `identity-missing`, `unknown-model` and others). +- The signal handler no longer waits for the exit event's lock, so Ctrl-C cannot deadlock a run. + # Modpoll 2.0.0a12 preview Modpoll 2.0.0a12 pins modpoll-wot 0.7.0a1: diff --git a/packages/modpoll/modpoll/arg_parser.py b/packages/modpoll/modpoll/arg_parser.py index 5976df6..cf9cf55 100644 --- a/packages/modpoll/modpoll/arg_parser.py +++ b/packages/modpoll/modpoll/arg_parser.py @@ -69,7 +69,8 @@ def get_parser(): "for confirmation and uploaded once you agree; you are signed in " "with the browser only when no login exists. Together with " "--report, the report of the verification read is uploaded " - "instead of only being saved." + "instead of only being saved. Only a full read whose identity " + "points match can be uploaded." ), ) verification.add_argument( diff --git a/packages/modpoll/modpoll/main.py b/packages/modpoll/modpoll/main.py index 1773c88..7e852a4 100644 --- a/packages/modpoll/modpoll/main.py +++ b/packages/modpoll/modpoll/main.py @@ -136,11 +136,13 @@ def _ask(prompt): def _finish_full_read(args, handler): - """Summarize the verification read, save the report, and upload it when asked. + """Report the verification read, save the report, and upload it when asked. + Failures are listed as the device answered them; a report with any, or + with an identity point that does not match, is saved but never uploaded. On a terminal without --yes the save location, the judgment of the values - and the upload are asked interactively. The result is whether every point - was read. + and the upload are asked interactively. The result is whether the report + can be uploaded. """ try: report = verification.build_report(handler, args) @@ -148,27 +150,22 @@ def _finish_full_read(args, handler): logger.error("%s", exc) logger.debug("Report error details", exc_info=True) return False - print(f"\n{verification.summary(report)}", flush=True) - full = verification.is_full_read(report) - if sys.stdin.isatty() and not args.yes: - if not full and _ask( - "Not every point was read, so this report does not count as a " - "full read. Continue? [y/N] " - ) not in ("y", "yes"): - return False + lines = verification.failure_lines(handler) + verification.identity_lines( + handler, report + ) + print("\n" + "\n".join([*lines, verification.summary(report)]), flush=True) + refused = verification.refusal(report) + if refused is None and sys.stdin.isatty() and not args.yes: verdict = _ask( "Do the values in the table above look right? " "[y]es, [n]o, [Enter] not checked: " ) if verdict in ("y", "yes", "n", "no"): - # Judge only the points the device actually answered. - judged = [ - point["property"] for point in report["points"] if point["read"] == "ok" - ] + names = [point["property"] for point in report["points"]] if verdict in ("y", "yes"): - args.confirm = judged + args.confirm = names else: - args.reject = judged + args.reject = names try: report = verification.build_report(handler, args) except (ValueError, OSError, AcquisitionError) as exc: @@ -197,6 +194,16 @@ def _finish_full_read(args, handler): "serial numbers or values; review it before sharing.", flush=True, ) + if refused is not None: + print( + ( + "Only a full read can be uploaded." + if not verification.is_full_read(report) + else "The device may be a different product, so the report cannot be uploaded." + ), + flush=True, + ) + return False # --report includes the upload: interactive runs ask, --yes uploads without # asking and therefore needs an existing sign-in. upload = args.upload is not None or args.yes @@ -206,7 +213,7 @@ def _finish_full_read(args, handler): confirmed = upload if upload and not _upload(args, report, confirm=not confirmed): return False - return full + return True def _ensure_login(): @@ -263,12 +270,95 @@ def _upload_saved(args): return _upload(args, report) +def _choose(options): + """The number the user picks from a printed list, or None for Enter.""" + for number, (_, label) in enumerate(options, 1): + print(f" {number}. {label}", flush=True) + answer = input("Number of the product, or Enter for none: ").strip() + if answer.isdigit() and 1 <= int(answer) <= len(options): + return options[int(answer) - 1][0] + return None + + +def _identify_product(args, report): + """The report with the product it belongs to, or None when no catalog product fits. + + A Workspace model names its product; otherwise the matched products of the + point fingerprints decide: an exact model is identified by ModioHub, and + a report whose points all belong to one baseline gets that product. Other + cases are chosen interactively, from the matches or a search. + """ + if "product" in report: + return report + matches = verification.matched_products(report, timeout=args.timeout) + if any(match["exact"] for match in matches): + return report + total = len(report["points"]) + if len(matches) == 1 and matches[0]["matched"] == total: + print( + f"Product: {matches[0]['productId']} (all {total} points are in its baseline Thing Model).", + flush=True, + ) + return {**report, "product": matches[0]["productId"]} + interactive = sys.stdin.isatty() and not args.yes + if matches: + print( + "ModioHub does not know this Thing Model. Products that share points with it:", + flush=True, + ) + options = [ + ( + m["productId"], + f"{m['productId']}: {m['matched']} of {total} points match", + ) + for m in matches + ] + if not interactive: + for _, label in options: + print(f" {label}", flush=True) + logger.error("Upload interactively to choose the product.") + return None + product = _choose(options) + if product: + return {**report, "product": product} + elif not interactive: + logger.error("The report does not match a catalog product.") + while interactive: + text = input("Model number to search, or Enter to stop: ").strip() + if not text: + break + found = verification.search_products(text, timeout=args.timeout) + if not found: + print("No product found.", flush=True) + continue + product = _choose(found) + if product: + return {**report, "product": product} + print( + "Not uploaded. Request the product in the catalog and attach the report:\n" + + verification.catalog_request(report), + flush=True, + ) + return None + + def _upload(args, report, *, confirm=True): """Show the report and, once the user agrees, upload it. Returns whether it was uploaded. ``confirm`` is false when the caller already asked (a yes to the bare ``--report`` upload question), or with ``--yes``. """ + refused = verification.refusal(report) + if refused is not None: + logger.error("%s", refused) + return False + try: + report = _identify_product(args, report) + except ValueError as exc: + logger.error("%s", exc) + return False + if report is None: + return False print("\nReport to upload:\n" + json.dumps(report, indent=2), flush=True) if confirm and not args.yes: if not sys.stdin.isatty(): @@ -282,20 +372,15 @@ def _upload(args, report, *, confirm=True): return False try: _ensure_login() - stored = verification.upload_report(report, timeout=args.timeout) + verification.upload_report(report, timeout=args.timeout) except (ValueError, login.LoginError, OSError) as exc: logger.error("%s", exc) return False print( - "Uploaded. " - + ( - "This is a full read and counts toward the community level." - if stored["fullRead"] - else "It is not a full read, so it does not count toward the community level." - ), + "Uploaded. Thank you: every point you read counts toward the hardware " + "verification on ModioHub.", flush=True, ) - print("Thank you for verifying the Thing Model on real hardware.", flush=True) return True diff --git a/packages/modpoll/modpoll/modbus_task.py b/packages/modpoll/modpoll/modbus_task.py index 6ec734d..4a41ee9 100644 --- a/packages/modpoll/modpoll/modbus_task.py +++ b/packages/modpoll/modpoll/modbus_task.py @@ -206,10 +206,13 @@ def __init__( 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 + # Whether the last poll cycle did not send this group's request at all. + self.skipped = False self.logger = logging.getLogger(__name__) def poll(self, master) -> bool: self.failure = None + self.skipped = False try: result = None data = None @@ -633,6 +636,7 @@ def poll(self): dev.pollCount += 1 dev.errorCount += 1 for poller in active: + poller.failure, poller.skipped = None, True previous_failures = poller.failcounter poller.update_statistics(False) self._record_poller_result(poller, False, previous_failures) @@ -668,6 +672,7 @@ def poll(self): len(skipped), ) for rest in skipped: + rest.failure, rest.skipped = None, True previous = rest.failcounter rest.update_statistics(False) self._record_poller_result(rest, False, previous) diff --git a/packages/modpoll/modpoll/verification.py b/packages/modpoll/modpoll/verification.py index 89eca64..59ae0de 100644 --- a/packages/modpoll/modpoll/verification.py +++ b/packages/modpoll/modpoll/verification.py @@ -1,17 +1,19 @@ -"""Verification of a Thing Model against a real device and its report (POLL-02a). +"""Verification of a Thing Model against a real device and its report (POLL-02a, POLL-06). With ``--report`` or ``--upload`` the 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 receiving service resolves the catalog -product from the model fingerprint, so the user never names the product. +Unit ID, serial number or value. Failures are reported as the device +answered them, and only a full read whose identity points match can be +uploaded; modpoll neither diagnoses nor changes the configuration. """ import hashlib import json import os import tempfile +import urllib.parse import uuid from datetime import datetime, timezone from importlib.metadata import version as package_version @@ -24,6 +26,37 @@ from .login import headers as api_headers MAX_TIMEOUT = 10.0 +CATALOG_ISSUES = "https://github.com/top-maker/open-modbus-catalog/issues/new" + +TABLES = { + 1: "coils", + 2: "discrete inputs", + 3: "holding registers", + 4: "input registers", +} +# Exception names as the Modbus Application Protocol specification gives them. +EXCEPTIONS = { + 1: "illegal function", + 2: "illegal data address", + 3: "illegal data value", + 4: "server device failure", + 5: "acknowledge", + 6: "server device busy", + 8: "memory parity error", + 10: "gateway path unavailable", + 11: "gateway target device failed to respond", +} +# What each refusal of the upload means, by the problem code ModioHub answers with. +REFUSALS = { + "not-full-read": "Not every point was read; only a full read can be uploaded.", + "identity-mismatch": "An identity point does not match the Thing Model, so the device may be a different product.", + "identity-missing": "This product has identity points that the report does not include. " + "Read them together with the other points.", + "unknown-product": "The report does not match a catalog product.", + "unknown-model": "The report does not match a catalog product.", + "duplicate-point": "The report is damaged or was edited by hand. Read the device again.", + "fingerprint-mismatch": "The report is damaged or was edited by hand. Read the device again.", +} def validate_args(args): @@ -74,6 +107,7 @@ def resolve_models(args): args.model_payloads[location] = payload if args.full_read: args.model_source = {"source": "workspace", "ref": details["ref"]} + args.model_product = details["product"] def fetch_workspace_model(text, *, timeout): @@ -151,17 +185,71 @@ def upload_report(report, *, timeout): if response.status_code == 401: raise ValueError("Your ModioHub login is no longer valid; run modpoll login") if not response.ok: - detail = ( - response.json().get("detail") + body = ( + response.json() if "json" in response.headers.get("Content-Type", "") - else None + else {} ) - raise ValueError( - f"{server} refused the report: {detail or response.status_code}" + code = body.get("code") + message = REFUSALS.get(code) or body.get("detail") or response.status_code + if code in ("unknown-product", "unknown-model"): + message = f"{message} Request the product in the catalog: {catalog_request(report)}" + raise ValueError(f"{server} refused the report: {message}") + return response.json() + + +def _api(method, path, *, timeout, **kwargs): + """A call to the public ModioHub API: (server, decoded JSON).""" + server = modpoll_wot.active_server() + try: + response = requests.request( + method, + f"{server}/api/v1{path}", + timeout=timeout, + headers=api_headers(None), + **kwargs, ) + except requests.RequestException as exc: + raise ValueError(f"Could not reach {server}: {exc}") from exc + _check_server(response, server) return response.json() +def matched_products(report, *, timeout): + """Catalog products whose baseline Thing Models share point fingerprints with the report. + + Each is {productId, matched, readablePoints, exact}, the closest first. + """ + fingerprints = [point["fingerprint"] for point in report["points"]] + return _api( + "POST", "/products/match", timeout=timeout, json={"fingerprints": fingerprints} + ) + + +def search_products(text, *, timeout): + """Catalog products whose model number, alias or manufacturer matches the text: [(id, label)].""" + found = _api("GET", "/products", timeout=timeout, params={"q": text, "limit": 5}) + return [ + (item["id"], f"{item['modelNumber']} ({item['manufacturer']['name']['en']})") + for item in found["items"] + ] + + +def catalog_request(report): + """A prefilled catalog issue for a product the catalog does not have; no values or addresses.""" + body = ( + "A verification report matches no catalog product.\n\n" + f"- Model fingerprint: `{report['model']['fingerprint']}`\n" + f"- Points: {len(report['points'])}\n" + f"- Tool: {report['tool']['name']} {report['tool']['version']}\n\n" + "Attach the report file and name the product and its documents." + ) + query = urllib.parse.urlencode( + {"template": "product-feedback.md", "title": "Product request", "body": body} + ) + return f"{CATALOG_ISSUES}?{query}" + + def _transport(args): return "rtu" if args.serial else "tcp" @@ -191,6 +279,7 @@ def build_report(handler, args): ) judged.update({name: "confirmed" for name in args.confirm if name != "all"}) judged.update({name: "rejected" for name in args.reject}) + constants = modpoll_wot.identity_constants(payload) unknown = sorted(set(judged) - set(fingerprints)) if unknown: raise ValueError(f"No readable point named {', '.join(unknown)}") @@ -215,9 +304,15 @@ def build_report(handler, args): 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" + if read_ok and name in constants: + point["identity"] = modpoll_wot.identity_result( + constants[name], points_by_name[name].val + ) points.append(point) + product = getattr(args, "model_product", None) report = { - "reportVersion": 4, + "reportVersion": modpoll_wot.REPORT_VERSION, + **({"product": product} if product else {}), "model": { "sha256": hashlib.sha256(payload).hexdigest(), "fingerprint": modpoll_wot.model_fingerprint(payload), @@ -258,6 +353,90 @@ def is_full_read(report): return all(point["read"] == "ok" for point in report["points"]) +def refusal(report): + """Why this report cannot be uploaded, or None: ModioHub accepts only schema 5 full reads that match.""" + if report["reportVersion"] != modpoll_wot.REPORT_VERSION: + return ( + f"This report was written by an older modpoll (report version {report['reportVersion']}). " + "Update modpoll and read the device again." + ) + if not is_full_read(report): + ok = sum(point["read"] == "ok" for point in report["points"]) + return ( + f"Not a full read: {ok} of {len(report['points'])} points were read. " + "Only a full read can be uploaded." + ) + mismatched = [ + p["property"] for p in report["points"] if p.get("identity") == "mismatch" + ] + if mismatched: + return ( + f"Identity point {', '.join(mismatched)} does not match the Thing Model, " + "so the device may be a different product. The report cannot be uploaded." + ) + return None + + +def _span(poller): + last = poller.start_address + poller.size - 1 + addresses = ( + f"{poller.start_address}-{last}" if last > poller.start_address else str(last) + ) + return f"{TABLES[poller.fc]} {addresses}" + + +def failure_lines(handler): + """What went wrong in the read, as the device answered, one line per group or point. + + Groups are numbered in ``modpoll:acquisition`` order from 1, with the + zero-based addresses of the Thing Model. Nothing is inferred about why. + """ + lines = [] + for device in handler.get_device_list(): + pollers = device.pollerList + total = len(pollers) + skipped = [index for index, poller in enumerate(pollers, 1) if poller.skipped] + for index, poller in enumerate(pollers, 1): + where = f"Group {index} of {total} ({_span(poller)})" + if poller.failure is not None: + kind, code = poller.failure + if kind == "exception": + name = EXCEPTIONS.get(code) + lines.append( + f"{where}: exception code {code:02X}" + + (f" ({name})." if name else ".") + ) + else: + lines.append(f"{where}: no response.") + elif not poller.skipped: + lines.extend( + f"Point {point.name} (group {index}): the answer could not be decoded as {point.dtype}." + for point in poller.readablePoints + if not point.valid_this_poll + ) + if skipped: + first, last = skipped[0], skipped[-1] + groups = f"Group {first}" if first == last else f"Groups {first}-{last}" + lines.append(f"{groups} of {total}: not tried.") + return lines + + +def identity_lines(handler, report): + """The identity points that did not match: the value read and the value the Thing Model gives.""" + constants = modpoll_wot.identity_constants(handler.model_bytes) + values = { + point.name: point.val + for device in handler.get_device_list() + for point in device.points.values() + } + return [ + f"Identity point {p['property']}: read {values[p['property']]!r}, " + f"the Thing Model expects {constants[p['property']]!r}." + for p in report["points"] + if p.get("identity") == "mismatch" + ] + + 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" @@ -279,4 +458,7 @@ def write_report(report, target): 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." + total = len(report["points"]) + if ok == total: + return f"Full read: all {total} points read." + return f"Not a full read: {ok} of {total} points read." diff --git a/packages/modpoll/tests/conftest.py b/packages/modpoll/tests/conftest.py index 12ee7c1..1d97a56 100644 --- a/packages/modpoll/tests/conftest.py +++ b/packages/modpoll/tests/conftest.py @@ -45,3 +45,22 @@ def live_modsim(): process.wait(timeout=5) process.stderr.close() assert process.returncode == 0 + + +@pytest.fixture(autouse=True) +def known_model(monkeypatch): + """Uploads go to a ModioHub that knows the model exactly, unless a test says otherwise.""" + from modpoll import verification + + monkeypatch.setattr( + verification, + "matched_products", + lambda report, *, timeout: [ + { + "productId": "acme/meter", + "matched": len(report["points"]), + "readablePoints": len(report["points"]), + "exact": True, + } + ], + ) diff --git a/packages/modpoll/tests/test_login.py b/packages/modpoll/tests/test_login.py index d5613b5..331b050 100644 --- a/packages/modpoll/tests/test_login.py +++ b/packages/modpoll/tests/test_login.py @@ -241,7 +241,7 @@ def test_full_read_of_a_workspace_model_names_the_workspace_as_its_source( FakeClient(), ) report = json.loads(report_path.read_text()) - assert "product" not in report + assert report["product"] == PRODUCT assert ( report["model"]["source"] == "workspace" and report["model"]["ref"] == f"{ID}@2" ) @@ -260,7 +260,7 @@ def test_upload_shows_the_report_and_sends_it_with_the_login( def post(url, json=None, headers=None, timeout=None): sent.update(url=url, body=json, headers=headers) - return Reply(201, {"id": "p7n2d9x4k8m3q5ra", "fullRead": True}) + return Reply(201, {"id": "p7n2d9x4k8m3q5ra"}) monkeypatch.setattr(verification.requests, "post", post) run_app( @@ -269,9 +269,9 @@ def post(url, json=None, headers=None, timeout=None): FakeClient(False, False), ) out = capsys.readouterr().out - assert "Report to upload:" in out and "Uploaded. This is a full read" in out + assert "Report to upload:" in out and "Uploaded. Thank you" in out assert ( - sent["url"] == f"{SERVER}/api/v1/reports" and sent["body"]["reportVersion"] == 4 + sent["url"] == f"{SERVER}/api/v1/reports" and sent["body"]["reportVersion"] == 5 ) assert "product" not in sent["body"] assert ( @@ -289,7 +289,8 @@ def test_upload_asks_first_and_needs_a_login(monkeypatch, tmp_path, capsys): monkeypatch.setattr( verification.requests, "post", - lambda *args, **kwargs: posted.append(args) or Reply(201, {"fullRead": True}), + lambda *args, **kwargs: posted.append(args) + or Reply(201, {"id": "p7n2d9x4k8m3q5ra"}), ) arguments = ["-f", str(path), "--tcp", "x", "--report", "--upload"] # Not a terminal and no --yes: nothing is sent. @@ -339,7 +340,8 @@ def test_upload_signs_in_inline_when_there_is_no_session(monkeypatch, tmp_path, monkeypatch.setattr( verification.requests, "post", - lambda *args, **kwargs: posted.append(args) or Reply(201, {"fullRead": True}), + lambda *args, **kwargs: posted.append(args) + or Reply(201, {"id": "p7n2d9x4k8m3q5ra"}), ) monkeypatch.setattr(sys.stdin, "isatty", lambda: True) monkeypatch.setattr("builtins.input", lambda prompt: "y") diff --git a/packages/modpoll/tests/test_verification.py b/packages/modpoll/tests/test_verification.py index d5cb583..b9e6d13 100644 --- a/packages/modpoll/tests/test_verification.py +++ b/packages/modpoll/tests/test_verification.py @@ -3,7 +3,9 @@ import hashlib import json import os +import re import sys +import urllib.parse import modpoll_wot import pytest from pymodbus.exceptions import ModbusIOException @@ -100,9 +102,9 @@ def write_model(tmp_path, model): def saved_report(model, *, transport="tcp"): - """A schema-4 report for a model, as a read on a device would have written it.""" + """A schema-5 report for a model, as a read on a device would have written it.""" return { - "reportVersion": 4, + "reportVersion": 5, "model": { "sha256": hashlib.sha256(model).hexdigest(), "fingerprint": modpoll_wot.model_fingerprint(model), @@ -126,7 +128,7 @@ def saved_report(model, *, transport="tcp"): def patch_upload(monkeypatch, uploaded): def fake_upload(report, *, timeout): uploaded["report"] = report - return {"fullRead": True} + return {"id": "p7n2d9x4k8m3q5ra"} monkeypatch.setattr(main, "_ensure_login", lambda: None) monkeypatch.setattr(verification, "upload_report", fake_upload) @@ -177,7 +179,14 @@ def test_full_read_records_each_group_and_never_retries(monkeypatch, tmp_path, c 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 + out = capsys.readouterr().out + assert ( + "Group 2 of 3 (holding registers 10): exception code 02 (illegal data address).\n" + "Group 3 of 3 (holding registers 20): no response.\n" + "Not a full read: 2 of 4 points read.\n" + ) in out + assert "Only a full read can be uploaded." in out + assert "Upload this report" not in out and "Continue?" not in out def test_full_read_of_a_healthy_device_succeeds_and_exports_a_snapshot( @@ -223,7 +232,7 @@ def test_report_goes_to_standard_output_with_dash(monkeypatch, tmp_path, capsys) FakeClient(False, False), ) out = capsys.readouterr().out - assert json.loads(out[out.index("{") : out.rindex("}") + 1])["reportVersion"] == 4 + assert json.loads(out[out.index("{") : out.rindex("}") + 1])["reportVersion"] == 5 def test_a_point_that_was_not_read_cannot_be_judged(monkeypatch, tmp_path): @@ -327,7 +336,7 @@ def test_bare_report_uploads_after_a_yes(monkeypatch, tmp_path, capsys): ["-f", str(path), "--tcp", "192.0.2.10", "--report"], FakeClient(False, False), ) - assert uploaded["report"]["reportVersion"] == 4 + assert uploaded["report"]["reportVersion"] == 5 out = capsys.readouterr().out assert "Report to upload:" in out assert "Uploaded." in out @@ -344,7 +353,7 @@ def test_upload_only_sends_a_saved_report_without_a_read(monkeypatch, tmp_path, with pytest.raises(SystemExit) as exit_info: run_app(monkeypatch, ["--upload", str(report_path), "--yes"], None) assert exit_info.value.code == 0 - assert uploaded["report"]["reportVersion"] == 4 + assert uploaded["report"]["reportVersion"] == 5 assert "Uploaded." in capsys.readouterr().out @@ -396,7 +405,7 @@ def test_report_yes_saves_the_default_file_and_uploads(monkeypatch, tmp_path, ca FakeClient(False, False), ) (saved,) = tmp_path.glob("report-*.json") - assert uploaded["report"]["reportVersion"] == 4 + assert uploaded["report"]["reportVersion"] == 5 out = capsys.readouterr().out assert f"Report written to {saved.name}" in out assert "Uploaded." in out @@ -431,3 +440,229 @@ def test_bare_report_without_a_terminal_names_a_file(monkeypatch, tmp_path, capl ) assert exit_info.value.code == 1 assert "Add --report FILE" in caplog.text + + +class ShortClient(FakeClient): + """Address 10 does not answer, so group 3 is not tried; address 0 answers one register short.""" + + def read_holding_registers(self, address, count, device_id): + self.requests.append((address, count, device_id)) + if address == 10: + return ModbusIOException("no response") + return Answer(list(range(100, 100 + count - (address == 0)))) + + +def test_failures_are_reported_as_the_device_answered(monkeypatch, tmp_path, capsys): + """A decode failure names its point, and groups after a silent device are listed as not tried.""" + model = three_group_model() + model["properties"]["ok1"]["forms"] = [raw_form("float32", 0)] + model["properties"]["ok1"]["type"] = "number" + del model["properties"]["ok2"] + model["modpoll:acquisition"][0]["modpoll:members"] = ["ok1"] + path = write_model(tmp_path, model) + with pytest.raises(SystemExit) as exit_info: + run_app( + monkeypatch, + ["-f", str(path), "--tcp", "x", "--report", str(tmp_path / "r.json")], + ShortClient(), + ) + assert exit_info.value.code == 1 + out = capsys.readouterr().out + assert ( + "Point ok1 (group 1): the answer could not be decoded as float32.\n" + "Group 2 of 3 (holding registers 10): no response.\n" + "Group 3 of 3: not tried.\n" + "Not a full read: 0 of 3 points read.\n" + ) in out + report = json.loads((tmp_path / "r.json").read_text()) + assert [p["read"] for p in report["points"]] == [ + "not-tested", + "no-response", + "not-tested", + ] + + +def identity_model(meter_code): + model = three_group_model() + model["properties"]["ok1"]["const"] = meter_code + return model + + +@pytest.mark.parametrize("meter_code, result", [(100, "match"), (7, "mismatch")]) +def test_identity_points_are_compared_on_this_computer( + monkeypatch, tmp_path, capsys, meter_code, result +): + path = write_model(tmp_path, identity_model(meter_code)) + monkeypatch.chdir(tmp_path) + uploaded = {} + patch_upload(monkeypatch, uploaded) + with pytest.raises(SystemExit) as exit_info: + run_app( + monkeypatch, + ["-f", str(path), "--tcp", "x", "--report", "r.json", "--yes"], + FakeClient(False, False), + ) + raise SystemExit(0) + report = json.loads((tmp_path / "r.json").read_text()) + assert report["reportVersion"] == 5 + assert report["points"][0]["identity"] == result + assert all("identity" not in point for point in report["points"][1:]) + modpoll_wot.validate_report(report, model=path.read_bytes()) + out = capsys.readouterr().out + if result == "match": + assert exit_info.value.code == 0 and uploaded + else: + assert exit_info.value.code == 1 and not uploaded + assert "Identity point ok1: read 100, the Thing Model expects 7." in out + assert "may be a different product" in out + + +@pytest.mark.parametrize( + "change, message", + [ + ( + lambda r: r["points"][0].update(read="no-response"), + "Not a full read: 3 of 4", + ), + ( + lambda r: r["points"][0].update(identity="mismatch"), + "does not match the Thing Model", + ), + (lambda r: r.update(reportVersion=4), "older modpoll (report version 4)"), + ], +) +def test_a_saved_report_that_cannot_be_uploaded_is_refused_here( + monkeypatch, tmp_path, caplog, change, message +): + model = json.dumps(identity_model(100)).encode() + report = saved_report(model) + report["points"][0]["identity"] = "match" + change(report) + if report["points"][0]["read"] != "ok": + del report["points"][0]["identity"] + report["points"][0]["expected"] = "unchecked" + if report["reportVersion"] == 4: + del report["points"][0]["identity"] + path = tmp_path / "report.json" + path.write_text(json.dumps(report)) + uploaded = {} + patch_upload(monkeypatch, uploaded) + with pytest.raises(SystemExit) as exit_info: + run_app(monkeypatch, ["--upload", str(path), "--yes"], None) + assert exit_info.value.code == 1 and not uploaded + assert message in caplog.text + + +def upload_saved(monkeypatch, tmp_path, matches, answers=(), report=None): + report = report or saved_report(json.dumps(three_group_model()).encode()) + path = tmp_path / "report.json" + path.write_text(json.dumps(report)) + monkeypatch.setattr(verification, "matched_products", lambda r, *, timeout: matches) + monkeypatch.setattr( + verification, + "search_products", + lambda text, *, timeout: ( + [("acme/meter-2", "METER-2 (Acme)")] if text == "meter" else [] + ), + ) + replies = iter(answers) + monkeypatch.setattr(sys.stdin, "isatty", lambda: bool(answers)) + monkeypatch.setattr("builtins.input", lambda prompt: next(replies)) + uploaded = {} + patch_upload(monkeypatch, uploaded) + with pytest.raises(SystemExit) as exit_info: + run_app( + monkeypatch, ["--upload", str(path), *([] if answers else ["--yes"])], None + ) + return exit_info.value.code, uploaded.get("report") + + +def match(product, matched, exact=False): + return { + "productId": product, + "matched": matched, + "readablePoints": 4, + "exact": exact, + } + + +def test_a_report_with_a_product_is_uploaded_as_it_is(monkeypatch, tmp_path): + report = saved_report(json.dumps(three_group_model()).encode()) + report["product"] = "acme/meter" + code, sent = upload_saved(monkeypatch, tmp_path, [], report=report) + assert code == 0 and sent["product"] == "acme/meter" + + +def test_an_exact_model_is_left_for_modiohub_to_identify(monkeypatch, tmp_path): + code, sent = upload_saved( + monkeypatch, tmp_path, [match("acme/meter", 4, exact=True)] + ) + assert code == 0 and "product" not in sent + + +def test_points_that_all_belong_to_one_baseline_name_its_product( + monkeypatch, tmp_path, capsys +): + code, sent = upload_saved(monkeypatch, tmp_path, [match("acme/meter", 4)]) + assert code == 0 and sent["product"] == "acme/meter" + assert ( + "Product: acme/meter (all 4 points are in its baseline Thing Model)." + in capsys.readouterr().out + ) + + +def test_other_matches_are_chosen_interactively(monkeypatch, tmp_path, capsys): + matches = [match("acme/meter", 3), match("acme/meter-2", 2)] + code, sent = upload_saved(monkeypatch, tmp_path, matches, answers=["2", "y"]) + assert code == 0 and sent["product"] == "acme/meter-2" + assert "acme/meter: 3 of 4 points match" in capsys.readouterr().out + # Without a terminal there is nobody to choose. + code, sent = upload_saved(monkeypatch, tmp_path, matches) + assert code == 1 and sent is None + + +def test_without_a_match_a_search_or_a_catalog_request_follows( + monkeypatch, tmp_path, capsys +): + code, sent = upload_saved(monkeypatch, tmp_path, [], answers=["meter", "1", "y"]) + assert code == 0 and sent["product"] == "acme/meter-2" + code, sent = upload_saved(monkeypatch, tmp_path, [], answers=["nothing", ""]) + assert code == 1 and sent is None + out = capsys.readouterr().out + assert "No product found." in out + link = out[ + out.index("https://github.com/top-maker/open-modbus-catalog/issues/new?") : + ].split()[0] + body = urllib.parse.parse_qs(urllib.parse.urlsplit(link).query)["body"][0] + assert "Model fingerprint: `mf1:" in body and "Points: 4" in body + assert "100" not in body + + +@pytest.mark.parametrize( + "code, message", + [ + ("identity-missing", "Read them together with the other points."), + ("not-full-read", "only a full read can be uploaded"), + ("unknown-model", "Request the product in the catalog: https://github.com/"), + ], +) +def test_a_refusal_is_explained_by_its_code(monkeypatch, code, message): + class Refused: + status_code, ok, headers = ( + 422, + False, + {"Content-Type": "application/problem+json"}, + ) + + def json(self): + return {"code": code, "detail": "server text"} + + monkeypatch.setattr( + verification.modpoll_wot, + "load_session", + lambda server: type("S", (), {"token": "t"}), + ) + monkeypatch.setattr(verification.requests, "post", lambda *a, **k: Refused()) + report = saved_report(json.dumps(three_group_model()).encode()) + with pytest.raises(ValueError, match=re.escape(message)): + verification.upload_report(report, timeout=3)