lunalink 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.
lunalink/__init__.py ADDED
@@ -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)
lunalink/crc.py ADDED
@@ -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
lunalink/frame.py ADDED
@@ -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)
lunalink/guid.py ADDED
@@ -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))
lunalink/messages.py ADDED
@@ -0,0 +1,360 @@
1
+ """Message payloads (spec sections 5.5, 5.6 and 7). Every message is a MessagePack array."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass, field
5
+ from typing import Any, List, Optional
6
+
7
+ from . import mp
8
+ from .frame import MsgType
9
+ from .guid import EMPTY_GUID_BYTES, guid_from_wire, guid_to_wire
10
+
11
+
12
+ def _g(lst: list, i: int, default: Any = None) -> Any:
13
+ """Field ``i`` of a decoded array. Missing trailing elements take the default (section 4.1)."""
14
+ if i < len(lst) and lst[i] is not None:
15
+ return lst[i]
16
+ return default
17
+
18
+
19
+ def _arr(data: bytes) -> list:
20
+ obj = mp.unpack(data)
21
+ if not isinstance(obj, list):
22
+ raise ValueError("payload is not an array")
23
+ return obj
24
+
25
+
26
+ # ---------------------------------------------------------------- Hello / HelloAck
27
+
28
+ @dataclass
29
+ class Hello:
30
+ node_id: str = ""
31
+ node_name: str = ""
32
+ version: str = ""
33
+ capabilities: List[str] = field(default_factory=list)
34
+ timestamp_ms: int = 0
35
+ auth_token: Optional[str] = None
36
+
37
+ def to_payload(self) -> bytes:
38
+ return mp.pack([self.node_id, self.node_name, self.version, list(self.capabilities),
39
+ self.timestamp_ms, self.auth_token])
40
+
41
+
42
+ @dataclass
43
+ class HelloAck:
44
+ assigned_node_id: str = ""
45
+ server_time_ms: int = 0
46
+ heartbeat_interval_seconds: int = 5
47
+ accepted: bool = False
48
+ reject_reason: Optional[str] = None
49
+ capabilities: List[str] = field(default_factory=list)
50
+ supported_versions: List[int] = field(default_factory=list)
51
+
52
+ @classmethod
53
+ def from_payload(cls, data: bytes) -> "HelloAck":
54
+ a = _arr(data)
55
+ return cls(_g(a, 0, ""), _g(a, 1, 0), _g(a, 2, 5), bool(_g(a, 3, False)), _g(a, 4),
56
+ list(_g(a, 5, [])), list(_g(a, 6, [])))
57
+
58
+ def to_payload(self) -> bytes: # used by tests
59
+ return mp.pack([self.assigned_node_id, self.server_time_ms, self.heartbeat_interval_seconds,
60
+ self.accepted, self.reject_reason, self.capabilities, self.supported_versions])
61
+
62
+
63
+ # ---------------------------------------------------------------- TagDelta
64
+
65
+ @dataclass
66
+ class TagDeltaItem:
67
+ tag_id: bytes = EMPTY_GUID_BYTES
68
+ value_bytes: bytes = b""
69
+ quality: int = 0
70
+ timestamp_ms: int = 0
71
+ data_type: int = 0
72
+ tag_name: Optional[str] = None
73
+
74
+ def to_list(self) -> list:
75
+ return [guid_to_wire(self.tag_id), self.value_bytes, self.quality, self.timestamp_ms,
76
+ self.data_type, self.tag_name]
77
+
78
+ @classmethod
79
+ def from_list(cls, a: list) -> "TagDeltaItem":
80
+ return cls(bytes(_g(a, 0, EMPTY_GUID_BYTES)), bytes(_g(a, 1, b"")), _g(a, 2, 0), _g(a, 3, 0),
81
+ _g(a, 4, 0), _g(a, 5))
82
+
83
+ @property
84
+ def guid(self):
85
+ return guid_from_wire(self.tag_id)
86
+
87
+
88
+ @dataclass
89
+ class EventItem:
90
+ """A discrete event (section 5.6). ``event_id`` and ``source_tag_id`` accept UUID, str or wire bytes."""
91
+ event_id: Any = EMPTY_GUID_BYTES
92
+ source_tag_id: Any = None
93
+ severity: int = 0
94
+ message: str = ""
95
+ timestamp_ms: int = 0
96
+ category: Optional[str] = None
97
+ requires_ack: bool = False
98
+ active: bool = True
99
+
100
+ def to_list(self) -> list:
101
+ return [guid_to_wire(self.event_id),
102
+ None if self.source_tag_id is None else guid_to_wire(self.source_tag_id),
103
+ self.severity, self.message, self.timestamp_ms, self.category,
104
+ self.requires_ack, self.active]
105
+
106
+ @classmethod
107
+ def from_list(cls, a: list) -> "EventItem":
108
+ src = _g(a, 1)
109
+ return cls(bytes(_g(a, 0, EMPTY_GUID_BYTES)), None if src is None else bytes(src), _g(a, 2, 0),
110
+ _g(a, 3, ""), _g(a, 4, 0), _g(a, 5), bool(_g(a, 6, False)), bool(_g(a, 7, True)))
111
+
112
+
113
+ @dataclass
114
+ class TagDelta:
115
+ deltas: List[TagDeltaItem] = field(default_factory=list)
116
+ batch_timestamp_ms: int = 0
117
+ node_sequence: int = 0
118
+ is_resync_baseline: bool = False
119
+ events: Optional[List[EventItem]] = None
120
+
121
+ def to_payload(self) -> bytes:
122
+ arr: list = [[d.to_list() for d in self.deltas], self.batch_timestamp_ms, self.node_sequence,
123
+ self.is_resync_baseline]
124
+ if self.events is not None:
125
+ arr.append([e.to_list() for e in self.events])
126
+ return mp.pack(arr)
127
+
128
+ @classmethod
129
+ def from_payload(cls, data: bytes) -> "TagDelta":
130
+ a = _arr(data)
131
+ ev = _g(a, 4)
132
+ return cls([TagDeltaItem.from_list(x) for x in _g(a, 0, [])], _g(a, 1, 0), _g(a, 2, 0),
133
+ bool(_g(a, 3, False)), None if ev is None else [EventItem.from_list(x) for x in ev])
134
+
135
+
136
+ @dataclass
137
+ class TagDeltaAck:
138
+ node_sequence: int = 0
139
+ accepted: bool = False
140
+ expected_sequence: int = 0
141
+ duplicate: bool = False
142
+ error: Optional[str] = None
143
+
144
+ @classmethod
145
+ def from_payload(cls, data: bytes) -> "TagDeltaAck":
146
+ a = _arr(data)
147
+ return cls(_g(a, 0, 0), bool(_g(a, 1, False)), _g(a, 2, 0), bool(_g(a, 3, False)), _g(a, 4))
148
+
149
+ def to_payload(self) -> bytes: # used by tests
150
+ return mp.pack([self.node_sequence, self.accepted, self.expected_sequence, self.duplicate, self.error])
151
+
152
+
153
+ # ---------------------------------------------------------------- Writes
154
+
155
+ class WriteStatus:
156
+ UNKNOWN = 0
157
+ SUCCEEDED = 1
158
+ FAILED = 2
159
+ EXPIRED = 3
160
+ NAMES = {0: "Unknown", 1: "Succeeded", 2: "Failed", 3: "Expired"}
161
+
162
+
163
+ @dataclass
164
+ class TagWriteCmd:
165
+ seq_ref: int = 0
166
+ tag_id: bytes = EMPTY_GUID_BYTES
167
+ value_bytes: bytes = b""
168
+ data_type: int = 0
169
+ tag_name: Optional[str] = None
170
+ command_id: Optional[str] = None
171
+ expires_at_ms: int = 0
172
+ query_only: bool = False
173
+
174
+ @classmethod
175
+ def from_payload(cls, data: bytes) -> "TagWriteCmd":
176
+ a = _arr(data)
177
+ return cls(_g(a, 0, 0), bytes(_g(a, 1, EMPTY_GUID_BYTES)), bytes(_g(a, 2, b"")), _g(a, 3, 0),
178
+ _g(a, 4), _g(a, 5), _g(a, 6, 0), bool(_g(a, 7, False)))
179
+
180
+ def to_payload(self) -> bytes: # used by tests
181
+ return mp.pack([self.seq_ref, self.tag_id, self.value_bytes, self.data_type, self.tag_name,
182
+ self.command_id, self.expires_at_ms, self.query_only])
183
+
184
+
185
+ @dataclass
186
+ class TagWriteAck:
187
+ seq_ref: int = 0
188
+ success: bool = False
189
+ error_message: Optional[str] = None
190
+ command_id: Optional[str] = None
191
+ status: int = 0
192
+
193
+ def to_payload(self) -> bytes:
194
+ return mp.pack([self.seq_ref, self.success, self.error_message, self.command_id, self.status])
195
+
196
+
197
+ # ---------------------------------------------------------------- Heartbeat
198
+
199
+ @dataclass
200
+ class Heartbeat:
201
+ timestamp_ms: int = 0
202
+ connected_device_count: int = 0
203
+ cpu_percent: float = 0.0
204
+ available_memory_bytes: int = 0
205
+ pending_outbox_batches: int = 0
206
+ pending_outbox_tag_values: int = 0
207
+ pending_outbox_bytes: int = 0
208
+ oldest_outbox_age_seconds: float = 0.0
209
+ last_successful_sync_ms: Optional[int] = None
210
+ connected_at_ms: int = 0
211
+ reconnect_count: int = 0
212
+ history_sync_mode: str = "parallel"
213
+
214
+ def to_payload(self) -> bytes:
215
+ return mp.pack([
216
+ self.timestamp_ms, self.connected_device_count, mp.Float32(self.cpu_percent),
217
+ self.available_memory_bytes, self.pending_outbox_batches, self.pending_outbox_tag_values,
218
+ self.pending_outbox_bytes, float(self.oldest_outbox_age_seconds), self.last_successful_sync_ms,
219
+ self.connected_at_ms, self.reconnect_count, [], [], self.history_sync_mode,
220
+ False, 0, 0, 0, 0.0, None,
221
+ ])
222
+
223
+
224
+ # ---------------------------------------------------------------- Snapshot / Subscribe
225
+
226
+ @dataclass
227
+ class SnapshotReq:
228
+ tag_ids: Optional[list] = None
229
+
230
+ def to_payload(self) -> bytes:
231
+ return mp.pack([None if self.tag_ids is None else [guid_to_wire(t) for t in self.tag_ids]])
232
+
233
+
234
+ @dataclass
235
+ class SnapshotResp:
236
+ tags: List[TagDeltaItem] = field(default_factory=list)
237
+ server_time_ms: int = 0
238
+
239
+ @classmethod
240
+ def from_payload(cls, data: bytes) -> "SnapshotResp":
241
+ a = _arr(data)
242
+ return cls([TagDeltaItem.from_list(x) for x in _g(a, 0, [])], _g(a, 1, 0))
243
+
244
+
245
+ @dataclass
246
+ class Subscribe:
247
+ tag_ids: list = field(default_factory=list)
248
+
249
+ def to_payload(self) -> bytes:
250
+ return mp.pack([[guid_to_wire(t) for t in self.tag_ids]])
251
+
252
+
253
+ # ---------------------------------------------------------------- Error / Ping / Ack / Goodbye
254
+
255
+ ERROR_NAMES = {
256
+ 1: "bad-magic", 2: "frame-too-large", 3: "not-authenticated", 4: "unsupported-version",
257
+ 5: "decode-failed", 6: "rate-limited", 7: "heartbeat-timeout", 8: "shutting-down", 9: "unauthorized-tag",
258
+ }
259
+
260
+
261
+ @dataclass
262
+ class ErrorMsg:
263
+ code: int = 0
264
+ message: str = ""
265
+
266
+ @property
267
+ def name(self) -> str:
268
+ return ERROR_NAMES.get(self.code, f"unknown-{self.code}")
269
+
270
+ def to_payload(self) -> bytes:
271
+ return mp.pack([self.code, self.message[:200]])
272
+
273
+ @classmethod
274
+ def from_payload(cls, data: bytes) -> "ErrorMsg":
275
+ a = _arr(data)
276
+ return cls(_g(a, 0, 0), _g(a, 1, ""))
277
+
278
+
279
+ def ping_payload(ts_ms: int) -> bytes:
280
+ return mp.pack([ts_ms])
281
+
282
+
283
+ def ack_payload(acked_seq: int) -> bytes:
284
+ return mp.pack([acked_seq])
285
+
286
+
287
+ def goodbye_payload(reason: Optional[str]) -> bytes:
288
+ return mp.pack([None if reason is None else reason[:200]])
289
+
290
+
291
+ # ---------------------------------------------------------------- Browse
292
+
293
+ @dataclass
294
+ class BrowseReq:
295
+ request_id: str = ""
296
+ offset: int = 0
297
+ max_items: int = 0
298
+ path_prefix: Optional[str] = None
299
+
300
+ @classmethod
301
+ def from_payload(cls, data: bytes) -> "BrowseReq":
302
+ a = _arr(data)
303
+ return cls(_g(a, 0, ""), _g(a, 1, 0), _g(a, 2, 0), _g(a, 3))
304
+
305
+
306
+ @dataclass
307
+ class TagInventory:
308
+ """Tag metadata for ``BrowseResp`` (section 7.7)."""
309
+ id: str = ""
310
+ name: str = ""
311
+ description: str = ""
312
+ unit: str = ""
313
+ current_value: Optional[str] = None
314
+ quality: int = 0
315
+ data_type: str = ""
316
+ timestamp_ms: int = 0
317
+ path: Optional[str] = None
318
+ range_low: Optional[float] = None
319
+ range_high: Optional[float] = None
320
+ writable: bool = False
321
+ deadband: Optional[float] = None
322
+
323
+ def to_list(self) -> list:
324
+ return [self.id, self.name, self.description, self.unit, self.current_value, self.quality,
325
+ self.data_type, self.timestamp_ms, self.path,
326
+ None if self.range_low is None else float(self.range_low),
327
+ None if self.range_high is None else float(self.range_high),
328
+ self.writable, None if self.deadband is None else float(self.deadband)]
329
+
330
+
331
+ @dataclass
332
+ class BrowseResp:
333
+ request_id: str = ""
334
+ tags: List[TagInventory] = field(default_factory=list)
335
+ has_more: bool = False
336
+ next_offset: int = 0
337
+ error: Optional[str] = None
338
+
339
+ def to_payload(self) -> bytes:
340
+ return mp.pack([self.request_id, [t.to_list() for t in self.tags], self.has_more,
341
+ self.next_offset, self.error])
342
+
343
+
344
+ @dataclass
345
+ class EventAck:
346
+ event_id: bytes = EMPTY_GUID_BYTES
347
+ acked_by: Optional[str] = None
348
+ acked_at_ms: int = 0
349
+ comment: Optional[str] = None
350
+
351
+ @classmethod
352
+ def from_payload(cls, data: bytes) -> "EventAck":
353
+ a = _arr(data)
354
+ return cls(bytes(_g(a, 0, EMPTY_GUID_BYTES)), _g(a, 1), _g(a, 2, 0), _g(a, 3))
355
+
356
+ @property
357
+ def guid(self):
358
+ return guid_from_wire(self.event_id)
359
+
360
+