aioebus 0.7.2__tar.gz → 0.7.4__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.
Files changed (68) hide show
  1. aioebus-0.7.4/PKG-INFO +111 -0
  2. aioebus-0.7.4/README.md +86 -0
  3. {aioebus-0.7.2 → aioebus-0.7.4}/pyproject.toml +6 -0
  4. aioebus-0.7.4/src/aioebus/__init__.py +109 -0
  5. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/active.py +24 -175
  6. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/catalog.py +197 -115
  7. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/codecs.py +43 -19
  8. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/conditions.py +1 -1
  9. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/convert.py +16 -39
  10. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/defs/vaillant/PROVENANCE.md +9 -7
  11. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/defs/vaillant/index.json +3 -3
  12. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/discovery.py +17 -13
  13. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/engine.py +55 -26
  14. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/frame.py +15 -3
  15. aioebus-0.7.4/src/aioebus/link.py +68 -0
  16. aioebus-0.7.4/src/aioebus/messages.py +410 -0
  17. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/passive.py +34 -37
  18. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/poll.py +7 -17
  19. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/scan.py +17 -3
  20. aioebus-0.7.4/src/aioebus/translations.py +30 -0
  21. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/transport.py +8 -69
  22. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/values.py +35 -14
  23. aioebus-0.7.4/src/aioebus.egg-info/PKG-INFO +111 -0
  24. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus.egg-info/SOURCES.txt +2 -2
  25. {aioebus-0.7.2 → aioebus-0.7.4}/tests/test_active.py +2 -12
  26. {aioebus-0.7.2 → aioebus-0.7.4}/tests/test_active_read.py +10 -139
  27. {aioebus-0.7.2 → aioebus-0.7.4}/tests/test_catalog.py +103 -8
  28. aioebus-0.7.4/tests/test_codecs.py +130 -0
  29. aioebus-0.7.2/tests/test_condition_eval.py → aioebus-0.7.4/tests/test_conditions.py +24 -1
  30. {aioebus-0.7.2 → aioebus-0.7.4}/tests/test_discovery.py +13 -2
  31. {aioebus-0.7.2 → aioebus-0.7.4}/tests/test_engine.py +82 -1
  32. aioebus-0.7.4/tests/test_link.py +73 -0
  33. aioebus-0.7.4/tests/test_messages.py +257 -0
  34. aioebus-0.7.4/tests/test_passive.py +99 -0
  35. {aioebus-0.7.2 → aioebus-0.7.4}/tests/test_poll.py +26 -4
  36. {aioebus-0.7.2 → aioebus-0.7.4}/tests/test_scan.py +6 -0
  37. aioebus-0.7.4/tests/test_translations.py +66 -0
  38. {aioebus-0.7.2 → aioebus-0.7.4}/tests/test_transport.py +33 -19
  39. {aioebus-0.7.2 → aioebus-0.7.4}/tests/test_values.py +19 -0
  40. {aioebus-0.7.2 → aioebus-0.7.4}/tests/test_write.py +4 -157
  41. aioebus-0.7.2/PKG-INFO +0 -188
  42. aioebus-0.7.2/README.md +0 -163
  43. aioebus-0.7.2/src/aioebus/__init__.py +0 -87
  44. aioebus-0.7.2/src/aioebus/messages.py +0 -280
  45. aioebus-0.7.2/src/aioebus/translations.py +0 -53
  46. aioebus-0.7.2/src/aioebus.egg-info/PKG-INFO +0 -188
  47. aioebus-0.7.2/tests/test_codecs.py +0 -56
  48. aioebus-0.7.2/tests/test_conditions.py +0 -38
  49. aioebus-0.7.2/tests/test_messages.py +0 -92
  50. aioebus-0.7.2/tests/test_passive.py +0 -46
  51. aioebus-0.7.2/tests/test_tr.py +0 -73
  52. aioebus-0.7.2/tests/test_translations.py +0 -27
  53. {aioebus-0.7.2 → aioebus-0.7.4}/LICENSE +0 -0
  54. {aioebus-0.7.2 → aioebus-0.7.4}/setup.cfg +0 -0
  55. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/defs/vaillant/broadcast.json +0 -0
  56. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/defs/vaillant/ctlv3.json +0 -0
  57. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/defs/vaillant/eloblock.json +0 -0
  58. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/defs/vaillant/f6.netx3.json +0 -0
  59. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/defs/vaillant/hmu.json +0 -0
  60. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/defs/vaillant/pmw.json +0 -0
  61. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/defs/vaillant/vr_71.json +0 -0
  62. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/defs/vaillant/vwzio.json +0 -0
  63. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus/py.typed +0 -0
  64. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus.egg-info/dependency_links.txt +0 -0
  65. {aioebus-0.7.2 → aioebus-0.7.4}/src/aioebus.egg-info/top_level.txt +0 -0
  66. {aioebus-0.7.2 → aioebus-0.7.4}/tests/test_bitfields.py +0 -0
  67. {aioebus-0.7.2 → aioebus-0.7.4}/tests/test_datatypes.py +0 -0
  68. {aioebus-0.7.2 → aioebus-0.7.4}/tests/test_frame.py +0 -0
