Skip to content
This repository was archived by the owner on Nov 15, 2026. It is now read-only.
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
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,22 @@ the working directory. See [transport details](docs/site/index.md#unconfigured-d
The checked-in ADAM-6024 TD and its source hash can be checked with
`uv run python tools/generate-td.py --check`; omit `--check` to regenerate.

### Models in your ModioHub Workspace

`modsim login` signs in to ModioHub 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). modpoll uses the same
file, so signing in with either tool signs in both. `MODIOHUB_TOKEN` replaces the file for scripts,
`MODIOHUB_URL` selects another server, and `login` and `logout` take `--server URL` for the same. `modsim logout` forgets the login on this computer.

Then `--config modiohub:<id>@<version>` (the version is a number or `latest`) simulates one of your custom
Thing Models, or a shared one without signing in; the download is checked against the SHA-256 the server states.
Deployment manifests do not take `modiohub:` models, so a hosted deployment never carries your login.

```sh
modsim --config modiohub:k3x9f2m7q4a8n5bd@latest --port 5020
```

## Development

See [CONTRIBUTING.md](CONTRIBUTING.md) for the v2 workflow and checks. The
Expand Down
13 changes: 12 additions & 1 deletion docs/preview-notes.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,15 @@
# Modsim 2.0.0a8 preview
# Modsim 2.0.0a9 preview

Modsim 2.0.0a9 pins modpoll-wot 0.5.0a1 and connects to ModioHub:

- `modsim login` signs in with your browser and `modsim logout` forgets the login. The 7-day tool session is
kept in `~/.config/modiohub/credentials.json` and is shared with modpoll 2.0.0a7.
- `--config modiohub:<id>@<version>` simulates a custom Thing Model from your ModioHub Workspace (a shared one
needs no login). Deployment manifests do not accept it.
- It also carries the SIM-06 fixes: only writable points are held after a client write, management requests
and device builds no longer block the event loop, and `script:` paths stay inside the deployment directory.

## Modsim 2.0.0a8 preview

Modsim 2.0.0a8 loads [simulation data](https://github.com/top-maker/modpoll-wot/blob/main/profile.md#simulation-data)
with `--data` and pins modpoll-wot 0.4.0a1. This preview breaks the previous
Expand Down
2 changes: 1 addition & 1 deletion modsim/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "2.0.0a8"
__version__ = "2.0.0a9"
42 changes: 42 additions & 0 deletions modsim/hub.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""Bounded requests to ModioHub, with a tool session token when there is one."""

import json
from typing import Any
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen

from modpoll_wot.loading import MAX_BYTES # type: ignore[import-untyped]

from . import __version__

TIMEOUT = 15


def call(
url: str, *, method: str = "GET", body: Any = None, token: str | None = None
) -> tuple[int, bytes]:
"""One request; returns the status and at most 1 MiB of the answer. An error status is a result."""
headers = {"User-Agent": f"modsim/{__version__}", "Accept": "application/json"}
if token:
headers["Authorization"] = f"Bearer {token}"
data = None
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
request = Request(url, data=data, headers=headers, method=method)
try:
with urlopen(request, timeout=TIMEOUT) as response:
return response.status, response.read(MAX_BYTES + 1)[:MAX_BYTES]
except HTTPError as error:
return error.code, error.read(MAX_BYTES + 1)[:MAX_BYTES]
except (URLError, TimeoutError, OSError) as exc:
raise ValueError(f"Could not reach {url}: {exc}") from exc


def call_json(url: str, **options: Any) -> tuple[int, dict]:
status, payload = call(url, **options)
try:
document = json.loads(payload)
except ValueError:
document = {}
return status, document if isinstance(document, dict) else {}
119 changes: 119 additions & 0 deletions modsim/login.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
"""Sign in to ModioHub with the browser authorization flow (OAuth device authorization grant, RFC 8628).

``modsim 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 modpoll (see modpoll_wot.session). ``modsim logout`` removes it.
"""

import sys
import time
import webbrowser
from typing import Any, Callable, TextIO

import modpoll_wot # type: ignore[import-untyped]

from .hub import call_json

CLIENT_ID = "modsim"
GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code"


class LoginError(ValueError):
"""The login did not complete; the message says why and what to do."""


def login(
server: str,
*,
sleep: Callable[[float], Any] | None = None,
monotonic: Callable[[], float] | None = None,
open_browser: Callable[[str], bool] | None = None,
out: TextIO | None = None,
) -> Any:
"""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
status, grant = call_json(
f"{server}/api/v1/tool-sessions/device-authorization",
method="POST",
body={"client_id": CLIENT_ID},
)
if status != 200:
raise LoginError(f"{server} refused the login ({status})")
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)
status, body = call_json(
f"{server}/api/v1/tool-sessions/token",
method="POST",
body={
"grant_type": GRANT_TYPE,
"device_code": grant["device_code"],
"client_id": CLIENT_ID,
},
)
if status == 200:
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 status}).")
raise LoginError(
"The code expired before it was confirmed; run modsim login again."
)


def _save(server: str, body: dict) -> Any:
token = body["access_token"]
status, me = call_json(f"{server}/api/v1/me", token=token)
modpoll_wot.save_session(
server,
token,
expires_in=body["expires_in"],
github_user=me.get("githubUser") if status == 200 else None,
)
return modpoll_wot.load_session(server)


