pytuya-pilot-wire 0.5.2__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,36 @@
1
+ """Tuya pilot-wire thermostats: data points, codecs, device model and channels.
2
+
3
+ No Home Assistant import. The channel clients need optional dependencies (extras ``sharing``,
4
+ ``lan``, ``developer``), imported only when a channel is used.
5
+ """
6
+
7
+ from .errors import (
8
+ AuthenticationError,
9
+ ChannelError,
10
+ ChannelUnavailable,
11
+ DialectError,
12
+ PilotWireError,
13
+ RouteRefused,
14
+ WriteRefused,
15
+ )
16
+ from .model import Bounds, Channel, Device, DeviceSpec, DeviceState, Reading, Sourced
17
+
18
+ __version__ = "0.5.2"
19
+
20
+ __all__ = [
21
+ "AuthenticationError",
22
+ "Bounds",
23
+ "Channel",
24
+ "ChannelError",
25
+ "ChannelUnavailable",
26
+ "Device",
27
+ "DeviceSpec",
28
+ "DeviceState",
29
+ "DialectError",
30
+ "PilotWireError",
31
+ "Reading",
32
+ "RouteRefused",
33
+ "Sourced",
34
+ "WriteRefused",
35
+ "__version__",
36
+ ]
@@ -0,0 +1,563 @@
1
+ """Reusable daemon core of the bridge: read loop, publication, command handling.
2
+
3
+ :class:`Bridge` ties the channels, the router, the write gate and the dialect codec to an MQTT
4
+ transport, and speaks the contract of ``tuyapilot2mqtt/docs/mqtt-contract.md``. It imports
5
+ neither Home Assistant nor an MQTT library: the transport is anything with ``publish`` and
6
+ ``subscribe`` (:class:`pytuya_pilot_wire.mqtt.PahoTransport`, or a double in tests).
7
+
8
+ What the caller (the bridge daemon) keeps for itself: configuration, secrets, building the
9
+ channels, and the process life cycle. Then::
10
+
11
+ bridge = Bridge(transport, sharing=..., lan=..., developer=..., config=BridgeConfig())
12
+ bridge.run(stop_event)
13
+
14
+ Rules it enforces:
15
+
16
+ - every Tuya call runs on the thread that calls :meth:`Bridge.run`; MQTT callbacks only queue;
17
+ - a reading is trusted for the keys proven for its channel (the router decides), a property that
18
+ was not read is absent, and a state changes only from a reading, never from a request;
19
+ - a ``/set`` payload is validated as a whole before anything is sent; a command without a proven
20
+ route is refused and answered on ``bridge/response/device/set``;
21
+ - a channel that refuses its credentials is left alone until the caller replaces it; another
22
+ failure is retried with a growing delay. The account is never hammered.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import contextlib
28
+ import dataclasses
29
+ import json
30
+ import logging
31
+ import queue
32
+ import threading
33
+ import time
34
+ from collections.abc import Callable, Mapping, Sequence
35
+ from dataclasses import dataclass, field
36
+ from datetime import UTC, datetime
37
+ from typing import Any, Protocol
38
+
39
+ from . import __version__, dialect, dps
40
+ from .errors import AuthenticationError, ChannelError, PilotWireError, RouteRefused
41
+ from .gate import PlannedWrite, ScheduleWriter, SharingWriter, WriteGate
42
+ from .model import Channel, Device, DeviceSpec, DeviceState, Reading
43
+ from .router import Operation, Router
44
+
45
+ _LOGGER = logging.getLogger(__name__)
46
+
47
+ DEFAULT_PREFIX = "tuyapilot2mqtt"
48
+ MAX_BACKOFF = 900.0
49
+
50
+
51
+ class MqttTransport(Protocol):
52
+ """The MQTT client the bridge needs."""
53
+
54
+ def publish(self, topic: str, payload: str, *, retain: bool = False) -> None: ...
55
+
56
+ def subscribe(self, topic: str, callback: Callable[[str, str], None]) -> None: ...
57
+
58
+
59
+ class SharingSource(SharingWriter, Protocol):
60
+ def discover(self) -> list[Device]: ...
61
+
62
+ def spec(self, dev_id: str) -> DeviceSpec | None: ...
63
+
64
+
65
+ class LanSource(Protocol):
66
+ def read(self, devices: Sequence[Device]) -> list[Reading]: ...
67
+
68
+
69
+ class DeveloperSource(ScheduleWriter, Protocol):
70
+ def read(self, device: Device) -> Reading: ...
71
+
72
+ def read_schedule(self, dev_id: str) -> dict[str, Any]: ...
73
+
74
+ def lan_inventory(self) -> Any: ...
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class BridgeConfig:
79
+ """Runtime settings of the bridge. Intervals are in seconds."""
80
+
81
+ prefix: str = DEFAULT_PREFIX
82
+ sharing_interval: float = 60.0
83
+ lan_interval: float = 60.0
84
+ developer_interval: float = 3600.0
85
+ discovery_interval: float = 6 * 3600.0
86
+ stale_after: float = 600.0
87
+ writes_enabled: bool = False
88
+ names: Mapping[str, str] = field(default_factory=dict)
89
+ # Trial designations by write name (``router.write_name``): one device per candidate.
90
+ trials: Mapping[str, str] = field(default_factory=dict)
91
+ bridge_version: str | None = None
92
+
93
+
94
+ @dataclass
95
+ class ChannelStatus:
96
+ """Health of one channel, as published in ``bridge/info``."""
97
+
98
+ state: str = "idle" # idle, ok, error, unauthenticated
99
+ error: str | None = None
100
+ last_ok: float | None = None
101
+ failures: int = 0
102
+ next_try: float = 0.0
103
+
104
+
105
+ def _iso(at: float | None) -> str | None:
106
+ return None if at is None else datetime.fromtimestamp(at, tz=UTC).isoformat(timespec="seconds")
107
+
108
+
109
+ class Bridge:
110
+ """The daemon core. See the module documentation."""
111
+
112
+ def __init__(
113
+ self,
114
+ transport: MqttTransport,
115
+ *,
116
+ sharing: SharingSource | None = None,
117
+ lan: LanSource | None = None,
118
+ developer: DeveloperSource | None = None,
119
+ config: BridgeConfig | None = None,
120
+ gate: WriteGate | None = None,
121
+ clock: Callable[[], float] = time.time,
122
+ ) -> None:
123
+ self.config = config or BridgeConfig()
124
+ self.transport = transport
125
+ self.sharing, self.lan, self.developer = sharing, lan, developer
126
+ present = [
127
+ channel
128
+ for channel, client in (
129
+ (Channel.SHARING, sharing),
130
+ (Channel.LAN, lan),
131
+ (Channel.DEVELOPER, developer),
132
+ )
133
+ if client is not None
134
+ ]
135
+ self.router = Router(present, self.config.trials)
136
+ self.gate = gate or WriteGate(
137
+ self.router, sharing=sharing, developer=developer, enabled=self.config.writes_enabled
138
+ )
139
+ self.status = {channel: ChannelStatus() for channel in present}
140
+ self.devices: dict[str, Device] = {}
141
+ self.states: dict[str, DeviceState] = {}
142
+ self.names: dict[str, str] = {}
143
+ self._clock = clock
144
+ self._inbox: queue.Queue[tuple[str, str]] = queue.Queue()
145
+ self._last_read: dict[str, float] = {}
146
+ self._availability: dict[str, bool] = {}
147
+ self._due: dict[str, float] = {}
148
+ self._info: str | None = None
149
+
150
+ # -- topics ----------------------------------------------------------------------------
151
+
152
+ def _topic(self, *levels: str) -> str:
153
+ return "/".join((self.config.prefix, *levels))
154
+
155
+ def _publish(self, topic: str, payload: Any, *, retain: bool = True) -> None:
156
+ self.transport.publish(topic, json.dumps(payload, ensure_ascii=False), retain=retain)
157
+
158
+ def _respond(
159
+ self,
160
+ action: str,
161
+ *,
162
+ data: Any = None,
163
+ error: str | None = None,
164
+ transaction: Any = None,
165
+ ) -> None:
166
+ payload: dict[str, Any] = {"status": "error" if error else "ok", "data": data or {}}
167
+ if error:
168
+ payload["error"] = error
169
+ if transaction is not None:
170
+ payload["transaction"] = transaction
171
+ self._publish(self._topic("bridge", "response", action), payload, retain=False)
172
+
173
+ # -- life cycle ------------------------------------------------------------------------
174
+
175
+ def start(self) -> None:
176
+ """Subscribe to commands and requests, and announce the bridge."""
177
+ self.transport.subscribe(self._topic("+", "set"), self._enqueue)
178
+ self.transport.subscribe(self._topic("bridge", "request", "#"), self._enqueue)
179
+ self.announce()
180
+ self.publish_info()
181
+
182
+ def announce(self) -> None:
183
+ """Say the bridge is online. Call it again after each MQTT reconnection."""
184
+ self._publish(self._topic("bridge", "state"), {"state": "online"})
185
+
186
+ def stop(self) -> None:
187
+ """Say the bridge is gone. The broker's last will covers a crash."""
188
+ self._publish(self._topic("bridge", "state"), {"state": "offline"})
189
+
190
+ def run(self, stop: threading.Event, *, idle: float = 1.0) -> None:
191
+ """Serve until ``stop`` is set: handle queued messages, poll when due."""
192
+ self.start()
193
+ try:
194
+ while not stop.is_set():
195
+ self.step(idle)
196
+ finally:
197
+ self.stop()
198
+
199
+ def step(self, timeout: float = 0.0) -> None:
200
+ """One turn of the loop: the queued messages, then whatever read is due."""
201
+ try:
202
+ topic, payload = (
203
+ self._inbox.get(timeout=timeout) if timeout else self._inbox.get_nowait()
204
+ )
205
+ except queue.Empty:
206
+ pass
207
+ else:
208
+ self.handle_message(topic, payload)
209
+ while True:
210
+ try:
211
+ topic, payload = self._inbox.get_nowait()
212
+ except queue.Empty:
213
+ break
214
+ self.handle_message(topic, payload)
215
+ self.poll()
216
+
217
+ def _enqueue(self, topic: str, payload: str) -> None:
218
+ self._inbox.put((topic, payload))
219
+
220
+ # -- channel health --------------------------------------------------------------------
221
+
222
+ def _usable(self, channel: Channel) -> bool:
223
+ status = self.status.get(channel)
224
+ return (
225
+ status is not None
226
+ and status.state != "unauthenticated"
227
+ and self._clock() >= status.next_try
228
+ )
229
+
230
+ def _attempt(self, channel: Channel, interval: float, call: Callable[[], Any]) -> Any:
231
+ """Run a channel call, recording its outcome. Returns ``None`` when it failed."""
232
+ status = self.status[channel]
233
+ try:
234
+ result = call()
235
+ except AuthenticationError as err:
236
+ status.state, status.error = "unauthenticated", str(err)
237
+ _LOGGER.error("%s channel: credentials refused, channel paused", channel.value)
238
+ return None
239
+ except ChannelError as err:
240
+ status.failures += 1
241
+ status.state, status.error = "error", str(err)
242
+ status.next_try = self._clock() + min(interval * 2**status.failures, MAX_BACKOFF)
243
+ _LOGGER.warning("%s channel: %s", channel.value, err)
244
+ return None
245
+ status.state, status.error, status.failures = "ok", None, 0
246
+ status.last_ok, status.next_try = self._clock(), 0.0
247
+ return result
248
+
249
+ def replace_channel(
250
+ self, channel: Channel, client: SharingSource | LanSource | DeveloperSource
251
+ ) -> None:
252
+ """Swap in a rebuilt channel client (new session or key) and resume it."""
253
+ if channel not in self.status:
254
+ raise ValueError(f"the bridge was started without a {channel.value} channel")
255
+ if channel is Channel.SHARING:
256
+ self.sharing = client # type: ignore[assignment]
257
+ self.gate.replace(sharing=self.sharing)
258
+ elif channel is Channel.LAN:
259
+ self.lan = client # type: ignore[assignment]
260
+ else:
261
+ self.developer = client # type: ignore[assignment]
262
+ self.gate.replace(developer=self.developer)
263
+ self.status[channel] = ChannelStatus()
264
+ self._due.pop(channel.value, None)
265
+
266
+ def publish_info(self) -> None:
267
+ """Publish ``bridge/info`` when it changed."""
268
+ info = {
269
+ "version": self.config.bridge_version,
270
+ "library_version": __version__,
271
+ "contract_version": dialect.CONTRACT_VERSION,
272
+ "writes_enabled": self.gate.enabled,
273
+ "channels": {
274
+ channel.value: (
275
+ {"state": "absent"}
276
+ if channel not in self.status
277
+ else {
278
+ "state": self.status[channel].state,
279
+ "error": self.status[channel].error,
280
+ "last_ok": _iso(self.status[channel].last_ok),
281
+ }
282
+ )
283
+ for channel in Channel
284
+ },
285
+ "routes": self.router.describe(dps.PRODUCT_FP_THERMOSTAT),
286
+ }
287
+ # ``last_ok`` moves at every read: it is published, but does not by itself make the
288
+ # bridge publish again.
289
+ signature = json.dumps(
290
+ [info["writes_enabled"], [(s.state, s.error) for s in self.status.values()]]
291
+ )
292
+ if signature != self._info:
293
+ self._info = signature
294
+ self._publish(self._topic("bridge", "info"), info)
295
+
296
+ # -- discovery -------------------------------------------------------------------------
297
+
298
+ def discover(self) -> bool:
299
+ """List the supported thermostats and publish ``bridge/devices``. False when it failed."""
300
+ found: list[Device] | None = None
301
+ inventory: dict[str, Device] = {}
302
+ if self.developer is not None and self._usable(Channel.DEVELOPER):
303
+ listed = self._attempt(
304
+ Channel.DEVELOPER, self.config.developer_interval, self.developer.lan_inventory
305
+ )
306
+ if listed is not None:
307
+ inventory = {device.dev_id: device for device in listed.devices}
308
+ if self.sharing is not None:
309
+ if self._usable(Channel.SHARING):
310
+ found = self._attempt(
311
+ Channel.SHARING, self.config.sharing_interval, self.sharing.discover
312
+ )
313
+ elif inventory:
314
+ found = list(inventory.values())
315
+ if found is None:
316
+ return False
317
+ devices: dict[str, Device] = {}
318
+ for device in found:
319
+ if not device.supported:
320
+ continue
321
+ known = inventory.get(device.dev_id)
322
+ if known is not None:
323
+ device = dataclasses.replace(
324
+ device,
325
+ gateway_id=device.gateway_id or known.gateway_id,
326
+ node_id=device.node_id or known.node_id,
327
+ )
328
+ devices[device.dev_id] = device
329
+ for dev_id in set(self.devices) - set(devices):
330
+ self._set_availability(dev_id, False)
331
+ self.states.pop(dev_id, None)
332
+ self.devices = devices
333
+ names = dialect.friendly_names(list(devices.values()))
334
+ for dev_id, name in self.config.names.items():
335
+ if dev_id in names:
336
+ names[dev_id] = dialect.friendly_name(name, names[dev_id])
337
+ if len(set(names.values())) != len(names):
338
+ names = dialect.friendly_names(
339
+ [dataclasses.replace(d, name=names[d.dev_id]) for d in devices.values()]
340
+ )
341
+ self.names = names
342
+ for dev_id, device in devices.items():
343
+ state = self.states.setdefault(dev_id, DeviceState(device))
344
+ state.device = device
345
+ self._publish(
346
+ self._topic("bridge", "devices"),
347
+ [
348
+ dialect.encode_descriptor(device, names[dev_id])
349
+ for dev_id, device in sorted(devices.items(), key=lambda item: names[item[0]])
350
+ ],
351
+ )
352
+ return True
353
+
354
+ def _spec(self, dev_id: str) -> DeviceSpec | None:
355
+ return None if self.sharing is None else self.sharing.spec(dev_id)
356
+
357
+ def _device_named(self, name: Any) -> Device:
358
+ for dev_id, known in self.names.items():
359
+ if known == name:
360
+ return self.devices[dev_id]
361
+ raise PilotWireError(f"unknown device {name!r}")
362
+
363
+ # -- reads -----------------------------------------------------------------------------
364
+
365
+ def _is_due(self, what: str, interval: float) -> bool:
366
+ now = self._clock()
367
+ if now < self._due.get(what, 0.0):
368
+ return False
369
+ self._due[what] = now + interval
370
+ return True
371
+
372
+ def poll(self) -> None:
373
+ """Run the reads that are due, then publish what they brought."""
374
+ now = self._clock()
375
+ if now >= self._due.get("discovery", 0.0):
376
+ retry = min(self.config.sharing_interval, self.config.discovery_interval)
377
+ self._due["discovery"] = now + (
378
+ self.config.discovery_interval if self.discover() else retry
379
+ )
380
+ read: set[str] = set()
381
+ devices = list(self.devices.values())
382
+ if devices:
383
+ if (
384
+ self.sharing is not None
385
+ and self._usable(Channel.SHARING)
386
+ and self._is_due("sharing", self.config.sharing_interval)
387
+ ):
388
+ sharing = self.sharing
389
+ read |= self._apply(
390
+ Channel.SHARING,
391
+ self._attempt(
392
+ Channel.SHARING,
393
+ self.config.sharing_interval,
394
+ lambda: sharing.read([device.dev_id for device in devices]),
395
+ ),
396
+ )
397
+ if (
398
+ self.lan is not None
399
+ and self._usable(Channel.LAN)
400
+ and self._is_due("lan", self.config.lan_interval)
401
+ ):
402
+ lan = self.lan
403
+ read |= self._apply(
404
+ Channel.LAN,
405
+ self._attempt(Channel.LAN, self.config.lan_interval, lambda: lan.read(devices)),
406
+ )
407
+ if (
408
+ self.developer is not None
409
+ and self._usable(Channel.DEVELOPER)
410
+ and self._is_due("developer", self.config.developer_interval)
411
+ ):
412
+ developer = self.developer
413
+ read |= self._apply(
414
+ Channel.DEVELOPER,
415
+ self._attempt(
416
+ Channel.DEVELOPER,
417
+ self.config.developer_interval,
418
+ lambda: [developer.read(device) for device in devices],
419
+ ),
420
+ )
421
+ for dev_id in sorted(read):
422
+ self.publish_state(dev_id)
423
+ self._refresh_availability()
424
+ self.publish_info()
425
+
426
+ def _apply(self, channel: Channel, readings: list[Reading] | None) -> set[str]:
427
+ """Merge readings, keeping from each only the keys proven for its channel."""
428
+ applied: set[str] = set()
429
+ for reading in readings or []:
430
+ state = self.states.get(reading.dev_id)
431
+ if state is None:
432
+ continue
433
+ keys = self.router.read_keys(state.device, channel)
434
+ trusted = {key: value for key, value in reading.values.items() if key in keys}
435
+ if not trusted and reading.online is None:
436
+ continue
437
+ state.apply(dataclasses.replace(reading, values=trusted))
438
+ self._last_read[reading.dev_id] = reading.at
439
+ applied.add(reading.dev_id)
440
+ return applied
441
+
442
+ def publish_state(self, dev_id: str) -> None:
443
+ """Publish the state object of one device."""
444
+ state = self.states[dev_id]
445
+ self._publish(
446
+ self._topic(self.names[dev_id]), dialect.encode_state(state, self._spec(dev_id))
447
+ )
448
+
449
+ def _set_availability(self, dev_id: str, online: bool) -> None:
450
+ if self._availability.get(dev_id) is online or dev_id not in self.names:
451
+ return
452
+ self._availability[dev_id] = online
453
+ self._publish(
454
+ self._topic(self.names[dev_id], "availability"), dialect.encode_availability(online)
455
+ )
456
+
457
+ def _refresh_availability(self) -> None:
458
+ now = self._clock()
459
+ for dev_id, state in self.states.items():
460
+ last = self._last_read.get(dev_id)
461
+ fresh = last is not None and now - last <= self.config.stale_after
462
+ # Without the sharing API nothing tells whether the device is online: a fresh
463
+ # reading is the only evidence.
464
+ online = (
465
+ state.online is True
466
+ if Channel.SHARING in self.status
467
+ else state.online is not False
468
+ )
469
+ self._set_availability(dev_id, fresh and online)
470
+
471
+ # -- commands --------------------------------------------------------------------------
472
+
473
+ def handle_message(self, topic: str, payload: str) -> None:
474
+ """Dispatch one inbound message. Failures are answered on the response topic."""
475
+ levels = topic.split("/")
476
+ prefix = self.config.prefix.split("/")
477
+ if levels[: len(prefix)] != prefix:
478
+ return
479
+ rest = levels[len(prefix) :]
480
+ if len(rest) >= 3 and rest[:2] == ["bridge", "request"]:
481
+ self.handle_request("/".join(rest[2:]), payload)
482
+ elif len(rest) == 2 and rest[1] == "set" and rest[0] != "bridge":
483
+ self.handle_set(rest[0], payload)
484
+
485
+ @staticmethod
486
+ def _object(raw: str) -> dict[str, Any]:
487
+ try:
488
+ payload = json.loads(raw)
489
+ except (TypeError, ValueError) as err:
490
+ raise PilotWireError("payload is not valid JSON") from err
491
+ if not isinstance(payload, dict):
492
+ raise PilotWireError("payload is not a JSON object")
493
+ return payload
494
+
495
+ def handle_set(self, name: str, raw: str) -> None:
496
+ """Execute a ``<name>/set`` payload through the write gate and answer."""
497
+ transaction: Any = None
498
+ results: list[dict[str, Any]] = []
499
+ data: dict[str, Any] = {"device": name, "results": results}
500
+ try:
501
+ payload = self._object(raw)
502
+ transaction = payload.pop("transaction", None)
503
+ device = self._device_named(name)
504
+ commands = dialect.decode_command(payload)
505
+ spec = self._spec(device.dev_id)
506
+ planned: list[tuple[dialect.Command, PlannedWrite]] = [
507
+ (command, self.gate.plan(device, spec, command.key, command.value))
508
+ for command in commands
509
+ ]
510
+ except PilotWireError as err:
511
+ self._respond("device/set", data=data, error=str(err), transaction=transaction)
512
+ return
513
+ error: str | None = None
514
+ touched = False
515
+ for command, plan in planned:
516
+ entry: dict[str, Any] = {
517
+ "property": command.property,
518
+ "value": payload[command.property],
519
+ }
520
+ results.append(entry)
521
+ try:
522
+ result = self.gate.execute(plan)
523
+ except PilotWireError as err:
524
+ entry["confirmed"] = False
525
+ error = f"{command.property}: {err}"
526
+ break
527
+ entry["confirmed"] = result.confirmed
528
+ if result.reading is not None:
529
+ touched = bool(self._apply(result.channel, [result.reading])) or touched
530
+ if not result.confirmed:
531
+ error = f"{command.property}: not confirmed, {result.detail}"
532
+ break
533
+ if touched:
534
+ self.publish_state(device.dev_id)
535
+ self._refresh_availability()
536
+ self._respond("device/set", data=data, error=error, transaction=transaction)
537
+
538
+ def handle_request(self, action: str, raw: str) -> None:
539
+ """Serve ``bridge/request/<action>``: ``schedule/get`` and ``schedule/set``."""
540
+ transaction: Any = None
541
+ try:
542
+ payload = self._object(raw)
543
+ transaction = payload.get("transaction")
544
+ if action == "schedule/get":
545
+ device = self._device_named(payload.get("device"))
546
+ self.router.route(device, Operation.READ_SCHEDULE)
547
+ assert self.developer is not None
548
+ week = self.developer.read_schedule(device.dev_id)
549
+ self._respond(action, data=week, transaction=transaction)
550
+ elif action == "schedule/set":
551
+ device = self._device_named(payload.get("device"))
552
+ result = self.gate.write_schedule(device, payload.get("days")) # type: ignore[arg-type]
553
+ self._respond(
554
+ action,
555
+ data=result.week,
556
+ error=None if result.confirmed else f"not confirmed: {result.detail}",
557
+ transaction=transaction,
558
+ )
559
+ else:
560
+ raise RouteRefused(f"unknown request {action!r}")
561
+ except PilotWireError as err:
562
+ with contextlib.suppress(Exception):
563
+ self._respond(action, error=str(err), transaction=transaction)
@@ -0,0 +1,5 @@
1
+ """Channel clients: device-sharing API, LAN, developer API.
2
+
3
+ Each one needs an optional dependency (extras ``sharing``, ``lan``, ``developer``), imported only
4
+ when the channel is first used.
5
+ """