zeptrionair-api 0.1.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.
@@ -0,0 +1,69 @@
1
+ """Async client for Feller zeptrionAir devices (local HTTP and WebSocket API)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .const import (
6
+ Category,
7
+ Command,
8
+ scene_command,
9
+ timed_command,
10
+ validate_command,
11
+ )
12
+ from .device import ZeptrionDevice
13
+ from .events import EventStream
14
+ from .exceptions import (
15
+ ZeptrionConnectionError,
16
+ ZeptrionError,
17
+ ZeptrionNotFoundError,
18
+ ZeptrionParseError,
19
+ ZeptrionResponseError,
20
+ ZeptrionTimeoutError,
21
+ )
22
+ from .models import (
23
+ Capabilities,
24
+ Channel,
25
+ ChannelUpdate,
26
+ ConnectionEvent,
27
+ DeviceInfo,
28
+ DiscoveredDevice,
29
+ Event,
30
+ KeyEvent,
31
+ KeyFunction,
32
+ LedState,
33
+ SensorValues,
34
+ SmartfrontInfo,
35
+ )
36
+
37
+ try:
38
+ from ._version import __version__
39
+ except ImportError: # pragma: no cover - only when running from a source tree without a build
40
+ __version__ = "0.0.0"
41
+
42
+ __all__ = [
43
+ "Capabilities",
44
+ "Category",
45
+ "Channel",
46
+ "ChannelUpdate",
47
+ "Command",
48
+ "ConnectionEvent",
49
+ "DeviceInfo",
50
+ "DiscoveredDevice",
51
+ "Event",
52
+ "EventStream",
53
+ "KeyEvent",
54
+ "KeyFunction",
55
+ "LedState",
56
+ "SensorValues",
57
+ "SmartfrontInfo",
58
+ "ZeptrionConnectionError",
59
+ "ZeptrionDevice",
60
+ "ZeptrionError",
61
+ "ZeptrionNotFoundError",
62
+ "ZeptrionParseError",
63
+ "ZeptrionResponseError",
64
+ "ZeptrionTimeoutError",
65
+ "__version__",
66
+ "scene_command",
67
+ "timed_command",
68
+ "validate_command",
69
+ ]
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.1.0'
22
+ __version_tuple__ = version_tuple = (0, 1, 0)
23
+
24
+ __commit_id__ = commit_id = None
@@ -0,0 +1,194 @@
1
+ """Capture anonymised, read-only fixtures from zApp devices.
2
+
3
+ Used by ``zeptrion dump`` and runnable directly::
4
+
5
+ python -m zeptrionair_api.capture OUTDIR HOST [HOST ...]
6
+
7
+ Only GET requests are sent. Anonymisation:
8
+
9
+ - serial numbers -> 99990001, 99990002, ... (in the order the hosts are given)
10
+ - MAC addresses -> 02:00:00:00:00:NN
11
+ - channel names -> generic names derived from the category ("Light 1", "Shade 1", ...)
12
+ - channel groups -> "Room A", "Room B", ...
13
+
14
+ Hostnames and IP addresses are never written.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import asyncio
20
+ import json
21
+ import re
22
+ import sys
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ import aiohttp
27
+
28
+ ENDPOINTS = (
29
+ "/zrap/id",
30
+ "/zrap/chdes",
31
+ "/zrap/chscan",
32
+ "/zrap/rssi",
33
+ "/zrap/net/mac",
34
+ "/zapi/smartfront/id",
35
+ "/zapi/smartfront/led",
36
+ "/zapi/smartfront/sensor",
37
+ "/zapi/smartfront/sensors",
38
+ "/zapi/smartbt/prgm",
39
+ "/zrap/does-not-exist",
40
+ )
41
+
42
+ CATEGORY_NAMES = {"1": "Light", "3": "Dimmer", "5": "Shade", "6": "Awning"}
43
+ _MAC_RE = re.compile(r"(?i)\b[0-9a-f]{2}(?::[0-9a-f]{2}){5}\b")
44
+
45
+
46
+ class Anonymiser:
47
+ """Replaces identifying values consistently across all captured devices."""
48
+
49
+ def __init__(self) -> None:
50
+ self.serials: dict[str, str] = {}
51
+ self.macs: dict[str, str] = {}
52
+ self.groups: dict[str, str] = {}
53
+ self._counters: dict[str, int] = {}
54
+
55
+ def serial(self, real: str) -> str:
56
+ if real not in self.serials:
57
+ self.serials[real] = f"9999{len(self.serials) + 1:04d}"
58
+ return self.serials[real]
59
+
60
+ def _mac(self, match: re.Match[str]) -> str:
61
+ real = match.group(0).lower()
62
+ if real not in self.macs:
63
+ self.macs[real] = f"02:00:00:00:00:{len(self.macs) + 1:02x}"
64
+ return self.macs[real]
65
+
66
+ def group(self, real: str) -> str:
67
+ if not real:
68
+ return real
69
+ if real not in self.groups:
70
+ self.groups[real] = f"Room {chr(ord('A') + len(self.groups) % 26)}"
71
+ return self.groups[real]
72
+
73
+ def channel_name(self, category: str, real: str) -> str:
74
+ kind = CATEGORY_NAMES.get(category.strip())
75
+ if kind is None:
76
+ # Unused channels keep the firmware default "zApp-<serial> (<n>)"; the serial
77
+ # inside is replaced by text().
78
+ return real
79
+ self._counters[kind] = self._counters.get(kind, 0) + 1
80
+ return f"{kind} {self._counters[kind]}"
81
+
82
+ def chdes(self, body: str) -> str:
83
+ def fix_channel(match: re.Match[str]) -> str:
84
+ inner = match.group(2)
85
+ category = re.search(r"<cat>(.*?)</cat>", inner)
86
+ cat = category.group(1) if category else ""
87
+ inner = re.sub(
88
+ r"<name>(.*?)</name>",
89
+ lambda m: f"<name>{self.channel_name(cat, m.group(1))}</name>",
90
+ inner,
91
+ )
92
+ inner = re.sub(
93
+ r"<group>(.*?)</group>", lambda m: f"<group>{self.group(m.group(1))}</group>", inner
94
+ )
95
+ return f"<ch{match.group(1)}>{inner}</ch{match.group(1)}>"
96
+
97
+ return re.sub(r"<ch(\d+)>(.*?)</ch\1>", fix_channel, body, flags=re.S)
98
+
99
+ def text(self, body: str) -> str:
100
+ for real, fake in self.serials.items():
101
+ body = body.replace(real, fake)
102
+ return _MAC_RE.sub(self._mac, body)
103
+
104
+
105
+ async def _fetch(session: aiohttp.ClientSession, host: str, path: str) -> dict[str, Any]:
106
+ try:
107
+ async with session.get(f"http://{host}{path}", allow_redirects=False) as response:
108
+ return {
109
+ "status": response.status,
110
+ "content_type": response.headers.get("Content-Type"),
111
+ "body": (await response.read()).decode("utf-8", errors="replace"),
112
+ }
113
+ except (aiohttp.ClientError, TimeoutError) as err:
114
+ return {"status": None, "error": type(err).__name__}
115
+
116
+
117
+ async def capture_device(
118
+ host: str, anonymiser: Anonymiser, session: aiohttp.ClientSession
119
+ ) -> dict[str, dict[str, Any]]:
120
+ """Fetch every endpoint of one device (sequentially) and anonymise the bodies."""
121
+ raw = {path: await _fetch(session, host, path) for path in ENDPOINTS}
122
+ serial = re.search(r"<sn>(.*?)</sn>", str(raw["/zrap/id"].get("body", "")))
123
+ if serial is None:
124
+ raise ValueError(f"{host}: no serial number in /zrap/id; is this a zApp device?")
125
+ anonymiser.serial(serial.group(1))
126
+ for path, response in raw.items():
127
+ if "body" not in response:
128
+ continue
129
+ body = str(response["body"])
130
+ if path == "/zrap/chdes" and response["status"] == 200:
131
+ body = anonymiser.chdes(body)
132
+ response["body"] = anonymiser.text(body)
133
+ return raw
134
+
135
+
136
+ def summarise(responses: dict[str, dict[str, Any]]) -> dict[str, Any]:
137
+ def body(path: str) -> str:
138
+ response = responses.get(path, {})
139
+ return str(response.get("body", "")) if response.get("status") == 200 else ""
140
+
141
+ def tag(path: str, name: str) -> str | None:
142
+ match = re.search(rf"<{name}>(.*?)</{name}>", body(path))
143
+ return match.group(1) if match else None
144
+
145
+ front: dict[str, Any] = {}
146
+ if body("/zapi/smartfront/id"):
147
+ try:
148
+ front = json.loads(body("/zapi/smartfront/id"))
149
+ except json.JSONDecodeError:
150
+ front = {}
151
+ return {
152
+ "type": tag("/zrap/id", "type"),
153
+ "sw": tag("/zrap/id", "sw"),
154
+ "categories": re.findall(r"<cat>(.*?)</cat>", body("/zrap/chdes")),
155
+ "smartfront_type": front.get("type"),
156
+ "btfu": front.get("btfu"),
157
+ "status": {path: response.get("status") for path, response in responses.items()},
158
+ }
159
+
160
+
161
+ async def capture(outdir: Path, hosts: list[str]) -> dict[str, Any]:
162
+ """Capture all ``hosts`` into ``outdir`` and return the index."""
163
+ anonymiser = Anonymiser()
164
+ index: dict[str, Any] = {}
165
+ timeout = aiohttp.ClientTimeout(total=10)
166
+ async with aiohttp.ClientSession(timeout=timeout) as session:
167
+ for number, host in enumerate(hosts, start=1):
168
+ responses = await capture_device(host, anonymiser, session)
169
+ name = f"device_{number:02d}"
170
+ folder = outdir / name
171
+ folder.mkdir(parents=True, exist_ok=True)
172
+ (folder / "responses.json").write_text(
173
+ json.dumps(responses, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
174
+ )
175
+ index[name] = summarise(responses)
176
+ (outdir / "index.json").write_text(
177
+ json.dumps(index, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
178
+ )
179
+ return index
180
+
181
+
182
+ def main(argv: list[str] | None = None) -> int:
183
+ args = sys.argv[1:] if argv is None else argv
184
+ if len(args) < 2:
185
+ print(__doc__, file=sys.stderr)
186
+ return 2
187
+ index = asyncio.run(capture(Path(args[0]), args[1:]))
188
+ for name, summary in index.items():
189
+ print(f"{name}: {summary['type']} categories={summary['categories']}")
190
+ return 0
191
+
192
+
193
+ if __name__ == "__main__":
194
+ sys.exit(main())