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
10 changes: 5 additions & 5 deletions docs/guide/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ This site describes the 2.x preview. The three tools need Python 3.10 or later a
Windows PowerShell.

```bash
uv tool install --prerelease allow "modpoll==2.0.0a14"
uv tool install --prerelease allow "modsim==2.0.0a16"
uv tool install --prerelease allow "modpoll-wot==0.7.0a3"
uv tool install --prerelease allow "modpoll==2.0.0a15"
uv tool install --prerelease allow "modsim==2.0.0a17"
uv tool install --prerelease allow "modpoll-wot==0.7.0a4"
```

Modbus RTU support (pyserial) is included in modpoll since 2.0.0a12. For existing CSV installations use
Expand All @@ -30,14 +30,14 @@ package ships `py.typed`.
The preview images run without a local installation and show the tool version by default:

```bash
docker run --rm topmaker/modpoll:2.0.0a14
docker run --rm topmaker/modpoll:2.0.0a15
```

The stable `latest` tag stays on 1.x. To read a local configuration file, mount its folder into the container.
On Linux, host networking connects the container to a simulator on the host; `-d` (daemon mode) suppresses the
tables:

```bash
docker run --rm --network host -v "$(pwd)/examples:/app/examples:ro" topmaker/modpoll:2.0.0a14 \
docker run --rm --network host -v "$(pwd)/examples:/app/examples:ro" topmaker/modpoll:2.0.0a15 \
modpoll -d --tcp 127.0.0.1 --tcp-port 5020 --config /app/examples/modsim.tm.json
```
2 changes: 1 addition & 1 deletion packages/modpoll-wot/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "modpoll-wot"
version = "0.7.0a3"
version = "0.7.0a4"
description = "Shared WoT Modbus configuration interpreter"
authors = [{ name = "Ying Shaodong", email = "helloysd@gmail.com" }]
readme = "README.md"
Expand Down
2 changes: 1 addition & 1 deletion packages/modpoll/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ A command-line tool that reads Modbus TCP and RTU devices from a W3C WoT Thing M
MQTT and writes verification reports. v1 CSV configurations keep working.

```bash
uv tool install --prerelease allow "modpoll==2.0.0a14"
uv tool install --prerelease allow "modpoll==2.0.0a15"
modpoll --once --tcp 192.168.1.10 --config device.tm.json
```

Expand Down
13 changes: 12 additions & 1 deletion packages/modpoll/docs/preview-notes.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,15 @@
# Modpoll 2.0.0a14 preview
# Modpoll 2.0.0a15 preview

Modpoll 2.0.0a15 pins modpoll-wot 0.7.0a4, which publishes the rejection vectors for other implementations of the
Thing Model rules (`conformance.rejections.json`, with no change to the package code).

- `modpoll login` prints what ModioHub answered when it refuses a sign-in, as an upload already did: during
maintenance or when the request limit is reached you see the platform's explanation and, when it sends one, how
long to wait. The exit code is not zero and the tool never retries on its own.
- Every request to ModioHub (reading a `--config` link, the API, signing in, a Workspace download and a report
upload) identifies the tool as `modpoll/<version> (+https://github.com/top-maker/modpoll)`.

## Modpoll 2.0.0a14 preview

Modpoll 2.0.0a14 pins modpoll-wot 0.7.0a3 and moves its documentation to the shared site for modpoll, modsim
and modpoll-wot at <https://top-maker.github.io/modpoll/v2/>. The `--upload` help names saved reports
Expand Down
49 changes: 41 additions & 8 deletions packages/modpoll/modpoll/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import sys
import time
import webbrowser
from http import HTTPStatus

import modpoll_wot
import requests
Expand All @@ -19,6 +20,9 @@
CLIENT_ID = "modpoll"
GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code"
REQUEST_TIMEOUT = 15
PROJECT_URL = "https://github.com/top-maker/modpoll"
# The one identity of every request this tool makes to ModioHub or to a --config link (the tool User-Agent).
USER_AGENT = f"modpoll/{__version__} (+{PROJECT_URL})"


class LoginError(ValueError):
Expand All @@ -27,12 +31,41 @@ class LoginError(ValueError):

def headers(token=None):
return {
"User-Agent": f"modpoll/{__version__}",
"User-Agent": USER_AGENT,
"Accept": "application/json",
**({"Authorization": f"Bearer {token}"} if token else {}),
}


def _body(response):
"""The JSON object of an answer, or {} when it is plain text (the edge answers some refusals so)."""
if "json" not in response.headers.get("Content-Type", ""):
return {}
try:
body = response.json()
except ValueError:
return {}
return body if isinstance(body, dict) else {}


def _why(response):
"""What the platform said about a refusal: its detail (or the status name) and how long to wait."""
status = response.status_code
try:
phrase = HTTPStatus(status).phrase
except ValueError:
phrase = "refused"
text = _body(response).get("detail") or phrase
if not text.endswith("."):
text += "."
wait = response.headers.get("Retry-After")
if wait and wait.isdigit():
text += f" Wait {wait} seconds before trying again."
elif wait:
text += f" Retry after {wait}."
return text


