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
20 changes: 18 additions & 2 deletions packages/modpoll/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,24 @@ The report records, per point, whether the read worked (`ok`, a Modbus `exceptio
ID, serial number or value; review it before sharing. It is checked with
[modpoll-wot](https://github.com/top-maker/modpoll/tree/v2/packages/modpoll-wot) (`modpoll-wot validate-report report.json --model
model.tm.json`), and `--export` still writes the snapshot of the same read. ModioHub resolves the product
from the model fingerprint, so you never name the product. The exit
code is 1 unless every point was read.
from the model fingerprint; when it does not know the model, modpoll names the product whose baseline
Thing Model holds all of the report's points, or lets you choose one from the matched products or a search,
and otherwise prints a prefilled catalog request. A point whose DataSchema declares `const` (an identity
point, such as a meter code) is compared with the value read, and the report records only `match` or
`mismatch`.

When a read fails, modpoll lists each failed group as the device answered it, without guessing why:

```text
Group 3 of 8 (holding registers 40-59): exception code 02 (illegal data address).
Group 5 of 8 (input registers 0-59): no response.
Groups 6-8 of 8: not tried.
Not a full read: 21 of 44 points read.
```

Only a full read whose identity points match can be uploaded; any other report is saved for your own checks
or a catalog request, and `--upload` refuses it without contacting ModioHub. The exit code is 1 unless the
report can be uploaded.

### Sign in to ModioHub, read a Workspace Thing Model and upload the report

Expand Down
19 changes: 19 additions & 0 deletions packages/modpoll/docs/preview-notes.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,22 @@
# Modpoll 2.0.0a13 preview (unreleased)

Modpoll 2.0.0a13 writes verification report schema 5 (modpoll-wot with `identity_constants`):

- A failed read lists each failed group as the device answered it (data table, addresses, exception code and
its Modbus name, or no response), each point whose answer could not be decoded, and the groups not tried.
modpoll does not guess why and does not change the configuration.
- Only a full read whose identity points match can be uploaded. The `Continue?` question is gone: a report
with failures is saved and not offered for upload, and `--upload FILE` refuses it, or a schema 3 or 4
report, without contacting ModioHub.
- Points whose DataSchema declares `const` are compared with the value read; the report records `match` or
`mismatch`, never the value.
- Before an upload, a model ModioHub does not know is matched by its point fingerprints: a report whose points
all belong to one baseline gets that product, other matches or a search are offered interactively, and
otherwise a prefilled catalog request is printed. A Workspace model's report names its product.
- Refusals from ModioHub are explained by their code (`not-full-read`, `identity-mismatch`,
`identity-missing`, `unknown-model` and others).
- The signal handler no longer waits for the exit event's lock, so Ctrl-C cannot deadlock a run.

# Modpoll 2.0.0a12 preview

Modpoll 2.0.0a12 pins modpoll-wot 0.7.0a1:
Expand Down
3 changes: 2 additions & 1 deletion packages/modpoll/modpoll/arg_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@ def get_parser():
"for confirmation and uploaded once you agree; you are signed in "
"with the browser only when no login exists. Together with "
"--report, the report of the verification read is uploaded "
"instead of only being saved."
"instead of only being saved. Only a full read whose identity "
"points match can be uploaded."
),
)
verification.add_argument(
Expand Down
137 changes: 111 additions & 26 deletions packages/modpoll/modpoll/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,39 +136,36 @@ def _ask(prompt):


def _finish_full_read(args, handler):
"""Summarize the verification read, save the report, and upload it when asked.
"""Report the verification read, save the report, and upload it when asked.

Failures are listed as the device answered them; a report with any, or
with an identity point that does not match, is saved but never uploaded.
On a terminal without --yes the save location, the judgment of the values
and the upload are asked interactively. The result is whether every point
was read.
and the upload are asked interactively. The result is whether the report
can be uploaded.
"""
try:
report = verification.build_report(handler, args)
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)
full = verification.is_full_read(report)
if sys.stdin.isatty() and not args.yes:
if not full and _ask(
"Not every point was read, so this report does not count as a "
"full read. Continue? [y/N] "
) not in ("y", "yes"):
return False
lines = verification.failure_lines(handler) + verification.identity_lines(
handler, report
)
print("\n" + "\n".join([*lines, verification.summary(report)]), flush=True)
refused = verification.refusal(report)
if refused is None and sys.stdin.isatty() and not args.yes:
verdict = _ask(
"Do the values in the table above look right? "
"[y]es, [n]o, [Enter] not checked: "
)
if verdict in ("y", "yes", "n", "no"):
# Judge only the points the device actually answered.
judged = [
point["property"] for point in report["points"] if point["read"] == "ok"
]
names = [point["property"] for point in report["points"]]
if verdict in ("y", "yes"):
args.confirm = judged
args.confirm = names
else:
args.reject = judged
args.reject = names
try:
report = verification.build_report(handler, args)
except (ValueError, OSError, AcquisitionError) as exc:
Expand Down Expand Up @@ -197,6 +194,16 @@ def _finish_full_read(args, handler):
"serial numbers or values; review it before sharing.",
flush=True,
)
if refused is not None:
print(
(
"Only a full read can be uploaded."
if not verification.is_full_read(report)
else "The device may be a different product, so the report cannot be uploaded."
),
flush=True,
)
return False
# --report includes the upload: interactive runs ask, --yes uploads without
# asking and therefore needs an existing sign-in.
upload = args.upload is not None or args.yes
Expand All @@ -206,7 +213,7 @@ def _finish_full_read(args, handler):
confirmed = upload
if upload and not _upload(args, report, confirm=not confirmed):
return False
return full
return True


def _ensure_login():
Expand Down Expand Up @@ -263,12 +270,95 @@ def _upload_saved(args):
return _upload(args, report)


def _choose(options):
"""The number the user picks from a printed list, or None for Enter."""
for number, (_, label) in enumerate(options, 1):
print(f" {number}. {label}", flush=True)
answer = input("Number of the product, or Enter for none: ").strip()
if answer.isdigit() and 1 <= int(answer) <= len(options):
return options[int(answer) - 1][0]
return None


def _identify_product(args, report):
"""The report with the product it belongs to, or None when no catalog product fits.

A Workspace model names its product; otherwise the matched products of the
point fingerprints decide: an exact model is identified by ModioHub, and
a report whose points all belong to one baseline gets that product. Other
cases are chosen interactively, from the matches or a search.
"""
if "product" in report:
return report
matches = verification.matched_products(report, timeout=args.timeout)
if any(match["exact"] for match in matches):
return report
total = len(report["points"])
if len(matches) == 1 and matches[0]["matched"] == total:
print(
f"Product: {matches[0]['productId']} (all {total} points are in its baseline Thing Model).",
flush=True,
)
return {**report, "product": matches[0]["productId"]}
interactive = sys.stdin.isatty() and not args.yes
if matches:
print(
"ModioHub does not know this Thing Model. Products that share points with it:",
flush=True,
)
options = [
(
m["productId"],
f"{m['productId']}: {m['matched']} of {total} points match",
)
for m in matches
]
if not interactive:
for _, label in options:
print(f" {label}", flush=True)
logger.error("Upload interactively to choose the product.")
return None
product = _choose(options)
if product:
return {**report, "product": product}
elif not interactive:
logger.error("The report does not match a catalog product.")
while interactive:
text = input("Model number to search, or Enter to stop: ").strip()
if not text:
break
found = verification.search_products(text, timeout=args.timeout)
if not found:
print("No product found.", flush=True)
continue
product = _choose(found)
if product:
return {**report, "product": product}
print(
"Not uploaded. Request the product in the catalog and attach the report:\n"
+ verification.catalog_request(report),
flush=True,
)
return None


def _upload(args, report, *, confirm=True):
"""Show the report and, once the user agrees, upload it. Returns whether it was uploaded.

``confirm`` is false when the caller already asked (a yes to the bare
``--report`` upload question), or with ``--yes``.
"""
refused = verification.refusal(report)
if refused is not None:
logger.error("%s", refused)
return False
try:
report = _identify_product(args, report)
except ValueError as exc:
logger.error("%s", exc)
return False
if report is None:
return False
print("\nReport to upload:\n" + json.dumps(report, indent=2), flush=True)
if confirm and not args.yes:
if not sys.stdin.isatty():
Expand All @@ -282,20 +372,15 @@ def _upload(args, report, *, confirm=True):
return False
try:
_ensure_login()
stored = verification.upload_report(report, timeout=args.timeout)
verification.upload_report(report, timeout=args.timeout)
except (ValueError, login.LoginError, OSError) 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."
),
"Uploaded. Thank you: every point you read counts toward the hardware "
"verification on ModioHub.",
flush=True,
)
print("Thank you for verifying the Thing Model on real hardware.", flush=True)
return True


Expand Down
5 changes: 5 additions & 0 deletions packages/modpoll/modpoll/modbus_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,10 +206,13 @@ def __init__(
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
# Whether the last poll cycle did not send this group's request at all.
self.skipped = False
self.logger = logging.getLogger(__name__)

def poll(self, master) -> bool:
self.failure = None
self.skipped = False
try:
result = None
data = None
Expand Down Expand Up @@ -633,6 +636,7 @@ def poll(self):
dev.pollCount += 1
dev.errorCount += 1
for poller in active:
poller.failure, poller.skipped = None, True
previous_failures = poller.failcounter
poller.update_statistics(False)
self._record_poller_result(poller, False, previous_failures)
Expand Down Expand Up @@ -668,6 +672,7 @@ def poll(self):
len(skipped),
)
for rest in skipped:
rest.failure, rest.skipped = None, True
previous = rest.failcounter
rest.update_statistics(False)
self._record_poller_result(rest, False, previous)
Expand Down
Loading
Loading