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 README.md
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand Down
30 changes: 24 additions & 6 deletions docs/preview-notes.md
Original file line number Diff line number Diff line change
@@ -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 <manufacturer>/<model>`.
- `--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:<id>@<version>`, 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 <manufacturer>/<model>[@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:<id>@<version>` 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:<id>@<version>` 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

Expand Down
10 changes: 5 additions & 5 deletions docs/site/installation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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 <https://top-maker.github.io/modpoll/1.x/>`_.
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.
Expand All @@ -19,13 +19,13 @@ The package is available in the `Python Package Index <https://pypi.org/>`_,

.. 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,

Expand All @@ -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.
50 changes: 47 additions & 3 deletions modpoll/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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}
)
Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
96 changes: 94 additions & 2 deletions tests/test_login.py
Original file line number Diff line number Diff line change
Expand Up @@ -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) == (
Expand Down Expand Up @@ -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 (
Expand Down Expand Up @@ -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
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading