mechbase 0.2.2__tar.gz → 0.3.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {mechbase-0.2.2 → mechbase-0.3.0}/PKG-INFO +19 -2
- {mechbase-0.2.2 → mechbase-0.3.0}/README.md +17 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/pyproject.toml +4 -1
- mechbase-0.3.0/src/mechbase/cli.py +263 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/src/mechbase/resources/measurements.py +17 -1
- mechbase-0.3.0/tests/test_cli.py +64 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/uv.lock +1 -1
- {mechbase-0.2.2 → mechbase-0.3.0}/.gitignore +0 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/examples/list_assets.py +0 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/examples/push_measurement.py +0 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/examples/run_survey.py +0 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/examples/sync_registry.py +0 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/src/mechbase/__init__.py +0 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/src/mechbase/_http.py +0 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/src/mechbase/client.py +0 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/src/mechbase/errors.py +0 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/src/mechbase/maintnode.py +0 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/src/mechbase/models.py +0 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/src/mechbase/resources/__init__.py +0 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/src/mechbase/resources/_base.py +0 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/src/mechbase/resources/registry.py +0 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/src/mechbase/resources/routes.py +0 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/tests/test_client.py +0 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/tests/test_idempotency.py +0 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/tests/test_maintnode.py +0 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/tests/test_null_safety.py +0 -0
- {mechbase-0.2.2 → mechbase-0.3.0}/tests/test_registry.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: mechbase
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Official Python client for the Mechbase condition-monitoring API
|
|
5
5
|
Project-URL: Homepage, https://app.mechbase.io
|
|
6
6
|
Project-URL: Source, https://github.com/arpedon/mechbase-sdk
|
|
@@ -34,6 +34,23 @@ assets = inst.assets.list(q="pump", limit=50)
|
|
|
34
34
|
inst.measurements.create(point_id=42, data={"rms": 2.3}, notes="manual reading")
|
|
35
35
|
```
|
|
36
36
|
|
|
37
|
+
## Command line
|
|
38
|
+
|
|
39
|
+
The package installs a `mechbase` command:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pipx install mechbase
|
|
43
|
+
mechbase login # once; token stored in ~/.config/mechbase/config.json
|
|
44
|
+
mechbase points --asset 1
|
|
45
|
+
mechbase readings 2 # latest readings of point 2
|
|
46
|
+
mechbase reading show 2 766 # values, state and top spectrum peaks (electrical lines tagged)
|
|
47
|
+
mechbase reading delete 2 767
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Reading numbers are the ones in the web URL (`…/measurementpoints/2/measurements/766/`).
|
|
51
|
+
Add `--json` to any command for scripting; `MECHBASE_TOKEN`, `MECHBASE_URL` and
|
|
52
|
+
`MECHBASE_INSTALLATION` override the stored config.
|
|
53
|
+
|
|
37
54
|
For edge agents identified by a `node_uuid` rather than a bearer token, use `MaintNode`.
|
|
38
55
|
|
|
39
56
|
Full docs and the other language SDKs (Go, Swift, Kotlin) live in the
|
|
@@ -19,6 +19,23 @@ assets = inst.assets.list(q="pump", limit=50)
|
|
|
19
19
|
inst.measurements.create(point_id=42, data={"rms": 2.3}, notes="manual reading")
|
|
20
20
|
```
|
|
21
21
|
|
|
22
|
+
## Command line
|
|
23
|
+
|
|
24
|
+
The package installs a `mechbase` command:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pipx install mechbase
|
|
28
|
+
mechbase login # once; token stored in ~/.config/mechbase/config.json
|
|
29
|
+
mechbase points --asset 1
|
|
30
|
+
mechbase readings 2 # latest readings of point 2
|
|
31
|
+
mechbase reading show 2 766 # values, state and top spectrum peaks (electrical lines tagged)
|
|
32
|
+
mechbase reading delete 2 767
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Reading numbers are the ones in the web URL (`…/measurementpoints/2/measurements/766/`).
|
|
36
|
+
Add `--json` to any command for scripting; `MECHBASE_TOKEN`, `MECHBASE_URL` and
|
|
37
|
+
`MECHBASE_INSTALLATION` override the stored config.
|
|
38
|
+
|
|
22
39
|
For edge agents identified by a `node_uuid` rather than a bearer token, use `MaintNode`.
|
|
23
40
|
|
|
24
41
|
Full docs and the other language SDKs (Go, Swift, Kotlin) live in the
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "mechbase"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.3.0"
|
|
8
8
|
description = "Official Python client for the Mechbase condition-monitoring API"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -15,6 +15,9 @@ dependencies = [
|
|
|
15
15
|
"httpx>=0.27",
|
|
16
16
|
]
|
|
17
17
|
|
|
18
|
+
[project.scripts]
|
|
19
|
+
mechbase = "mechbase.cli:main"
|
|
20
|
+
|
|
18
21
|
[project.optional-dependencies]
|
|
19
22
|
dev = [
|
|
20
23
|
"pytest>=8",
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
"""`mechbase` command line — readings, points and spectra from a terminal.
|
|
2
|
+
|
|
3
|
+
mechbase login # once; stores a token in ~/.config/mechbase/config.json
|
|
4
|
+
mechbase points --asset 1
|
|
5
|
+
mechbase readings 2
|
|
6
|
+
mechbase reading show 2 766 # values, state and the top spectrum peaks
|
|
7
|
+
mechbase reading delete 2 767
|
|
8
|
+
|
|
9
|
+
Every command takes --json for scripting. MECHBASE_TOKEN / MECHBASE_URL /
|
|
10
|
+
MECHBASE_INSTALLATION override the stored config.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import argparse
|
|
16
|
+
import getpass
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import platform
|
|
20
|
+
import sys
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
from . import Mechbase
|
|
24
|
+
from ._http import HttpClient
|
|
25
|
+
from .errors import MechbaseError
|
|
26
|
+
|
|
27
|
+
STATUS = {1: "good", 2: "elevated", 3: "minor", 4: "major"}
|
|
28
|
+
# Headline values for `readings`; `reading show` prints everything.
|
|
29
|
+
HEADLINE = ("value", "rms", "peak", "vel_10hz", "crest_factor", "kurtosis", "temperature")
|
|
30
|
+
|
|
31
|
+
CONFIG = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "mechbase" / "config.json"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _load() -> dict:
|
|
35
|
+
try:
|
|
36
|
+
cfg = json.loads(CONFIG.read_text())
|
|
37
|
+
except (OSError, ValueError):
|
|
38
|
+
cfg = {}
|
|
39
|
+
for key, env in (("token", "MECHBASE_TOKEN"), ("url", "MECHBASE_URL"), ("installation", "MECHBASE_INSTALLATION")):
|
|
40
|
+
if os.environ.get(env):
|
|
41
|
+
cfg[key] = os.environ[env]
|
|
42
|
+
cfg.setdefault("url", Mechbase.DEFAULT_BASE_URL)
|
|
43
|
+
return cfg
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _save(cfg: dict) -> None:
|
|
47
|
+
CONFIG.parent.mkdir(parents=True, exist_ok=True)
|
|
48
|
+
CONFIG.write_text(json.dumps(cfg, indent=2))
|
|
49
|
+
CONFIG.chmod(0o600)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _client(cfg: dict) -> Mechbase:
|
|
53
|
+
if not cfg.get("token"):
|
|
54
|
+
sys.exit("Not signed in. Run: mechbase login")
|
|
55
|
+
return Mechbase(token=cfg["token"], base_url=cfg["url"])
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _inst(args, cfg, client):
|
|
59
|
+
iid = args.installation or cfg.get("installation") or client.me().current_installation_id
|
|
60
|
+
return client.for_installation(int(iid))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _out(args, rows: list[dict], cols: list[str]) -> None:
|
|
64
|
+
if args.json:
|
|
65
|
+
print(json.dumps(rows, indent=2, default=str))
|
|
66
|
+
return
|
|
67
|
+
widths = [max(len(c), *(len(str(r.get(c, ""))) for r in rows)) for c in cols] if rows else [len(c) for c in cols]
|
|
68
|
+
print(" ".join(c.upper().ljust(w) for c, w in zip(cols, widths)))
|
|
69
|
+
for r in rows:
|
|
70
|
+
print(" ".join(str(r.get(c, "")).ljust(w) for c, w in zip(cols, widths)))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def peaks(freq: list[float], amp: list[float], *, top: int = 10, line_hz: float = 50.0) -> list[dict]:
|
|
74
|
+
"""Top local maxima, each tagged when it sits on a mains multiple (k × line_hz).
|
|
75
|
+
|
|
76
|
+
ponytail: plain local-max scan; no interpolation or noise floor — add when
|
|
77
|
+
peaks need sub-bin accuracy or the list fills with grass.
|
|
78
|
+
"""
|
|
79
|
+
df = freq[1] - freq[0] if len(freq) > 1 else 0
|
|
80
|
+
found = [
|
|
81
|
+
(freq[i], amp[i])
|
|
82
|
+
for i in range(1, len(amp) - 1)
|
|
83
|
+
if freq[i] > 0 and amp[i] > amp[i - 1] and amp[i] >= amp[i + 1]
|
|
84
|
+
]
|
|
85
|
+
found.sort(key=lambda p: p[1], reverse=True)
|
|
86
|
+
out = []
|
|
87
|
+
for f, a in found[:top]:
|
|
88
|
+
k = round(f / line_hz)
|
|
89
|
+
# within half a bin: a mains line lands on k×line_hz, a shaft speed near it doesn't
|
|
90
|
+
tag = f"{k}×{line_hz:g} Hz (electrical)" if k and abs(f - k * line_hz) <= df / 2 else ""
|
|
91
|
+
out.append({"hz": round(f, 2), "amplitude": round(a, 4), "note": tag})
|
|
92
|
+
return out
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# --- commands ---------------------------------------------------------------
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def cmd_login(args, cfg):
|
|
99
|
+
email = args.email or input("Email: ")
|
|
100
|
+
password = getpass.getpass("Password: ")
|
|
101
|
+
url = args.url or cfg["url"]
|
|
102
|
+
with HttpClient(token=None, base_url=url) as http:
|
|
103
|
+
body = http.request(
|
|
104
|
+
"POST",
|
|
105
|
+
"/api/auth/token",
|
|
106
|
+
json={"username": email, "password": password, "device_id": f"cli-{platform.node()}"},
|
|
107
|
+
)
|
|
108
|
+
cfg.update(token=body["token"], url=url)
|
|
109
|
+
_save(cfg)
|
|
110
|
+
me = Mechbase(token=cfg["token"], base_url=url).me()
|
|
111
|
+
print(f"Signed in as {me.user.email or me.user.username} on {url}")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def cmd_whoami(args, cfg):
|
|
115
|
+
me = _client(cfg).me()
|
|
116
|
+
current = int(cfg.get("installation") or me.current_installation_id)
|
|
117
|
+
rows = [{"id": i.installation_id, "name": i.name, "current": "*" if i.installation_id == current else ""}
|
|
118
|
+
for i in me.installations]
|
|
119
|
+
if not args.json:
|
|
120
|
+
print(f"{me.user.email or me.user.username} @ {cfg['url']}")
|
|
121
|
+
_out(args, rows, ["current", "id", "name"])
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def cmd_use(args, cfg):
|
|
125
|
+
cfg["installation"] = args.installation_id
|
|
126
|
+
_save(cfg)
|
|
127
|
+
print(f"Using installation {args.installation_id}")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def cmd_assets(args, cfg):
|
|
131
|
+
inst = _inst(args, cfg, _client(cfg))
|
|
132
|
+
rows = [{"id": a.asset_id, "name": a.name, "status": STATUS.get(a.status, a.status)} for a in inst.assets.list(q=args.q, limit=args.limit)]
|
|
133
|
+
_out(args, rows, ["id", "name", "status"])
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def cmd_points(args, cfg):
|
|
137
|
+
inst = _inst(args, cfg, _client(cfg))
|
|
138
|
+
pts = inst.measurement_points.list(q=args.q, asset_id=args.asset, limit=args.limit)
|
|
139
|
+
rows = [{"id": p.point_id, "asset": p.asset_id, "name": p.name, "type": p.transducer_type,
|
|
140
|
+
"unit": p.measurement_unit_code, "status": STATUS.get(p.status, p.status)} for p in pts]
|
|
141
|
+
_out(args, rows, ["id", "asset", "name", "type", "unit", "status"])
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _reading_row(m) -> dict:
|
|
145
|
+
data = {k: m.data[k] for k in HEADLINE if k in m.data} or m.data
|
|
146
|
+
vals = ", ".join(f"{k}={v:.3g}" if isinstance(v, (int, float)) else f"{k}={v}" for k, v in data.items())
|
|
147
|
+
return {"reading": m.point_sequence, "when": m.created_at[:16].replace("T", " "), "state": m.status, "values": vals}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def cmd_readings(args, cfg):
|
|
151
|
+
inst = _inst(args, cfg, _client(cfg))
|
|
152
|
+
ms = inst.measurements.list_for_point(args.point, limit=args.limit)
|
|
153
|
+
if args.json:
|
|
154
|
+
print(json.dumps([m.__dict__ for m in ms], indent=2, default=str))
|
|
155
|
+
return
|
|
156
|
+
_out(args, [_reading_row(m) for m in ms], ["reading", "when", "state", "values"])
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def cmd_reading_show(args, cfg):
|
|
160
|
+
inst = _inst(args, cfg, _client(cfg))
|
|
161
|
+
m = inst.measurements.get(args.point, args.reading)
|
|
162
|
+
spec = inst.measurements.spectra(m.uuid) if args.peaks else {}
|
|
163
|
+
found = peaks(spec.get("freq_hz") or [], spec.get(args.signal) or [], top=args.peaks, line_hz=args.line_hz)
|
|
164
|
+
if args.json:
|
|
165
|
+
print(json.dumps({**m.__dict__, "peaks": found, "signal": args.signal}, indent=2, default=str))
|
|
166
|
+
return
|
|
167
|
+
r = _reading_row(m)
|
|
168
|
+
print(f"Point {args.point} · reading {m.point_sequence} · {r['when']} · {m.status.upper()}")
|
|
169
|
+
width = max(map(len, [*m.data, "file"]))
|
|
170
|
+
for k, v in m.data.items():
|
|
171
|
+
print(f" {k:<{width}} {v}")
|
|
172
|
+
if m.file_url:
|
|
173
|
+
print(f" {'file':<{width}} {m.file_url}")
|
|
174
|
+
if args.peaks:
|
|
175
|
+
if found:
|
|
176
|
+
print(f"\nTop {len(found)} {args.signal} peaks:")
|
|
177
|
+
_out(args, found, ["hz", "amplitude", "note"])
|
|
178
|
+
else:
|
|
179
|
+
print("\nNo spectrum (reading has no waveform).")
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def cmd_reading_delete(args, cfg):
|
|
183
|
+
inst = _inst(args, cfg, _client(cfg))
|
|
184
|
+
if not args.yes:
|
|
185
|
+
m = inst.measurements.get(args.point, args.reading)
|
|
186
|
+
print(_reading_row(m))
|
|
187
|
+
if input(f"Delete reading {args.reading} of point {args.point}? It cannot be undone. [y/N] ").lower() != "y":
|
|
188
|
+
sys.exit("Cancelled.")
|
|
189
|
+
inst.measurements.delete(args.point, args.reading)
|
|
190
|
+
print(f"Deleted reading {args.reading} of point {args.point}.")
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
# --- wiring -----------------------------------------------------------------
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
197
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
198
|
+
common.add_argument("--json", action="store_true", help="machine-readable output")
|
|
199
|
+
common.add_argument("-i", "--installation", type=int, help="installation id (default: `mechbase use`, else your current one)")
|
|
200
|
+
|
|
201
|
+
p = argparse.ArgumentParser(prog="mechbase", description="Mechbase from the command line.")
|
|
202
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
203
|
+
|
|
204
|
+
s = sub.add_parser("login", help="sign in and store a token")
|
|
205
|
+
s.add_argument("--email")
|
|
206
|
+
s.add_argument("--url", help=f"server (default {Mechbase.DEFAULT_BASE_URL})")
|
|
207
|
+
s.set_defaults(fn=cmd_login)
|
|
208
|
+
|
|
209
|
+
s = sub.add_parser("whoami", parents=[common], help="who you are and which installations you can see")
|
|
210
|
+
s.set_defaults(fn=cmd_whoami)
|
|
211
|
+
|
|
212
|
+
s = sub.add_parser("use", help="set the default installation")
|
|
213
|
+
s.add_argument("installation_id", type=int)
|
|
214
|
+
s.set_defaults(fn=cmd_use)
|
|
215
|
+
|
|
216
|
+
s = sub.add_parser("assets", parents=[common], help="list assets")
|
|
217
|
+
s.add_argument("-q", default="", help="search")
|
|
218
|
+
s.add_argument("-n", "--limit", type=int, default=100)
|
|
219
|
+
s.set_defaults(fn=cmd_assets)
|
|
220
|
+
|
|
221
|
+
s = sub.add_parser("points", parents=[common], help="list measurement points")
|
|
222
|
+
s.add_argument("--asset", type=int)
|
|
223
|
+
s.add_argument("-q", default="", help="search")
|
|
224
|
+
s.add_argument("-n", "--limit", type=int, default=100)
|
|
225
|
+
s.set_defaults(fn=cmd_points)
|
|
226
|
+
|
|
227
|
+
s = sub.add_parser("readings", parents=[common], help="latest readings of a point")
|
|
228
|
+
s.add_argument("point", type=int)
|
|
229
|
+
s.add_argument("-n", "--limit", type=int, default=20)
|
|
230
|
+
s.set_defaults(fn=cmd_readings)
|
|
231
|
+
|
|
232
|
+
reading = sub.add_parser("reading", help="one reading").add_subparsers(dest="action", required=True)
|
|
233
|
+
s = reading.add_parser("show", parents=[common], help="values, state and spectrum peaks")
|
|
234
|
+
s.add_argument("point", type=int)
|
|
235
|
+
s.add_argument("reading", type=int, help="the number in the web URL")
|
|
236
|
+
s.add_argument("--peaks", type=int, default=10, help="how many spectrum peaks (0 = skip spectrum)")
|
|
237
|
+
s.add_argument("--signal", choices=["velocity", "acceleration", "envelope"], default="velocity")
|
|
238
|
+
s.add_argument("--line-hz", type=float, default=50.0, help="mains frequency for the electrical tag (60 in the Americas)")
|
|
239
|
+
s.set_defaults(fn=cmd_reading_show)
|
|
240
|
+
|
|
241
|
+
s = reading.add_parser("delete", parents=[common], help="delete a reading")
|
|
242
|
+
s.add_argument("point", type=int)
|
|
243
|
+
s.add_argument("reading", type=int)
|
|
244
|
+
s.add_argument("-y", "--yes", action="store_true", help="skip the confirmation")
|
|
245
|
+
s.set_defaults(fn=cmd_reading_delete)
|
|
246
|
+
return p
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def main(argv: list[str] | None = None) -> None:
|
|
250
|
+
args = build_parser().parse_args(argv)
|
|
251
|
+
try:
|
|
252
|
+
args.fn(args, _load())
|
|
253
|
+
except MechbaseError as e:
|
|
254
|
+
if isinstance(e.body, str) and "<html" in e.body.lower():
|
|
255
|
+
# a proxy/error page, not the API: don't dump the HTML
|
|
256
|
+
sys.exit(f"Error: {e.status} from {_load()['url']} (server unavailable or not a Mechbase API)")
|
|
257
|
+
sys.exit(f"Error: {e}")
|
|
258
|
+
except KeyboardInterrupt:
|
|
259
|
+
sys.exit(130)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
if __name__ == "__main__":
|
|
263
|
+
main()
|
|
@@ -5,7 +5,7 @@ import json
|
|
|
5
5
|
from pathlib import Path
|
|
6
6
|
from typing import Any, BinaryIO
|
|
7
7
|
|
|
8
|
-
from ..models import BatchResult, FileAttachment, Measurement
|
|
8
|
+
from ..models import BatchResult, DeleteResult, FileAttachment, Measurement
|
|
9
9
|
from ._base import InstallationScoped, _paginated
|
|
10
10
|
|
|
11
11
|
|
|
@@ -67,6 +67,22 @@ class Measurements(InstallationScoped):
|
|
|
67
67
|
parse=Measurement.from_dict,
|
|
68
68
|
)
|
|
69
69
|
|
|
70
|
+
def get(self, point_id: int, point_sequence: int) -> Measurement:
|
|
71
|
+
"""One reading, by the number shown in the web URL (…/measurements/766/)."""
|
|
72
|
+
return Measurement.from_dict(
|
|
73
|
+
self._http.request("GET", self._path(f"/measurement-points/{point_id}/measurements/{point_sequence}/"))
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
def delete(self, point_id: int, point_sequence: int) -> DeleteResult:
|
|
77
|
+
"""Delete one reading; the point's state rolls back to its newest surviving reading."""
|
|
78
|
+
return DeleteResult.from_dict(
|
|
79
|
+
self._http.request("DELETE", self._path(f"/measurement-points/{point_id}/measurements/{point_sequence}/"))
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
def spectra(self, measurement_uuid: str) -> dict:
|
|
83
|
+
"""FFT arrays: freq_hz, velocity, acceleration, envelope (empty without a waveform)."""
|
|
84
|
+
return self._http.request("GET", self._path(f"/analytics/measurements/{measurement_uuid}/spectra/"))
|
|
85
|
+
|
|
70
86
|
def create_batch(self, items: list[dict]) -> BatchResult:
|
|
71
87
|
body = self._http.request(
|
|
72
88
|
"POST", self._path("/measurements/batch/"), json={"items": list(items)}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""CLI: peak tagging + the reading show/delete round trip, offline via respx."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
import respx
|
|
7
|
+
|
|
8
|
+
from mechbase.cli import main, peaks
|
|
9
|
+
|
|
10
|
+
READING = {
|
|
11
|
+
"uuid": "u-766", "measurement_point_id": 2, "point_sequence": 766, "data": {"rms": 0.62},
|
|
12
|
+
"status": "warning", "notes": "", "created_at": "2026-11-14T14:02:00Z",
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_peaks_tags_mains_multiples_only():
|
|
17
|
+
freq = [i * 0.5 for i in range(400)] # 0..199.5 Hz
|
|
18
|
+
amp = [0.0] * 400
|
|
19
|
+
amp[200] = 3.0 # 100 Hz -> 2×50
|
|
20
|
+
amp[49] = 0.5 # 24.5 Hz -> shaft, untagged
|
|
21
|
+
found = peaks(freq, amp, top=5)
|
|
22
|
+
assert found[0] == {"hz": 100.0, "amplitude": 3.0, "note": "2×50 Hz (electrical)"}
|
|
23
|
+
assert found[1]["hz"] == 24.5 and found[1]["note"] == ""
|
|
24
|
+
# a shaft line one bin off a mains multiple is not electrical
|
|
25
|
+
amp[103] = 1.0 # 51.5 Hz
|
|
26
|
+
assert next(p for p in peaks(freq, amp) if p["hz"] == 51.5)["note"] == ""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@respx.mock
|
|
30
|
+
def test_reading_show_and_delete(monkeypatch, tmp_path, capsys):
|
|
31
|
+
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
|
|
32
|
+
monkeypatch.setenv("MECHBASE_TOKEN", "tok")
|
|
33
|
+
monkeypatch.setenv("MECHBASE_URL", "https://example.test")
|
|
34
|
+
base = "https://example.test/api/installations/2044"
|
|
35
|
+
respx.get(f"{base}/measurement-points/2/measurements/766/").mock(return_value=httpx.Response(200, json=READING))
|
|
36
|
+
respx.get(f"{base}/analytics/measurements/u-766/spectra/").mock(
|
|
37
|
+
return_value=httpx.Response(200, json={"freq_hz": [0, 50, 100, 150], "velocity": [0, 1, 3, 0]})
|
|
38
|
+
)
|
|
39
|
+
delete = respx.delete(f"{base}/measurement-points/2/measurements/766/").mock(
|
|
40
|
+
return_value=httpx.Response(200, json={"deleted": True, "uuid": "u-766"})
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
main(["reading", "show", "-i", "2044", "2", "766"])
|
|
44
|
+
out = capsys.readouterr().out
|
|
45
|
+
assert "WARNING" in out and "2×50 Hz (electrical)" in out
|
|
46
|
+
|
|
47
|
+
main(["reading", "delete", "-i", "2044", "-y", "2", "766"])
|
|
48
|
+
assert delete.called
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@respx.mock
|
|
52
|
+
def test_html_error_page_is_not_dumped(monkeypatch, tmp_path):
|
|
53
|
+
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
|
|
54
|
+
monkeypatch.setenv("MECHBASE_TOKEN", "tok")
|
|
55
|
+
monkeypatch.setenv("MECHBASE_URL", "https://example.test")
|
|
56
|
+
respx.get("https://example.test/api/me/").mock(
|
|
57
|
+
return_value=httpx.Response(503, text="<!DOCTYPE html><html><body>Service Not Available</body></html>")
|
|
58
|
+
)
|
|
59
|
+
try:
|
|
60
|
+
main(["whoami"])
|
|
61
|
+
except SystemExit as e:
|
|
62
|
+
assert str(e.code) == "Error: 503 from https://example.test (server unavailable or not a Mechbase API)"
|
|
63
|
+
else:
|
|
64
|
+
raise AssertionError("expected exit")
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|