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
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,29 @@ meter (2026-10-28). See [validation](docs/validation.rst) for the evidence scope
For a complete local simulator/MQTT demonstration, use the repository's
[Docker Compose example](examples/README.md).

### Read a catalog product and write a verification report

`--device <manufacturer>/<model-number>[@<commit>]` reads the baseline Thing Model of a product in the
[Open Modbus Catalog](https://github.com/top-maker/open-modbus-catalog) instead of a file. A branch or tag
(default `main`) is resolved to its commit, and the download is checked against the Git object id GitHub
reports for it. `--full-read` reads every point once: read-only, without retries and with a timeout of at
most 10 seconds, so a lost request is a result and not something to repeat. `--report FILE` also writes the
verification report (`-` prints it):

```sh
modpoll --device advantech/adam-5017uh --tcp 192.168.1.20 --unit-id 3 --report report.json
```

The report records, per point, whether the read worked (`ok`, a Modbus `exception` with its code,
`no-response`, or `not-tested` when the answer could not be decoded) and your judgment of the value:
`--confirm POINT...` (or `all`) and `--reject POINT...` for values you compared with the device, otherwise
`unchecked`. `--chassis`, `--firmware` and `--configuration` add context. The report holds no address, Unit
ID, serial number or value; review it before sharing. It is checked with
[modpoll-wot](https://github.com/top-maker/modpoll-wot) (`modpoll-wot validate-report report.json --model
model.tm.json`), and `--export` still writes the snapshot of the same read. With `-f` for a local Thing
Model, add `--product <manufacturer>/<model-number>`; the report then names the model as local. The exit
code is 1 unless every point was read.

### MQTT data and write behavior

The local example above uses the `adam6024_raw` TD title for its default topics:
Expand Down
62 changes: 60 additions & 2 deletions modpoll/arg_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,70 @@ def get_parser():
parser.add_argument(
"-f",
"--config",
required=True,
default=None,
help=(
"Local path or URL of a WoT TM/TD JSON configuration. "
"Type is detected from content, not the filename. Required!"
"Type is detected from content, not the filename. "
"Required unless --device is given."
),
nargs="+",
)
parser.add_argument(
"--device",
metavar="MANUFACTURER/MODEL[@COMMIT]",
help=(
"Read the baseline Thing Model of a product in the Open Modbus Catalog, "
"for example advantech/adam-5017uh, at a commit, tag or branch "
"(default: main). Use instead of -f."
),
)
parser.add_argument(
"--full-read",
action="store_true",
help=(
"Read every point of the model once, read-only and without retries, "
"and report which points could be read. Implies --once."
),
)
parser.add_argument(
"--report",
metavar="FILE",
help=(
"Write the verification report of a full read to FILE ('-' prints it). "
"It lists each point's result and carries no address, Unit ID, serial "
"number or value; review it before sharing. Implies --full-read."
),
)
parser.add_argument(
"--product",
metavar="MANUFACTURER/MODEL",
help="Catalog product ID the report is for; needed with -f, taken from --device otherwise",
)
parser.add_argument(
"--chassis",
metavar="MANUFACTURER/MODEL",
help="Chassis product ID, for the report",
)
parser.add_argument(
"--firmware", help="Firmware version of the device, for the report"
)
parser.add_argument(
"--configuration",
help="Short note on the device configuration, such as an input range, for the report",
)
parser.add_argument(
"--confirm",
nargs="+",
default=[],
metavar="POINT",
help="Points whose values you checked and found right ('all' for every point), for the report",
)
parser.add_argument(
"--reject",
nargs="+",
default=[],
metavar="POINT",
help="Points whose values you checked and found wrong, for the report",
)
parser.add_argument(
"--param",
Expand Down
33 changes: 32 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__
from . import __version__, verification
from .utils import set_threading_event, delay_thread, on_threading_event, get_utc_time


Expand Down Expand Up @@ -128,6 +128,26 @@ def process_mqtt_command(topic, payload, retained, topic_pattern, handlers):
return success


def _finish_full_read(args, handler):
"""Summarize the full read and write its report; the result is whether every point was read."""
try:
report = verification.build_report(handler, args)
if args.report:
verification.write_report(report, args.report)
except (ValueError, OSError, AcquisitionError) as exc:
logger.error("%s", exc)
logger.debug("Report error details", exc_info=True)
return False
print(f"\n{verification.summary(report)}", flush=True)
if args.report and args.report != "-":
print(
f"Report written to {args.report}. It has no addresses, Unit IDs, serial "
"numbers or values; review it before sharing.",
flush=True,
)
return verification.is_full_read(report)


def _signal_handler(signal_number, frame):
if logger:
logger.info(f"Exiting {sys.argv[0]}")
Expand Down Expand Up @@ -158,6 +178,12 @@ def app(name="modpoll"):
global logger
logger = logging.getLogger(__name__)

try:
verification.validate_args(args)
except ValueError as exc:
logger.error("%s", exc)
sys.exit(2)

# setup mqtt
if not args.mqtt_host:
logger.info("No MQTT host specified, skip MQTT setup.")
Expand Down Expand Up @@ -205,6 +231,7 @@ def app(name="modpoll"):
try:
# setup modbus tasks
try:
verification.resolve_models(args)
modbus_handlers = setup_modbus_handlers(args, mqtt_handler)
except (ValueError, AcquisitionError) as exc:
# A mistake in the command line or model is reported, not a stack.
Expand Down Expand Up @@ -267,6 +294,10 @@ def app(name="modpoll"):
timestamp=now if args.timestamp else None,
)
cycle_success = export_success and cycle_success
if args.full_read and not on_threading_event():
cycle_success = (
_finish_full_read(args, modbus_handlers[0]) and cycle_success
)
if args.diagnostics_rate > 0 and (
last_diag is None or monotonic_now >= last_diag + args.diagnostics_rate
):
Expand Down
34 changes: 32 additions & 2 deletions modpoll/modbus_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import tempfile
from decimal import Decimal
from pathlib import Path
from typing import List, Optional
from typing import List, Optional, Tuple

import requests
from prettytable import PrettyTable
Expand Down Expand Up @@ -204,9 +204,12 @@ def __init__(
self.readablePoints: List[Point] = []
self.disabled = False
self.failcounter = 0
# Why the last read of this group failed: ("exception", code) or ("no-response", None).
self.failure: Optional[Tuple[str, Optional[int]]] = None
self.logger = logging.getLogger(__name__)

def poll(self, master) -> bool:
self.failure = None
try:
result = None
data = None
Expand Down Expand Up @@ -336,10 +339,13 @@ def _call_read(method):
self.update_statistics(decode_success)
return decode_success
except ModbusException:
self.failure = ("no-response", None)
self.logger.error(
f"Modbus exception: {self.device.name} {self.fc} {self.start_address} {self.size}"
)

if self.failure is None:
self.failure = _read_failure(result)
self.update_statistics(False)
for point in self.readablePoints:
point.update_value(None)
Expand Down Expand Up @@ -414,6 +420,14 @@ def update_statistics(self, success: bool):
self.device.pollSuccess = False


def _read_failure(result):
"""Classify a failed read: the device answered with an exception code, or did not answer."""
code = getattr(result, "exception_code", None)
if isinstance(code, int) and 1 <= code <= 255:
return ("exception", code)
return ("no-response", None)


def _multiplier(scale):
"""The float the engine computes with, and the exact decimal of it.

Expand Down Expand Up @@ -523,13 +537,16 @@ def __init__(
instance_port: Optional[int] = None,
instance_parameters=None,
precision: Optional[int] = None,
model_bytes: Optional[bytes] = None,
):
self.modbus_client = modbus_client
self.config_file = config_file
self.unit_id = unit_id
self.instance_host = instance_host
self.instance_port = instance_port
self.instance_parameters = instance_parameters
# The exact bytes of the model; given by the caller or read from the configuration location.
self.model_bytes = model_bytes
self.model = None
self.mqtt_handler = mqtt_handler
self.timeout = timeout
Expand All @@ -550,13 +567,16 @@ def __init__(
)

def load_config(self) -> bool:
from .wot_config import create_devices, read_model
from .wot_config import create_devices, read_model, read_payload

self.logger.info(f"Loading WoT config from: {self.config_file}")
try:
if self.model_bytes is None:
self.model_bytes = read_payload(self.config_file, timeout=self.timeout)
model = read_model(
self.config_file,
timeout=self.timeout,
payload=self.model_bytes,
unit_id=self.unit_id,
host=self.instance_host,
port=self.instance_port,
Expand Down Expand Up @@ -837,6 +857,8 @@ def get_device_list(self) -> List[Device]:


def setup_modbus_handlers(args, mqtt_handler: Optional[MqttHandler] = None):
# ``args.model_payloads`` maps a configuration name to model bytes already in hand (--device).
models = getattr(args, "model_payloads", None) or {}
modbus_handlers = []
current_handler = None
device_names = set()
Expand Down Expand Up @@ -865,6 +887,7 @@ def setup_modbus_handlers(args, mqtt_handler: Optional[MqttHandler] = None):
instance_port=args.tcp_port,
instance_parameters=parameters,
precision=parse_precision(getattr(args, "precision", None)),
model_bytes=models.get(config_file),
)
if current_handler.load_config():
effective_args = copy.copy(args)
Expand Down Expand Up @@ -906,6 +929,11 @@ def _valid_write_address(address) -> bool:
return type(address) is int and 0 <= address <= 65535


def _read_options(args):
"""A full read asks each group once: a lost request is a result, not something to repeat."""
return {"retries": 0} if getattr(args, "full_read", False) else {}


def _create_modbus_client(args):
transport = _determine_transport(args)

Expand Down Expand Up @@ -935,6 +963,7 @@ def _create_serial_client(args, port, framer):
"parity": parity,
"stopbits": 1,
"timeout": args.timeout,
**_read_options(args),
}
if framer:
client_args["framer"] = framer
Expand All @@ -946,6 +975,7 @@ def _create_tcp_client(args, framer):
"host": args.tcp,
"port": 502 if args.tcp_port is None else args.tcp_port,
"timeout": args.timeout,
**_read_options(args),
}
if framer:
client_args["framer"] = framer
Expand Down
Loading
Loading