mechbase 0.2.0__py3-none-any.whl
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/__init__.py +16 -0
- mechbase/_http.py +84 -0
- mechbase/client.py +55 -0
- mechbase/errors.py +27 -0
- mechbase/maintnode.py +75 -0
- mechbase/models.py +365 -0
- mechbase/resources/__init__.py +0 -0
- mechbase/resources/_base.py +28 -0
- mechbase/resources/measurements.py +122 -0
- mechbase/resources/registry.py +134 -0
- mechbase/resources/routes.py +120 -0
- mechbase-0.2.0.dist-info/METADATA +40 -0
- mechbase-0.2.0.dist-info/RECORD +14 -0
- mechbase-0.2.0.dist-info/WHEEL +4 -0
mechbase/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Mechbase Python SDK."""
|
|
2
|
+
|
|
3
|
+
from .client import Mechbase
|
|
4
|
+
from .errors import MechbaseError, AuthError, NotFoundError, ValidationError, ConflictError, PayloadTooLargeError
|
|
5
|
+
from .maintnode import MaintNode
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"Mechbase",
|
|
9
|
+
"MechbaseError",
|
|
10
|
+
"AuthError",
|
|
11
|
+
"NotFoundError",
|
|
12
|
+
"ValidationError",
|
|
13
|
+
"ConflictError",
|
|
14
|
+
"PayloadTooLargeError",
|
|
15
|
+
"MaintNode",
|
|
16
|
+
]
|
mechbase/_http.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
|
|
7
|
+
from .errors import (
|
|
8
|
+
AuthError,
|
|
9
|
+
ConflictError,
|
|
10
|
+
MechbaseError,
|
|
11
|
+
NotFoundError,
|
|
12
|
+
PayloadTooLargeError,
|
|
13
|
+
ValidationError,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class HttpClient:
|
|
18
|
+
def __init__(self, *, token: str | None, base_url: str, timeout: float = 30.0):
|
|
19
|
+
headers = {
|
|
20
|
+
"User-Agent": "mechbase-python/0.2",
|
|
21
|
+
"Accept": "application/json",
|
|
22
|
+
}
|
|
23
|
+
if token:
|
|
24
|
+
headers["Authorization"] = f"Bearer {token}"
|
|
25
|
+
self._client = httpx.Client(
|
|
26
|
+
base_url=base_url.rstrip("/"),
|
|
27
|
+
headers=headers,
|
|
28
|
+
timeout=timeout,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
def close(self) -> None:
|
|
32
|
+
self._client.close()
|
|
33
|
+
|
|
34
|
+
def __enter__(self):
|
|
35
|
+
return self
|
|
36
|
+
|
|
37
|
+
def __exit__(self, *a):
|
|
38
|
+
self.close()
|
|
39
|
+
|
|
40
|
+
def request(
|
|
41
|
+
self,
|
|
42
|
+
method: str,
|
|
43
|
+
path: str,
|
|
44
|
+
*,
|
|
45
|
+
params: dict | None = None,
|
|
46
|
+
json: Any = None,
|
|
47
|
+
data: dict | None = None,
|
|
48
|
+
files: dict | None = None,
|
|
49
|
+
) -> Any:
|
|
50
|
+
response = self._client.request(
|
|
51
|
+
method,
|
|
52
|
+
path,
|
|
53
|
+
params=params,
|
|
54
|
+
json=json,
|
|
55
|
+
data=data,
|
|
56
|
+
files=files,
|
|
57
|
+
)
|
|
58
|
+
return self._handle(response)
|
|
59
|
+
|
|
60
|
+
@staticmethod
|
|
61
|
+
def _handle(response: httpx.Response) -> Any:
|
|
62
|
+
if response.status_code == 204:
|
|
63
|
+
return None
|
|
64
|
+
try:
|
|
65
|
+
body = response.json()
|
|
66
|
+
except Exception:
|
|
67
|
+
body = response.text
|
|
68
|
+
|
|
69
|
+
if 200 <= response.status_code < 300:
|
|
70
|
+
return body
|
|
71
|
+
|
|
72
|
+
detail = body.get("detail") if isinstance(body, dict) else str(body)
|
|
73
|
+
message = f"{response.status_code} {detail}"
|
|
74
|
+
if response.status_code in (401, 403):
|
|
75
|
+
raise AuthError(message, status=response.status_code, body=body)
|
|
76
|
+
if response.status_code == 404:
|
|
77
|
+
raise NotFoundError(message, status=response.status_code, body=body)
|
|
78
|
+
if response.status_code == 422:
|
|
79
|
+
raise ValidationError(message, status=response.status_code, body=body)
|
|
80
|
+
if response.status_code == 409:
|
|
81
|
+
raise ConflictError(message, status=response.status_code, body=body)
|
|
82
|
+
if response.status_code == 413:
|
|
83
|
+
raise PayloadTooLargeError(message, status=response.status_code, body=body)
|
|
84
|
+
raise MechbaseError(message, status=response.status_code, body=body)
|
mechbase/client.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from ._http import HttpClient
|
|
4
|
+
from .models import Me
|
|
5
|
+
from .resources.measurements import Measurements
|
|
6
|
+
from .resources.registry import Assets, MeasurementPoints, Sections, Zones
|
|
7
|
+
from .resources.routes import Routes
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class InstallationHandle:
|
|
11
|
+
"""All resources scoped to a single installation."""
|
|
12
|
+
|
|
13
|
+
def __init__(self, http: HttpClient, installation_id: int):
|
|
14
|
+
self._http = http
|
|
15
|
+
self.installation_id = installation_id
|
|
16
|
+
self.assets = Assets(http, installation_id)
|
|
17
|
+
self.measurement_points = MeasurementPoints(http, installation_id)
|
|
18
|
+
self.measurements = Measurements(http, installation_id)
|
|
19
|
+
self.routes = Routes(http, installation_id)
|
|
20
|
+
self.sections = Sections(http, installation_id)
|
|
21
|
+
self.zones = Zones(http, installation_id)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Mechbase:
|
|
25
|
+
"""Top-level client.
|
|
26
|
+
|
|
27
|
+
Usage::
|
|
28
|
+
|
|
29
|
+
from mechbase import Mechbase
|
|
30
|
+
|
|
31
|
+
client = Mechbase(token="...") # defaults to https://app.mechbase.io
|
|
32
|
+
me = client.me()
|
|
33
|
+
inst = client.for_installation(me.current_installation_id)
|
|
34
|
+
inst.measurements.create(point_id=1, data={"rms": 2.3})
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
DEFAULT_BASE_URL = "https://app.mechbase.io"
|
|
38
|
+
|
|
39
|
+
def __init__(self, *, token: str, base_url: str = DEFAULT_BASE_URL, timeout: float = 30.0):
|
|
40
|
+
self._http = HttpClient(token=token, base_url=base_url, timeout=timeout)
|
|
41
|
+
|
|
42
|
+
def me(self) -> Me:
|
|
43
|
+
return Me.from_dict(self._http.request("GET", "/api/me/"))
|
|
44
|
+
|
|
45
|
+
def for_installation(self, installation_id: int) -> InstallationHandle:
|
|
46
|
+
return InstallationHandle(self._http, installation_id)
|
|
47
|
+
|
|
48
|
+
def close(self) -> None:
|
|
49
|
+
self._http.close()
|
|
50
|
+
|
|
51
|
+
def __enter__(self):
|
|
52
|
+
return self
|
|
53
|
+
|
|
54
|
+
def __exit__(self, *a):
|
|
55
|
+
self.close()
|
mechbase/errors.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
class MechbaseError(Exception):
|
|
2
|
+
"""Base class for all SDK errors."""
|
|
3
|
+
|
|
4
|
+
def __init__(self, message: str, *, status: int | None = None, body=None):
|
|
5
|
+
super().__init__(message)
|
|
6
|
+
self.status = status
|
|
7
|
+
self.body = body
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class AuthError(MechbaseError):
|
|
11
|
+
"""401 / 403."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class NotFoundError(MechbaseError):
|
|
15
|
+
"""404."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ValidationError(MechbaseError):
|
|
19
|
+
"""422."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ConflictError(MechbaseError):
|
|
23
|
+
"""409."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class PayloadTooLargeError(MechbaseError):
|
|
27
|
+
"""413."""
|
mechbase/maintnode.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import io
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, BinaryIO
|
|
6
|
+
|
|
7
|
+
from ._http import HttpClient
|
|
8
|
+
from .models import MeasurementResult
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class MaintNode:
|
|
12
|
+
"""Device-facing client for the maintnode integration API.
|
|
13
|
+
|
|
14
|
+
Unauthenticated; the node is identified by ``node_uuid`` in the path.
|
|
15
|
+
|
|
16
|
+
Usage::
|
|
17
|
+
|
|
18
|
+
node = MaintNode(node_uuid="...") # defaults to https://app.mechbase.io
|
|
19
|
+
cfg = node.config()
|
|
20
|
+
node.push_measurements([{"mapping_uuid": "...", "data": {"rms": 2.3}}])
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
DEFAULT_BASE_URL = "https://app.mechbase.io"
|
|
24
|
+
|
|
25
|
+
def __init__(self, *, node_uuid: str, base_url: str = DEFAULT_BASE_URL, timeout: float = 30.0):
|
|
26
|
+
self._http = HttpClient(token=None, base_url=base_url, timeout=timeout)
|
|
27
|
+
self.node_uuid = node_uuid
|
|
28
|
+
|
|
29
|
+
def _path(self, suffix: str) -> str:
|
|
30
|
+
return f"/api/maintnode/{self.node_uuid}{suffix}"
|
|
31
|
+
|
|
32
|
+
def config(self) -> str:
|
|
33
|
+
return self._http.request("GET", self._path("/config/"))
|
|
34
|
+
|
|
35
|
+
def heartbeat(self, *, balena_uuid: str = "", services: dict | None = None) -> dict:
|
|
36
|
+
return self._http.request(
|
|
37
|
+
"POST", self._path("/heartbeat/"),
|
|
38
|
+
json={"balena_uuid": balena_uuid, "services": services or {}},
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
def push_measurements(self, items: list[dict]) -> list[MeasurementResult]:
|
|
42
|
+
body = self._http.request(
|
|
43
|
+
"POST", self._path("/measurements/"), json={"measurements": list(items)}
|
|
44
|
+
)
|
|
45
|
+
return [MeasurementResult.from_dict(r) for r in body]
|
|
46
|
+
|
|
47
|
+
def add_measurement_file(
|
|
48
|
+
self, measurement_uuid: str, *,
|
|
49
|
+
file: str | Path | BinaryIO | bytes, filename: str = "attachment",
|
|
50
|
+
) -> dict:
|
|
51
|
+
fh: Any = file
|
|
52
|
+
opened = False
|
|
53
|
+
if isinstance(file, (str, Path)):
|
|
54
|
+
filename = Path(file).name
|
|
55
|
+
fh = open(file, "rb") # noqa: SIM115
|
|
56
|
+
opened = True
|
|
57
|
+
elif isinstance(file, (bytes, bytearray)):
|
|
58
|
+
fh = io.BytesIO(file)
|
|
59
|
+
try:
|
|
60
|
+
return self._http.request(
|
|
61
|
+
"POST", self._path(f"/measurements/{measurement_uuid}/file/"),
|
|
62
|
+
files={"file": (filename, fh)},
|
|
63
|
+
)
|
|
64
|
+
finally:
|
|
65
|
+
if opened:
|
|
66
|
+
fh.close()
|
|
67
|
+
|
|
68
|
+
def close(self) -> None:
|
|
69
|
+
self._http.close()
|
|
70
|
+
|
|
71
|
+
def __enter__(self):
|
|
72
|
+
return self
|
|
73
|
+
|
|
74
|
+
def __exit__(self, *a):
|
|
75
|
+
self.close()
|
mechbase/models.py
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
"""Lightweight dataclass mirrors of the API response schemas.
|
|
2
|
+
|
|
3
|
+
Kept intentionally small; unknown fields are preserved in ``extra`` so the SDK
|
|
4
|
+
doesn't break when the API adds fields.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _pop(d: dict, key: str, default=None):
|
|
14
|
+
return d.pop(key, default) if key in d else default
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class User:
|
|
19
|
+
id: int
|
|
20
|
+
username: str
|
|
21
|
+
full_name: str
|
|
22
|
+
email: str
|
|
23
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
24
|
+
|
|
25
|
+
@classmethod
|
|
26
|
+
def from_dict(cls, d: dict) -> "User":
|
|
27
|
+
d = dict(d)
|
|
28
|
+
return cls(
|
|
29
|
+
id=d.pop("id"),
|
|
30
|
+
username=d.pop("username"),
|
|
31
|
+
# `d.pop("full_name")` raises on missing *and* silently coerces a
|
|
32
|
+
# present-but-null value to `None`, lying about the type. Mirror
|
|
33
|
+
# the Kotlin `coerceInputValues = true` + default pattern (and
|
|
34
|
+
# the Swift `(try? decode(...)) ?? ""` pattern) by falling back
|
|
35
|
+
# to "" on *either* case. The `or ""` (vs. `d.pop(..., "")`) is
|
|
36
|
+
# what handles the present-but-null case — `dict.get`'s default
|
|
37
|
+
# only fires on missing keys, not on None values. The property
|
|
38
|
+
# stays `str`; the type stops lying. See issue #2.
|
|
39
|
+
full_name=d.pop("full_name") or "",
|
|
40
|
+
email=d.pop("email") or "",
|
|
41
|
+
extra=d,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class Installation:
|
|
47
|
+
installation_id: int
|
|
48
|
+
name: str
|
|
49
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
50
|
+
|
|
51
|
+
@classmethod
|
|
52
|
+
def from_dict(cls, d: dict) -> "Installation":
|
|
53
|
+
d = dict(d)
|
|
54
|
+
return cls(
|
|
55
|
+
installation_id=d.pop("installation_id"),
|
|
56
|
+
name=d.pop("name"),
|
|
57
|
+
extra=d,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass
|
|
62
|
+
class Me:
|
|
63
|
+
user: User
|
|
64
|
+
installations: list[Installation]
|
|
65
|
+
current_installation_id: int
|
|
66
|
+
|
|
67
|
+
@classmethod
|
|
68
|
+
def from_dict(cls, d: dict) -> "Me":
|
|
69
|
+
return cls(
|
|
70
|
+
user=User.from_dict(d["user"]),
|
|
71
|
+
installations=[Installation.from_dict(i) for i in d["installations"]],
|
|
72
|
+
current_installation_id=d["current_installation_id"],
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass
|
|
77
|
+
class Asset:
|
|
78
|
+
uuid: str
|
|
79
|
+
asset_id: int | None
|
|
80
|
+
name: str
|
|
81
|
+
section_id: int | None
|
|
82
|
+
zone_id: int | None
|
|
83
|
+
machine_class: str
|
|
84
|
+
equipment_type: str
|
|
85
|
+
status: int
|
|
86
|
+
external_id: str | None = None
|
|
87
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
88
|
+
|
|
89
|
+
@classmethod
|
|
90
|
+
def from_dict(cls, d: dict) -> "Asset":
|
|
91
|
+
d = dict(d)
|
|
92
|
+
return cls(
|
|
93
|
+
uuid=d.pop("uuid"),
|
|
94
|
+
asset_id=d.pop("asset_id", None),
|
|
95
|
+
name=d.pop("name"),
|
|
96
|
+
section_id=d.pop("section_id", None),
|
|
97
|
+
zone_id=d.pop("zone_id", None),
|
|
98
|
+
machine_class=d.pop("machine_class", ""),
|
|
99
|
+
equipment_type=d.pop("equipment_type", ""),
|
|
100
|
+
status=d.pop("status"),
|
|
101
|
+
external_id=d.pop("external_id", None),
|
|
102
|
+
extra=d,
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@dataclass
|
|
107
|
+
class MeasurementPoint:
|
|
108
|
+
uuid: str
|
|
109
|
+
point_id: int | None
|
|
110
|
+
name: str
|
|
111
|
+
asset_id: int | None
|
|
112
|
+
# Backing columns are `blank=True, default=""` NOT NULL by intent, but
|
|
113
|
+
# they're optional metadata drift-plausible from a legacy import. The
|
|
114
|
+
# original `d["key"]` access raises on missing *and* silently coerces a
|
|
115
|
+
# present-but-null value to `None`, lying about the type. Switch to
|
|
116
|
+
# `d.get("key") or ""` to mirror the Kotlin `coerceInputValues = true`
|
|
117
|
+
# plus a default, and the Swift `(try? decode(...)) ?? ""` pattern.
|
|
118
|
+
# The `or ""` (vs. `d.get("key", "")`) is what handles the
|
|
119
|
+
# present-but-null case — `dict.get`'s default only fires on missing
|
|
120
|
+
# keys, not on None values. Properties stay `str` (no call-site
|
|
121
|
+
# changes); the decode path is what becomes resilient. See issue #2.
|
|
122
|
+
transducer_type: str
|
|
123
|
+
measurement_unit_code: str
|
|
124
|
+
location: str
|
|
125
|
+
status: int
|
|
126
|
+
external_id: str | None = None
|
|
127
|
+
# Effective working instruction (the point's override, else the
|
|
128
|
+
# transducer-type default) as sanitized HTML; embedded image URLs are
|
|
129
|
+
# absolute. The server always populates it; `or ""` keeps decode resilient.
|
|
130
|
+
instructions: str = ""
|
|
131
|
+
|
|
132
|
+
@classmethod
|
|
133
|
+
def from_dict(cls, d: dict) -> "MeasurementPoint":
|
|
134
|
+
return cls(
|
|
135
|
+
uuid=d["uuid"],
|
|
136
|
+
point_id=d["point_id"],
|
|
137
|
+
name=d["name"],
|
|
138
|
+
asset_id=d["asset_id"],
|
|
139
|
+
transducer_type=d.get("transducer_type") or "",
|
|
140
|
+
measurement_unit_code=d.get("measurement_unit_code") or "",
|
|
141
|
+
location=d.get("location") or "",
|
|
142
|
+
status=d["status"],
|
|
143
|
+
external_id=d.get("external_id"),
|
|
144
|
+
instructions=d.get("instructions") or "",
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@dataclass
|
|
149
|
+
class Measurement:
|
|
150
|
+
uuid: str
|
|
151
|
+
measurement_point_id: int
|
|
152
|
+
# `point_sequence` is genuinely DB-nullable on the server
|
|
153
|
+
# (`Measurement.point_sequence: null=True`); new rows always get a
|
|
154
|
+
# value via `MeasurementService.create`, but legacy/imported rows can
|
|
155
|
+
# be null. Mirror the Kotlin/Swift widening: type widens to
|
|
156
|
+
# `int | None` and the decoder uses `d.get(...)` (no default — null
|
|
157
|
+
# is a meaningful state, not a missing-data state). Callers must
|
|
158
|
+
# handle "no sequence." See issue #2.
|
|
159
|
+
point_sequence: int | None
|
|
160
|
+
data: dict
|
|
161
|
+
status: str
|
|
162
|
+
# `or ""` (vs. `d.get("notes", "")`) coerces a present-but-null to "",
|
|
163
|
+
# not just a missing key — same null-coercion rationale as the other
|
|
164
|
+
# defaulted text fields in this file. See issue #2.
|
|
165
|
+
notes: str
|
|
166
|
+
created_at: str
|
|
167
|
+
external_id: str | None = None
|
|
168
|
+
file_url: str | None = None
|
|
169
|
+
|
|
170
|
+
@classmethod
|
|
171
|
+
def from_dict(cls, d: dict) -> "Measurement":
|
|
172
|
+
return cls(
|
|
173
|
+
uuid=d["uuid"],
|
|
174
|
+
measurement_point_id=d["measurement_point_id"],
|
|
175
|
+
point_sequence=d.get("point_sequence"),
|
|
176
|
+
data=d["data"],
|
|
177
|
+
status=d["status"],
|
|
178
|
+
notes=d.get("notes") or "",
|
|
179
|
+
created_at=d["created_at"],
|
|
180
|
+
external_id=d.get("external_id"),
|
|
181
|
+
file_url=d.get("file_url"),
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
@dataclass
|
|
186
|
+
class Route:
|
|
187
|
+
uuid: str
|
|
188
|
+
name: str
|
|
189
|
+
description: str
|
|
190
|
+
|
|
191
|
+
@classmethod
|
|
192
|
+
def from_dict(cls, d: dict) -> "Route":
|
|
193
|
+
# `or ""` (vs. `d.get("description", "")`) coerces a
|
|
194
|
+
# present-but-null to "" — same rationale as the other defaulted
|
|
195
|
+
# text fields. The exact production crash on installations 2012/2013
|
|
196
|
+
# (issue #164 server side; #2 client side). See issue #2.
|
|
197
|
+
return cls(uuid=d["uuid"], name=d["name"], description=d.get("description") or "")
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
@dataclass
|
|
201
|
+
class RouteExecution:
|
|
202
|
+
uuid: str
|
|
203
|
+
route_uuid: str
|
|
204
|
+
status: str
|
|
205
|
+
started_at: str | None
|
|
206
|
+
completed_at: str | None
|
|
207
|
+
session_id: str
|
|
208
|
+
|
|
209
|
+
@classmethod
|
|
210
|
+
def from_dict(cls, d: dict) -> "RouteExecution":
|
|
211
|
+
return cls(
|
|
212
|
+
uuid=d["uuid"],
|
|
213
|
+
route_uuid=d["route_uuid"],
|
|
214
|
+
status=d["status"],
|
|
215
|
+
started_at=d.get("started_at"),
|
|
216
|
+
completed_at=d.get("completed_at"),
|
|
217
|
+
session_id=d["session_id"],
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@dataclass
|
|
222
|
+
class ItemResponse:
|
|
223
|
+
uuid: str
|
|
224
|
+
route_item_uuid: str
|
|
225
|
+
data: dict
|
|
226
|
+
notes: str
|
|
227
|
+
status: int
|
|
228
|
+
created_at: str
|
|
229
|
+
|
|
230
|
+
@classmethod
|
|
231
|
+
def from_dict(cls, d: dict) -> "ItemResponse":
|
|
232
|
+
return cls(
|
|
233
|
+
uuid=d["uuid"],
|
|
234
|
+
route_item_uuid=d["route_item_uuid"],
|
|
235
|
+
# `or ""` (vs. `d.get(key, default)`) coerces a
|
|
236
|
+
# present-but-null to "" — see issue #2.
|
|
237
|
+
data=d.get("data") or {},
|
|
238
|
+
notes=d.get("notes") or "",
|
|
239
|
+
status=d["status"],
|
|
240
|
+
created_at=d["created_at"],
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
@dataclass
|
|
245
|
+
class Section:
|
|
246
|
+
uuid: str
|
|
247
|
+
section_id: int | None
|
|
248
|
+
name: str
|
|
249
|
+
external_id: str | None = None
|
|
250
|
+
|
|
251
|
+
@classmethod
|
|
252
|
+
def from_dict(cls, d: dict) -> "Section":
|
|
253
|
+
return cls(
|
|
254
|
+
uuid=d["uuid"],
|
|
255
|
+
section_id=d.get("section_id"),
|
|
256
|
+
name=d["name"],
|
|
257
|
+
external_id=d.get("external_id"),
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
@dataclass
|
|
262
|
+
class Zone:
|
|
263
|
+
uuid: str
|
|
264
|
+
zone_id: int | None
|
|
265
|
+
name: str
|
|
266
|
+
section_id: int | None = None
|
|
267
|
+
external_id: str | None = None
|
|
268
|
+
|
|
269
|
+
@classmethod
|
|
270
|
+
def from_dict(cls, d: dict) -> "Zone":
|
|
271
|
+
return cls(
|
|
272
|
+
uuid=d["uuid"],
|
|
273
|
+
zone_id=d.get("zone_id"),
|
|
274
|
+
name=d["name"],
|
|
275
|
+
section_id=d.get("section_id"),
|
|
276
|
+
external_id=d.get("external_id"),
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
@dataclass
|
|
281
|
+
class DeleteResult:
|
|
282
|
+
deleted: bool
|
|
283
|
+
uuid: str
|
|
284
|
+
|
|
285
|
+
@classmethod
|
|
286
|
+
def from_dict(cls, d: dict) -> "DeleteResult":
|
|
287
|
+
return cls(deleted=d["deleted"], uuid=d["uuid"])
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
@dataclass
|
|
291
|
+
class BatchItemResult:
|
|
292
|
+
index: int
|
|
293
|
+
status: str
|
|
294
|
+
measurement_point_id: int | None = None
|
|
295
|
+
point_sequence: int | None = None
|
|
296
|
+
uuid: str | None = None
|
|
297
|
+
external_id: str | None = None
|
|
298
|
+
detail: str | None = None
|
|
299
|
+
|
|
300
|
+
@classmethod
|
|
301
|
+
def from_dict(cls, d: dict) -> "BatchItemResult":
|
|
302
|
+
return cls(
|
|
303
|
+
index=d["index"],
|
|
304
|
+
status=d["status"],
|
|
305
|
+
measurement_point_id=d.get("measurement_point_id"),
|
|
306
|
+
point_sequence=d.get("point_sequence"),
|
|
307
|
+
uuid=d.get("uuid"),
|
|
308
|
+
external_id=d.get("external_id"),
|
|
309
|
+
detail=d.get("detail"),
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
@dataclass
|
|
314
|
+
class BatchResult:
|
|
315
|
+
created: int
|
|
316
|
+
duplicates: int
|
|
317
|
+
errors: int
|
|
318
|
+
results: list[BatchItemResult]
|
|
319
|
+
|
|
320
|
+
@classmethod
|
|
321
|
+
def from_dict(cls, d: dict) -> "BatchResult":
|
|
322
|
+
return cls(
|
|
323
|
+
created=d["created"],
|
|
324
|
+
duplicates=d["duplicates"],
|
|
325
|
+
errors=d["errors"],
|
|
326
|
+
results=[BatchItemResult.from_dict(r) for r in d["results"]],
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
@dataclass
|
|
331
|
+
class FileAttachment:
|
|
332
|
+
uuid: str
|
|
333
|
+
name: str
|
|
334
|
+
kind: str
|
|
335
|
+
file_url: str
|
|
336
|
+
created_at: str
|
|
337
|
+
|
|
338
|
+
@classmethod
|
|
339
|
+
def from_dict(cls, d: dict) -> "FileAttachment":
|
|
340
|
+
return cls(
|
|
341
|
+
uuid=d["uuid"],
|
|
342
|
+
name=d["name"],
|
|
343
|
+
kind=d["kind"],
|
|
344
|
+
file_url=d["file_url"],
|
|
345
|
+
created_at=d["created_at"],
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
@dataclass
|
|
350
|
+
class MeasurementResult:
|
|
351
|
+
mapping_uuid: str
|
|
352
|
+
ok: bool
|
|
353
|
+
measurement_uuid: str | None = None
|
|
354
|
+
local_uuid: str = ""
|
|
355
|
+
error: str = ""
|
|
356
|
+
|
|
357
|
+
@classmethod
|
|
358
|
+
def from_dict(cls, d: dict) -> "MeasurementResult":
|
|
359
|
+
return cls(
|
|
360
|
+
mapping_uuid=d["mapping_uuid"],
|
|
361
|
+
ok=d["ok"],
|
|
362
|
+
measurement_uuid=d.get("measurement_uuid"),
|
|
363
|
+
local_uuid=d.get("local_uuid", ""),
|
|
364
|
+
error=d.get("error", ""),
|
|
365
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING
|
|
4
|
+
|
|
5
|
+
if TYPE_CHECKING:
|
|
6
|
+
from .._http import HttpClient
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class InstallationScoped:
|
|
10
|
+
"""Mixin: holds an HttpClient and an installation_id."""
|
|
11
|
+
|
|
12
|
+
def __init__(self, http: "HttpClient", installation_id: int):
|
|
13
|
+
self._http = http
|
|
14
|
+
self._iid = installation_id
|
|
15
|
+
|
|
16
|
+
def _path(self, suffix: str) -> str:
|
|
17
|
+
return f"/api/installations/{self._iid}{suffix}"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _paginated(http, path: str, *, params: dict, parse) -> list:
|
|
21
|
+
params = {k: v for k, v in params.items() if v is not None and v != ""}
|
|
22
|
+
body = http.request("GET", path, params=params)
|
|
23
|
+
return [parse(i) for i in body["items"]]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _clean(d: dict) -> dict:
|
|
27
|
+
"""Drop keys whose value is None (keeps PATCH partial)."""
|
|
28
|
+
return {k: v for k, v in d.items() if v is not None}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import io
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any, BinaryIO
|
|
7
|
+
|
|
8
|
+
from ..models import BatchResult, FileAttachment, Measurement
|
|
9
|
+
from ._base import InstallationScoped, _paginated
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Measurements(InstallationScoped):
|
|
13
|
+
def create(
|
|
14
|
+
self,
|
|
15
|
+
*,
|
|
16
|
+
point_id: int,
|
|
17
|
+
data: dict,
|
|
18
|
+
notes: str = "",
|
|
19
|
+
session_id: str | None = None,
|
|
20
|
+
timestamp: str | None = None,
|
|
21
|
+
file: str | Path | BinaryIO | None = None,
|
|
22
|
+
) -> Measurement:
|
|
23
|
+
payload: dict[str, Any] = {
|
|
24
|
+
"measurement_point_id": point_id,
|
|
25
|
+
"data": data,
|
|
26
|
+
"notes": notes,
|
|
27
|
+
}
|
|
28
|
+
if session_id:
|
|
29
|
+
payload["session_id"] = session_id
|
|
30
|
+
if timestamp:
|
|
31
|
+
payload["timestamp"] = timestamp
|
|
32
|
+
|
|
33
|
+
if file is None:
|
|
34
|
+
body = self._http.request(
|
|
35
|
+
"POST", self._path("/measurements/"), json=payload
|
|
36
|
+
)
|
|
37
|
+
return Measurement.from_dict(body)
|
|
38
|
+
|
|
39
|
+
fh = file
|
|
40
|
+
opened = False
|
|
41
|
+
if isinstance(file, (str, Path)):
|
|
42
|
+
fh = open(file, "rb") # noqa: SIM115
|
|
43
|
+
opened = True
|
|
44
|
+
try:
|
|
45
|
+
body = self._http.request(
|
|
46
|
+
"POST",
|
|
47
|
+
self._path("/measurements/upload/"),
|
|
48
|
+
data={"payload": json.dumps(payload)},
|
|
49
|
+
files={"file": (Path(getattr(fh, "name", "attachment")).name, fh)},
|
|
50
|
+
)
|
|
51
|
+
finally:
|
|
52
|
+
if opened:
|
|
53
|
+
fh.close()
|
|
54
|
+
return Measurement.from_dict(body)
|
|
55
|
+
|
|
56
|
+
def list_for_point(self, point_id: int, *, limit: int = 50, offset: int = 0,
|
|
57
|
+
created_from: str | None = None, created_to: str | None = None) -> list[Measurement]:
|
|
58
|
+
return _paginated(
|
|
59
|
+
self._http,
|
|
60
|
+
self._path(f"/measurement-points/{point_id}/measurements/"),
|
|
61
|
+
params={"limit": limit, "offset": offset,
|
|
62
|
+
"created_from": created_from, "created_to": created_to},
|
|
63
|
+
parse=Measurement.from_dict,
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
def create_batch(self, items: list[dict]) -> BatchResult:
|
|
67
|
+
body = self._http.request(
|
|
68
|
+
"POST", self._path("/measurements/batch/"), json={"items": list(items)}
|
|
69
|
+
)
|
|
70
|
+
return BatchResult.from_dict(body)
|
|
71
|
+
|
|
72
|
+
def add_file(
|
|
73
|
+
self,
|
|
74
|
+
measurement_uuid: str,
|
|
75
|
+
*,
|
|
76
|
+
file: str | Path | BinaryIO | bytes,
|
|
77
|
+
filename: str = "attachment",
|
|
78
|
+
) -> FileAttachment:
|
|
79
|
+
fh = file
|
|
80
|
+
opened = False
|
|
81
|
+
if isinstance(file, (str, Path)):
|
|
82
|
+
filename = Path(file).name
|
|
83
|
+
fh = open(file, "rb") # noqa: SIM115
|
|
84
|
+
opened = True
|
|
85
|
+
elif isinstance(file, (bytes, bytearray)):
|
|
86
|
+
fh = io.BytesIO(file)
|
|
87
|
+
try:
|
|
88
|
+
body = self._http.request(
|
|
89
|
+
"POST",
|
|
90
|
+
self._path(f"/measurements/{measurement_uuid}/files/"),
|
|
91
|
+
files={"file": (filename, fh)},
|
|
92
|
+
)
|
|
93
|
+
finally:
|
|
94
|
+
if opened:
|
|
95
|
+
fh.close()
|
|
96
|
+
return FileAttachment.from_dict(body)
|
|
97
|
+
|
|
98
|
+
def iter_for_point(
|
|
99
|
+
self,
|
|
100
|
+
point_id: int,
|
|
101
|
+
*,
|
|
102
|
+
created_from: str | None = None,
|
|
103
|
+
created_to: str | None = None,
|
|
104
|
+
page_size: int = 100,
|
|
105
|
+
):
|
|
106
|
+
"""Yield every measurement for a point, following cursor pages."""
|
|
107
|
+
cursor: str | None = ""
|
|
108
|
+
path = self._path(f"/measurement-points/{point_id}/measurements/")
|
|
109
|
+
while True:
|
|
110
|
+
params = {
|
|
111
|
+
"limit": page_size,
|
|
112
|
+
"cursor": cursor,
|
|
113
|
+
"created_from": created_from,
|
|
114
|
+
"created_to": created_to,
|
|
115
|
+
}
|
|
116
|
+
params = {k: v for k, v in params.items() if v is not None}
|
|
117
|
+
body = self._http.request("GET", path, params=params)
|
|
118
|
+
for item in body["items"]:
|
|
119
|
+
yield Measurement.from_dict(item)
|
|
120
|
+
cursor = body.get("next_cursor")
|
|
121
|
+
if not cursor:
|
|
122
|
+
break
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from ..models import Asset, DeleteResult, MeasurementPoint, Section, Zone
|
|
4
|
+
from ._base import InstallationScoped, _clean, _paginated
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def locals_no_self(d: dict) -> dict:
|
|
8
|
+
return {k: v for k, v in d.items() if k != "self"}
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Assets(InstallationScoped):
|
|
12
|
+
def list(self, *, q: str = "", zone_id: int | None = None, limit: int = 50, offset: int = 0) -> list[Asset]:
|
|
13
|
+
return _paginated(
|
|
14
|
+
self._http, self._path("/assets"),
|
|
15
|
+
params={"q": q, "zone_id": zone_id, "limit": limit, "offset": offset},
|
|
16
|
+
parse=Asset.from_dict,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
def get(self, asset_id: int) -> Asset:
|
|
20
|
+
return Asset.from_dict(self._http.request("GET", self._path(f"/assets/{asset_id}")))
|
|
21
|
+
|
|
22
|
+
def create(self, *, name: str | None = None, external_id: str | None = None,
|
|
23
|
+
section_id: int | None = None, section_external_id: str | None = None,
|
|
24
|
+
zone_id: int | None = None, zone_external_id: str | None = None,
|
|
25
|
+
equipment_type: str | None = None, machine_class: str | None = None) -> Asset:
|
|
26
|
+
return Asset.from_dict(self._http.request("POST", self._path("/assets"), json=_clean(locals_no_self(locals()))))
|
|
27
|
+
|
|
28
|
+
def upsert(self, *, name: str | None = None, external_id: str | None = None,
|
|
29
|
+
section_id: int | None = None, section_external_id: str | None = None,
|
|
30
|
+
zone_id: int | None = None, zone_external_id: str | None = None,
|
|
31
|
+
equipment_type: str | None = None, machine_class: str | None = None) -> Asset:
|
|
32
|
+
return Asset.from_dict(self._http.request("PUT", self._path("/assets"), json=_clean(locals_no_self(locals()))))
|
|
33
|
+
|
|
34
|
+
def update(self, asset_id: int, *, name: str | None = None, external_id: str | None = None,
|
|
35
|
+
section_id: int | None = None, section_external_id: str | None = None,
|
|
36
|
+
zone_id: int | None = None, zone_external_id: str | None = None,
|
|
37
|
+
equipment_type: str | None = None, machine_class: str | None = None) -> Asset:
|
|
38
|
+
body = _clean({k: v for k, v in locals().items() if k not in ("self", "asset_id")})
|
|
39
|
+
return Asset.from_dict(self._http.request("PATCH", self._path(f"/assets/{asset_id}"), json=body))
|
|
40
|
+
|
|
41
|
+
def delete(self, asset_id: int, *, cascade: bool = False) -> DeleteResult:
|
|
42
|
+
params = {"cascade": "true"} if cascade else None
|
|
43
|
+
return DeleteResult.from_dict(self._http.request("DELETE", self._path(f"/assets/{asset_id}"), params=params))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class MeasurementPoints(InstallationScoped):
|
|
47
|
+
def list(self, *, q: str = "", asset_id: int | None = None, transducer_type: str = "",
|
|
48
|
+
limit: int = 50, offset: int = 0) -> list[MeasurementPoint]:
|
|
49
|
+
return _paginated(
|
|
50
|
+
self._http, self._path("/measurement-points"),
|
|
51
|
+
params={"q": q, "asset_id": asset_id, "transducer_type": transducer_type,
|
|
52
|
+
"limit": limit, "offset": offset},
|
|
53
|
+
parse=MeasurementPoint.from_dict,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
def get(self, point_id: int) -> MeasurementPoint:
|
|
57
|
+
return MeasurementPoint.from_dict(self._http.request("GET", self._path(f"/measurement-points/{point_id}")))
|
|
58
|
+
|
|
59
|
+
def create(self, *, name: str | None = None, external_id: str | None = None,
|
|
60
|
+
asset_id: int | None = None, asset_external_id: str | None = None,
|
|
61
|
+
transducer_type: str | None = None, measurement_unit_code: str | None = None,
|
|
62
|
+
location: str | None = None, body_segment: int | None = None,
|
|
63
|
+
body_angle: int | None = None, machine_class: str | None = None) -> MeasurementPoint:
|
|
64
|
+
return MeasurementPoint.from_dict(self._http.request("POST", self._path("/measurement-points"), json=_clean(locals_no_self(locals()))))
|
|
65
|
+
|
|
66
|
+
def upsert(self, *, name: str | None = None, external_id: str | None = None,
|
|
67
|
+
asset_id: int | None = None, asset_external_id: str | None = None,
|
|
68
|
+
transducer_type: str | None = None, measurement_unit_code: str | None = None,
|
|
69
|
+
location: str | None = None, body_segment: int | None = None,
|
|
70
|
+
body_angle: int | None = None, machine_class: str | None = None) -> MeasurementPoint:
|
|
71
|
+
return MeasurementPoint.from_dict(self._http.request("PUT", self._path("/measurement-points"), json=_clean(locals_no_self(locals()))))
|
|
72
|
+
|
|
73
|
+
def update(self, point_id: int, *, name: str | None = None, external_id: str | None = None,
|
|
74
|
+
asset_id: int | None = None, asset_external_id: str | None = None,
|
|
75
|
+
transducer_type: str | None = None, measurement_unit_code: str | None = None,
|
|
76
|
+
location: str | None = None, body_segment: int | None = None,
|
|
77
|
+
body_angle: int | None = None, machine_class: str | None = None) -> MeasurementPoint:
|
|
78
|
+
body = _clean({k: v for k, v in locals().items() if k not in ("self", "point_id")})
|
|
79
|
+
return MeasurementPoint.from_dict(self._http.request("PATCH", self._path(f"/measurement-points/{point_id}"), json=body))
|
|
80
|
+
|
|
81
|
+
def delete(self, point_id: int, *, cascade: bool = False) -> DeleteResult:
|
|
82
|
+
params = {"cascade": "true"} if cascade else None
|
|
83
|
+
return DeleteResult.from_dict(self._http.request("DELETE", self._path(f"/measurement-points/{point_id}"), params=params))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class Sections(InstallationScoped):
|
|
87
|
+
def list(self, *, q: str = "", limit: int = 50, offset: int = 0) -> list[Section]:
|
|
88
|
+
return _paginated(self._http, self._path("/sections"),
|
|
89
|
+
params={"q": q, "limit": limit, "offset": offset},
|
|
90
|
+
parse=Section.from_dict)
|
|
91
|
+
|
|
92
|
+
def get(self, section_id: int) -> Section:
|
|
93
|
+
return Section.from_dict(self._http.request("GET", self._path(f"/sections/{section_id}")))
|
|
94
|
+
|
|
95
|
+
def create(self, *, name: str | None = None, external_id: str | None = None) -> Section:
|
|
96
|
+
return Section.from_dict(self._http.request("POST", self._path("/sections"), json=_clean(locals_no_self(locals()))))
|
|
97
|
+
|
|
98
|
+
def upsert(self, *, name: str | None = None, external_id: str | None = None) -> Section:
|
|
99
|
+
return Section.from_dict(self._http.request("PUT", self._path("/sections"), json=_clean(locals_no_self(locals()))))
|
|
100
|
+
|
|
101
|
+
def update(self, section_id: int, *, name: str | None = None, external_id: str | None = None) -> Section:
|
|
102
|
+
body = _clean({k: v for k, v in locals().items() if k not in ("self", "section_id")})
|
|
103
|
+
return Section.from_dict(self._http.request("PATCH", self._path(f"/sections/{section_id}"), json=body))
|
|
104
|
+
|
|
105
|
+
def delete(self, section_id: int, *, cascade: bool = False) -> DeleteResult:
|
|
106
|
+
params = {"cascade": "true"} if cascade else None
|
|
107
|
+
return DeleteResult.from_dict(self._http.request("DELETE", self._path(f"/sections/{section_id}"), params=params))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class Zones(InstallationScoped):
|
|
111
|
+
def list(self, *, q: str = "", section_id: int | None = None, limit: int = 50, offset: int = 0) -> list[Zone]:
|
|
112
|
+
return _paginated(self._http, self._path("/zones"),
|
|
113
|
+
params={"q": q, "section_id": section_id, "limit": limit, "offset": offset},
|
|
114
|
+
parse=Zone.from_dict)
|
|
115
|
+
|
|
116
|
+
def get(self, zone_id: int) -> Zone:
|
|
117
|
+
return Zone.from_dict(self._http.request("GET", self._path(f"/zones/{zone_id}")))
|
|
118
|
+
|
|
119
|
+
def create(self, *, name: str | None = None, external_id: str | None = None,
|
|
120
|
+
section_id: int | None = None, section_external_id: str | None = None) -> Zone:
|
|
121
|
+
return Zone.from_dict(self._http.request("POST", self._path("/zones"), json=_clean(locals_no_self(locals()))))
|
|
122
|
+
|
|
123
|
+
def upsert(self, *, name: str | None = None, external_id: str | None = None,
|
|
124
|
+
section_id: int | None = None, section_external_id: str | None = None) -> Zone:
|
|
125
|
+
return Zone.from_dict(self._http.request("PUT", self._path("/zones"), json=_clean(locals_no_self(locals()))))
|
|
126
|
+
|
|
127
|
+
def update(self, zone_id: int, *, name: str | None = None, external_id: str | None = None,
|
|
128
|
+
section_id: int | None = None, section_external_id: str | None = None) -> Zone:
|
|
129
|
+
body = _clean({k: v for k, v in locals().items() if k not in ("self", "zone_id")})
|
|
130
|
+
return Zone.from_dict(self._http.request("PATCH", self._path(f"/zones/{zone_id}"), json=body))
|
|
131
|
+
|
|
132
|
+
def delete(self, zone_id: int, *, cascade: bool = False) -> DeleteResult:
|
|
133
|
+
params = {"cascade": "true"} if cascade else None
|
|
134
|
+
return DeleteResult.from_dict(self._http.request("DELETE", self._path(f"/zones/{zone_id}"), params=params))
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, BinaryIO
|
|
6
|
+
|
|
7
|
+
from ..models import ItemResponse, Route, RouteExecution
|
|
8
|
+
from ._base import InstallationScoped, _paginated
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Executions(InstallationScoped):
|
|
12
|
+
"""Operations on an existing execution."""
|
|
13
|
+
|
|
14
|
+
def __init__(self, http, installation_id: int, execution_uuid: str):
|
|
15
|
+
super().__init__(http, installation_id)
|
|
16
|
+
self.uuid = execution_uuid
|
|
17
|
+
|
|
18
|
+
def _url(self, suffix: str) -> str:
|
|
19
|
+
return self._path(f"/executions/{self.uuid}{suffix}")
|
|
20
|
+
|
|
21
|
+
def respond(
|
|
22
|
+
self,
|
|
23
|
+
*,
|
|
24
|
+
route_item_uuid: str,
|
|
25
|
+
data: dict,
|
|
26
|
+
notes: str = "",
|
|
27
|
+
photos: list[str | Path | BinaryIO] | None = None,
|
|
28
|
+
) -> ItemResponse:
|
|
29
|
+
payload: dict[str, Any] = {
|
|
30
|
+
"route_item_uuid": route_item_uuid,
|
|
31
|
+
"data": data,
|
|
32
|
+
"notes": notes,
|
|
33
|
+
}
|
|
34
|
+
if not photos:
|
|
35
|
+
body = self._http.request("POST", self._url("/responses"), json=payload)
|
|
36
|
+
return ItemResponse.from_dict(body)
|
|
37
|
+
|
|
38
|
+
files = []
|
|
39
|
+
opened = []
|
|
40
|
+
try:
|
|
41
|
+
for p in photos:
|
|
42
|
+
if isinstance(p, (str, Path)):
|
|
43
|
+
fh = open(p, "rb") # noqa: SIM115
|
|
44
|
+
opened.append(fh)
|
|
45
|
+
files.append(("files", (Path(p).name, fh)))
|
|
46
|
+
else:
|
|
47
|
+
files.append(("files", (getattr(p, "name", "photo"), p)))
|
|
48
|
+
body = self._http.request(
|
|
49
|
+
"POST",
|
|
50
|
+
self._url("/responses/upload"),
|
|
51
|
+
data={"payload": json.dumps(payload)},
|
|
52
|
+
files=files,
|
|
53
|
+
)
|
|
54
|
+
finally:
|
|
55
|
+
for fh in opened:
|
|
56
|
+
fh.close()
|
|
57
|
+
return ItemResponse.from_dict(body)
|
|
58
|
+
|
|
59
|
+
def add_field_item(
|
|
60
|
+
self,
|
|
61
|
+
*,
|
|
62
|
+
label: str,
|
|
63
|
+
item_type: str = "pass_fail",
|
|
64
|
+
data: dict | None = None,
|
|
65
|
+
zone_id: int | None = None,
|
|
66
|
+
config: dict | None = None,
|
|
67
|
+
notes: str = "",
|
|
68
|
+
) -> ItemResponse:
|
|
69
|
+
"""Append a new checklist item to this execution, field-authored.
|
|
70
|
+
|
|
71
|
+
The item is zone-anchored (``zone_id``) or route-level (``None``).
|
|
72
|
+
Asset assignment happens afterward via :meth:`triage`.
|
|
73
|
+
"""
|
|
74
|
+
payload = {
|
|
75
|
+
"label": label,
|
|
76
|
+
"item_type": item_type,
|
|
77
|
+
"data": data or {},
|
|
78
|
+
"zone_id": zone_id,
|
|
79
|
+
"config": config or {},
|
|
80
|
+
"notes": notes,
|
|
81
|
+
}
|
|
82
|
+
body = self._http.request("POST", self._url("/items"), json=payload)
|
|
83
|
+
return ItemResponse.from_dict(body)
|
|
84
|
+
|
|
85
|
+
def triage(self, *, route_item_uuid: str, asset_id: int) -> ItemResponse:
|
|
86
|
+
body = self._http.request(
|
|
87
|
+
"POST",
|
|
88
|
+
self._url("/triage"),
|
|
89
|
+
json={"route_item_uuid": route_item_uuid, "asset_id": asset_id},
|
|
90
|
+
)
|
|
91
|
+
return ItemResponse.from_dict(body)
|
|
92
|
+
|
|
93
|
+
def complete(self) -> RouteExecution:
|
|
94
|
+
body = self._http.request("POST", self._url("/complete"))
|
|
95
|
+
return RouteExecution.from_dict(body)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class Routes(InstallationScoped):
|
|
99
|
+
def list(self, *, q: str = "", limit: int = 50, offset: int = 0) -> list[Route]:
|
|
100
|
+
return _paginated(
|
|
101
|
+
self._http,
|
|
102
|
+
self._path("/routes"),
|
|
103
|
+
params={"q": q, "limit": limit, "offset": offset},
|
|
104
|
+
parse=Route.from_dict,
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
def get(self, route_uuid: str) -> dict:
|
|
108
|
+
return self._http.request("GET", self._path(f"/routes/{route_uuid}"))
|
|
109
|
+
|
|
110
|
+
def start(self, route_uuid: str) -> Executions:
|
|
111
|
+
body = self._http.request(
|
|
112
|
+
"POST", self._path(f"/routes/{route_uuid}/executions")
|
|
113
|
+
)
|
|
114
|
+
execution = RouteExecution.from_dict(body)
|
|
115
|
+
handle = Executions(self._http, self._iid, execution.uuid)
|
|
116
|
+
handle.execution = execution # type: ignore[attr-defined]
|
|
117
|
+
return handle
|
|
118
|
+
|
|
119
|
+
def execution(self, execution_uuid: str) -> Executions:
|
|
120
|
+
return Executions(self._http, self._iid, execution_uuid)
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mechbase
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Official Python client for the Mechbase condition-monitoring API
|
|
5
|
+
Project-URL: Homepage, https://app.mechbase.io
|
|
6
|
+
Project-URL: Source, https://github.com/arpedon/mechbase-sdk
|
|
7
|
+
Author: Arpedon
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Requires-Dist: httpx>=0.27
|
|
11
|
+
Provides-Extra: dev
|
|
12
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
13
|
+
Requires-Dist: respx>=0.21; extra == 'dev'
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# mechbase
|
|
17
|
+
|
|
18
|
+
Official Python client for the [Mechbase](https://app.mechbase.io) condition-monitoring API.
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pip install mechbase
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from mechbase import Mechbase
|
|
26
|
+
|
|
27
|
+
client = Mechbase(token="...") # defaults to https://app.mechbase.io
|
|
28
|
+
# self-hosted: Mechbase(token="...", base_url="https://mechbase.internal.acme.com")
|
|
29
|
+
|
|
30
|
+
me = client.me()
|
|
31
|
+
inst = client.for_installation(me.current_installation_id)
|
|
32
|
+
|
|
33
|
+
assets = inst.assets.list(q="pump", limit=50)
|
|
34
|
+
inst.measurements.create(point_id=42, data={"rms": 2.3}, notes="manual reading")
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
For edge agents identified by a `node_uuid` rather than a bearer token, use `MaintNode`.
|
|
38
|
+
|
|
39
|
+
Full docs and the other language SDKs (Go, Swift, Kotlin) live in the
|
|
40
|
+
[mechbase-sdk repo](https://github.com/arpedon/mechbase-sdk).
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
mechbase/__init__.py,sha256=cyn35yWb9Hc7apiveXT_qFCboGKLQ55GfGPBRwotiHw,383
|
|
2
|
+
mechbase/_http.py,sha256=FVKLo3mHDr7F_oZ3wzXG0cuGRdE6JHme8m_SIj0OsmE,2409
|
|
3
|
+
mechbase/client.py,sha256=aR3AtSloyJGdyFwo8Yxqch8szjzEzAmMXfMgx1LlPmw,1773
|
|
4
|
+
mechbase/errors.py,sha256=uI2g-wagNuaaCBvuuBRbrmrmjU9NdpyKO5wbSW67gHQ,517
|
|
5
|
+
mechbase/maintnode.py,sha256=UNxLopc3TH6Oyxo06N2ZpekNUpXv-AwnwCwNu4XVvF0,2393
|
|
6
|
+
mechbase/models.py,sha256=pg-wzBdTyd0z-h6g9j_qcAHsbsBTLo0-aaBWD21A2lA,10535
|
|
7
|
+
mechbase/resources/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
mechbase/resources/_base.py,sha256=qlhj4Z6LSzyH5bVgR7mlpqmRwTL0vDrvF1L3hZyEx5Q,831
|
|
9
|
+
mechbase/resources/measurements.py,sha256=ZEgSvXbu8y-4onhSlOcXvWZjTSLxrYaYCee7WzA4__8,3987
|
|
10
|
+
mechbase/resources/registry.py,sha256=SR9EadI5DpPXLRg-mQADVdmruaDHhNoJiEL1vSHXsA8,8449
|
|
11
|
+
mechbase/resources/routes.py,sha256=7PtpKTc9FO3uXvhQdnAeA6Nx95MMfEkuloqRDy8YUC4,3998
|
|
12
|
+
mechbase-0.2.0.dist-info/METADATA,sha256=kg4B-c55XJh_dZT9xb3dvFqW4PhZRbczIWiF7KgvTaQ,1237
|
|
13
|
+
mechbase-0.2.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
|
|
14
|
+
mechbase-0.2.0.dist-info/RECORD,,
|