1"""CMSDK DataMessage in pure Python: byte-exact with the C++ library (and the Kotlin codec).
3Both wire forms are supported: the regular block (C++ ``DataMessage::data``, 200-byte header +
4entries) and the packed form (C++ ``DataMessage::toPacked()``), which Psyclone services accept and
5answer in. The layout must stay in step with CMSDK ``include/DataMessage.h``; the tests check it
6against the golden messages the C++ library writes (``CMSDK/kotlin/fixtures``).
8 from psyclone_client import DataMessage
9 m = DataMessage().set_string("PsyPost", "AudioFrame").set_data("pcm", pcm)
10 m["Gain"] = 0.7 # str -> text, int -> int64, float -> double, bytes -> data
11 wire = m.to_bytes() # or m.to_packed_bytes()
12 back = DataMessage.from_bytes(wire) # either form
17__all__ = [
"DataMessage",
"PsyType",
"PsyContext",
"PsyTime",
"Time",
"Raw",
"Layout"]
24 """Byte layout of the C++ ``DataMessageHeader`` (format version VERSION), padding included."""
31 DATAMESSAGEID = (41 << 16) | 41
32 PACKEDDATAMESSAGEID = (43 << 16) | 43
34 UNUSEDID = (1 << 16) | 1
35 CONSTCHARID = (2 << 16) | 2
36 TIMEID = (3 << 16) | 3
37 CHARDATAID = (4 << 16) | 4
39 DOUBLEID = (6 << 16) | 6
43 "size": (0, 4,
"I"),
"cid": (4, 4,
"I"),
"cver": (8, 2,
"H"),
"cenc": (10, 2,
"H"),
44 "memid": (16, 8,
"Q"),
"time": (24, 8,
"Q"),
"sendtime": (32, 8,
"Q"),
"recvtime": (40, 8,
"Q"),
45 "origin": (48, 2,
"H"),
"destination": (50, 2,
"H"),
"ttl": (56, 8,
"Q"),
46 "priority": (64, 2,
"H"),
"policy": (66, 1,
"B"),
"from": (68, 4,
"I"),
"to": (72, 4,
"I"),
47 "type": (76, 32,
None),
"tag": (108, 4,
"I"),
"status": (112, 2,
"H"),
48 "reference": (120, 8,
"Q"),
"serial": (128, 8,
"Q"),
"contextchange": (136, 32,
None),
49 "userSize": (168, 4,
"I"),
"userCount": (172, 4,
"I"),
"cyclecputime": (176, 4,
"I"),
50 "cyclewalltime": (180, 4,
"I"),
"chaincputime": (184, 4,
"I"),
"chainwalltime": (188, 4,
"I"),
51 "chaincount": (192, 4,
"I"),
"systemid": (196, 4,
"I"),
56_ATTRS = [(
"cenc",
"cenc"), (
"memid",
"memid"), (
"time",
"time"), (
"sendtime",
"send_time"),
57 (
"recvtime",
"recv_time"), (
"origin",
"origin"), (
"destination",
"destination"), (
"ttl",
"ttl"),
58 (
"priority",
"priority"), (
"policy",
"policy"), (
"from",
"from_id"), (
"to",
"to_id"),
59 (
"tag",
"tag"), (
"status",
"status"), (
"reference",
"reference"), (
"serial",
"serial"),
60 (
"cyclecputime",
"cycle_cpu_time"), (
"cyclewalltime",
"cycle_wall_time"),
61 (
"chaincputime",
"chain_cpu_time"), (
"chainwalltime",
"chain_wall_time"),
62 (
"chaincount",
"chain_count"), (
"systemid",
"system_id")]
66 """PsyTime = microseconds since year 0 (CMSDK ``GetTimeNow()``), not the Unix epoch."""
67 USEC_YEAR_0_TO_1970 = 62167305600000000
71 return PsyTime.from_unix_micros(_time.time_ns() // 1000)
75 return us + PsyTime.USEC_YEAR_0_TO_1970
79 return psytime - PsyTime.USEC_YEAR_0_TO_1970
86 lv = [int(x)
for x
in levels][: self.
LEVELS]
88 if not 0 <= x <= 0xFFFF:
89 raise ValueError(
"level %d out of range" % x)
94 return cls([int(p)
for p
in str(s).split(
".")
if p])
109 return "%s(%r)" % (type(self).__name__, str(self))
112 return type(other)
is type(self)
and other.levels == self.
levels
119 """Hierarchical message type, numeric form "16.34.35". Clients never set one: they name a post."""
123 """Hierarchical context, numeric form "3.7"."""
127 """An int that is stored as a PsyTime entry (``DataMessage.set_time``)."""
131 """Any other C++ content type, kept verbatim: cid is the content id, data the payload."""
132 __slots__ = (
"cid",
"data")
139 return isinstance(other, Raw)
and other.cid == self.
cid and other.data == self.
data
142 return "Raw(cid=0x%08x, %d bytes)" % (self.
cid, len(self.
data))
146 """A CMSDK DataMessage: header fields as attributes, user entries by key (insertion order kept)."""
178 if not isinstance(key, str)
or not key
or "\0" in key:
179 raise ValueError(
"entry keys are non-empty strings without NUL")
184 return self.
_put(key, str(value))
188 if not -(1 << 63) <= v < (1 << 63):
189 raise ValueError(
"int entries are 64-bit signed")
190 return self.
_put(key, v)
193 return self.
_put(key, float(value))
196 return self.
_put(key,
Time(int(value) & M64))
199 return self.
_put(key, bytes(value))
202 if not isinstance(value, DataMessage):
203 raise TypeError(
"attached messages are DataMessages")
204 return self.
_put(key, value)
207 return self.
_put(key,
Raw(cid, data))
209 def set(self, key, value):
210 """Set by Python type: str, bool/int, float, bytes, DataMessage, Time, Raw."""
211 if isinstance(value, (Time, Raw, DataMessage)):
212 return self.
_put(key, value)
213 if isinstance(value, str):
215 if isinstance(value, (bytes, bytearray, memoryview)):
217 if isinstance(value, bool)
or isinstance(value, int):
218 return self.
set_int(key, int(value))
219 if isinstance(value, float):
221 raise TypeError(
"cannot store %s in a DataMessage" % type(value).__name__)
226 return v
if (type(v)
is int)
else default
227 return v
if isinstance(v, t)
else default
230 return self.
_typed(key, str, default)
233 return self.
_typed(key, int, default)
236 return self.
_typed(key, float, default)
240 return int(v)
if isinstance(v, Time)
else default
243 return self.
_typed(key, bytes, default)
246 return self.
_typed(key, DataMessage, default)
248 def get(self, key, default=None):
255 return self.
_entries.pop(key,
None)
is not None
282 return "DataMessage(type=%s, serial=%d, entries=%s)" % (self.
type, self.
serial, list(self.
_entries))
285 setString = set_string
287 setDouble = set_double
290 setDataBytes = set_data
291 setAttachedMessage = set_attached_message
292 getString = get_string
294 getDouble = get_double
297 getDataBytes = get_data
298 getAttachedMessage = get_attached_message
308 return DataMessage.from_bytes(data)
313 if isinstance(v, Time):
314 return Layout.TIMEID, struct.pack(
"<Q", int(v) & M64)
315 if isinstance(v, str):
316 return Layout.CONSTCHARID, v.encode(
"utf-8") + b
"\0"
317 if isinstance(v, int):
318 return Layout.INTID, struct.pack(
"<q", v)
319 if isinstance(v, float):
320 return Layout.DOUBLEID, struct.pack(
"<d", v)
321 if isinstance(v, bytes):
322 return Layout.CHARDATAID, v
323 if isinstance(v, DataMessage):
324 return Layout.DATAMESSAGEID, v.to_bytes()
325 if isinstance(v, Raw):
327 raise TypeError(type(v).__name__)
330 """Encode to the C++ wire format; built in the same order as in C++ it is byte-identical."""
333 user_size = sum(2 * L.ENTRY_HEADER_SIZE + len(k) + 1 + len(p)
for k, _, p
in payloads)
334 total = L.HEADER_SIZE + user_size
338 def put(name, value):
339 off, _, fmt = F[name]
340 mask = {
"B": 0xFF,
"H": 0xFFFF,
"I": M32,
"Q": M64}[fmt]
341 struct.pack_into(
"<" + fmt, b, off, int(value) & mask)
344 put(
"cid", L.DATAMESSAGEID)
345 put(
"cver", L.VERSION)
346 for field, attr
in _ATTRS:
347 put(field, getattr(self, attr))
348 struct.pack_into(
"<16H", b, F[
"type"][0], *self.
type.levels)
349 struct.pack_into(
"<16H", b, F[
"contextchange"][0], *self.
context_change.levels)
350 put(
"userSize", user_size)
351 put(
"userCount", len(payloads))
353 for k, cid, v
in payloads:
355 struct.pack_into(
"<II", b, p, 2 * L.ENTRY_HEADER_SIZE + len(k) + 1 + len(v), L.CONSTCHARID)
356 p += L.ENTRY_HEADER_SIZE
359 struct.pack_into(
"<II", b, p, L.ENTRY_HEADER_SIZE + len(v), cid & M32)
360 p += L.ENTRY_HEADER_SIZE
367 """Decode a C++ DataMessage, either wire form. Raises ValueError on anything else."""
368 mv = memoryview(data)
370 length = len(mv) - offset
371 buf = bytes(mv[offset:offset + length])
373 if len(buf) >= 8
and struct.unpack_from(
"<I", buf, 4)[0] == L.PACKEDDATAMESSAGEID:
374 return _Packed.decode(buf)
375 if len(buf) < L.HEADER_SIZE:
376 raise ValueError(
"too short for a DataMessage header (%d bytes)" % len(buf))
377 size, cid, cver = struct.unpack_from(
"<IIH", buf, 0)
378 if cid != L.DATAMESSAGEID:
379 raise ValueError(
"not a DataMessage (object id %d)" % cid)
380 if not L.HEADER_SIZE <= size <= len(buf):
381 raise ValueError(
"declared size %d outside 200..%d" % (size, len(buf)))
382 if cver != L.VERSION:
383 raise ValueError(
"DataMessage format version %d, this codec reads %d" % (cver, L.VERSION))
386 for field, attr
in _ATTRS:
387 off, _, fmt = F[field]
388 setattr(m, attr, struct.unpack_from(
"<" + fmt, buf, off)[0])
389 m.type =
PsyType(struct.unpack_from(
"<16H", buf, F[
"type"][0]))
390 m.context_change =
PsyContext(struct.unpack_from(
"<16H", buf, F[
"contextchange"][0]))
392 while p + L.ENTRY_HEADER_SIZE <= size:
393 slot, ecid = struct.unpack_from(
"<II", buf, p)
394 if slot < L.ENTRY_HEADER_SIZE
or p + slot > size:
395 raise ValueError(
"corrupt entry slot at %d (size %d)" % (p, slot))
396 if ecid == L.CONSTCHARID:
397 k0 = p + L.ENTRY_HEADER_SIZE
398 k = buf.find(b
"\0", k0, p + slot)
400 raise ValueError(
"unterminated key at %d" % p)
401 key = buf[k0:k].decode(
"utf-8")
403 if vh + L.ENTRY_HEADER_SIZE > p + slot:
404 raise ValueError(
"corrupt value of %r at %d" % (key, vh))
405 vsize, vcid = struct.unpack_from(
"<II", buf, vh)
406 vsize -= L.ENTRY_HEADER_SIZE
407 v0 = vh + L.ENTRY_HEADER_SIZE
408 if vsize < 0
or v0 + vsize > p + slot:
409 raise ValueError(
"corrupt value of %r at %d" % (key, vh))
410 v = buf[v0:v0 + vsize]
411 if vcid == L.CONSTCHARID:
412 val = (v[:-1]
if v.endswith(b
"\0")
else v).decode(
"utf-8")
413 elif vcid == L.INTID:
414 val = struct.unpack(
"<q", v)[0]
415 elif vcid == L.DOUBLEID:
416 val = struct.unpack(
"<d", v)[0]
417 elif vcid == L.TIMEID:
418 val =
Time(struct.unpack(
"<Q", v)[0])
419 elif vcid == L.CHARDATAID:
421 elif vcid == L.DATAMESSAGEID:
422 val = DataMessage.from_bytes(v)
425 m._entries[key] = val
432 """The packed form (C++ ``DataMessage::toPacked()``): ~3x less overhead on a device message."""
433 return _Packed.encode(self)
437 """[u32 size][u32 PACKEDDATAMESSAGEID][u8 version][varint field mask][non-zero header fields]
438 [varint entry count] { [varint key length][key][u8 kind][value] } (DataMessage.h)"""
439 RAW, TEXT, INT, DOUBLE, TIME, DATA, MESSAGE = range(7)
445 ORDER = [
"cenc",
"memid",
"time",
"send_time",
"recv_time",
"origin",
"destination",
"ttl",
446 "priority",
"policy",
"from_id",
"to_id",
None,
"tag",
"status",
"reference",
"serial",
None,
447 "cycle_cpu_time",
"cycle_wall_time",
"chain_cpu_time",
"chain_wall_time",
"chain_count",
"system_id"]
448 WIDTH = {
"cenc": 0xFFFF,
"origin": 0xFFFF,
"destination": 0xFFFF,
"priority": 0xFFFF,
"policy": 0xFF,
449 "status": 0xFFFF,
"from_id": M32,
"to_id": M32,
"tag": M32,
"cycle_cpu_time": M32,
450 "cycle_wall_time": M32,
"chain_cpu_time": M32,
"chain_wall_time": M32,
"chain_count": M32,
457 out.append((v & 0x7F) | 0x80)
469 while n > 0
and lv[n - 1] == 0:
478 raise ValueError(
"attached messages nested deeper than %d" % cls.
MAX_DEPTH)
480 out.append(Layout.VERSION)
483 for i, attr
in enumerate(cls.
ORDER):
485 present, v = any(m.type.levels),
None
487 present, v = any(m.context_change.levels),
None
489 v = int(getattr(m, attr)) & cls.
WIDTH.get(attr, M64)
491 v &= ~Layout.CENC_PACKED & 0xFFFF
497 for i
in range(cls.
FIELDS):
498 if not mask & (1 << i):
501 cls.
_levels(out, m.type.levels)
503 cls.
_levels(out, m.context_change.levels)
506 cls.
_varint(out, len(m._entries))
507 for k, v
in m._entries.items():
508 cls.
_bytes(out, k.encode(
"utf-8"))
509 if isinstance(v, Time):
512 elif isinstance(v, str):
514 cls.
_bytes(out, v.encode(
"utf-8"))
515 elif isinstance(v, int):
517 cls.
_varint(out, ((v << 1) ^ (v >> 63)) & M64)
518 elif isinstance(v, float):
520 out += struct.pack(
"<d", v)
521 elif isinstance(v, bytes):
524 elif isinstance(v, DataMessage):
527 elif isinstance(v, Raw):
532 raise TypeError(type(v).__name__)
533 struct.pack_into(
"<II", out, 0, len(out), Layout.PACKEDDATAMESSAGEID)
538 self.
b, self.
p, self.
end = b, p, len(b)
541 if n < 0
or n > self.
end - self.
p:
542 raise ValueError(
"packed DataMessage truncated")
558 raise ValueError(
"packed DataMessage: varint too long")
563 r = self.
b[self.
p:self.
p + n]
570 raise ValueError(
"packed DataMessage: %d levels" % n)
575 raise ValueError(
"level %d" % x)
583 raise ValueError(
"attached messages nested deeper than %d" % cls.
MAX_DEPTH)
585 raise ValueError(
"too short for a packed DataMessage (%d bytes)" % len(buf))
586 size, cid = struct.unpack_from(
"<II", buf, 0)
588 raise ValueError(
"packed DataMessage declares %d bytes, got %d" % (size, len(buf)))
589 if cid != L.PACKEDDATAMESSAGEID:
590 raise ValueError(
"not a packed DataMessage")
591 if buf[8] != L.VERSION:
592 raise ValueError(
"packed DataMessage format version %d, this codec reads %d" % (buf[8], L.VERSION))
596 raise ValueError(
"packed DataMessage: field mask %d" % mask)
599 for i, attr
in enumerate(cls.
ORDER):
600 if not mask & (1 << i):
603 m.type = r.levels(PsyType)
605 m.context_change = r.levels(PsyContext)
607 setattr(m, attr, r.varint() & cls.
WIDTH.get(attr, M64))
609 m.cenc |= L.CENC_PACKED
612 raise ValueError(
"packed DataMessage: %d entries" % count)
613 for _
in range(count):
615 if not kb
or b
"\0" in kb:
616 raise ValueError(
"packed DataMessage: bad key")
617 key = kb.decode(
"utf-8")
620 v = r.bytes().
decode(
"utf-8")
621 elif kind == cls.
INT:
623 v = (z >> 1) ^ -(z & 1)
626 v = struct.unpack_from(
"<d", buf, r.p)[0]
628 elif kind == cls.
TIME:
630 elif kind == cls.
DATA:
633 v = cls.
decode(r.bytes(), depth + 1)
634 elif kind == cls.
RAW:
636 if c > M32
or c
in (L.CONSTCHARID, L.UNUSEDID):
637 raise ValueError(
"packed DataMessage: content id %d" % c)
638 v =
Raw(c, r.bytes())
640 raise ValueError(
"packed DataMessage: entry kind %d" % kind)
643 raise ValueError(
"packed DataMessage: %d trailing bytes" % (r.end - r.p))
__init__(self, levels=())
decode(cls, buf, depth=0)
set_int(self, key, value)
set_string(self, key, value)
get_double(self, key, default=None)
get_time(self, key, default=None)
from_bytes(data, offset=0, length=None)
__setitem__(self, key, value)
get_attached_message(self, key, default=None)
get_string(self, key, default=None)
get_int(self, key, default=None)
_typed(self, key, t, default)
set_double(self, key, value)
set_raw(self, key, cid, data)
set_attached_message(self, key, value)
set_time(self, key, value)
get_data(self, key, default=None)
get(self, key, default=None)
set_data(self, key, value)
__init__(self, cid, data)
Usage: std::string msg = "The quick brown fox jumps over the lazy dog"; std::string key = "key"; std:...
Hierarchical execution-context identifier.