mechbase 0.2.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.
@@ -0,0 +1,30 @@
1
+ ## Python
2
+ .venv/
3
+ __pycache__/
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ .pytest_cache/
8
+
9
+ ## Go
10
+ /go/bin/
11
+
12
+ ## Swift
13
+ .build/
14
+ .swiftpm/
15
+ Package.resolved
16
+
17
+ ## Kotlin / Gradle
18
+ .gradle/
19
+ kotlin/build/
20
+ kotlin/.gradle/
21
+ !kotlin/gradle/wrapper/gradle-wrapper.jar
22
+
23
+ ## Editors
24
+ .idea/
25
+ .vscode/
26
+ *.iml
27
+ .DS_Store
28
+
29
+ ## AI planning artifacts (local-only working memory, never committed)
30
+ docs/
@@ -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,25 @@
1
+ # mechbase
2
+
3
+ Official Python client for the [Mechbase](https://app.mechbase.io) condition-monitoring API.
4
+
5
+ ```bash
6
+ pip install mechbase
7
+ ```
8
+
9
+ ```python
10
+ from mechbase import Mechbase
11
+
12
+ client = Mechbase(token="...") # defaults to https://app.mechbase.io
13
+ # self-hosted: Mechbase(token="...", base_url="https://mechbase.internal.acme.com")
14
+
15
+ me = client.me()
16
+ inst = client.for_installation(me.current_installation_id)
17
+
18
+ assets = inst.assets.list(q="pump", limit=50)
19
+ inst.measurements.create(point_id=42, data={"rms": 2.3}, notes="manual reading")
20
+ ```
21
+
22
+ For edge agents identified by a `node_uuid` rather than a bearer token, use `MaintNode`.
23
+
24
+ Full docs and the other language SDKs (Go, Swift, Kotlin) live in the
25
+ [mechbase-sdk repo](https://github.com/arpedon/mechbase-sdk).
@@ -0,0 +1,22 @@
1
+ """List assets in the current installation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+
7
+ from mechbase import Mechbase
8
+
9
+
10
+ def main() -> None:
11
+ token = os.environ["MECHBASE_TOKEN"]
12
+ base = os.environ.get("MECHBASE_URL", "http://localhost:8000")
13
+
14
+ with Mechbase(token=token, base_url=base) as client:
15
+ me = client.me()
16
+ inst = client.for_installation(me.current_installation_id)
17
+ for a in inst.assets.list(limit=100):
18
+ print(f"#{a.asset_id:<4} {a.name:<40} status={a.status} class={a.machine_class}")
19
+
20
+
21
+ if __name__ == "__main__":
22
+ main()
@@ -0,0 +1,33 @@
1
+ """Push a measurement from a maintnode-style Python script.
2
+
3
+ MECHBASE_TOKEN=... MECHBASE_URL=http://localhost:8000 python push_measurement.py
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+
10
+ from mechbase import Mechbase
11
+
12
+
13
+ def main() -> None:
14
+ token = os.environ["MECHBASE_TOKEN"]
15
+ base = os.environ.get("MECHBASE_URL", "http://localhost:8000")
16
+
17
+ with Mechbase(token=token, base_url=base) as client:
18
+ me = client.me()
19
+ inst = client.for_installation(me.current_installation_id)
20
+
21
+ point = inst.measurement_points.list(transducer_type="VB", limit=1)[0]
22
+ print(f"pushing to point {point.point_id} ({point.name})")
23
+
24
+ m = inst.measurements.create(
25
+ point_id=point.point_id,
26
+ data={"rms": 2.3, "peak": 4.1},
27
+ notes="from push_measurement.py",
28
+ )
29
+ print(f"ok -> {m.uuid} sequence={m.point_sequence} status={m.status}")
30
+
31
+
32
+ if __name__ == "__main__":
33
+ main()
@@ -0,0 +1,41 @@
1
+ """Run a field survey — start an execution, author items on the fly, complete.
2
+
3
+ Mirrors the Android/iOS survey flow so the same API shape can be exercised
4
+ end-to-end from Python.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import sys
11
+
12
+ from mechbase import Mechbase
13
+
14
+
15
+ def main() -> None:
16
+ token = os.environ["MECHBASE_TOKEN"]
17
+ base = os.environ.get("MECHBASE_URL", "http://localhost:8000")
18
+ route_uuid = sys.argv[1] if len(sys.argv) > 1 else os.environ["ROUTE_UUID"]
19
+
20
+ with Mechbase(token=token, base_url=base) as client:
21
+ me = client.me()
22
+ inst = client.for_installation(me.current_installation_id)
23
+
24
+ execution = inst.routes.start(route_uuid)
25
+ print(f"started execution {execution.uuid}")
26
+
27
+ resp = execution.add_field_item(
28
+ label="Oil leak under pump",
29
+ item_type="pass_fail",
30
+ zone_id=None, # route-level — triage to an asset later
31
+ data={"passed": False, "severity": "major"},
32
+ notes="under coupling",
33
+ )
34
+ print(f"added field item -> response {resp.uuid} status={resp.status}")
35
+
36
+ final = execution.complete()
37
+ print(f"completed at {final.completed_at}")
38
+
39
+
40
+ if __name__ == "__main__":
41
+ main()
@@ -0,0 +1,18 @@
1
+ """Upsert a section/zone/asset/point chain by external_id, then batch-push readings."""
2
+ from mechbase import Mechbase
3
+
4
+ client = Mechbase(token="...")
5
+ inst = client.for_installation(client.me().current_installation_id)
6
+
7
+ inst.sections.upsert(external_id="HALL-A", name="Hall A")
8
+ inst.zones.upsert(external_id="Z-1", name="Pump Row", section_external_id="HALL-A")
9
+ inst.assets.upsert(external_id="PUMP-1", name="Feed Pump 1", zone_external_id="Z-1",
10
+ equipment_type="pump", machine_class="II")
11
+ inst.measurement_points.upsert(external_id="PUMP-1-DE", name="Drive End",
12
+ asset_external_id="PUMP-1", transducer_type="accel",
13
+ measurement_unit_code="mm_s")
14
+
15
+ result = inst.measurements.create_batch([
16
+ {"measurement_point_external_id": "PUMP-1-DE", "data": {"rms": 2.3}, "external_id": "r-1"},
17
+ ])
18
+ print(f"created={result.created} duplicates={result.duplicates} errors={result.errors}")
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "mechbase"
7
+ version = "0.2.0"
8
+ description = "Official Python client for the Mechbase condition-monitoring API"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ authors = [{ name = "Arpedon" }]
13
+ urls = { Homepage = "https://app.mechbase.io", Source = "https://github.com/arpedon/mechbase-sdk" }
14
+ dependencies = [
15
+ "httpx>=0.27",
16
+ ]
17
+
18
+ [project.optional-dependencies]
19
+ dev = [
20
+ "pytest>=8",
21
+ "respx>=0.21",
22
+ ]
23
+
24
+ [tool.hatch.build.targets.wheel]
25
+ packages = ["src/mechbase"]
@@ -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
+ ]
@@ -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)
@@ -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()
@@ -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."""
@@ -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()