From d2faa9ed3f41fd4e605b10d96c72572f8400e417 Mon Sep 17 00:00:00 2001 From: Gavin Ying Date: Thu, 12 Nov 2026 19:59:27 +0800 Subject: [PATCH 1/2] feat: sign in to ModioHub, read Workspace Thing Models and upload reports (POLL-02b) modpoll login runs the browser authorization flow and keeps the tool session in the credentials file shared with modsim; logout forgets it. --tm modiohub:@ reads a custom Thing Model with the login (a shared one without), checked against the SHA-256 the server states; --upload shows the full-read report and uploads it after confirmation. Needs modpoll-wot 0.5.0a1, which is not released yet. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 17 +++ modpoll/arg_parser.py | 19 ++- modpoll/login.py | 131 +++++++++++++++++ modpoll/main.py | 36 ++++- modpoll/verification.py | 129 +++++++++++++++-- pyproject.toml | 2 +- tests/test_login.py | 314 ++++++++++++++++++++++++++++++++++++++++ 7 files changed, 631 insertions(+), 17 deletions(-) create mode 100644 modpoll/login.py create mode 100644 tests/test_login.py diff --git a/README.md b/README.md index 6776b36..3c52038 100644 --- a/README.md +++ b/README.md @@ -126,6 +126,23 @@ model.tm.json`), and `--export` still writes the snapshot of the same read. With Model, add `--product /`; the report then names the model as local. The exit code is 1 unless every point was read. +### Sign in to ModioHub, read a Workspace Thing Model and upload the report + +`modpoll login` signs in with your browser: it prints a code and an address (and opens the address where a +browser can open), you confirm the code there, and the 7-day tool session is kept in a file only you can read +(`~/.config/modiohub/credentials.json`, or `%APPDATA%\modiohub` on Windows). modsim uses the same file, so +signing in with either tool signs in both. `MODIOHUB_TOKEN` in the environment replaces the file for scripts, +`MODIOHUB_URL` selects another server, and `login` and `logout` take `--server URL` for the same. `modpoll logout` forgets the login on this computer; +revoke the session in your ModioHub settings to end it on the server. + +Once signed in, `--tm modiohub:@` (`-f` works too; the version is a number or `latest`) reads one +of your custom Thing Models. A shared one needs no login. A full read of it writes a report that names the +Workspace model, and `--upload` shows the report and, after you confirm (or with `--yes`), uploads it: + +```sh +modpoll --tm modiohub:k3x9f2m7q4a8n5bd@latest --tcp 192.168.1.20 --upload +``` + ### 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 21a0dad..4bae190 100644 --- a/modpoll/arg_parser.py +++ b/modpoll/arg_parser.py @@ -25,9 +25,13 @@ def get_parser(): parser.add_argument( "-f", "--config", + "--tm", + dest="config", default=None, help=( - "Local path or URL of a WoT TM/TD JSON configuration. " + "Local path or URL of a WoT TM/TD JSON configuration, or " + "modiohub:@ for a custom Thing Model in your ModioHub " + "Workspace (run modpoll login first unless it is shared). " "Type is detected from content, not the filename. " "Required unless --device is given." ), @@ -59,6 +63,19 @@ def get_parser(): "number or value; review it before sharing. Implies --full-read." ), ) + parser.add_argument( + "--upload", + action="store_true", + help=( + "After a full read, show the report and, once you confirm, upload it to " + "ModioHub (run modpoll login first). Implies --full-read." + ), + ) + parser.add_argument( + "--yes", + action="store_true", + help="Upload without asking for confirmation after the report is shown", + ) parser.add_argument( "--product", metavar="MANUFACTURER/MODEL", diff --git a/modpoll/login.py b/modpoll/login.py new file mode 100644 index 0000000..5ffa8bc --- /dev/null +++ b/modpoll/login.py @@ -0,0 +1,131 @@ +"""Sign in to ModioHub with the browser authorization flow (OAuth device authorization grant, RFC 8628). + +``modpoll login`` asks for a code, the user confirms it in the browser, and the tool session token that comes +back is kept in the credentials file shared with modsim (see modpoll_wot.session). ``modpoll logout`` removes it. +""" + +import sys +import time +import webbrowser + +import modpoll_wot +import requests + +from . import __version__ + +CLIENT_ID = "modpoll" +GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code" +REQUEST_TIMEOUT = 15 + + +class LoginError(ValueError): + """The login did not complete; the message says why and what to do.""" + + +def headers(token=None): + return { + "User-Agent": f"modpoll/{__version__}", + "Accept": "application/json", + **({"Authorization": f"Bearer {token}"} if token else {}), + } + + +def _post(url, body): + try: + return requests.post(url, json=body, headers=headers(), timeout=REQUEST_TIMEOUT) + except requests.RequestException as exc: + raise LoginError(f"Could not reach {url}: {exc}") from exc + + +def login(server, *, sleep=None, monotonic=None, open_browser=None, out=None): + """Run the flow against a server; returns the saved Session.""" + sleep, monotonic = sleep or time.sleep, monotonic or time.monotonic + open_browser, out = open_browser or webbrowser.open, out or sys.stdout + start = _post( + f"{server}/api/v1/tool-sessions/device-authorization", {"client_id": CLIENT_ID} + ) + if not start.ok: + raise LoginError(f"{server} refused the login ({start.status_code})") + grant = start.json() + print( + f"To sign in, confirm the code {grant['user_code']} at:\n {grant['verification_uri_complete']}", + file=out, + flush=True, + ) + # A browser opens only where one can; otherwise the address and code above are all there is. + if not open_browser(grant["verification_uri_complete"]): + print("Open that address in a browser on any computer.", file=out, flush=True) + interval = grant["interval"] + deadline = monotonic() + grant["expires_in"] + while monotonic() < deadline: + sleep(interval) + answer = _post( + f"{server}/api/v1/tool-sessions/token", + { + "grant_type": GRANT_TYPE, + "device_code": grant["device_code"], + "client_id": CLIENT_ID, + }, + ) + body = ( + answer.json() + if answer.headers.get("Content-Type", "").startswith("application/json") + else {} + ) + if answer.ok: + return _save(server, body) + error = body.get("error") + if error == "authorization_pending": + continue + if error == "slow_down": + interval += 5 + continue + if error == "access_denied": + raise LoginError("The login was denied in the browser.") + if error == "expired_token": + break + raise LoginError(f"The login failed ({error or answer.status_code}).") + raise LoginError( + "The code expired before it was confirmed; run modpoll login again." + ) + + +def _save(server, body): + token = body["access_token"] + me = requests.get( + f"{server}/api/v1/me", headers=headers(token), timeout=REQUEST_TIMEOUT + ) + user = me.json().get("githubUser") if me.ok else None + modpoll_wot.save_session( + server, token, expires_in=body["expires_in"], github_user=user + ) + return modpoll_wot.load_session(server) + + +def command(arguments, *, out=None): + """``login`` or ``logout`` with an optional ``--server``; returns the exit code.""" + out = out or sys.stdout + name, rest = arguments[0], arguments[1:] + try: + if rest[:1] == ["--server"] and len(rest) == 2: + server = modpoll_wot.server_url({"MODIOHUB_URL": rest[1]}) + elif not rest: + server = modpoll_wot.server_url() + else: + raise LoginError(f"usage: modpoll {name} [--server URL]") + if name == "logout": + if modpoll_wot.forget_session(server): + print( + f"Signed out of {server} on this computer. The token stays valid on the server until it expires; revoke it in Settings to end it now.", + file=out, + ) + else: + print(f"No stored login for {server}.", file=out) + return 0 + session = login(server, out=out) + who = f" as @{session.github_user}" if session.github_user else "" + print(f"Signed in to {server}{who}. modsim uses the same login.", file=out) + return 0 + except (LoginError, modpoll_wot.CredentialError) as exc: + print(str(exc), file=sys.stderr) + return 1 diff --git a/modpoll/main.py b/modpoll/main.py index 3794408..6a57123 100644 --- a/modpoll/main.py +++ b/modpoll/main.py @@ -14,7 +14,7 @@ snapshot_timestamp_conflicts, ) -from . import __version__, verification +from . import __version__, login, verification from .utils import set_threading_event, delay_thread, on_threading_event, get_utc_time @@ -139,6 +139,8 @@ def _finish_full_read(args, handler): logger.debug("Report error details", exc_info=True) return False print(f"\n{verification.summary(report)}", 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 " @@ -148,6 +150,36 @@ def _finish_full_read(args, handler): return verification.is_full_read(report) +def _upload(args, report): + """Show the report and, once the user agrees, upload it. Returns whether it was uploaded.""" + print("\nReport to upload:\n" + json.dumps(report, indent=2), flush=True) + if not args.yes: + if not sys.stdin.isatty(): + logger.error("Add --yes to upload without being asked.") + return False + if input("Upload this report to ModioHub? [y/N] ").strip().lower() not in ( + "y", + "yes", + ): + print("Not uploaded.", flush=True) + return False + try: + stored = verification.upload_report(report, timeout=args.timeout) + except ValueError 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." + ), + flush=True, + ) + return True + + def _signal_handler(signal_number, frame): if logger: logger.info(f"Exiting {sys.argv[0]}") @@ -159,6 +191,8 @@ def setup_logging(level, format): def app(name="modpoll"): + if sys.argv[1:2] in (["login"], ["logout"]): + sys.exit(login.command(sys.argv[1:])) mqtt_handler = None modbus_handlers = [] diff --git a/modpoll/verification.py b/modpoll/verification.py index 15a029a..2169595 100644 --- a/modpoll/verification.py +++ b/modpoll/verification.py @@ -11,6 +11,7 @@ import os import re import tempfile +import uuid from datetime import datetime, timezone from importlib.metadata import version as package_version from pathlib import Path @@ -19,6 +20,7 @@ import requests from . import __version__ +from .login import headers as api_headers CATALOG_API = "https://api.github.com/repos/top-maker/open-modbus-catalog" MAX_TIMEOUT = 10.0 @@ -39,7 +41,7 @@ def parse_device(text): 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) + args.full_read = args.full_read or bool(args.report) or args.upload if args.device and args.config: raise ValueError("Use either --device or -f, not both") if not args.device and not args.config: @@ -59,10 +61,16 @@ def validate_args(args): 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): + workspace = any( + location.startswith(modpoll_wot.REFERENCE_PREFIX) + for location in args.config or [] + ) + if (args.report or args.upload) and not (args.device or args.product or workspace): raise ValueError( "--report with -f needs --product /" ) + 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 /") if args.timeout > MAX_TIMEOUT: @@ -144,20 +152,113 @@ def _check_github(response): def resolve_models(args): - """For ``--device``, fetch the model and name it as the configuration. + """Fetch the models that are not files: a catalog product (``--device``) or Workspace Thing Models. - The bytes go to ``args.model_payloads`` for the handler, and where they came from to ``args.model_source`` - for the report. + The bytes go to ``args.model_payloads`` for the handlers, and where a full-read model 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} + args.model_payloads = {} + if args.device: + 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} + for location in args.config or []: + if location.startswith(modpoll_wot.REFERENCE_PREFIX): + 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"]} + + +def fetch_workspace_model(text, *, timeout): + """A custom Thing Model version of the user's Workspace: (bytes, {product, ref}). + + The login is used when there is one; a shared version can be read without it. The token only goes to the + server it was issued for, and the download is checked against the SHA-256 the server states. + """ + reference = modpoll_wot.parse_reference(text) + server = modpoll_wot.server_url() + session = modpoll_wot.load_session(server) + token = session.token if session else None + base = f"{server}/api/v1/thing-models/{reference.id}" + + def get(url): + if not url.startswith(server + "/"): + raise ValueError(f"{server} pointed to another address for {text}") + try: + return requests.get(url, headers=api_headers(token), timeout=timeout) + except requests.RequestException as exc: + raise ValueError(f"Could not reach {server}: {exc}") from exc + + response = get(base) + if response.status_code == 401: + raise ValueError("Your ModioHub login is no longer valid; run modpoll login") + if response.status_code == 404: + raise ValueError( + f"No custom Thing Model {reference.id} is shared" + + (" or yours" if token else "; run modpoll login if it is yours") + ) + _check_server(response, server) + thing_model = response.json() + versions = {str(version["version"]): version for version in thing_model["versions"]} + version = ( + versions.get(reference.version) + if reference.version != "latest" + else thing_model["versions"][0] + ) + if version is None: + raise ValueError(f"{text} has no version {reference.version}") + response = get(version["fileUrl"]) + _check_server(response, server) + payload = response.content + if hashlib.sha256(payload).hexdigest() != version["sha256"]: + raise ValueError(f"{text} does not match the SHA-256 {server} reports for it") + return payload, { + "product": thing_model["productId"], + "ref": f"{reference.id}@{version['version']}", + } + + +def _check_server(response, server): + if not response.ok: + raise ValueError(f"{server} answered {response.status_code}") + + +def upload_report(report, *, timeout): + """Upload a report as the signed-in user; returns the stored report summary.""" + server = modpoll_wot.server_url() + session = modpoll_wot.load_session(server) + if session is None: + raise ValueError(f"Sign in to {server} first with modpoll login") + try: + response = requests.post( + f"{server}/api/v1/reports", + json=report, + timeout=timeout, + headers={ + **api_headers(session.token), + "Idempotency-Key": str(uuid.uuid4()), + }, + ) + except requests.RequestException as exc: + raise ValueError(f"Could not reach {server}: {exc}") from exc + 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") + if "json" in response.headers.get("Content-Type", "") + else None + ) + raise ValueError( + f"{server} refused the report: {detail or response.status_code}" + ) + return response.json() def _transport(args): diff --git a/pyproject.toml b/pyproject.toml index 8ce14f0..b543b08 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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.4.0a1", + "modpoll-wot==0.5.0a1", ] [project.optional-dependencies] diff --git a/tests/test_login.py b/tests/test_login.py new file mode 100644 index 0000000..b0a0e84 --- /dev/null +++ b/tests/test_login.py @@ -0,0 +1,314 @@ +"""Sign in, Workspace Thing Models and report upload (POLL-02b).""" + +import hashlib +import io +import json +import os +import stat +import sys + +import modpoll_wot +import pytest + +from modpoll import login, main, utils, verification + +from .test_verification import ( # noqa: F401 (the fixture clears the process-wide stop event) + FakeClient, + PRODUCT, + fresh_stop_event, + run_app, + three_group_model, +) + +SERVER = "https://hub.test" +ID = "k3x9f2m7q4a8n5bd" + + +@pytest.fixture(autouse=True) +def isolated_login(monkeypatch, tmp_path): + monkeypatch.setenv("MODIOHUB_URL", SERVER) + monkeypatch.setenv("MODIOHUB_CREDENTIALS", str(tmp_path / "credentials.json")) + monkeypatch.delenv("MODIOHUB_TOKEN", raising=False) + return tmp_path / "credentials.json" + + +class Reply: + def __init__( + self, status=200, body=None, content=b"", content_type="application/json" + ): + self.status_code, self._body, self.content = status, body, content + self.headers = {"Content-Type": content_type} + self.ok = status < 400 + + def json(self): + return self._body + + +def device_flow(monkeypatch, answers): + """Fake the three requests of a login; `answers` are the token endpoint's replies in order.""" + calls = [] + + def post(url, json=None, headers=None, timeout=None): + calls.append(("POST", url, json)) + if url.endswith("/device-authorization"): + return Reply( + body={ + "device_code": "secret", + "user_code": "ABCD1234", + "interval": 5, + "expires_in": 900, + "verification_uri": f"{SERVER}/activate/", + "verification_uri_complete": f"{SERVER}/activate/?user_code=ABCD1234", + } + ) + return answers.pop(0) + + def get(url, headers=None, timeout=None): + calls.append(("GET", url, headers.get("Authorization"))) + return Reply(body={"githubUser": "octo"}) + + monkeypatch.setattr(login.requests, "post", post) + monkeypatch.setattr(login.requests, "get", get) + return calls + + +def test_login_waits_for_the_browser_and_keeps_one_login_for_both_tools( + monkeypatch, isolated_login +): + answers = [ + Reply(400, {"error": "authorization_pending"}), + Reply(400, {"error": "slow_down"}), + Reply( + 200, {"access_token": "tok", "token_type": "Bearer", "expires_in": 604800} + ), + ] + calls = device_flow(monkeypatch, answers) + slept, out = [], io.StringIO() + session = login.login( + SERVER, sleep=slept.append, open_browser=lambda url: False, out=out + ) + assert slept == [5, 5, 10] # slow_down adds five seconds + assert ( + "ABCD1234" in out.getvalue() + and f"{SERVER}/activate/?user_code=ABCD1234" in out.getvalue() + ) + assert "Open that address in a browser" in out.getvalue() + assert calls[0][2] == {"client_id": "modpoll"} + assert ("GET", f"{SERVER}/api/v1/me", "Bearer tok") in calls + assert (session.token, session.github_user, session.source) == ( + "tok", + "octo", + "file", + ) + # modsim reads the same file through modpoll-wot. + assert modpoll_wot.load_session(SERVER).token == "tok" + if os.name == "posix": + assert stat.S_IMODE(isolated_login.stat().st_mode) == 0o600 + + +@pytest.mark.parametrize( + "reply, message", + [ + (Reply(400, {"error": "access_denied"}), "denied"), + (Reply(400, {"error": "expired_token"}), "expired"), + (Reply(500, None, content_type="text/plain"), "failed"), + ], +) +def test_login_ends_with_a_reason(monkeypatch, reply, message): + device_flow(monkeypatch, [reply]) + with pytest.raises(login.LoginError, match=message): + login.login( + SERVER, + sleep=lambda seconds: None, + open_browser=lambda url: True, + out=io.StringIO(), + ) + assert modpoll_wot.load_session(SERVER) is None + + +def test_the_code_expires_when_nobody_confirms(monkeypatch): + device_flow(monkeypatch, [Reply(400, {"error": "authorization_pending"})] * 100) + clock = iter(range(0, 10_000, 400)) + with pytest.raises(login.LoginError, match="expired"): + login.login( + SERVER, + sleep=lambda seconds: None, + monotonic=lambda: next(clock), + open_browser=lambda url: True, + out=io.StringIO(), + ) + + +def test_login_and_logout_commands(monkeypatch, capsys): + device_flow(monkeypatch, [Reply(200, {"access_token": "tok", "expires_in": 60})]) + monkeypatch.setattr(login.webbrowser, "open", lambda url: True) + monkeypatch.setattr(login.time, "sleep", lambda seconds: None) + assert login.command(["login"]) == 0 + assert ( + "Signed in to https://hub.test as @octo. modsim uses the same login." + in capsys.readouterr().out + ) + assert login.command(["logout"]) == 0 + assert "revoke it in Settings" in capsys.readouterr().out + assert login.command(["logout"]) == 0 + assert "No stored login" in capsys.readouterr().out + assert login.command(["login", "--server", "http://example.com"]) == 1 + assert login.command(["login", "--bogus"]) == 1 + + +def test_login_and_logout_run_before_the_normal_arguments(monkeypatch): + monkeypatch.setattr(sys, "argv", ["modpoll", "logout"]) + with pytest.raises(SystemExit) as exit_info: + main.app() + assert exit_info.value.code == 0 + + +def workspace( + monkeypatch, *, payload, versions=None, status=200, file_url=None, sha256=None +): + versions = versions or [ + { + "version": 2, + "sha256": sha256 or hashlib.sha256(payload).hexdigest(), + "fileUrl": file_url or f"{SERVER}/api/v1/thing-models/{ID}/versions/2/file", + } + ] + seen = [] + + def get(url, headers=None, timeout=None): + seen.append((url, headers.get("Authorization"))) + if url.endswith(f"/thing-models/{ID}"): + return Reply(status, {"productId": PRODUCT, "versions": versions}) + return Reply(200, content=payload) + + monkeypatch.setattr(verification.requests, "get", get) + return seen + + +def test_a_workspace_model_is_fetched_with_the_login_and_checked(monkeypatch): + payload = json.dumps(three_group_model()).encode() + modpoll_wot.save_session(SERVER, "tok", expires_in=3600, github_user="octo") + seen = workspace(monkeypatch, payload=payload) + assert verification.fetch_workspace_model(f"modiohub:{ID}@latest", timeout=3) == ( + payload, + {"product": PRODUCT, "ref": f"{ID}@2"}, + ) + assert {token for _, token in seen} == {"Bearer tok"} + with pytest.raises(ValueError, match="no version 5"): + verification.fetch_workspace_model(f"modiohub:{ID}@5", timeout=3) + + +def test_a_shared_model_needs_no_login_and_a_private_one_says_so(monkeypatch): + payload = b'{"title": "x"}' + seen = workspace(monkeypatch, payload=payload) + verification.fetch_workspace_model(f"modiohub:{ID}@2", timeout=3) + assert {token for _, token in seen} == {None} + workspace(monkeypatch, payload=payload, status=404) + with pytest.raises(ValueError, match="run modpoll login if it is yours"): + verification.fetch_workspace_model(f"modiohub:{ID}", timeout=3) + + +def test_a_download_that_does_not_match_or_leaves_the_server_is_refused(monkeypatch): + modpoll_wot.save_session(SERVER, "tok", expires_in=3600) + workspace(monkeypatch, payload=b"{}", sha256="0" * 64) + with pytest.raises(ValueError, match="SHA-256"): + verification.fetch_workspace_model(f"modiohub:{ID}@2", timeout=3) + seen = workspace( + monkeypatch, payload=b"{}", file_url="https://elsewhere.test/model.json" + ) + with pytest.raises(ValueError, match="another address"): + verification.fetch_workspace_model(f"modiohub:{ID}@2", timeout=3) + assert all(url.startswith(SERVER) for url, _ in seen) + + +def test_full_read_of_a_workspace_model_names_the_workspace_as_its_source( + monkeypatch, tmp_path +): + payload = json.dumps(three_group_model()).encode() + workspace(monkeypatch, payload=payload) + report_path = tmp_path / "report.json" + with pytest.raises(SystemExit): + run_app( + monkeypatch, + ["--tm", f"modiohub:{ID}@2", "--tcp", "x", "--report", str(report_path)], + FakeClient(), + ) + report = json.loads(report_path.read_text()) + assert report["product"] == PRODUCT + assert ( + report["model"]["source"] == "workspace" and report["model"]["ref"] == f"{ID}@2" + ) + modpoll_wot.validate_report(report, model=payload) + + +def test_upload_shows_the_report_and_sends_it_with_the_login( + monkeypatch, tmp_path, capsys +): + payload = json.dumps(three_group_model()).encode() + path = tmp_path / "meter.tm.json" + path.write_bytes(payload) + modpoll_wot.save_session(SERVER, "tok", expires_in=3600) + sent = {} + + def post(url, json=None, headers=None, timeout=None): + sent.update(url=url, body=json, headers=headers) + return Reply(201, {"id": "p7n2d9x4k8m3q5ra", "fullRead": True}) + + monkeypatch.setattr(verification.requests, "post", post) + run_app( + monkeypatch, + ["-f", str(path), "--tcp", "x", "--product", PRODUCT, "--upload", "--yes"], + FakeClient(False, False), + ) + out = capsys.readouterr().out + assert "Report to upload:" in out and "Uploaded. This is a full read" in out + assert ( + sent["url"] == f"{SERVER}/api/v1/reports" and sent["body"]["reportVersion"] == 3 + ) + assert ( + sent["headers"]["Authorization"] == "Bearer tok" + and sent["headers"]["Idempotency-Key"] + ) + + +def test_upload_asks_first_and_needs_a_login(monkeypatch, tmp_path, capsys): + path = tmp_path / "meter.tm.json" + path.write_text(json.dumps(three_group_model())) + posted = [] + monkeypatch.setattr( + verification.requests, + "post", + lambda *args, **kwargs: posted.append(args) or Reply(201, {"fullRead": True}), + ) + arguments = ["-f", str(path), "--tcp", "x", "--product", PRODUCT, "--upload"] + # Not a terminal and no --yes: nothing is sent. + with pytest.raises(SystemExit) as exit_info: + run_app(monkeypatch, arguments, FakeClient(False, False)) + assert exit_info.value.code == 1 and not posted + # A terminal where the user declines. + utils._thread_event.clear() + monkeypatch.setattr(sys.stdin, "isatty", lambda: True) + monkeypatch.setattr("builtins.input", lambda prompt: "n") + with pytest.raises(SystemExit): + run_app(monkeypatch, arguments, FakeClient(False, False)) + assert "Not uploaded." in capsys.readouterr().out and not posted + # Agreeing without a login. + utils._thread_event.clear() + monkeypatch.setattr("builtins.input", lambda prompt: "y") + with pytest.raises(SystemExit): + run_app(monkeypatch, arguments, FakeClient(False, False)) + assert not posted + + +def test_a_refused_upload_reports_why(monkeypatch): + modpoll_wot.save_session(SERVER, "tok", expires_in=3600) + monkeypatch.setattr( + verification.requests, + "post", + lambda *a, **k: Reply(422, {"detail": "No product x/y in the catalog."}), + ) + with pytest.raises(ValueError, match="No product x/y"): + verification.upload_report({}, timeout=3) + monkeypatch.setattr(verification.requests, "post", lambda *a, **k: Reply(401, {})) + with pytest.raises(ValueError, match="modpoll login"): + verification.upload_report({}, timeout=3) From bd3e3bef72b6469b9dc8e3e4735b03b4a9b220d5 Mon Sep 17 00:00:00 2001 From: Gavin Ying Date: Thu, 12 Nov 2026 20:28:02 +0800 Subject: [PATCH 2/2] chore: release 2.0.0a7 with modpoll-wot 0.5.0a1 Co-Authored-By: Claude Sonnet 5.5 --- README.md | 10 +++++----- docs/preview-notes.md | 16 ++++++++++++++-- docs/site/installation.rst | 10 +++++----- pyproject.toml | 2 +- uv.lock | 10 +++++----- 5 files changed, 30 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 3c52038..713a089 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 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.0a7'`; 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 @@ -47,13 +47,13 @@ This tool requires Python 3.10+ (Ubuntu 22.04+ or equivalent) and is available o Install *modpoll* using the following command, ```bash -uv tool install --prerelease allow "modpoll==2.0.0a6" +uv tool install --prerelease allow "modpoll==2.0.0a7" ``` Optionally, [pyserial](https://pyserial.readthedocs.io/) library can be installed for Modbus-RTU communication, ```bash -uv tool install --prerelease allow 'modpoll[serial]==2.0.0a6' +uv tool install --prerelease allow 'modpoll[serial]==2.0.0a7' ``` Upgrade the tool via the following command, @@ -171,7 +171,7 @@ so `modsim --config device.tm.json --data snapshot.json` replays it locally. A docker image has been provided for user to directly run the tool without local installation, ```bash - docker run --rm topmaker/modpoll:2.0.0a6 + docker run --rm topmaker/modpoll:2.0.0a7 ``` It shows the version of the tool by default. @@ -183,7 +183,7 @@ If you want to load a local configure file, you need to mount a local folder ont for example, if the child folder `examples` contains the config file `modsim.tm.json`, we can use it via the following command, ```bash - docker run --rm --network host -v "$(pwd)/examples:/app/examples:ro" topmaker/modpoll:2.0.0a6 \ + docker run --rm --network host -v "$(pwd)/examples:/app/examples:ro" topmaker/modpoll:2.0.0a7 \ modpoll -d \ --tcp 127.0.0.1 --tcp-port 5020 \ --config /app/examples/modsim.tm.json diff --git a/docs/preview-notes.md b/docs/preview-notes.md index 0feb75d..6ff2b96 100644 --- a/docs/preview-notes.md +++ b/docs/preview-notes.md @@ -1,7 +1,19 @@ -# Modpoll 2.0.0a6 preview +# Modpoll 2.0.0a7 preview + +Modpoll 2.0.0a7 pins modpoll-wot 0.5.0a1 and connects to ModioHub: + +- `--device /[@commit]` reads the baseline Thing Model of a catalog product. +- `--full-read` reads every point once, read-only and without retries; `--report FILE` writes the + verification report (schema 3), which holds no address, Unit ID, serial number or value. +- `modpoll login` signs in with your browser and `modpoll logout` forgets the login. The 7-day tool session + is kept in `~/.config/modiohub/credentials.json` and is shared with modsim 2.0.0a9. +- `--tm modiohub:@` reads a custom Thing Model from your ModioHub Workspace, and `--upload` shows + the report of a full read and uploads it after you confirm. + +## Modpoll 2.0.0a6 preview Modpoll 2.0.0a6 pins modpoll-wot 0.4.0a1, which defines simulation data. A -`--export` snapshot is simulation data as it stands, so modsim 2.0.0a7 can +`--export` snapshot is simulation data as it stands, so modsim 2.0.0a8 can replay a device read once, on your computer: ```sh diff --git a/docs/site/installation.rst b/docs/site/installation.rst index 46a1534..7911e06 100644 --- a/docs/site/installation.rst +++ b/docs/site/installation.rst @@ -3,11 +3,11 @@ Installation This documentation describes the 2.x functional preview. Install the exact version:: - uv tool install --prerelease allow 'modpoll[serial]==2.0.0a6' + uv tool install --prerelease allow 'modpoll[serial]==2.0.0a7' For existing CSV installations use ``uv tool install 'modpoll<2'`` and the `1.x documentation `_. -The preview image is ``topmaker/modpoll:2.0.0a6``; stable ``latest`` stays on 1.x. +The preview image is ``topmaker/modpoll:2.0.0a7``; stable ``latest`` stays on 1.x. See :doc:`v1-compatibility` for tested platforms and hardware limitations. This program is tested on python 3.10+ (Ubuntu 22.04+ or equivalent). Ubuntu 20.04 and python 3.8 are no longer supported. @@ -19,13 +19,13 @@ The package is available in the `Python Package Index `_, .. code-block:: shell - uv tool install --prerelease allow "modpoll==2.0.0a6" + uv tool install --prerelease allow "modpoll==2.0.0a7" Optionally, pyserial library can be installed for Modbus-RTU communication, .. code-block:: shell - uv tool install --prerelease allow 'modpoll[serial]==2.0.0a6' + uv tool install --prerelease allow 'modpoll[serial]==2.0.0a7' Run the following command to check if there is new version available, @@ -51,6 +51,6 @@ without the local installation, .. code-block:: shell - docker run --rm topmaker/modpoll:2.0.0a6 + docker run --rm topmaker/modpoll:2.0.0a7 It shows the version of the tool by default. diff --git a/pyproject.toml b/pyproject.toml index b543b08..adda1fd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "modpoll" -version = "2.0.0a6" +version = "2.0.0a7" description = "A New Command-line Tool for Modbus and MQTT" authors = [{ name = "Ying Shaodong", email = "helloysd@gmail.com" }] readme = "README.md" diff --git a/uv.lock b/uv.lock index ef83344..5c002bb 100644 --- a/uv.lock +++ b/uv.lock @@ -683,7 +683,7 @@ wheels = [ [[package]] name = "modpoll" -version = "2.0.0a6" +version = "2.0.0a7" source = { editable = "." } dependencies = [ { name = "modpoll-wot", marker = "python_full_version < '3.15'" }, @@ -717,7 +717,7 @@ docs = [ [package.metadata] requires-dist = [ - { name = "modpoll-wot", specifier = "==0.4.0a1" }, + { name = "modpoll-wot", specifier = "==0.5.0a1" }, { name = "paho-mqtt", specifier = ">=2.1.0,<3.0.0" }, { name = "prettytable", specifier = ">=3.9.0,<4.0.0" }, { name = "pymodbus", specifier = "~=3.16.1" }, @@ -745,15 +745,15 @@ docs = [ [[package]] name = "modpoll-wot" -version = "0.4.0a1" +version = "0.5.0a1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "jsonschema", marker = "python_full_version < '3.15'" }, { name = "referencing", marker = "python_full_version < '3.15'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/f6/19/f27b28a5e50b5ff8c7cb25e3593df58f31c65d4da5f29d051d29ee0f4d2a/modpoll_wot-0.4.0a1.tar.gz", hash = "sha256:81d25997407a64799a034ad4df9c53dbb4f8a7842f4416dacb81a7e26d95b6b6", size = 54976, upload-time = "2026-11-12T03:52:27.323Z" } +sdist = { url = "https://files.pythonhosted.org/packages/2b/a4/477adeef74d9b4ce969ab377e9d00c90c115ab006aea6bb15dd3dd4c3176/modpoll_wot-0.5.0a1.tar.gz", hash = "sha256:c510a352bedf2c01a8d42abf21b394cacab208e46277c82e4531ea3799195cb1", size = 59242, upload-time = "2026-11-12T12:24:59.788Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e4/d3/4400813559fd11ca7d758d5ab343505366a7dd94c65be0c293b8048d915c/modpoll_wot-0.4.0a1-py3-none-any.whl", hash = "sha256:9708d2cadf65ce93626eb5755905f25e7aedcc1b9746e66277d5d94f08aa4c76", size = 46936, upload-time = "2026-11-12T03:52:26.239Z" }, + { url = "https://files.pythonhosted.org/packages/89/3a/a24f047c949d4b866ea0f511a2d1f7f1c15bbb13249755dfcfb0bdf8e3f3/modpoll_wot-0.5.0a1-py3-none-any.whl", hash = "sha256:59dcd551d95ebd549de3e3e04170d7dec2fe8ea58e643e2b6d5ab6d91b0acb21", size = 50246, upload-time = "2026-11-12T12:24:58.568Z" }, ] [[package]]