def _post(url, body):
try:
return requests.post(url, json=body, headers=headers(), timeout=REQUEST_TIMEOUT)
Expand Down Expand Up @@ -81,7 +114,9 @@ def login(server, *, sleep=None, monotonic=None, open_browser=None, out=None):
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})")
raise LoginError(
f"{server} refused the login ({start.status_code}): {_why(start)}"
)
grant = start.json()
print(
f"To sign in, confirm the code {grant['user_code']} at:\n {grant['verification_uri_complete']}",
Expand All @@ -107,11 +142,7 @@ def login(server, *, sleep=None, monotonic=None, open_browser=None, out=None):
"client_id": CLIENT_ID,
},
)
body = (
answer.json()
if answer.headers.get("Content-Type", "").startswith("application/json")
else {}
)
body = _body(answer)
if answer.ok:
return _save(server, body)
error = body.get("error")
Expand All @@ -124,7 +155,9 @@ def login(server, *, sleep=None, monotonic=None, open_browser=None, out=None):
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}).")
if error:
raise LoginError(f"The login failed ({error}).")
raise LoginError(f"The login failed ({answer.status_code}): {_why(answer)}")
raise LoginError(
"The code expired before it was confirmed; run modpoll login again."
)
Expand Down
6 changes: 5 additions & 1 deletion packages/modpoll/modpoll/wot_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,15 @@
from modpoll_wot import MAX_BYTES, loads_model
import requests

from .login import headers


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:
with requests.get(
location, headers=headers(), timeout=timeout, stream=True
) as response:
response.raise_for_status()
chunks, size = [], 0
for chunk in response.iter_content(65536):
Expand Down
4 changes: 2 additions & 2 deletions packages/modpoll/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "modpoll"
version = "2.0.0a14"
version = "2.0.0a15"
description = "A New Command-line Tool for Modbus and MQTT"
authors = [{ name = "Ying Shaodong", email = "helloysd@gmail.com" }]
readme = "README.md"
Expand All @@ -12,7 +12,7 @@ dependencies = [
"requests>=2.32.5,<3.0.0",
# Modbus RTU works out of the box; pyserial is pure Python and installs everywhere.
"pyserial>=3.5,<4.0",
"modpoll-wot==0.7.0a3",
"modpoll-wot==0.7.0a4",
]

[project.optional-dependencies]
Expand Down
141 changes: 138 additions & 3 deletions packages/modpoll/tests/test_login.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@
import io
import json
import os
import re
import stat
import sys

import modpoll_wot
import pytest

from modpoll import login, main, utils, verification
from modpoll import __version__, login, main, utils, verification, wot_config

from .test_verification import ( # noqa: F401 (the fixture clears the process-wide stop event)
FakeClient,
Expand All @@ -34,10 +35,15 @@ def isolated_login(monkeypatch, tmp_path):

class Reply:
def __init__(
self, status=200, body=None, content=b"", content_type="application/json"
self,
status=200,
body=None,
content=b"",
content_type="application/json",
headers=None,
):
self.status_code, self._body, self.content = status, body, content
self.headers = {"Content-Type": content_type}
self.headers = {"Content-Type": content_type, **(headers or {})}
self.ok = status < 400

def json(self):
Expand Down Expand Up @@ -126,6 +132,79 @@ def test_login_ends_with_a_reason(monkeypatch, reply, message):
assert modpoll_wot.load_session(SERVER) is None


MAINTENANCE = Reply(
503,
{
"title": "Service Unavailable",
"code": "maintenance",
"detail": "The service is in maintenance. Reading works; saving, uploading and signing in are paused. Try again later.",
},
content_type="application/problem+json",
headers={"Retry-After": "300"},
)
RATE_LIMIT = Reply(
429,
{"code": "rate-limit", "detail": "Too many requests. Try again later."},
content_type="application/problem+json",
headers={"Retry-After": "42"},
)
# The edge rule answers before the API does, in plain text.
EDGE_RATE_LIMIT = Reply(
429,
None,
content_type="text/plain; charset=UTF-8",
headers={"Retry-After": "10"},
)


@pytest.mark.parametrize(
"reply, expected",
[
(
MAINTENANCE,
["(503)", "in maintenance", "Wait 300 seconds before trying again."],
),
(
RATE_LIMIT,
["(429)", "Too many requests", "Wait 42 seconds before trying again."],
),
(
EDGE_RATE_LIMIT,
["(429): Too Many Requests.", "Wait 10 seconds before trying again."],
),
],
)
@pytest.mark.parametrize("step", ["start", "poll"])
def test_a_refused_login_says_why_and_exits_non_zero(
monkeypatch, capsys, reply, expected, step
):
posts = []

def post(url, json=None, headers=None, timeout=None):
posts.append(url)
if step == "start" or not url.endswith("/device-authorization"):
return reply
return Reply(
body={
"device_code": "secret",
"user_code": "ABCD1234",
"interval": 5,
"expires_in": 900,
"verification_uri_complete": f"{SERVER}/activate/?user_code=ABCD1234",
}
)

monkeypatch.setattr(login.requests, "post", post)
monkeypatch.setattr(login, "open_in_browser", lambda url: False)
monkeypatch.setattr(login.time, "sleep", lambda seconds: None)
assert login.command(["login"]) == 1
error = capsys.readouterr().err
assert all(text in error for text in expected), error
assert "Traceback" not in error
# One refusal ends the login: the tool never retries on its own.
assert len(posts) == (1 if step == "start" else 2)


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))
Expand Down Expand Up @@ -331,6 +410,62 @@ def test_a_refused_upload_reports_why(monkeypatch):
verification.upload_report({}, timeout=3)