def command(arguments: list[str], *, out: TextIO | None = None) -> int:
"""``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: modsim {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}. modpoll uses the same login.", file=out)
return 0
except (LoginError, modpoll_wot.CredentialError) as exc:
print(str(exc), file=sys.stderr)
return 1
3 changes: 3 additions & 0 deletions modsim/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,10 @@ async def run_async_server(args: Any) -> Any:

def app() -> None:
from .commands import ACTIONS, run
from .login import command

if sys.argv[1:2] in (["login"], ["logout"]):
raise SystemExit(command(sys.argv[1:]))
if len(sys.argv) > 1 and sys.argv[1] in ACTIONS:
run(sys.argv[1:])
return
Expand Down
49 changes: 49 additions & 0 deletions modsim/sources.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
"""Bounded local JSON and HTTPS model and simulation data loading."""

import hashlib
import tempfile
from pathlib import Path
from urllib.parse import urlparse
from urllib.request import Request, urlopen

import modpoll_wot # type: ignore[import-untyped]
from modpoll_wot.loading import MAX_BYTES, load_document # type: ignore[import-untyped]

from . import __version__
from .hub import call, call_json

# Some CDNs reject the default Python-urllib agent; identify the tool instead.
USER_AGENT = f"modsim/{__version__}"
Expand All @@ -24,11 +27,53 @@ def local_path(base: Path, value: str) -> str:


def model_document(source: str) -> dict:
if source.startswith(modpoll_wot.REFERENCE_PREFIX):
return workspace_document(source)
if not is_remote(source):
return load_document(source) # type: ignore[no-any-return]
return remote_document(source)


def workspace_document(text: str) -> dict:
"""A custom Thing Model version of the user's ModioHub Workspace: ``modiohub:<id>@<version>``.

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
status, thing_model = call_json(
f"{server}/api/v1/thing-models/{reference.id}", token=token
)
if status == 401:
raise ValueError("Your ModioHub login is no longer valid; run modsim login")
if status == 404:
raise ValueError(
f"No custom Thing Model {reference.id} is shared"
+ (" or yours" if token else "; run modsim login if it is yours")
)
if status != 200:
raise ValueError(f"{server} answered {status}")
versions = {str(item["version"]): item for item in thing_model["versions"]}
version = (
thing_model["versions"][0]
if reference.version == "latest"
else versions.get(reference.version)
)
if version is None:
raise ValueError(f"{text} has no version {reference.version}")
if not version["fileUrl"].startswith(server + "/"):
raise ValueError(f"{server} pointed to another address for {text}")
status, payload = call(version["fileUrl"], token=token)
if status != 200:
raise ValueError(f"{server} answered {status}")
if hashlib.sha256(payload).hexdigest() != version["sha256"]:
raise ValueError(f"{text} does not match the SHA-256 {server} reports for it")
return _bounded_document(payload)


def remote_document(source: str) -> dict:
"""Load bounded JSON from an HTTPS URL with the shared loader's rules."""
url = urlparse(source)
Expand All @@ -47,6 +92,10 @@ def remote_document(source: str) -> dict:
payload = response.read(MAX_BYTES + 1)
if len(payload) > MAX_BYTES:
raise ValueError(f"document exceeds {MAX_BYTES} bytes")
return _bounded_document(payload)


def _bounded_document(payload: bytes) -> dict:
# Reuse all bounded JSON parsing rules from the public shared loader.
with tempfile.TemporaryDirectory(prefix="modsim-model-") as directory:
path = Path(directory) / "model.json"
Expand Down
7 changes: 5 additions & 2 deletions modsim/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,16 @@
def get_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description=f"Modsim v{__version__} - A Simple Modbus TCP Device Simulator used for modpoll tool",
epilog="Managed commands: up, down, ps, logs, export, reset. Use modsim COMMAND --help.",
epilog="Managed commands: up, down, ps, logs, export, reset. Use modsim COMMAND --help. Sign in to ModioHub with modsim login.",
)
parser.add_argument(
"-v", "--version", action="version", version=f"{__package__} v{__version__}"
)
sources = parser.add_mutually_exclusive_group()
sources.add_argument("--config", help="Profile 0.2 TM/TD local path or HTTPS URL")
sources.add_argument(
"--config",
help="Profile 0.2 TM/TD local path, HTTPS URL, or modiohub:<id>@<version> for a custom Thing Model in your ModioHub Workspace",
)
parser.add_argument(
"--data",
help=(
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
[project]
name = "modsim"
version = "2.0.0a8"
version = "2.0.0a9"
description = "A Simple Modbus TCP Device Simulator used for modpoll tool"
authors = [{ name = "Ying Shaodong", email = "helloysd@gmail.com" }]
readme = "README.md"
requires-python = ">=3.10,<4.0"
dependencies = [
"pymodbus~=3.16.1",
"modpoll-wot==0.4.0a1",
"modpoll-wot==0.5.0a1",
"jsonschema>=4.21,<5",
"PyYAML>=6,<7",
]
Expand Down
2 changes: 1 addition & 1 deletion tests/fixtures/io-module/generated.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"source_sha256": "4c2aee3334faf6622f4ee34a23108fa0ec100a6b3110a78200eee79da8935596",
"generator": {
"package": "modpoll-wot",
"version": "0.4.0a1"
"version": "0.5.0a1"
},
"instance": {
"host": "127.0.0.1",
Expand Down
Loading
Loading