lunalink 0.1.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.
lunalink-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sarvin Aliyev (lunasoft.az)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,115 @@
1
+ Metadata-Version: 2.4
2
+ Name: lunalink
3
+ Version: 0.1.0
4
+ Summary: LunaLink node (edge side) for Python: reliable, ordered tag telemetry to a LunaLink master
5
+ License: MIT
6
+ Keywords: lunalink,scada,telemetry,industrial,iot
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Topic :: System :: Networking
10
+ Requires-Python: >=3.9
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: msgpack>=1.0
14
+ Requires-Dist: lz4>=4.0
15
+ Provides-Extra: test
16
+ Requires-Dist: pytest>=7; extra == "test"
17
+ Dynamic: license-file
18
+
19
+ # lunalink (Python node)
20
+
21
+ A LunaLink **node** for Python 3.9+: it connects to a LunaLink master, publishes tag values with durable,
22
+ ordered, duplicate-free delivery, answers remote writes idempotently and speaks revision 2.0 of the
23
+ [LunaLink protocol](https://github.com/lunasoft-llc/LunaLink/blob/main/docs/PROTOCOL.md). It is meant for
24
+ Raspberry Pi gateways, quick integrations and protocol test tooling.
25
+
26
+ ```
27
+ pip install lunalink
28
+ ```
29
+
30
+ Dependencies: `msgpack`, `lz4`. Everything else is the standard library (`asyncio`, `ssl`, `sqlite3`).
31
+
32
+ ## Quick start
33
+
34
+ ```python
35
+ import asyncio, uuid
36
+ from lunalink import LunaLinkNode, DataType
37
+
38
+ TEMP = uuid.UUID("00112233-4455-6677-8899-aabbccddeeff")
39
+
40
+ async def main():
41
+ node = LunaLinkNode("master.example", 7788, node_id="pi-1", db_path="lunalink.db",
42
+ auth_token="secret")
43
+ await node.start() # connects in the background, reconnects forever
44
+ node.publish(TEMP, 21.5, DataType.FLOAT32, tag_name="Temperature") # durable when it returns
45
+ await node.wait_delivered(30) # until the master acknowledged everything
46
+ await node.close() # Goodbye (if negotiated), then close
47
+
48
+ asyncio.run(main())
49
+ ```
50
+
51
+ A complete example is in `examples/node_example.py`.
52
+
53
+ ## API
54
+
55
+ | Item | Purpose |
56
+ |---|---|
57
+ | `LunaLinkNode(host, port, node_id=, db_path=, ...)` | The node. `endpoints=[(host, port), ...]` enables master failover order. |
58
+ | `await node.start()` / `await node.close()` | Start the connection task / send `Goodbye` and stop. |
59
+ | `node.publish(tag_id, value, data_type=None, ...)` | Persist one value as a batch. Returns its NodeSequence. Thread safe. |
60
+ | `node.publish_batch([TagValue, ...])` | Several values, one NodeSequence. |
61
+ | `node.publish_event(message, severity=, ...)` | Event delivered through the outbox (needs `events-v1`). |
62
+ | `await node.wait_delivered(timeout)` | Wait until the outbox is empty. |
63
+ | `on_write=` | Callback `(WriteRequest) -> bool`. Called at most once per `CommandId`. Raise `WriteOutcomeUnknown` when the result cannot be determined. |
64
+ | `on_remote_values=`, `on_event_ack=`, `on_error=` | Master to node values (`TagDelta`, `SnapshotResp`), `EventAck`, `Error`. |
65
+ | `browse_tags=` | Callable returning `TagInventory` items; answers `BrowseReq`. |
66
+ | `Features(...)` | What to offer in `Hello` (compression, `max-payload`, `window`, `goodbye`, `events-v1`, ...). |
67
+ | `TlsConfig(ca_file=, cert_file=, key_file=)` | TLS 1.3, optional client certificate (mutual TLS). `verify=False` is for testing only. |
68
+
69
+ Value types: pass a `DataType` (0 to 13) or let it be inferred (`bool`, `int`, `float`, `str`, `bytes`,
70
+ lists). GUIDs are `uuid.UUID`, their text form, or the 16 wire bytes; they are converted to .NET byte order.
71
+
72
+ ### Delivery
73
+
74
+ State lives in one SQLite file (`synchronous=FULL`): the outbox, the persistent NodeSequence, the last value
75
+ of every tag, queued events and the result of every write command. A batch is deleted only after
76
+ `TagDeltaAck` with `Accepted = true`. With `window=<n>` granted by the master, up to `n` batches are in
77
+ flight with go-back-N on rejection. If the master expects a sequence the outbox no longer holds (or the
78
+ backlog reaches 1024 batches) the node sends a resync baseline that also carries the events of the batches
79
+ it replaces. Without a granted window it uses stop-and-wait.
80
+
81
+ ## Tests
82
+
83
+ ```
84
+ pip install -e ".[test]"
85
+ pytest # unit tests, scripted-master tests, interop (if dotnet is present)
86
+ dotnet build interop/Harness -c Release -o interop/Harness/bin # once, for the interop tests
87
+ ```
88
+
89
+ * `tests/test_vectors.py`: Appendix A vectors byte for byte (CRC, GUID, Float32, Ping frame, Hello,
90
+ TagDelta, Ack, TagWriteAck, compression containers) plus codec edge cases.
91
+ * `tests/test_node.py`: the node against an in-process scripted master (`tests/fake_master.py`).
92
+ * `tests/test_interop.py`: the node against a real .NET master. `interop/Harness` is a small console
93
+ program that references the NuGet package `LunaLink` **1.2.0**, runs `LunaLinkServer` and prints every
94
+ received data point. The tests check that values arrive in order without loss across forced
95
+ reconnects and a master restart.
96
+
97
+ ### What is only unit-tested until the 2.0 master is released
98
+
99
+ The released master (1.2.0) negotiates only `no-compression` and `max-payload`. It ignores every other
100
+ token, so these 2.0 features are covered by tests against the scripted master only, not against the
101
+ .NET reference:
102
+
103
+ `lz4-block` compression in both directions, `window=<n>` and go-back-N, `goodbye`, `events-v1`
104
+ (`EventItem`, `EventAck`), `browse-v1`, `arrays-v1` (types 10 to 13), `master-delta`, `no-crc`, the
105
+ `Error` code names beyond what 1.2.0 sends, the `SupportedVersions` field, `leased-by-other-master`
106
+ failover. K4os `LZ4Pickler` decompression is unit-tested with containers built to the spec (Appendix A.8
107
+ layout), not yet against compressed frames from a real master. The 1.x behaviours (stop-and-wait,
108
+ `TagDeltaAck`, heartbeat, scalar types 0 to 9, reconnect, master restart) are tested against the real
109
+ 1.2.0 master. Writes (`TagWriteCmd`) are tested against the scripted master only, because the 1.2.0 server
110
+ has no public API to send them from the harness.
111
+ TLS 1.3 with a client certificate is implemented with the standard `ssl` module but has no automated test yet.
112
+
113
+ ## License
114
+
115
+ MIT, see `LICENSE`.
@@ -0,0 +1,97 @@
1
+ # lunalink (Python node)
2
+
3
+ A LunaLink **node** for Python 3.9+: it connects to a LunaLink master, publishes tag values with durable,
4
+ ordered, duplicate-free delivery, answers remote writes idempotently and speaks revision 2.0 of the
5
+ [LunaLink protocol](https://github.com/lunasoft-llc/LunaLink/blob/main/docs/PROTOCOL.md). It is meant for
6
+ Raspberry Pi gateways, quick integrations and protocol test tooling.
7
+
8
+ ```
9
+ pip install lunalink
10
+ ```
11
+
12
+ Dependencies: `msgpack`, `lz4`. Everything else is the standard library (`asyncio`, `ssl`, `sqlite3`).
13
+
14
+ ## Quick start
15
+
16
+ ```python
17
+ import asyncio, uuid
18
+ from lunalink import LunaLinkNode, DataType
19
+
20
+ TEMP = uuid.UUID("00112233-4455-6677-8899-aabbccddeeff")
21
+
22
+ async def main():
23
+ node = LunaLinkNode("master.example", 7788, node_id="pi-1", db_path="lunalink.db",
24
+ auth_token="secret")
25
+ await node.start() # connects in the background, reconnects forever
26
+ node.publish(TEMP, 21.5, DataType.FLOAT32, tag_name="Temperature") # durable when it returns
27
+ await node.wait_delivered(30) # until the master acknowledged everything
28
+ await node.close() # Goodbye (if negotiated), then close
29
+
30
+ asyncio.run(main())
31
+ ```
32
+
33
+ A complete example is in `examples/node_example.py`.
34
+
35
+ ## API
36
+
37
+ | Item | Purpose |
38
+ |---|---|
39
+ | `LunaLinkNode(host, port, node_id=, db_path=, ...)` | The node. `endpoints=[(host, port), ...]` enables master failover order. |
40
+ | `await node.start()` / `await node.close()` | Start the connection task / send `Goodbye` and stop. |
41
+ | `node.publish(tag_id, value, data_type=None, ...)` | Persist one value as a batch. Returns its NodeSequence. Thread safe. |
42
+ | `node.publish_batch([TagValue, ...])` | Several values, one NodeSequence. |
43
+ | `node.publish_event(message, severity=, ...)` | Event delivered through the outbox (needs `events-v1`). |
44
+ | `await node.wait_delivered(timeout)` | Wait until the outbox is empty. |
45
+ | `on_write=` | Callback `(WriteRequest) -> bool`. Called at most once per `CommandId`. Raise `WriteOutcomeUnknown` when the result cannot be determined. |
46
+ | `on_remote_values=`, `on_event_ack=`, `on_error=` | Master to node values (`TagDelta`, `SnapshotResp`), `EventAck`, `Error`. |
47
+ | `browse_tags=` | Callable returning `TagInventory` items; answers `BrowseReq`. |
48
+ | `Features(...)` | What to offer in `Hello` (compression, `max-payload`, `window`, `goodbye`, `events-v1`, ...). |
49
+ | `TlsConfig(ca_file=, cert_file=, key_file=)` | TLS 1.3, optional client certificate (mutual TLS). `verify=False` is for testing only. |
50
+
51
+ Value types: pass a `DataType` (0 to 13) or let it be inferred (`bool`, `int`, `float`, `str`, `bytes`,
52
+ lists). GUIDs are `uuid.UUID`, their text form, or the 16 wire bytes; they are converted to .NET byte order.
53
+
54
+ ### Delivery
55
+
56
+ State lives in one SQLite file (`synchronous=FULL`): the outbox, the persistent NodeSequence, the last value
57
+ of every tag, queued events and the result of every write command. A batch is deleted only after
58
+ `TagDeltaAck` with `Accepted = true`. With `window=<n>` granted by the master, up to `n` batches are in
59
+ flight with go-back-N on rejection. If the master expects a sequence the outbox no longer holds (or the
60
+ backlog reaches 1024 batches) the node sends a resync baseline that also carries the events of the batches
61
+ it replaces. Without a granted window it uses stop-and-wait.
62
+
63
+ ## Tests
64
+
65
+ ```
66
+ pip install -e ".[test]"
67
+ pytest # unit tests, scripted-master tests, interop (if dotnet is present)
68
+ dotnet build interop/Harness -c Release -o interop/Harness/bin # once, for the interop tests
69
+ ```
70
+
71
+ * `tests/test_vectors.py`: Appendix A vectors byte for byte (CRC, GUID, Float32, Ping frame, Hello,
72
+ TagDelta, Ack, TagWriteAck, compression containers) plus codec edge cases.
73
+ * `tests/test_node.py`: the node against an in-process scripted master (`tests/fake_master.py`).
74
+ * `tests/test_interop.py`: the node against a real .NET master. `interop/Harness` is a small console
75
+ program that references the NuGet package `LunaLink` **1.2.0**, runs `LunaLinkServer` and prints every
76
+ received data point. The tests check that values arrive in order without loss across forced
77
+ reconnects and a master restart.
78
+
79
+ ### What is only unit-tested until the 2.0 master is released
80
+
81
+ The released master (1.2.0) negotiates only `no-compression` and `max-payload`. It ignores every other
82
+ token, so these 2.0 features are covered by tests against the scripted master only, not against the
83
+ .NET reference:
84
+
85
+ `lz4-block` compression in both directions, `window=<n>` and go-back-N, `goodbye`, `events-v1`
86
+ (`EventItem`, `EventAck`), `browse-v1`, `arrays-v1` (types 10 to 13), `master-delta`, `no-crc`, the
87
+ `Error` code names beyond what 1.2.0 sends, the `SupportedVersions` field, `leased-by-other-master`
88
+ failover. K4os `LZ4Pickler` decompression is unit-tested with containers built to the spec (Appendix A.8
89
+ layout), not yet against compressed frames from a real master. The 1.x behaviours (stop-and-wait,
90
+ `TagDeltaAck`, heartbeat, scalar types 0 to 9, reconnect, master restart) are tested against the real
91
+ 1.2.0 master. Writes (`TagWriteCmd`) are tested against the scripted master only, because the 1.2.0 server
92
+ has no public API to send them from the harness.
93
+ TLS 1.3 with a client certificate is implemented with the standard `ssl` module but has no automated test yet.
94
+
95
+ ## License
96
+
97
+ MIT, see `LICENSE`.
@@ -0,0 +1,28 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "lunalink"
7
+ version = "0.1.0"
8
+ description = "LunaLink node (edge side) for Python: reliable, ordered tag telemetry to a LunaLink master"
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.9"
12
+ dependencies = ["msgpack>=1.0", "lz4>=4.0"]
13
+ keywords = ["lunalink", "scada", "telemetry", "industrial", "iot"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Topic :: System :: Networking",
18
+ ]
19
+
20
+ [project.optional-dependencies]
21
+ test = ["pytest>=7"]
22
+
23
+ [tool.setuptools.packages.find]
24
+ where = ["src"]
25
+
26
+ [tool.pytest.ini_options]
27
+ testpaths = ["tests"]
28
+ markers = ["interop: needs dotnet and the built interop harness"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,14 @@
1
+ """LunaLink node for Python. See README.md and docs/PROTOCOL.md of the LunaLink repository."""
2
+ from .compression import DecompressError
3
+ from .frame import Frame, FrameDecoder, FrameError, MsgType, encode_frame
4
+ from .messages import ErrorMsg, EventAck, EventItem, TagInventory, WriteStatus
5
+ from .node import (Features, LunaLinkNode, TagValue, TlsConfig, WriteOutcomeUnknown, WriteRequest)
6
+ from .values import DataType, Quality, decode_value, encode_value
7
+
8
+ __version__ = "0.1.0"
9
+ __all__ = [
10
+ "LunaLinkNode", "Features", "TlsConfig", "TagValue", "WriteRequest", "WriteOutcomeUnknown",
11
+ "DataType", "Quality", "EventItem", "EventAck", "ErrorMsg", "TagInventory", "WriteStatus",
12
+ "Frame", "FrameDecoder", "FrameError", "MsgType", "encode_frame", "DecompressError",
13
+ "encode_value", "decode_value", "__version__",
14
+ ]
@@ -0,0 +1,109 @@
1
+ """Payload compression (spec section 4.2).
2
+
3
+ * ``lz4-block`` portable container (4.2.1): ULEB128 uncompressed length + raw LZ4 block.
4
+ * K4os ``LZ4Pickler`` container (4.2) used by 1.x masters. Decoding is always available; encoding
5
+ is provided for tests and tooling only (a node never needs to send it).
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import lz4.block
10
+
11
+ MAX_PAYLOAD = 4 * 1024 * 1024
12
+ THRESHOLD = 256
13
+
14
+
15
+ class DecompressError(ValueError):
16
+ pass
17
+
18
+
19
+ def uleb128_encode(n: int) -> bytes:
20
+ out = bytearray()
21
+ while True:
22
+ b = n & 0x7F
23
+ n >>= 7
24
+ if n:
25
+ out.append(b | 0x80)
26
+ else:
27
+ out.append(b)
28
+ return bytes(out)
29
+
30
+
31
+ def uleb128_decode(data: bytes) -> "tuple[int, int]":
32
+ n = shift = 0
33
+ for i, b in enumerate(data):
34
+ n |= (b & 0x7F) << shift
35
+ if not b & 0x80:
36
+ return n, i + 1
37
+ shift += 7
38
+ if shift > 35:
39
+ break
40
+ raise DecompressError("bad ULEB128 length")
41
+
42
+
43
+ def block_compress(payload: bytes) -> bytes:
44
+ """Portable container. Returns the container (caller decides whether it is smaller)."""
45
+ raw = lz4.block.compress(payload, store_size=False)
46
+ return uleb128_encode(len(payload)) + raw
47
+
48
+
49
+ def block_decompress(data: bytes, max_len: int = MAX_PAYLOAD) -> bytes:
50
+ n, used = uleb128_decode(data)
51
+ if not 1 <= n <= max_len:
52
+ raise DecompressError("uncompressed length out of range")
53
+ try:
54
+ out = lz4.block.decompress(data[used:], uncompressed_size=n)
55
+ except Exception as e:
56
+ raise DecompressError(f"lz4 block: {e}") from e
57
+ if len(out) != n:
58
+ raise DecompressError("block did not decompress to the announced length")
59
+ return out
60
+
61
+
62
+ _WIDTH = {0: 0, 1: 1, 2: 2, 3: 4}
63
+
64
+
65
+ def k4os_decompress(data: bytes, max_len: int = MAX_PAYLOAD) -> bytes:
66
+ if not data:
67
+ raise DecompressError("empty container")
68
+ hdr = data[0]
69
+ if hdr & 0x07 != 0:
70
+ raise DecompressError("unsupported container version")
71
+ w = _WIDTH[hdr >> 6]
72
+ if len(data) < 1 + w:
73
+ raise DecompressError("truncated container")
74
+ diff = int.from_bytes(data[1 : 1 + w], "little")
75
+ body = data[1 + w :]
76
+ if diff == 0:
77
+ return bytes(body)
78
+ n = len(body) + diff
79
+ if n > max_len:
80
+ raise DecompressError("uncompressed length out of range")
81
+ try:
82
+ out = lz4.block.decompress(body, uncompressed_size=n)
83
+ except Exception as e:
84
+ raise DecompressError(f"lz4 block: {e}") from e
85
+ if len(out) != n:
86
+ raise DecompressError("length mismatch")
87
+ return out
88
+
89
+
90
+ def k4os_compress(payload: bytes) -> bytes:
91
+ raw = lz4.block.compress(payload, store_size=False)
92
+ diff = len(payload) - len(raw)
93
+ if diff <= 0:
94
+ return b"\x00" + payload
95
+ if diff <= 0xFF:
96
+ code, width = 1, 1
97
+ elif diff <= 0xFFFF:
98
+ code, width = 2, 2
99
+ else:
100
+ code, width = 3, 4
101
+ return bytes((code << 6,)) + diff.to_bytes(width, "little") + raw
102
+
103
+
104
+ def maybe_compress_block(payload: bytes) -> "tuple[bytes, bool]":
105
+ """Apply the sender rules: >= 256 bytes and strictly smaller."""
106
+ if len(payload) < THRESHOLD:
107
+ return payload, False
108
+ c = block_compress(payload)
109
+ return (c, True) if len(c) < len(payload) else (payload, False)
@@ -0,0 +1,15 @@
1
+ """CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF, no reflection, no final XOR), spec section 3.3."""
2
+ from __future__ import annotations
3
+
4
+ _TABLE = []
5
+ for _i in range(256):
6
+ _c = _i << 8
7
+ for _ in range(8):
8
+ _c = ((_c << 1) ^ 0x1021) & 0xFFFF if _c & 0x8000 else (_c << 1) & 0xFFFF
9
+ _TABLE.append(_c)
10
+
11
+
12
+ def crc16(data: bytes, crc: int = 0xFFFF) -> int:
13
+ for b in data:
14
+ crc = ((crc << 8) & 0xFFFF) ^ _TABLE[((crc >> 8) ^ b) & 0xFF]
15
+ return crc
@@ -0,0 +1,123 @@
1
+ """Frame codec (spec section 3)."""
2
+ from __future__ import annotations
3
+
4
+ import struct
5
+ from dataclasses import dataclass
6
+
7
+ from .crc import crc16
8
+
9
+ MAGIC = 0x4C4C4E4B
10
+ VERSION = 1
11
+ HEADER_LEN = 15
12
+ MAX_PAYLOAD_LEN = 4 * 1024 * 1024
13
+
14
+ FLAG_COMPRESSED = 0x01
15
+ FLAG_REQUIRES_ACK = 0x02
16
+
17
+ _HDR = struct.Struct(">IBBBII")
18
+
19
+
20
+ class MsgType:
21
+ HELLO = 0x01
22
+ HELLO_ACK = 0x02
23
+ TAG_DELTA = 0x03
24
+ TAG_WRITE_CMD = 0x04
25
+ TAG_WRITE_ACK = 0x05
26
+ HEARTBEAT = 0x06
27
+ HEARTBEAT_ACK = 0x07
28
+ SNAPSHOT_REQ = 0x08
29
+ SNAPSHOT_RESP = 0x09
30
+ SUBSCRIBE = 0x0A
31
+ ERROR = 0x0B
32
+ PING = 0x0C
33
+ PONG = 0x0D
34
+ ACK = 0x0E
35
+ TAG_DELTA_ACK = 0x0F
36
+ HISTORY_BATCH = 0x10
37
+ HISTORY_BATCH_ACK = 0x11
38
+ GOODBYE = 0x12
39
+ BROWSE_REQ = 0x13
40
+ BROWSE_RESP = 0x14
41
+ EVENT_ACK = 0x15
42
+
43
+
44
+ class FrameError(Exception):
45
+ """Unrecoverable framing problem. ``code`` is the LunaLink Error code to send (1 bad-magic, 2 too large)."""
46
+
47
+ def __init__(self, code: int, message: str):
48
+ super().__init__(message)
49
+ self.code = code
50
+
51
+
52
+ @dataclass
53
+ class Frame:
54
+ msg_type: int
55
+ payload: bytes
56
+ flags: int = 0
57
+ sequence: int = 0
58
+ version: int = VERSION
59
+ crc_ok: bool = True
60
+
61
+ @property
62
+ def compressed(self) -> bool:
63
+ return bool(self.flags & FLAG_COMPRESSED)
64
+
65
+ @property
66
+ def requires_ack(self) -> bool:
67
+ return bool(self.flags & FLAG_REQUIRES_ACK)
68
+
69
+
70
+ def encode_frame(msg_type: int, payload: bytes, sequence: int, flags: int = 0, with_crc: bool = True) -> bytes:
71
+ if len(payload) > MAX_PAYLOAD_LEN:
72
+ raise ValueError("payload too large")
73
+ head = _HDR.pack(MAGIC, VERSION, msg_type, flags & 0xFF, sequence & 0xFFFFFFFF, len(payload))
74
+ body = head + payload
75
+ return body + struct.pack(">H", crc16(body) if with_crc else 0)
76
+
77
+
78
+ def parse_header(head: bytes, max_payload: int = MAX_PAYLOAD_LEN):
79
+ """Validate a 15 byte header. Returns (version, type, flags, seq, payload_len)."""
80
+ magic, ver, mtype, flags, seq, plen = _HDR.unpack(head)
81
+ if magic != MAGIC:
82
+ raise FrameError(1, "bad magic")
83
+ if plen > max_payload:
84
+ raise FrameError(2, f"payload length {plen} exceeds limit {max_payload}")
85
+ return ver, mtype, flags, seq, plen
86
+
87
+
88
+ def finish_frame(head: bytes, payload: bytes, crc_bytes: bytes, check_crc: bool = True) -> Frame:
89
+ _, ver, mtype, flags, seq, _ = _HDR.unpack(head)
90
+ ok = True
91
+ if check_crc:
92
+ ok = struct.unpack(">H", crc_bytes)[0] == crc16(head + payload)
93
+ return Frame(mtype, payload, flags, seq, ver, ok)
94
+
95
+
96
+ class FrameDecoder:
97
+ """Incremental decoder for byte streams (tests and tooling)."""
98
+
99
+ def __init__(self, max_payload: int = MAX_PAYLOAD_LEN, check_crc: bool = True):
100
+ self._buf = bytearray()
101
+ self.max_payload = max_payload
102
+ self.check_crc = check_crc
103
+
104
+ def feed(self, data: bytes) -> "list[Frame]":
105
+ self._buf += data
106
+ frames = []
107
+ while len(self._buf) >= HEADER_LEN:
108
+ _, _, _, _, plen = parse_header(bytes(self._buf[:HEADER_LEN]), self.max_payload)
109
+ total = HEADER_LEN + plen + 2
110
+ if len(self._buf) < total:
111
+ break
112
+ raw = bytes(self._buf[:total])
113
+ del self._buf[:total]
114
+ frames.append(finish_frame(raw[:HEADER_LEN], raw[HEADER_LEN:-2], raw[-2:], self.check_crc))
115
+ return frames
116
+
117
+
118
+ async def read_frame(reader, max_payload: int = MAX_PAYLOAD_LEN, check_crc: bool = True) -> Frame:
119
+ """Read one frame from an ``asyncio.StreamReader``. May return a frame with ``crc_ok == False``."""
120
+ head = await reader.readexactly(HEADER_LEN)
121
+ _, _, _, _, plen = parse_header(head, max_payload)
122
+ rest = await reader.readexactly(plen + 2)
123
+ return finish_frame(head, rest[:-2], rest[-2:], check_crc)
@@ -0,0 +1,27 @@
1
+ """Tag GUIDs on the wire use .NET ``Guid.ToByteArray()`` order (spec section 5.2).
2
+
3
+ Python's ``uuid.UUID.bytes_le`` is exactly that order.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import uuid
8
+ from typing import Union
9
+
10
+ GuidLike = Union[uuid.UUID, str, bytes]
11
+ EMPTY_GUID_BYTES = bytes(16)
12
+
13
+
14
+ def guid_to_wire(g: GuidLike) -> bytes:
15
+ if isinstance(g, uuid.UUID):
16
+ return g.bytes_le
17
+ if isinstance(g, str):
18
+ return uuid.UUID(g).bytes_le
19
+ if isinstance(g, (bytes, bytearray)):
20
+ if len(g) != 16:
21
+ raise ValueError("GUID bytes must be 16 bytes (wire order)")
22
+ return bytes(g)
23
+ raise TypeError(type(g).__name__)
24
+
25
+
26
+ def guid_from_wire(b: bytes) -> uuid.UUID:
27
+ return uuid.UUID(bytes_le=bytes(b))