def test_an_upload_in_maintenance_keeps_the_local_report(monkeypatch, tmp_path, caplog):
path = tmp_path / "meter.tm.json"
path.write_text(json.dumps(three_group_model()))
monkeypatch.chdir(tmp_path)
modpoll_wot.save_session(SERVER, "tok", expires_in=3600)
posts = []
monkeypatch.setattr(
verification.requests,
"post",
lambda *args, **kwargs: posts.append(args) or MAINTENANCE,
)
with pytest.raises(SystemExit) as exit_info:
run_app(
monkeypatch,
["-f", str(path), "--tcp", "x", "--report", "--yes"],
FakeClient(False, False),
)
assert exit_info.value.code == 1 and len(posts) == 1
assert "in maintenance" in caplog.text and "refused the report" in caplog.text
(saved,) = tmp_path.glob("report-*.json")
assert json.loads(saved.read_text())["reportVersion"] == 5


def test_every_request_to_modiohub_carries_the_tool_user_agent(monkeypatch, tmp_path):
"""Sign-in, API, Workspace download, upload and a --config link all identify the tool the same way."""
seen = {}

def record(kind):
def fake(*args, **kwargs):
url = args[-1] if kind == "request" else args[0]
seen[(kind, url.rsplit("/", 1)[-1])] = kwargs["headers"]["User-Agent"]
raise login.requests.RequestException("stop here")

return fake

monkeypatch.setattr(login.requests, "get", record("get"))
monkeypatch.setattr(login.requests, "post", record("post"))
monkeypatch.setattr(login.requests, "request", record("request"))
modpoll_wot.save_session(SERVER, "tok", expires_in=3600)
with pytest.raises(login.LoginError):
login.login(SERVER) # device authorization
with pytest.raises(ValueError):
verification.upload_report({}, timeout=3) # upload
with pytest.raises(ValueError):
verification.search_products("meter", timeout=3) # API
with pytest.raises(ValueError):
verification.fetch_workspace_model(f"modiohub:{ID}@1", timeout=3) # Workspace
with pytest.raises(login.requests.RequestException):
wot_config.read_payload("https://example.test/m.tm.json", timeout=3) # --config
assert len(seen) == 5, seen
(agent,) = set(seen.values())
assert agent == f"modpoll/{__version__} (+https://github.com/top-maker/modpoll)"
assert re.fullmatch(r"modpoll/\S+ \(\+https://\S+\)", agent)
assert agent == login.USER_AGENT == login.headers()["User-Agent"]


def test_upload_signs_in_inline_when_there_is_no_session(monkeypatch, tmp_path, capsys):
"""An interactive upload without a login starts the browser flow and continues with the session."""
path = tmp_path / "meter.tm.json"
Expand Down
6 changes: 5 additions & 1 deletion packages/modpoll/tests/test_wot_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import pytest

from modpoll import login
from modpoll.modbus_task import ModbusHandler
from modpoll.wot_config import read_model, create_devices
from tests.wot_helpers import meter_model, write_meter
Expand Down Expand Up @@ -49,7 +50,10 @@ def get(url, **kwargs):
model = read_model("https://example.test/model.tm.json", timeout=2.5, unit_id=7)
assert model.unit_id == 7
assert calls == [
("https://example.test/model.tm.json", {"timeout": 2.5, "stream": True})
(
"https://example.test/model.tm.json",
{"headers": login.headers(), "timeout": 2.5, "stream": True},
)
]


Expand Down
2 changes: 1 addition & 1 deletion packages/modsim/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ A Modbus device simulator for integration and testing. It runs a device from a W
data, over Modbus TCP or a virtual serial port, and runs several devices on one listener from a deployment file.

```bash
uv tool install --prerelease allow "modsim==2.0.0a16"
uv tool install --prerelease allow "modsim==2.0.0a17"
modsim --config device.tm.json --port 5020
```

Expand Down
Loading
Loading