Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 12 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,15 +105,16 @@ 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).

### Verify a Thing Model on a real device and write a report
### Read a device and write a verification report

`modpoll verify --config MODEL --tcp HOST` reads every point of a Thing Model 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.
MODEL is a local TM/TD file, an http(s) URL or a `modiohub:<id>@<version>` Workspace reference. `--report
FILE` also writes the verification report (`-` prints it):
Adding `--report` to a normal read verifies the Thing Model on real hardware: every point is read 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. MODEL is a local TM/TD file, an http(s) URL or a `modiohub:<id>@<version>` Workspace
reference. `--report FILE` writes the verification report (`-` prints it); bare `--report` asks where to
save, whether the values look right, and whether to upload:

```sh
modpoll verify --config examples/modsim.tm.json --tcp 192.168.1.20 --unit-id 3 --product advantech/adam-5017uh --report report.json
modpoll --config examples/modsim.tm.json --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,
Expand All @@ -122,8 +123,8 @@ The report records, per point, whether the read worked (`ok`, a Modbus `exceptio
`unchecked`. 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 <manufacturer>/<model-number>`; the report then names the model as local. The exit
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.

### Sign in to ModioHub, read a Workspace Thing Model and upload the report
Expand All @@ -137,11 +138,11 @@ revoke the session in your ModioHub settings to end it on the server.

Once signed in, `--config modiohub:<id>@<version>` (the version is a number or `latest`) reads one
of your custom Thing Models. A shared one needs no login. Verifying it names the Workspace model in the
report, and `modpoll verify --config ... --upload` shows the report and, after you confirm (or with `--yes`),
uploads it:
report, and `modpoll --config ... --upload` shows the report and, after you confirm (or with `--yes`),
uploads it; without a login the sign-in flow starts right there:

```sh
modpoll verify --config modiohub:k3x9f2m7q4a8n5bd@latest --tcp 192.168.1.20 --upload
modpoll --config modiohub:k3x9f2m7q4a8n5bd@latest --tcp 192.168.1.20 --upload
```

### MQTT data and write behavior
Expand Down
13 changes: 13 additions & 0 deletions docs/preview-notes.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
# Next preview

The verification flags move back onto the normal read and the report drops the
product (modpoll-wot 0.6.0a1, report schema 4):

- `--report` on a normal read verifies a Thing Model on real hardware: every point read once, read-only and
without retries; the verification report (schema 4) holds no address, Unit ID, serial number or value.
Bare `--report` asks where to save, whether the values look right, and whether to upload.
- `--upload` shows the report and uploads it after you confirm (`--yes` skips the questions); without a
login the browser sign-in flow starts inline.
- The `verify` subcommand and `--product` are gone: ModioHub resolves the product from the model
fingerprint (identical for a Thing Model, its Thing Description exports and unmodified forks).

# Modpoll 2.0.0a8 preview

Modpoll 2.0.0a8 keeps modpoll-wot 0.5.0a1. It reshapes the ModioHub commands of 2.0.0a7 and restores v1 CSV
Expand Down
19 changes: 19 additions & 0 deletions docs/validation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -174,3 +174,22 @@ pointer to the command. After the change ``make check`` passed and the
offline suite passed 235 tests with 58 integration tests deselected,
including new refusal cases for the removed spellings and the verify
subcommand reaching the transport check.


Interactive report and upload on a normal read
----------------------------------------------

On 2026-11-13 the ``verify`` subcommand was replaced by plain flags on the
normal read (maintainer decision: the tools have no subcommand tradition, and
verification is a by-product of reading a device). ``--report`` without FILE
asks where to save (default ``report-<date>.json``), whether the values look
right (yes/no/not checked, judged as confirm-all or reject-all over the points
the device answered), and whether to upload; ``--upload`` signs in inline with
the browser flow when there is no session. ``--product`` is gone with schema 4
(modpoll-wot 0.6.0a1): the receiving service resolves the product from the
model fingerprint. After the change ``make check`` passed and the offline
suite passed 238 tests with 58 integration tests deselected, including the
interactive save/judgment flow, the inline sign-in, and refusal cases for
``--confirm``/``--yes`` without ``--report``/``--upload``. End-to-end against a
local modsim: ``--config examples/modsim.tm.json --tcp ... --report -`` prints
a schema-4 report with all 37 points ``ok``.
25 changes: 12 additions & 13 deletions modpoll/arg_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,36 +38,35 @@ def get_parser():
)
verification = parser.add_argument_group(
"verification",
"modpoll verify --config MODEL --tcp HOST reads every point of one Thing "
"Model once, read-only and without retries, and reports which points "
"could be read",
"--report/--upload read every point of one Thing Model once, read-only "
"and without retries, and report which points could be read",
)
verification.add_argument(
"--report",
nargs="?",
const="",
default=None,
metavar="FILE",
help=(
"Write the verification report to FILE ('-' prints it). "
"It lists each point's result and carries no address, Unit ID, serial "
"number or value; review it before sharing."
"Read every point of the model once and write the verification "
"report to FILE ('-' prints it). Without FILE the save location, "
"your judgment of the values and the upload are asked "
"interactively. The report lists each point's result and carries "
"no address, Unit ID, serial number or value."
),
)
verification.add_argument(
"--upload",
action="store_true",
help=(
"After the verification read, show the report and, once you confirm, "
"upload it to ModioHub (run modpoll login first)"
"upload it to ModioHub; signs you in with the browser when needed"
),
)
verification.add_argument(
"--yes",
action="store_true",
help="Upload without asking for confirmation after the report is shown",
)
verification.add_argument(
"--product",
metavar="MANUFACTURER/MODEL",
help="Catalog product ID the report is for; needed when the model does not name one",
help="Upload without being asked",
)
verification.add_argument(
"--confirm",
Expand Down
85 changes: 70 additions & 15 deletions modpoll/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import signal
import sys
import time
from datetime import datetime, timezone

from modpoll_wot import AcquisitionError

Expand Down Expand Up @@ -128,26 +129,82 @@ def process_mqtt_command(topic, payload, retained, topic_pattern, handlers):
return success


def _ask(prompt):
return input(prompt).strip().lower()


def _finish_full_read(args, handler):
"""Summarize the full read and write its report; the result is whether every point was read."""
"""Summarize the verification read, save the report, and upload it when asked.

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.
"""
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)
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
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"
]
if verdict in ("y", "yes"):
args.confirm = judged
else:
args.reject = judged
try:
report = verification.build_report(handler, args)
except (ValueError, OSError, AcquisitionError) as exc:
logger.error("%s", exc)
logger.debug("Report error details", exc_info=True)
return False
if args.report == "":
if not sys.stdin.isatty():
logger.error("Add --report FILE when not running interactively.")
return False
default = f"report-{datetime.now(timezone.utc).date().isoformat()}.json"
args.report = input(f"Save the report to [{default}]: ").strip() or default
if args.report:
try:
verification.write_report(report, args.report)
except (ValueError, OSError) as exc:
logger.error("%s", exc)
logger.debug("Report write details", exc_info=True)
return False
if 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,
)
if args.upload and not _upload(args, report):
return False
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)
return full


def _ensure_login():
"""A session for the upload; without one, sign in with the browser right here."""
import modpoll_wot

server = modpoll_wot.server_url()
if modpoll_wot.load_session(server) is None:
print(f"Sign in to {server} to upload.", flush=True)
login.login(server)


def _upload(args, report):
Expand All @@ -164,8 +221,9 @@ def _upload(args, report):
print("Not uploaded.", flush=True)
return False
try:
_ensure_login()
stored = verification.upload_report(report, timeout=args.timeout)
except ValueError as exc:
except (ValueError, login.LoginError, OSError) as exc:
logger.error("%s", exc)
return False
print(
Expand All @@ -177,6 +235,7 @@ def _upload(args, report):
),
flush=True,
)
print("Thank you for verifying the Thing Model on real hardware.", flush=True)
return True


Expand All @@ -193,9 +252,6 @@ def setup_logging(level, format):
def app(name="modpoll"):
if sys.argv[1:2] in (["login"], ["logout"]):
sys.exit(login.command(sys.argv[1:]))
verify_mode = sys.argv[1:2] == ["verify"]
if verify_mode:
sys.argv = [sys.argv[0], *sys.argv[2:]]
mqtt_handler = None
modbus_handlers = []

Expand All @@ -204,7 +260,6 @@ def app(name="modpoll"):

# parse args
args = get_parser().parse_args()
args.verify = verify_mode

print(
f"\nModpoll v{__version__} - A New Command-line Tool for Modbus and MQTT\n",
Expand Down
55 changes: 17 additions & 38 deletions modpoll/verification.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
"""Verification of a Thing Model against a real device and its report (POLL-02a).

``modpoll verify`` 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.
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.
"""

import hashlib
import json
import os
import re
import tempfile
import uuid
from datetime import datetime, timezone
Expand All @@ -23,51 +24,31 @@
from .login import headers as api_headers

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}}))?$")


def validate_args(args):
"""Reject option combinations a command cannot honour, before anything is connected."""
verify_options = ("report", "upload", "yes", "confirm", "reject", "product")
if args.verify:
args.full_read = True
else:
args.full_read = False
if any(getattr(args, option) for option in verify_options):
raise ValueError(
"Verification options belong to the verify command; for example: "
"modpoll verify --config model.tm.json --tcp HOST --upload"
)
args.full_read = args.report is not None or args.upload
if args.yes and not args.upload:
raise ValueError("--yes needs --upload")
if (args.confirm or args.reject) and not args.full_read:
raise ValueError("--confirm and --reject need --report or --upload")
sources = list(args.config or [])
if not sources:
raise ValueError("One of --config/-f is required")
if not args.full_read:
return
if args.mqtt_host:
raise ValueError("modpoll verify does not publish to MQTT")
raise ValueError("A verification report is not published to MQTT")
if args.udp:
raise ValueError("modpoll verify supports Modbus TCP and RTU, not UDP")
raise ValueError("A verification report supports Modbus TCP and RTU, not UDP")
if args.serial and args.framer == "ascii":
raise ValueError("modpoll verify supports Modbus RTU, not Modbus ASCII")
raise ValueError("A verification report supports Modbus RTU, not Modbus ASCII")
if len(sources) != 1:
raise ValueError("modpoll verify reads one Thing Model")
workspace = any(
location.startswith(modpoll_wot.REFERENCE_PREFIX)
for location in args.config or []
)
if (args.report or args.upload) and not (args.product or workspace):
raise ValueError(
"modpoll verify --report needs --product <manufacturer>/<model-number> "
"when the model does not name one"
)
if args.yes and not args.upload:
raise ValueError("--yes needs --upload")
if args.product and not _DEVICE.match(args.product):
raise ValueError("--product must be <manufacturer>/<model-number>")
raise ValueError("A verification report reads one Thing Model")
if args.timeout > MAX_TIMEOUT:
raise ValueError(
f"--timeout is at most {MAX_TIMEOUT:g} seconds in a verification"
f"--timeout is at most {MAX_TIMEOUT:g} seconds for a verification report"
)
args.once = True
args.daemon = False
Expand All @@ -85,7 +66,6 @@ def resolve_models(args):
payload, details = fetch_workspace_model(location, timeout=args.timeout)
args.model_payloads[location] = payload
if args.full_read:
args.product = args.product or details["product"]
args.model_source = {"source": "workspace", "ref": details["ref"]}


Expand Down Expand Up @@ -230,8 +210,7 @@ def build_report(handler, args):
point["expected"] = judged.get(name, "unchecked") if read_ok else "unchecked"
points.append(point)
report = {
"reportVersion": 3,
"product": args.product,
"reportVersion": 4,
"model": {
"sha256": hashlib.sha256(payload).hexdigest(),
"fingerprint": modpoll_wot.model_fingerprint(payload),
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ dependencies = [
"paho-mqtt>=2.1.0,<3.0.0",
"prettytable>=3.9.0,<4.0.0",
"requests>=2.32.5,<3.0.0",
"modpoll-wot==0.5.0a1",
"modpoll-wot==0.6.0a1",
]

[project.optional-dependencies]
Expand Down
Loading
Loading