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
27 changes: 22 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 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

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.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,
Expand Down Expand Up @@ -126,6 +126,23 @@ model.tm.json`), and `--export` still writes the snapshot of the same read. With
Model, add `--product <manufacturer>/<model-number>`; 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:<id>@<version>` (`-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:
Expand Down Expand Up @@ -154,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.
Expand All @@ -166,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
Expand Down
16 changes: 14 additions & 2 deletions docs/preview-notes.md
Original file line number Diff line number Diff line change
@@ -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 <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.
- `--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

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
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.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 <https://top-maker.github.io/modpoll/1.x/>`_.
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.
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.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,

Expand All @@ -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.
19 changes: 18 additions & 1 deletion modpoll/arg_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:<id>@<version> 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."
),
Expand Down Expand Up @@ -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",
Expand Down
131 changes: 131 additions & 0 deletions modpoll/login.py
Original file line number Diff line number Diff line change
@@ -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
36 changes: 35 additions & 1 deletion modpoll/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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 "
Expand All @@ -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]}")
Expand All @@ -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 = []

Expand Down
Loading
Loading