diff --git a/README.md b/README.md index 3233785..3ba0cdd 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -> **2.x development branch.** This checkout accepts v1 CSV and WoT TM/TD JSON using profile 0.2; `--config` detects the format from the content. 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`. +> **2.x development branch.** This checkout accepts v1 CSV and WoT TM/TD JSON using profile 0.2; `--config` detects the format from the content. Install the current preview with `uv tool install --prerelease allow 'modpoll[serial]==2.0.0a8'`; 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.0a7" +uv tool install --prerelease allow "modpoll==2.0.0a8" ``` Optionally, [pyserial](https://pyserial.readthedocs.io/) library can be installed for Modbus-RTU communication, ```bash -uv tool install --prerelease allow 'modpoll[serial]==2.0.0a7' +uv tool install --prerelease allow 'modpoll[serial]==2.0.0a8' ``` Upgrade the tool via the following command, @@ -172,7 +172,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.0a7 + docker run --rm topmaker/modpoll:2.0.0a8 ``` It shows the version of the tool by default. @@ -184,7 +184,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.0a7 \ + docker run --rm --network host -v "$(pwd)/examples:/app/examples:ro" topmaker/modpoll:2.0.0a8 \ 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 53a3087..f3af8ca 100644 --- a/docs/preview-notes.md +++ b/docs/preview-notes.md @@ -1,14 +1,32 @@ -# Modpoll 2.0.0a7 preview +# 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 +configurations: + +- `modpoll verify --config MODEL --tcp HOST` replaces `--device` and `--full-read`: it reads every point of a + Thing Model once, read-only and without retries, and reports which points could be read. `--report FILE` + writes the verification report (schema 3), which holds no address, Unit ID, serial number or value, and + `--upload` shows the report and uploads it after you confirm. `--device`, `--chassis`, `--firmware` and + `--configuration` are removed: give the model with `--config` (a file, an address, or a Workspace model) and + the catalog product with `--product /`. +- `--config` (`-f`) is the only configuration argument; `--tm` is removed. It takes a WoT Thing Model or + Thing Description, a v1 CSV file (detected from the content), or `modiohub:@`, a custom Thing + Model from your ModioHub Workspace. +- `modpoll login` prints the sign-in link and opens a browser only where one can be opened; the opener's + output no longer fills the terminal, and Ctrl-C cancels with one line. `modsim login` behaves the same in + modsim 2.0.0a10. + +## Modpoll 2.0.0a7 preview Modpoll 2.0.0a7 pins modpoll-wot 0.5.0a1 and connects to ModioHub: -- `modpoll verify --config MODEL --tcp HOST` reads every point of a Thing Model once, read-only and without - retries, and reports which points could be read; `--report FILE` writes the verification report (schema 3), - which holds no address, Unit ID, serial number or value. +- `--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. -- `--config modiohub:@` reads a custom Thing Model from your ModioHub Workspace, and - `modpoll verify --config ... --upload` shows the report and uploads it after you confirm. +- `--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 diff --git a/docs/site/installation.rst b/docs/site/installation.rst index 7911e06..37e2d7c 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.0a7' + uv tool install --prerelease allow 'modpoll[serial]==2.0.0a8' For existing CSV installations use ``uv tool install 'modpoll<2'`` and the `1.x documentation `_. -The preview image is ``topmaker/modpoll:2.0.0a7``; stable ``latest`` stays on 1.x. +The preview image is ``topmaker/modpoll:2.0.0a8``; 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.0a7" + uv tool install --prerelease allow "modpoll==2.0.0a8" Optionally, pyserial library can be installed for Modbus-RTU communication, .. code-block:: shell - uv tool install --prerelease allow 'modpoll[serial]==2.0.0a7' + uv tool install --prerelease allow 'modpoll[serial]==2.0.0a8' 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.0a7 + docker run --rm topmaker/modpoll:2.0.0a8 It shows the version of the tool by default. diff --git a/modpoll/login.py b/modpoll/login.py index 5ffa8bc..b053bd1 100644 --- a/modpoll/login.py +++ b/modpoll/login.py @@ -4,6 +4,9 @@ back is kept in the credentials file shared with modsim (see modpoll_wot.session). ``modpoll logout`` removes it. """ +import os +import shutil +import subprocess import sys import time import webbrowser @@ -37,10 +40,43 @@ def _post(url, body): raise LoginError(f"Could not reach {url}: {exc}") from exc +def open_in_browser( + url, *, environ=None, platform=None, run=subprocess.run, which=shutil.which +): + """Try to open an address in a browser; False means the user has to open it from the printed link. + + Where there is no desktop (SSH, a minimal WSL) nothing is tried, and the opener's own complaints + never reach the terminal. + """ + environ = os.environ if environ is None else environ + platform = platform or sys.platform + if environ.get("BROWSER") or platform in ("darwin", "win32"): + return webbrowser.open(url) + if not (environ.get("DISPLAY") or environ.get("WAYLAND_DISPLAY")) or environ.get( + "SSH_CONNECTION" + ): + return False + opener = which("xdg-open") + if not opener: + return False + try: + return ( + run( + [opener, url], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=10, + ).returncode + == 0 + ) + except (OSError, subprocess.SubprocessError): + return False + + 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 + open_browser, out = open_browser or open_in_browser, out or sys.stdout start = _post( f"{server}/api/v1/tool-sessions/device-authorization", {"client_id": CLIENT_ID} ) @@ -54,7 +90,11 @@ def login(server, *, sleep=None, monotonic=None, open_browser=None, out=None): ) # 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) + print( + "Open the address above in a browser on any computer, then wait here.", + file=out, + flush=True, + ) interval = grant["interval"] deadline = monotonic() + grant["expires_in"] while monotonic() < deadline: @@ -122,7 +162,11 @@ def command(arguments, *, out=None): else: print(f"No stored login for {server}.", file=out) return 0 - session = login(server, out=out) + try: + session = login(server, out=out) + except KeyboardInterrupt: + print("\nLogin cancelled.", file=sys.stderr) + return 130 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 diff --git a/pyproject.toml b/pyproject.toml index adda1fd..a051ecf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "modpoll" -version = "2.0.0a7" +version = "2.0.0a8" description = "A New Command-line Tool for Modbus and MQTT" authors = [{ name = "Ying Shaodong", email = "helloysd@gmail.com" }] readme = "README.md" diff --git a/tests/test_login.py b/tests/test_login.py index fcd0dff..7e24bf4 100644 --- a/tests/test_login.py +++ b/tests/test_login.py @@ -92,7 +92,7 @@ def test_login_waits_for_the_browser_and_keeps_one_login_for_both_tools( "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 "Open the address above 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) == ( @@ -141,7 +141,7 @@ def test_the_code_expires_when_nobody_confirms(monkeypatch): 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, "open_in_browser", lambda url: True) monkeypatch.setattr(login.time, "sleep", lambda seconds: None) assert login.command(["login"]) == 0 assert ( @@ -339,3 +339,95 @@ def test_a_refused_upload_reports_why(monkeypatch): monkeypatch.setattr(verification.requests, "post", lambda *a, **k: Reply(401, {})) with pytest.raises(ValueError, match="modpoll login"): verification.upload_report({}, timeout=3) + + +class Finished: + def __init__(self, returncode): + self.returncode = returncode + + +@pytest.mark.parametrize( + "environ, platform, expected_calls", + [ + ({"DISPLAY": ":0"}, "linux", 1), + ({"WAYLAND_DISPLAY": "wayland-0"}, "linux", 1), + ({}, "linux", 0), # no desktop: SSH or a minimal WSL + ({"DISPLAY": ":0", "SSH_CONNECTION": "1 2 3 4"}, "linux", 0), + ], +) +def test_a_browser_is_tried_only_where_there_is_a_desktop( + environ, platform, expected_calls +): + calls = [] + opened = login.open_in_browser( + "https://hub.test/activate/?user_code=X", + environ=environ, + platform=platform, + run=lambda command, **options: calls.append((command, options)) or Finished(0), + which=lambda name: "/usr/bin/xdg-open", + ) + assert len(calls) == expected_calls and opened is bool(expected_calls) + if calls: + # The opener's complaints stay out of the terminal. + assert ( + calls[0][1]["stdout"] == login.subprocess.DEVNULL + and calls[0][1]["stderr"] == login.subprocess.DEVNULL + ) + + +def test_an_opener_that_finds_no_browser_or_is_missing_is_a_failure_not_noise(): + environ = {"DISPLAY": ":0"} + assert ( + login.open_in_browser( + "https://x.test", + environ=environ, + platform="linux", + run=lambda *a, **k: Finished(3), + which=lambda name: "/usr/bin/xdg-open", + ) + is False + ) + assert ( + login.open_in_browser( + "https://x.test", environ=environ, platform="linux", which=lambda name: None + ) + is False + ) + + def broken(*args, **kwargs): + raise OSError("gone") + + assert ( + login.open_in_browser( + "https://x.test", + environ=environ, + platform="linux", + run=broken, + which=lambda name: "/usr/bin/xdg-open", + ) + is False + ) + + +def test_the_browser_variable_and_other_platforms_use_the_standard_opener(monkeypatch): + seen = [] + monkeypatch.setattr(login.webbrowser, "open", lambda url: seen.append(url) or True) + assert ( + login.open_in_browser( + "https://a.test", environ={"BROWSER": "wslview"}, platform="linux" + ) + is True + ) + assert ( + login.open_in_browser("https://b.test", environ={}, platform="darwin") is True + ) + assert seen == ["https://a.test", "https://b.test"] + + +def test_ctrl_c_while_waiting_is_a_one_line_cancel(monkeypatch, capsys): + def interrupted(*args, **kwargs): + raise KeyboardInterrupt + + monkeypatch.setattr(login, "login", interrupted) + assert login.command(["login"]) == 130 + assert "Login cancelled." in capsys.readouterr().err diff --git a/uv.lock b/uv.lock index 5c002bb..406cc54 100644 --- a/uv.lock +++ b/uv.lock @@ -683,7 +683,7 @@ wheels = [ [[package]] name = "modpoll" -version = "2.0.0a7" +version = "2.0.0a8" source = { editable = "." } dependencies = [ { name = "modpoll-wot", marker = "python_full_version < '3.15'" },