aioebus-0.7.4/PKG-INFO ADDED
@@ -0,0 +1,111 @@
1
+ Metadata-Version: 2.4
2
+ Name: aioebus
3
+ Version: 0.7.4
4
+ Summary: Standalone async eBUS library (decode-first). No ebusd daemon required.
5
+ Author-email: dneprojects <dne.projects.1@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/dneprojects/aioebus
8
+ Project-URL: Repository, https://github.com/dneprojects/aioebus
9
+ Project-URL: Issues, https://github.com/dneprojects/aioebus/issues
10
+ Keywords: ebus,ebusd,vaillant,heating,home-assistant,asyncio
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Home Automation
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.11
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Dynamic: license-file
25
+
26
+ # aioebus
27
+
28
+ A **standalone, async, pure-Python eBUS library**: it talks to an eBUS adapter
29
+ (enhanced protocol over TCP) and decodes Vaillant/eBUS messages **without an
30
+ ebusd daemon**. The [ebus Home Assistant integration](https://github.com/dneprojects/ebus)
31
+ is built on it and runs it in the field.
32
+
33
+ It ports [ebusd](https://github.com/john30/ebusd)'s behaviour to Python by spec
34
+ (not line by line) and checks every layer against real captured telegrams.
35
+
36
+ ## What it does
37
+
38
+ | Module | |
39
+ |---|---|
40
+ | `link` | TCP connection to the adapter (`connect`), liveness `probe` |
41
+ | `engine` | One connection: decodes what other masters put on the bus (free), slips its own reads/writes in when the bus is idle, keeps a value cache, polls by priority (`poll`) |
42
+ | `discovery` | Which devices are on the bus: scan, Vaillant identification (article, serial), deep scan of every slave address, phantom addresses |
43
+ | `catalog` | Each device's definitions: our bundled ones, else a user file, else the matching ebusd-configuration CSV from ebus.github.io (chosen as ebusd chooses it, with its `!load` includes), cached; display texts per language |
44
+ | `values` | What a message's values are: labels, stable keys, cache keys, numeric or not, the control a write allows |
45
+ | `messages`, `codecs` | Message model, ebusd-CSV ingest (default rows, conditions, value tables), every ebusd datatype |
46
+ | `frame`, `passive`, `transport`, `active` | Telegrams and CRC, matching telegrams to definitions, the adapter's byte protocol, the transaction state machine |
47
+
48
+ ## Example
49
+
50
+ ```python
51
+ import asyncio
52
+
53
+ from aioebus import Catalog, EbusEngine, MessageRegistry, PollScheduler, connect, discover
54
+
55
+
56
+ async def main() -> None:
57
+ link = await connect("192.168.1.50", 9999)
58
+ engine = EbusEngine(link.send, link.recv, MessageRegistry([]))
59
+ run = asyncio.create_task(engine.run())
60
+
61
+ found = await discover(engine) # which devices answer
62
+ catalog = Catalog() # bundled definitions only
63
+ await catalog.load({a: d.scan for a, d in found.devices.items()},
64
+ {a: d.ident for a, d in found.devices.items() if d.ident})
65
+ engine.registry = MessageRegistry(catalog.all_messages())
66
+ engine.scheduler = PollScheduler(catalog.device_messages("r"), base_interval=60)
67
+
68
+ await asyncio.sleep(120)
69
+ print(engine.cache) # (device, message, label) -> value
70
+ engine.stop()
71
+ link.close()
72
+ await run
73
+
74
+
75
+ asyncio.run(main())
76
+ ```
77
+
78
+ To load ebusd-configuration CSVs for devices without a bundled definition, give
79
+ the catalog a cache directory and a `fetch(url) -> str | None` coroutine
80
+ (`""` when the server says the file does not exist, `None` when unreachable).
81
+
82
+ Writing is opt-in (`EbusEngine(..., allow_write=True)`). A write that went out
83
+ completely but was not acknowledged raises `WriteUncertain` and is never sent
84
+ twice; read the value back instead.
85
+
86
+ Decoding a captured telegram needs no bus:
87
+
88
+ ```python
89
+ from aioebus import MessageRegistry, decode_raw, parse_csv
90
+
91
+ reg = MessageRegistry(parse_csv(open("38.v32.csv").read()))
92
+ decode_raw(reg, "3138b509030d1800740003910100bb00") # (FlowTemp def, {'FlowTemp': 25.0625})
93
+ ```
94
+
95
+ ## Definitions and licensing
96
+
97
+ The library ships only its own Vaillant definitions (`aioebus/defs/vaillant`,
98
+ Apache-2.0, provenance in its `PROVENANCE.md`): re-engineered from observed
99
+ telegrams or hand-written, facts only. The ebusd-configuration CSVs are GPL-3.0;
100
+ the catalog downloads them on the user's own machine and keeps them in the
101
+ caller's cache directory, never in this package. `python -m aioebus.convert`
102
+ turns an ebusd CSV into the native JSON format, for local use.
103
+
104
+ ## Dev
105
+
106
+ ```bash
107
+ python -m pytest # tests, incl. real captures
108
+ ruff check src tests tools
109
+ mypy
110
+ python tools/validate_frame_db.py /path/to/telegrams.db # frames vs ebusd
111
+ ```
@@ -0,0 +1,86 @@
1
+ # aioebus
2
+
3
+ A **standalone, async, pure-Python eBUS library**: it talks to an eBUS adapter
4
+ (enhanced protocol over TCP) and decodes Vaillant/eBUS messages **without an
5
+ ebusd daemon**. The [ebus Home Assistant integration](https://github.com/dneprojects/ebus)
6
+ is built on it and runs it in the field.
7
+
8
+ It ports [ebusd](https://github.com/john30/ebusd)'s behaviour to Python by spec
9
+ (not line by line) and checks every layer against real captured telegrams.
10
+
11
+ ## What it does
12
+
13
+ | Module | |
14
+ |---|---|
15
+ | `link` | TCP connection to the adapter (`connect`), liveness `probe` |
16
+ | `engine` | One connection: decodes what other masters put on the bus (free), slips its own reads/writes in when the bus is idle, keeps a value cache, polls by priority (`poll`) |
17
+ | `discovery` | Which devices are on the bus: scan, Vaillant identification (article, serial), deep scan of every slave address, phantom addresses |
18
+ | `catalog` | Each device's definitions: our bundled ones, else a user file, else the matching ebusd-configuration CSV from ebus.github.io (chosen as ebusd chooses it, with its `!load` includes), cached; display texts per language |
19
+ | `values` | What a message's values are: labels, stable keys, cache keys, numeric or not, the control a write allows |
20
+ | `messages`, `codecs` | Message model, ebusd-CSV ingest (default rows, conditions, value tables), every ebusd datatype |
21
+ | `frame`, `passive`, `transport`, `active` | Telegrams and CRC, matching telegrams to definitions, the adapter's byte protocol, the transaction state machine |
22
+
23
+ ## Example
24
+
25
+ ```python
26
+ import asyncio
27
+
28
+ from aioebus import Catalog, EbusEngine, MessageRegistry, PollScheduler, connect, discover
29
+
30
+
31
+ async def main() -> None:
32
+ link = await connect("192.168.1.50", 9999)
33
+ engine = EbusEngine(link.send, link.recv, MessageRegistry([]))
34
+ run = asyncio.create_task(engine.run())
35
+
36
+ found = await discover(engine) # which devices answer
37
+ catalog = Catalog() # bundled definitions only
38
+ await catalog.load({a: d.scan for a, d in found.devices.items()},
39
+ {a: d.ident for a, d in found.devices.items() if d.ident})
40
+ engine.registry = MessageRegistry(catalog.all_messages())
41
+ engine.scheduler = PollScheduler(catalog.device_messages("r"), base_interval=60)
42
+
43
+ await asyncio.sleep(120)
44
+ print(engine.cache) # (device, message, label) -> value
45
+ engine.stop()
46
+ link.close()
47
+ await run
48
+
49
+
50
+ asyncio.run(main())
51
+ ```
52
+
53
+ To load ebusd-configuration CSVs for devices without a bundled definition, give
54
+ the catalog a cache directory and a `fetch(url) -> str | None` coroutine
55
+ (`""` when the server says the file does not exist, `None` when unreachable).
56
+
57
+ Writing is opt-in (`EbusEngine(..., allow_write=True)`). A write that went out
58
+ completely but was not acknowledged raises `WriteUncertain` and is never sent
59
+ twice; read the value back instead.
60
+
61
+ Decoding a captured telegram needs no bus:
62
+
63
+ ```python
64
+ from aioebus import MessageRegistry, decode_raw, parse_csv
65
+
66
+ reg = MessageRegistry(parse_csv(open("38.v32.csv").read()))
67
+ decode_raw(reg, "3138b509030d1800740003910100bb00") # (FlowTemp def, {'FlowTemp': 25.0625})
68
+ ```
69
+
70
+ ## Definitions and licensing
71
+
72
+ The library ships only its own Vaillant definitions (`aioebus/defs/vaillant`,
73
+ Apache-2.0, provenance in its `PROVENANCE.md`): re-engineered from observed
74
+ telegrams or hand-written, facts only. The ebusd-configuration CSVs are GPL-3.0;
75
+ the catalog downloads them on the user's own machine and keeps them in the
76
+ caller's cache directory, never in this package. `python -m aioebus.convert`
77
+ turns an ebusd CSV into the native JSON format, for local use.
78
+
79
+ ## Dev
80
+
81
+ ```bash
82
+ python -m pytest # tests, incl. real captures
83
+ ruff check src tests tools
84
+ mypy
85
+ python tools/validate_frame_db.py /path/to/telegrams.db # frames vs ebusd
86
+ ```
@@ -43,6 +43,12 @@ aioebus = ["py.typed", "defs/vaillant/*.json", "defs/vaillant/PROVENANCE.md"]
43
43
  pythonpath = ["src"]
44
44
  testpaths = ["tests"]
45
45
 
46
+ [tool.mypy]
47
+ python_version = "3.11"
48
+ files = ["src/aioebus"]
49
+ warn_unused_ignores = true
50
+ warn_redundant_casts = true
51
+
46
52
  [tool.ruff]
47
53
  target-version = "py311"
48
54
  line-length = 110
@@ -0,0 +1,109 @@
1
+ """aioebus -- standalone async eBUS library (no ebusd daemon).
2
+
3
+ - link: the TCP connection to an enhanced adapter, and a liveness probe
4
+ - engine: one connection, passive decoding plus interleaved active reads and
5
+ writes, a value cache and a poll scheduler (poll)
6
+ - discovery: which devices are on the bus and what they are (scan, identification)
7
+ - catalog: each device's definitions (bundled, user files, ebusd CSVs from the CDN)
8
+ - values: what a message's values are (keys, labels, numeric, the control a write allows)
9
+ - messages / codecs: message definitions, ebusd-CSV ingest, datatype decoding
10
+ - frame / passive / transport / active: telegrams, CRC, the adapter protocol and
11
+ the transaction state machine
12
+ - translations: stable keys for display texts
13
+ """
14
+ from .active import (
15
+ DEFAULT_SOURCE,
16
+ ReadDriver,
17
+ ReadError,
18
+ WriteDriver,
19
+ WriteUncertain,
20
+ build_read_frame,
21
+ build_write_frame,
22
+ )
23
+ from .catalog import BROADCAST_SCAN, Catalog, ClimateZone, Definition, Texts
24
+ from .codecs import Codec, decode, encode, make_codec
25
+ from .conditions import ConditionContext, context_from_scan, evaluate, evaluate_all
26
+ from .discovery import BusSilent, Device, Discovery, discover, identify_later, remember
27
+ from .engine import EbusEngine, EngineStats
28
+ from .frame import BROADCAST, Telegram, crc8, escape, is_master, is_slave, parse_telegram, unescape
29
+ from .link import Link, connect, probe
30
+ from .messages import FieldDef, MessageDef, label_of, parse_csv
31
+ from .passive import MessageRegistry, decode_raw
32
+ from .poll import PollScheduler
33
+ from .scan import MANUFACTURERS, Identification, ScanResult, decode_identification, decode_scan
34
+ from .translations import slug, translation_key
35
+ from .values import (
36
+ Value,
37
+ closes_period,
38
+ control_of,
39
+ has_numeric_value,
40
+ is_float_type,
41
+ is_number_type,
42
+ value_key,
43
+ values_of,
44
+ )
45
+
46
+ __all__ = [
47
+ "BROADCAST",
48
+ "BROADCAST_SCAN",
49
+ "DEFAULT_SOURCE",
50
+ "MANUFACTURERS",
51
+ "BusSilent",
52
+ "Catalog",
53
+ "ClimateZone",
54
+ "Codec",
55
+ "ConditionContext",
56
+ "Definition",
57
+ "Device",
58
+ "Discovery",
59
+ "EbusEngine",
60
+ "EngineStats",
61
+ "FieldDef",
62
+ "Identification",
63
+ "Link",
64
+ "MessageDef",
65
+ "MessageRegistry",
66
+ "PollScheduler",
67
+ "ReadDriver",
68
+ "ReadError",
69
+ "ScanResult",
70
+ "Telegram",
71
+ "Texts",
72
+ "Value",
73
+ "WriteDriver",
74
+ "WriteUncertain",
75
+ "build_read_frame",
76
+ "build_write_frame",
77
+ "closes_period",
78
+ "connect",
79
+ "context_from_scan",
80
+ "control_of",
81
+ "crc8",
82
+ "decode",
83
+ "decode_identification",
84
+ "decode_raw",
85
+ "decode_scan",
86
+ "discover",
87
+ "encode",
88
+ "escape",
89
+ "evaluate",
90
+ "evaluate_all",
91
+ "has_numeric_value",
92
+ "identify_later",
93
+ "is_float_type",
94
+ "is_master",
95
+ "is_number_type",
96
+ "is_slave",
97
+ "label_of",
98
+ "make_codec",
99
+ "parse_csv",
100
+ "parse_telegram",
101
+ "probe",
102
+ "remember",
103
+ "slug",
104
+ "translation_key",
105
+ "unescape",
106
+ "value_key",
107
+ "values_of",
108
+ ]
109
+ __version__ = "0.7.4"
@@ -1,7 +1,6 @@
1
- """Active reads and writes over the enhanced adapter.
2
-
3
- Builds the master request and drives the read transaction. The transaction FSM
4
- is ported from ebusd's protocol_direct.cpp (active-get path):
1
+ """Active transactions over the enhanced adapter: the master request and the
2
+ byte-level state machine that drives one read or write. The FSM is ported from
3
+ ebusd's protocol_direct.cpp (active-get path):
5
4
 
6
5
  arbitrate(QQ via START) -> STARTED/FAILED
7
6
  send ZZ PB SB NN DD (each SEND byte is echoed back as RECEIVED, verified)
@@ -13,27 +12,13 @@ is ported from ebusd's protocol_direct.cpp (active-get path):
13
12
 
14
13
  `qq` defaults to 0x31 -- the address ebusd itself uses on the reference bus, so
15
14
  it is a proven-good master address that is free exactly when ebusd is stopped
16
- (the single-client adapter needs ebusd down anyway). The core `ReadDriver` is a
17
- pure byte-level state machine (testable against a simulated adapter); `read()`
18
- only pumps bytes between it and the socket. Nothing is sent until the caller
19
- explicitly runs a read -- this module never writes on import or construction.
15
+ (the single-client adapter needs ebusd down anyway). The drivers are pure (no
16
+ I/O, testable against a simulated adapter); the engine pumps bytes between them
17
+ and the adapter and owns the retry policy.
20
18
  """
21
19
  from __future__ import annotations
22
20
 
23
- import asyncio
24
- from collections.abc import Awaitable, Callable
25
-
26
- from .frame import BROADCAST, ESC, SYN, crc8, escape
27
- from .messages import MessageDef
28
- from .scan import (
29
- IDENT_MSGIDS,
30
- IDENT_PBSB,
31
- SCAN_PBSB,
32
- Identification,
33
- ScanResult,
34
- decode_identification,
35
- decode_scan,
36
- )
21
+ from .frame import BROADCAST, ESC, SYN, crc8, escape, is_master
37
22
  from .transport import FAILED, RECEIVED, STARTED, EnhDecoder
38
23
 
39
24
  DEFAULT_SOURCE = 0x31 # ebusd's own master address on the reference bus (free when ebusd is down)
@@ -85,13 +70,6 @@ def build_read_frame(
85
70
  return escape(logical) + escape(bytes((crc,)))
86
71
 
87
72
 
88
- def build_read(msg: MessageDef, qq: int = DEFAULT_SOURCE) -> bytes:
89
- """Build the read frame for a message definition (needs a 2-hex zz)."""
90
- if not (msg.zz and len(msg.zz) == 2):
91
- raise ValueError(f"{msg.name}: no destination address to read from")
92
- return build_read_frame(int(msg.zz, 16), msg.pbsb, msg.msgid, qq)
93
-
94
-
95
73
  def build_write_frame(
96
74
  zz: int, pbsb: str, master_data: bytes, qq: int = DEFAULT_SOURCE
97
75
  ) -> bytes:
@@ -100,14 +78,6 @@ def build_write_frame(
100
78
  return build_read_frame(zz, pbsb, "", qq, master_data)
101
79
 
102
80
 
103
- _MASTER_NIBBLES = frozenset((0x0, 0x1, 0x3, 0x7, 0xF))
104
-
105
-
106
- def is_master(addr: int) -> bool:
107
- """eBUS master addresses have both nibbles from {0, 1, 3, 7, F}."""
108
- return (addr >> 4) in _MASTER_NIBBLES and (addr & 0x0F) in _MASTER_NIBBLES
109
-
110
-
111
81
  class _CommandDriver:
112
82
  """Pure byte-level FSM shared by active reads and writes, by destination:
113
83
 
@@ -144,8 +114,11 @@ class _CommandDriver:
144
114
  self._slave = bytearray() # unescaped slave answer so far
145
115
  self._esc = False # an escape prefix arrived, its second byte is pending
146
116
  self.done = False
147
- self.result = None
117
+ self.result: bytes | bool | None = None
148
118
  self.error: str | None = None
119
+ # the bus was contended (arbitration lost, collision): worth starting
120
+ # over -- for a write only while it cannot have landed (the engine checks)
121
+ self.retryable = False
149
122
  self.lost_to: int | None = None # winning master address when arbitration is lost
150
123
 
151
124
  def start(self) -> list[bytes]:
@@ -171,11 +144,17 @@ class _CommandDriver:
171
144
  out += self._step(code, data)
172
145
  return out
173
146
 
174
- def _fail(self, msg: str) -> list[bytes]:
147
+ def _fail(self, msg: str, *, retryable: bool = False) -> list[bytes]:
175
148
  self.error = msg
149
+ self.retryable = retryable
176
150
  self.done = True
177
151
  return []
178
152
 
153
+ def abort(self, reason: str) -> None:
154
+ """Give the transaction up from outside (e.g. past its deadline)."""
155
+ if not self.done:
156
+ self._fail(reason)
157
+
179
158
  def _step(self, code: int, data: int) -> list[bytes]:
180
159
  if self._state == "arb":
181
160
  if code == STARTED:
@@ -183,12 +162,13 @@ class _CommandDriver:
183
162
  return self._send_next_cmd()
184
163
  if code == FAILED:
185
164
  self.lost_to = data # the master that won the bus (for passive capture)
186
- return self._fail(f"arbitration lost to {data:#04x}")
165
+ return self._fail(f"arbitration lost to {data:#04x}", retryable=True)
187
166
  return [] # ignore SYN/other while waiting to win
188
167
 
189
168
  if self._state == "cmd": # verify echo of the byte we just sent
190
169
  if code != RECEIVED or data != self._cmd[self._sendpos - 1]:
191
- return self._fail("collision: echo mismatch while sending command")
170
+ return self._fail("collision: echo mismatch while sending command",
171
+ retryable=True)
192
172
  return self._send_next_cmd()
193
173
 
194
174
  if self._state == "ack": # the destination's ACK/NAK of our command
@@ -214,7 +194,7 @@ class _CommandDriver:
214
194
  if code == RECEIVED and data == NAK:
215
195
  self._state = "res"
216
196
  return []
217
- return self._fail("collision: echo mismatch while sending NAK")
197
+ return self._fail("collision: echo mismatch while sending NAK", retryable=True)
218
198
 
219
199
  if self._state == "res" and code == RECEIVED:
220
200
  return self._answer_byte(data)
@@ -279,7 +259,8 @@ class ReadDriver(_CommandDriver):
279
259
 
280
260
  def __init__(self, zz: int, pbsb: str, msgid: str, qq: int = DEFAULT_SOURCE,
281
261
  master_data: bytes = b""):
282
- super().__init__(zz, pbsb, bytes.fromhex(msgid) + master_data, qq)
262
+ self.request = bytes.fromhex(msgid) + master_data # id + arguments
263
+ super().__init__(zz, pbsb, self.request, qq)
283
264
 
284
265
 
285
266
  class WriteDriver(_CommandDriver):
@@ -294,135 +275,3 @@ class WriteDriver(_CommandDriver):
294
275
  def _result(self, answer: bytes):
295
276
  self.answer = answer
296
277
  return True
297
-
298
-
299
- async def _run_with_retry(send, recv, make_driver, timeout: float, tries: int):
300
- """Run a command driver to completion, retrying only when the shared bus was
301
- not actually acquired (lost arbitration / collision before we owned it).
302
- Returns the finished driver; a NAK or other error is returned, not retried,
303
- and is never retried for a write because the slave may already have applied
304
- one copy. The bus acquire itself is safe to retry: an incomplete master frame
305
- is rejected on CRC, so no half-write lands. A read the slave ACKed but did not
306
- answer is retried too (up to NO_ANSWER_TRIES attempts, like ebusd's resend):
307
- some devices skip the odd answer, and the read has no side effect."""
308
- last = "no attempt"
309
- no_answer = 0
310
- for _ in range(tries):
311
- drv = make_driver()
312
- for sym in drv.start():
313
- await send(sym)
314
- try:
315
- while not drv.done:
316
- chunk = await asyncio.wait_for(recv(), timeout)
317
- if not chunk: # EOF: recv() would return b"" at once forever
318
- if isinstance(drv, WriteDriver) and drv.accepted:
319
- return drv # the destination ACKed it: applied
320
- if isinstance(drv, WriteDriver) and drv.may_have_landed:
321
- raise WriteUncertain("connection closed after sending")
322
- raise ConnectionResetError("adapter closed the connection")
323
- for sym in drv.feed(chunk):
324
- await send(sym)
325
- except TimeoutError:
326
- if drv.arbitrating:
327
- await send(CANCEL_ARBITRATION)
328
- drv.error = last = "timeout"
329
- if drv.error is None:
330
- return drv
331
- last = drv.error
332
- if isinstance(drv, WriteDriver):
333
- if drv.accepted:
334
- return drv # the destination ACKed it: applied, only the tail failed
335
- if drv.may_have_landed: # it may have landed: never resend
336
- raise WriteUncertain(last)
337
- if "arbitration lost" in last or "collision" in last:
338
- await asyncio.sleep(0.05) # let the bus reach a fresh SYN
339
- continue
340
- if last == "timeout":
341
- continue
342
- if last == NO_ANSWER and isinstance(drv, ReadDriver):
343
- no_answer += 1
344
- if no_answer < NO_ANSWER_TRIES:
345
- continue
346
- break
347
- raise ReadError(last)
348
-
349
-
350
- class ActiveReader:
351
- """Async active reader over an enh link. `send`/`recv` are the only I/O: on a
352
- socket, `send(bytes)` writes and `recv()` awaits the next chunk from the
353
- adapter. Read-only in the sense that it only ever issues read requests."""
354
-
355
- def __init__(self, send: Callable[[bytes], Awaitable[None]],
356
- recv: Callable[[], Awaitable[bytes]], qq: int = DEFAULT_SOURCE):
357
- self._send = send
358
- self._recv = recv
359
- self.qq = qq
360
-
361
- async def read_raw(self, zz: int, pbsb: str, msgid: str, master_data: bytes = b"",
362
- timeout: float = 3.0, tries: int = 12) -> bytes:
363
- """Perform one active read, returning the raw slave data bytes. A lost
364
- arbitration on the shared bus is retried at the next SYN, as ebusd does."""
365
- drv = await _run_with_retry(
366
- self._send, self._recv,
367
- lambda: ReadDriver(zz, pbsb, msgid, self.qq, master_data), timeout, tries)
368
- assert drv.result is not None
369
- return drv.result
370
-
371
- async def read(self, msg: MessageDef, timeout: float = 3.0) -> dict:
372
- """Active-read one message definition and return its labelled values."""
373
- if not (msg.zz and len(msg.zz) == 2):
374
- raise ValueError(f"{msg.name}: no destination address to read from")
375
- slave = await self.read_raw(int(msg.zz, 16), msg.pbsb, msg.msgid, timeout=timeout)
376
- return msg.decode_labeled(master=b"", slave=slave)
377
-
378
- async def scan(self, zz: int, timeout: float = 3.0) -> ScanResult:
379
- """Identify a device by reading 0704 (manufacturer, id, SW, HW)."""
380
- slave = await self.read_raw(zz, SCAN_PBSB, "", timeout=timeout)
381
- return decode_scan(slave)
382
-
383
- async def read_identification(
384
- self, zz: int, timeout: float = 2.0
385
- ) -> Identification | None:
386
- """Read the Vaillant extended identification (article/serial) from b509
387
- 24/25/26. Returns None if the device does not answer these reads."""
388
- try:
389
- parts = [await self.read_raw(zz, IDENT_PBSB, msgid, timeout=timeout, tries=3)
390
- for msgid in IDENT_MSGIDS]
391
- except ConnectionError:
392
- raise # the link itself is gone: the caller must reconnect, not skip
393
- except (ReadError, TimeoutError, OSError):
394
- return None
395
- return decode_identification(*parts)
396
-
397
-
398
- class ActiveWriter:
399
- """Async active writer over an enh link. Writing changes device settings, so
400
- it is gated: construction requires an explicit `allow_write=True`, and the
401
- caller is expected to confirm each change. A lost arbitration is retried
402
- safely (an incomplete frame is rejected on CRC), but a NAK is never retried.
403
- """
404
-
405
- def __init__(self, send: Callable[[bytes], Awaitable[None]],
406
- recv: Callable[[], Awaitable[bytes]], qq: int = DEFAULT_SOURCE,
407
- *, allow_write: bool = False):
408
- if not allow_write:
409
- raise PermissionError(
410
- "ActiveWriter is disabled; pass allow_write=True to send writes to the bus")
411
- self._send = send
412
- self._recv = recv
413
- self.qq = qq
414
-
415
- async def write_raw(self, zz: int, pbsb: str, master_data: bytes,
416
- timeout: float = 3.0, tries: int = 12) -> None:
417
- """Write a prepared master payload (id + encoded fields) to a device."""
418
- await _run_with_retry(
419
- self._send, self._recv,
420
- lambda: WriteDriver(zz, pbsb, master_data, self.qq), timeout, tries)
421
-
422
- async def write(self, msg: MessageDef, values: dict, timeout: float = 3.0) -> None:
423
- """Encode `values` for a write message and send it (needs a 2-hex zz)."""
424
- if not msg.is_write:
425
- raise ValueError(f"{msg.name}: not a write message")
426
- if not (msg.zz and len(msg.zz) == 2):
427
- raise ValueError(f"{msg.name}: no destination address to write to")
428
- await self.write_raw(int(msg.zz, 16), msg.pbsb, msg.encode(values), timeout=timeout)