Repository navigation
Expand file tree
/
Copy pathteleplot.py
More file actions
2537 lines (2202 loc) · 108 KB
/
Copy pathteleplot.py
File metadata and controls
2537 lines (2202 loc) · 108 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Teleplot client for Python: telemetry, pictures, and the settings and actions the page can use. One file, Python 3.9+, standard
library only (NumPy, Pillow or OpenCV are used for pictures when they are installed). The API of the C++ client, with its names:
doc/python-client-api.md. Source: https://github.com/nesnes/teleplot
from teleplot import Teleplot
tp = Teleplot.instance() # 127.0.0.1:47269, sent every 20 ms
tp.telemetry("battery").unit("V").range(10.5, 12.6) # described once
tp.update("battery", 12.4)
tp.telemetry("robot").shape(Teleplot.Cube).size(0.4, 0.3, 0.2)
tp.telemetry("robot").position(x, y).yaw(theta) # one chain, one time
Protocols: binary (doc/binaryProtocol.md, the default) or text (doc/textProtocol.md, Teleplot.TEXT_PROTOCOL).
"""
import atexit
import base64
import collections
import datetime
import io
import math
import numbers
import os
import re
import socket
import struct
import sys
import threading
import time
import zlib
__all__ = ["Teleplot", "TeleplotImage", "TeleplotError"]
class TeleplotError(Exception):
"""A misuse of the API (what the C++ client refuses to compile)"""
# --------------------------------------------------------------------------------------------------------------- protocol
_MARKER, _VERSION = 0x10, 1
_PACKET_SIZE = 1432
_MAX_TEXT = 1380
_MAX_ATTR_TEXT = 900
_MAX_NAME = 300
_PART_BYTES = 1380
_CALL_ID_SETTING = 0xFFFF
_FILE_MAGIC = bytes([0x54, 0x50, 0x4C, 0x54, 0x0A, 0x01, 0x00, 0x00])
(A_NAME, A_UNIT, A_COLOR, A_AUTOPLOT, A_TIMEOUT, A_SHAPE, A_LABEL, A_LOG, A_FRAME, A_RANGE, A_STACK, A_WRITE, _A_RETIRED, A_ARGS,
A_DESC, A_TITLE, A_PIXELS, A_MOMENT, A_INPUTS) = range(19) # (12: retired, the texts a setting can take are an enum structure: S_ENUM)
S_CLIENT_NAME, S_DASHBOARD, S_ATTR = 1, 2, 10
(S_NUMBER, S_NUMBER_2D, S_NUMBER_3D, S_TEXT, S_IMAGE, S_POSITION, S_ROTATION, S_QUATERNION, S_COLOR_STR, S_COLOR_RGB, S_OPACITY,
S_SIZE, S_TEXTURE, S_INTRINSICS, S_DISTORTION, S_CLOUD, S_FLOAT64, S_VECTOR, S_SHAPE_TEXT, S_LINE_WIDTH, S_THRESHOLD, S_CALL,
S_CALL_ANSWER, S_ENUM, S_EDGES) = range(20, 45) # (43, 44: the structure of a telemetry, doc/graph.md)
# Samples usually sent once: sent again with the descriptions (a page opened later gets them). Streams are not.
_LATCHED = set(range(S_POSITION, S_DISTORTION + 1)) | {S_VECTOR, S_SHAPE_TEXT, S_LINE_WIDTH, S_THRESHOLD, S_ENUM, S_EDGES}
_NUMERIC = {S_NUMBER, S_NUMBER_2D, S_NUMBER_3D, S_POSITION, S_ROTATION, S_QUATERNION, S_COLOR_RGB, S_OPACITY, S_SIZE, S_INTRINSICS,
S_DISTORTION, S_VECTOR, S_LINE_WIDTH}
_SHAPE_NAMES = {0: "cube", 1: "sphere", 2: "cylinder", 3: "rect", 4: "circle", 5: "line", 6: "polygon", 7: "arrow", 8: "text", 10: "stl"}
_WRITE_TYPES = ["", "number", "bool", "text", "xy", "xyz", "pose2d"]
def _fnv16(text):
h = 2166136261
for b in text.encode():
h = ((h ^ b) * 16777619) & 0xFFFFFFFF
return ((h >> 16) ^ (h & 0xFFFF)) & 0xFFFF
def _cstr(text):
return str(text).encode().split(b"\0")[0] + b"\0"
def _escape(text, special):
return "".join("%%%02X" % ord(c) if c in special else c for c in str(text))
def _unescape(text):
""""%3A" -> ":" (what the page escapes in what it writes)"""
return re.sub(r"%([0-9A-Fa-f]{2})", lambda m: chr(int(m.group(1), 16)), text)
def _round(v):
"""Halves away from zero, as C++ (std::round) and the page (Math.round for positives) do: round() of Python goes to even"""
return math.copysign(math.floor(abs(v) + 0.5), v)
def _number_text(v, precise=False):
"""A number for the text protocol: 9 significant digits (any float32 exactly), 17 when precise"""
v = float(v)
if math.isnan(v):
return "nan"
if math.isinf(v):
return "inf" if v > 0 else "-inf"
text = repr(v) if precise else format(v, ".9g")
if text.endswith(".0"):
text = text[:-2]
return text.replace("e+", "e")
def _time_text(ns):
ns = max(0, int(ns))
return "%d.%03d" % (ns // 1000000, (ns // 1000) % 1000)
def _steady_ms():
return time.monotonic_ns() // 1000000
# --------------------------------------------------------------------------------------------------------------- the client
class Teleplot:
"""A Teleplot client. Options (keyword arguments): see doc/python-client-api.md "Options"."""
# ---------------------------------------------------------------- types
Number2D = collections.namedtuple("Number2D", "x y")
Number3D = collections.namedtuple("Number3D", "x y z")
Pose2D = collections.namedtuple("Pose2D", "x y yaw")
Rgb = collections.namedtuple("Rgb", "r g b")
Stats = collections.namedtuple("Stats", "packets bytes samples dropped tooBig sendErrors wrongThread priorityRefused")
class Time:
"""A time: nanoseconds (since 1970, or since what the clock counts from)"""
__slots__ = ("ns",)
def __init__(self, ns=0):
self.ns = int(ns)
def __eq__(self, other):
return isinstance(other, Teleplot.Time) and other.ns == self.ns
def __hash__(self):
return hash(self.ns)
def __repr__(self):
return "Teleplot.Time(%d)" % self.ns
class Result:
"""What a handler or onChange answers"""
__slots__ = ("status", "text")
def __init__(self, status=0, text=""):
self.status, self.text = status, "" if text is None else str(text)
def __repr__(self):
return "Teleplot.Result(%s, %r)" % (["ok", "error", "running"][self.status], self.text)
Call = collections.namedtuple("Call", "action id telemetry")
# ---------------------------------------------------------------- constants (as in C++)
Below, Above = 0, 1
Cube, Sphere, Cylinder, Rect, Circle, Line, Polygon, Arrow, Text, Stl = 0, 1, 2, 3, 4, 5, 6, 7, 8, 10
Jpeg, Png, Raw = 0, 1, 2
X, Y, Yaw = 1, 2, 4
Caller, Thread = 0, 1
BelowCaller, Normal, Low, Realtime, PriorityValue = 0, 1, 2, 3, 4
BINARY_PROTOCOL, TEXT_PROTOCOL = "binary", "text"
class ThreadPriority:
"""The priority of the threads of Teleplot: BelowCaller (default), Normal, Low, realtime(p), value(v)"""
def __init__(self, kind=0, number=0, roundRobin=False):
self.kind, self.number, self.roundRobin = kind, number, roundRobin
@staticmethod
def belowCaller():
return Teleplot.ThreadPriority(Teleplot.BelowCaller)
@staticmethod
def normal():
return Teleplot.ThreadPriority(Teleplot.Normal)
@staticmethod
def low():
return Teleplot.ThreadPriority(Teleplot.Low)
@staticmethod
def realtime(priority, roundRobin=False):
return Teleplot.ThreadPriority(Teleplot.Realtime, priority, roundRobin)
@staticmethod
def value(number):
return Teleplot.ThreadPriority(Teleplot.PriorityValue, number)
def __eq__(self, other):
other = Teleplot.ThreadPriority._of(other)
return (self.kind, self.number, self.roundRobin) == (other.kind, other.number, other.roundRobin)
@staticmethod
def _of(v):
return v if isinstance(v, Teleplot.ThreadPriority) else Teleplot.ThreadPriority(int(v))
class ThreadAffinity:
"""The CPUs of the threads of Teleplot: automatic() (default), followCaller(), any(), cpus([2, 3])"""
Automatic, FollowCaller, Any, Cpus = 0, 1, 2, 3
def __init__(self, kind=0, cpus=()):
self.kind, self.list = kind, list(cpus)
@staticmethod
def automatic():
return Teleplot.ThreadAffinity(0)
@staticmethod
def followCaller():
return Teleplot.ThreadAffinity(1)
@staticmethod
def any():
return Teleplot.ThreadAffinity(2)
@staticmethod
def cpus(cpus):
return Teleplot.ThreadAffinity(3, cpus)
def __eq__(self, other):
return isinstance(other, Teleplot.ThreadAffinity) and (self.kind, self.list) == (other.kind, other.list)
# ---------------------------------------------------------------- static functions (as in C++)
@staticmethod
def ns(v):
return Teleplot.Time(int(v))
@staticmethod
def us(v):
return Teleplot.Time(round(v * 1000))
@staticmethod
def ms(v):
return Teleplot.Time(round(v * 1000000))
@staticmethod
def now():
return Teleplot.Time(time.time_ns())
@staticmethod
def deg(degrees):
return degrees * math.pi / 180.0
@staticmethod
def ok(text=""):
return Teleplot.Result(0, text)
@staticmethod
def error(why):
return Teleplot.Result(1, why)
@staticmethod
def running():
return Teleplot.Result(2, "")
@staticmethod
def threadName(name):
"""The name of the calling thread, for the telemetries of its stacks ("robot.task.control")"""
threading.current_thread().name = str(name)
_thread_names.name = str(name)
_instance = None
_instance_lock = threading.Lock()
@staticmethod
def instance():
"""The default client: 127.0.0.1:47269, sent at the end of the program too"""
with Teleplot._instance_lock:
if Teleplot._instance is None:
Teleplot._instance = Teleplot()
atexit.register(Teleplot._instance.close)
return Teleplot._instance
# ---------------------------------------------------------------- client
_DEFAULTS = dict(udp=None, file=None, output=None, protocol="binary", name="", clientId=0, flushInterval=0.02, sendFrom=0,
describeInterval=5.0, publishInterval=0.2, maxQueuedBytes=1 << 20, nonBlocking=False, threadPriority=0,
threadAffinity=None)
def __init__(self, **options):
self._lock = threading.Lock() # the queues (never held while user code runs or while sending)
self._send_lock = threading.Lock() # the outputs
self._thread_lock = threading.Lock() # thread settings
self._entries, self._by_name, self._by_id = [], {}, {}
self._params, self._actions = {}, {}
self._dashboards = collections.deque()
self._dashboard_lines = {} # path -> its latest dashboard line, in the order they came (sent again)
self._dashboards_sent_ms = -10 ** 12
self._queued = 0
self._rr = 0
self._name_sent_ms = -10 ** 12
self._published_ms = -10 ** 12
self._described_ms = -10 ** 12
self._last_flush_ms = 0
self._clock = None
self._enabled = os.environ.get("TELEPLOT_DISABLE", "") in ("", "0")
self._stats = dict(packets=0, bytes=0, samples=0, dropped=0, tooBig=0, sendErrors=0, wrongThread=0, priorityRefused=0)
self._stats_every, self._stats_at, self._stats_before = 0.0, 0, None
self._sockets, self._files, self._functions = [], [], []
self._thread, self._thread_stop, self._thread_wake = None, False, threading.Condition(self._thread_lock)
self._thread_generation, self._reference = 0, None
self._extensions = {}
self._closed = False
self._options = {}
self.setOptions(**options)
def __enter__(self):
return self
def __exit__(self, *exc):
self.close()
def setOptions(self, **options):
unknown = set(options) - set(Teleplot._DEFAULTS)
if unknown:
raise TeleplotError("unknown option(s): %s" % ", ".join(sorted(unknown)))
self._stop_thread()
with self._send_lock, self._lock:
self._close_outputs()
o = dict(Teleplot._DEFAULTS)
o.update(options)
o["flushInterval"] = _seconds(o["flushInterval"])
o["describeInterval"] = _seconds(o["describeInterval"])
o["publishInterval"] = _seconds(o["publishInterval"])
if o["protocol"] not in (Teleplot.BINARY_PROTOCOL, Teleplot.TEXT_PROTOCOL):
raise TeleplotError("protocol: Teleplot.BINARY_PROTOCOL or Teleplot.TEXT_PROTOCOL")
if not o["name"]:
program = os.path.basename(sys.argv[0]) if sys.argv and sys.argv[0] not in ("", "-c") else ""
o["name"] = os.path.splitext(program)[0] or "python"
self._options = o
self._text = o["protocol"] == Teleplot.TEXT_PROTOCOL
self._client_id = o["clientId"] or _fnv16(o["name"])
if self._client_id == 0xFFFF:
self._client_id = 0xFFFE
self._open_outputs()
self._name_sent_ms = -10 ** 12
self._dashboards_sent_ms = -10 ** 12
with self._thread_lock:
self._priority = Teleplot.ThreadPriority._of(o["threadPriority"])
self._affinity = o["threadAffinity"] or Teleplot.ThreadAffinity.automatic()
self._reference = _Scheduling.ofCurrentThread()
self._thread_generation += 1
if o["sendFrom"] == Teleplot.Thread:
self._start_thread()
def options(self):
return dict(self._options)
def close(self):
"""Sends what is queued, stops the threads, closes the outputs (also at the end of a with block)"""
if self._closed:
return
extensions, self._extensions = self._extensions, {}
for extension in extensions.values():
extension.close()
self._stop_thread()
self.flush()
with self._send_lock:
self._close_outputs()
self._closed = True
def enable(self):
self._enabled = True
def disable(self):
self._enabled = False
def clock(self, fn):
"""Where "now" comes from (default: time.time_ns()): fn gives a Teleplot.Time, seconds since 1970 or a datetime"""
self._clock = fn
def currentTime(self):
return Teleplot.Time(self._now_ns())
def threadPriority(self, priority=None):
if priority is None:
with self._thread_lock:
return self._priority
with self._thread_lock:
self._priority = Teleplot.ThreadPriority._of(priority)
self._reference = _Scheduling.ofCurrentThread()
self._thread_generation += 1
self._thread_wake.notify_all()
def threadAffinity(self, affinity=None):
if affinity is None:
with self._thread_lock:
return self._affinity
with self._thread_lock:
self._affinity = affinity
self._reference = _Scheduling.ofCurrentThread()
self._thread_generation += 1
self._thread_wake.notify_all()
def telemetry(self, name):
with self._lock:
return Telemetry(self, self._find(name))
def update(self, name, value, time=None):
if self._enabled:
self.telemetry(name)._chain(time).update(value)
def log(self, *args):
"""log(text), log(name, text), log(name, text, time), log(text, time)"""
if len(args) == 1 or (len(args) == 2 and not isinstance(args[1], str)):
name, text, when = "log", args[0], args[1] if len(args) == 2 else None
else:
name, text, when = args[0], args[1], args[2] if len(args) > 2 else None
if not self._enabled:
return
t = self.telemetry(name)
with self._lock:
entry = self._entries[t._index]
if not entry.log:
self._attr(entry, A_LOG, True)
t._chain(when).update(str(text))
def stack(self, name, path, time=None):
"""What runs, as a whole path ("loop/plan/search"; "" = nothing)"""
index = self._stack_entry(name)
if index is None:
return
with self._lock:
self._entries[index].stack_path = str(path)
Telemetry(self, index)._chain(time if time is not None else self._stack_now(index)).update(str(path))
def _stack_now(self, index):
"""The time of a stack sample the client dates itself: at least 1 µs after the previous one of the stack. Samples of a stack
with the same time are parts of one for the page (several paths at once, doc/graph.md): one step and the next must not look so"""
ns = self._now_ns()
with self._lock:
e = self._entries[index]
if e.last_stack_ns is not None and ns < e.last_stack_ns + 1000:
ns = e.last_stack_ns + 1000
e.last_stack_ns = ns
return Teleplot.ns(ns)
def dashboard(self, lines):
"""Dashboard lines of the text protocol (DASH|Robot/Motion:chart:speed|w=2), several separated by line feeds. Sent again with the
descriptions (every describeInterval: a page opened later gets the dashboard), the latest line of each path; "none" forgets what
it removes. The page applies a line only when it changed: sending them again does nothing more."""
if not self._enabled:
return
with self._lock:
for line in str(lines).split("\n"):
if not line:
continue
if len(line.encode()) > _MAX_TEXT:
self._stats["tooBig"] += 1
continue
self._keep_dashboard_line(line)
if self._text:
self._line(line)
else:
self._dashboards.append(line)
self._after_sample(False)
def param(self, name, initial, attribute=None):
"""A setting the page may write: param(name, initial) (its .value), or param(name, object, attribute) (bound)"""
p = Param(self, name, initial, attribute)
with self._lock:
p._index = self._find(name)
self._params[self._entries[p._index].id] = p
p._declare()
p._publish()
return p
def action(self, name, handler=None):
"""An action the page may call: handler(args) returns Teleplot.ok() / error("why") / running() / None. Without a handler,
the Action is a decorator."""
a = Action(self, name, handler)
with self._lock:
a._index = self._find(name)
self._actions[self._entries[a._index].id] = a
a._declare()
return a
def answer(self, call, result):
"""Finishes a call whose handler returned running()"""
action = self._actions.get(call.telemetry)
if action is not None:
action._recent = [(i, result if i == call.id else r) for i, r in action._recent]
self._answer(call.telemetry, call.action, call.id, result.status, result.text)
def poll(self):
"""Reads what the page wrote (settings, calls), applies it, answers, publishes the settings, sends"""
if not self._enabled:
return
received = []
with self._send_lock:
for s, _ in self._sockets:
while True:
try:
received.append(s.recv(65536))
except (BlockingIOError, InterruptedError):
break
except OSError:
break
for data in received:
if data[:1] == bytes([_MARKER]):
self.handlePacket(data)
else:
for line in data.decode(errors="replace").split("\n"):
self.handleLine(line)
now = _steady_ms()
publish_all = now - self._published_ms >= self._options["publishInterval"] * 1000
for p in list(self._params.values()):
if p._hold and p._written_ms and now - p._written_ms > p._hold: # nobody drives it any more: back to rest
p._rest()
p._written_ms = 0
p._publish()
elif publish_all:
p._publish()
if publish_all:
self._published_ms = now
self.flush()
def handlePacket(self, data):
"""A packet of the binary protocol written by the page (poll() reads them; public for other transports)"""
data = bytes(data)
# (the checksum is the sum of every byte before the last two: a packet that does not match is ignored)
if not self._enabled or len(data) < 6 or struct.unpack_from("<H", data, len(data) - 2)[0] != sum(data[:-2]) & 0xFFFF:
return
r = _Reader(data[:-2])
if r.u8() != _MARKER or r.u8() != _VERSION:
return
r.u16()
while r.ok and r.at < len(r.data):
section = r.u8()
if section == S_CALL:
if not self._binary_call(r):
return
continue
if section < S_NUMBER or section > S_TEXT:
return
telem_id, _, count = r.u16(), r.u64(), r.u8()
numbers_, text = [], ""
for _ in range(count):
r.u32()
if section == S_TEXT:
text = r.str()
else:
numbers_ = [r.f32() for _ in range(section - S_NUMBER + 1)]
if not r.ok or count == 0:
return
p = self._params.get(telem_id)
if p is not None:
p._written(numbers_, text, telem_id)
def handleLine(self, line):
"""A line written by the page: "name:value" for a setting, "!name#id:arg=value" for a call"""
if not self._enabled:
return
line = line.strip("\r\n ")
if not line:
return
if line.startswith("!"):
return self._text_call(line[1:])
name, colon, value = line.partition(":")
if not colon:
return
for p in list(self._params.values()):
if p._name == name:
parts = value.split(":")
numbers_ = []
try:
numbers_ = [float(v) for v in parts] if p._type != 3 else []
except ValueError:
numbers_ = []
return p._written(numbers_, _unescape(value), self._entries[p._index].id)
def flush(self):
"""Sends what is queued now"""
self._flush(False)
def stats(self):
with self._lock:
return Teleplot.Stats(**self._stats)
def sendStats(self, every):
"""The stats as telemetries every "every" (Teleplot.ms(1000); 0: no more, the default)"""
with self._lock:
self._stats_every = _seconds(every)
self._stats_at = _steady_ms()
self._stats_before = dict(self._stats)
def statsInterval(self):
return Teleplot.ms(self._stats_every * 1000)
# ---------------------------------------------------------------- inside
def _now_ns(self):
if self._clock is not None:
return _ns(self._clock())
return time.time_ns()
def _find(self, name): # (lock held)
name = str(name)[:_MAX_NAME]
index = self._by_name.get(name)
if index is not None:
return index
entry = _Entry(name)
telem_id = _fnv16(name)
while telem_id in self._by_id: # (two names with the same id: the second takes the next free one)
telem_id = (telem_id + 1) & 0xFFFF
entry.id = telem_id
self._entries.append(entry)
index = len(self._entries) - 1
self._by_name[name] = index
self._by_id[telem_id] = index
return index
def _attr(self, entry, code, value): # (lock held) a description: kept, sent before the next samples and again every 5 s
if entry.attrs.get(code) == value:
return
entry.attrs[code] = value
entry.dirty = True
if code == A_LOG:
entry.log = bool(value)
if code == A_STACK:
entry.stack = bool(value)
if code == A_MOMENT:
entry.moment = bool(value)
def _lock_for(self, entry):
non_blocking = entry.non_blocking if entry.non_blocking is not None else self._options["nonBlocking"]
if non_blocking:
if not self._lock.acquire(blocking=False):
self._stats["dropped"] += 1
return False
return True
self._lock.acquire()
return True
def _after_sample(self, non_blocking):
if self._options["sendFrom"] != Teleplot.Caller or self._options["flushInterval"] <= 0:
return
if _steady_ms() - self._last_flush_ms < self._options["flushInterval"] * 1000 and self._queued < _PACKET_SIZE:
return
self._flush(non_blocking)
# A sample (kind: a section type; values: what it holds) of an entry, at ns
def _sample(self, index, kind, ns, values, latch_key=None):
if not self._enabled:
return
entry = self._entries[index]
if not self._lock_for(entry):
return
try:
if kind >= S_POSITION and kind not in (S_INTRINSICS, S_DISTORTION, S_THRESHOLD, S_CLOUD, S_IMAGE, S_ENUM, S_EDGES):
entry.is_shape = True
if entry.max_rate > 0 and kind not in (S_THRESHOLD, S_ENUM, S_EDGES):
last = entry.last_kept.get(kind)
if last is not None and 0 <= ns - last < 1e9 / entry.max_rate:
return
entry.last_kept[kind] = ns
self._stats["samples"] += 1
if self._text:
self._text_sample(entry, kind, ns, values)
else:
self._binary_sample(entry, kind, ns, values)
if kind in _LATCHED or (kind == S_CLOUD and entry.shape_type in (5, 6)):
entry.latched[(kind, latch_key)] = [ns, values, _steady_ms()]
finally:
self._lock.release()
self._after_sample(entry.non_blocking if entry.non_blocking is not None else self._options["nonBlocking"])
# ---------------------------------------------------------------- binary
def _binary_sample(self, entry, kind, ns, values): # (lock held) encoded now, queued
if kind in _NUMERIC:
if entry.precise:
self._push(entry, (S_FLOAT64 << 8) | kind, ns, struct.pack("<%dd" % len(values), *values))
return
if kind == S_INTRINSICS:
payload = struct.pack("<HH4f", int(max(0, min(65535, values[0]))), int(max(0, min(65535, values[1]))), *values[2:])
elif kind in (S_COLOR_RGB, S_OPACITY):
payload = bytes(int(max(0, min(255, v))) for v in values)
else:
payload = struct.pack("<%df" % len(values), *values)
self._push(entry, kind, ns, payload)
elif kind in (S_TEXT, S_COLOR_STR, S_SHAPE_TEXT):
text = str(values[0]).encode()
if len(text) > _MAX_TEXT:
self._stats["tooBig"] += 1
text = text[:_MAX_TEXT]
self._push(entry, kind, ns, text.split(b"\0")[0] + b"\0")
elif kind == S_TEXTURE:
self._push(entry, kind, ns, bytes([values[0]]) + _cstr(values[1]))
elif kind in (S_ENUM, S_EDGES): # a part of a structure: its items separated by line feeds
self._push(entry, kind, ns, _cstr(values[0]))
elif kind == S_THRESHOLD:
operator, value, name, color = values
self._push(entry, kind, ns, bytes([operator]) + struct.pack("<d", value) + _cstr(name) + _cstr(color))
elif kind == S_IMAGE:
image_type, data = values
count = max(1, (len(data) + _PART_BYTES - 1) // _PART_BYTES)
if count > 0xFFFF:
self._stats["tooBig"] += 1
return
for part in range(count):
chunk = data[part * _PART_BYTES:(part + 1) * _PART_BYTES]
self._push(entry, kind, ns, struct.pack("<BHHH", image_type, part, count, len(chunk)) + bytes(chunk))
elif kind == S_CLOUD:
points, intensities, colors = values
flags = (1 if intensities is not None else 0) | (2 if colors is not None else 0)
point_bytes = 12 + (4 if intensities is not None else 0) + (3 if colors is not None else 0)
per_part = (_PART_BYTES - 7) // point_bytes
count = max(1, (len(points) + per_part - 1) // per_part)
for part in range(count):
chunk = bytearray(struct.pack("<BHHH", flags, part, count, len(points[part * per_part:(part + 1) * per_part])))
for i in range(part * per_part, min(len(points), (part + 1) * per_part)):
chunk += struct.pack("<3f", *points[i])
if intensities is not None:
chunk += struct.pack("<f", intensities[i])
if colors is not None:
chunk += bytes(int(max(0, min(255, c))) for c in colors[i])
self._push(entry, kind, ns, bytes(chunk))
def _push(self, entry, key, ns, payload): # (lock held)
entry.queues.setdefault(key, collections.deque()).append((ns, payload))
self._queued += len(payload) + 8
while self._queued > self._options["maxQueuedBytes"]: # the oldest samples of the biggest queue go first
biggest = None
for e in self._entries:
for q in e.queues.values():
if q and (biggest is None or sum(len(p) for _, p in q) > sum(len(p) for _, p in biggest)):
biggest = q
if biggest is None:
self._queued = 0
break
_, dropped = biggest.popleft()
self._queued -= len(dropped) + 8
self._stats["dropped"] += 1
def _attr_bytes(self, code, value):
if code in (A_NAME, A_UNIT, A_COLOR, A_LABEL, A_DESC, A_TITLE):
return _cstr(str(value)[:_MAX_ATTR_TEXT])
if code in (A_AUTOPLOT, A_LOG, A_STACK, A_MOMENT):
return bytes([1 if value else 0])
if code == A_TIMEOUT:
return struct.pack("<Q", max(0, int(value)))
if code == A_SHAPE:
shape_type, url = value
return bytes([shape_type]) + (_cstr(url[:_MAX_ATTR_TEXT]) if shape_type == Teleplot.Stl else b"")
if code == A_FRAME:
return bytes([value[0]]) + _cstr(value[1])
if code == A_RANGE:
return struct.pack("<dd", *(math.nan if v is None else v for v in value))
if code == A_WRITE:
kind, write_type, flags, step, rate, hold, axes = value
return struct.pack("<BBBdHHB", kind, write_type, flags, math.nan if step is None else step, rate, hold, axes)
if code == A_PIXELS:
return struct.pack("<ddB", value[0], value[1], 0 if value[2] else 1) # flags: 1 = not a depth map
if code == A_INPUTS:
return _cstr(value[0][:_MAX_ATTR_TEXT]) + _cstr(value[1][:_MAX_ATTR_TEXT])
raise ValueError(code)
def _keep_dashboard_line(self, line): # (lock held) kept to be sent again: replaces the line of its path; "none" forgets what it removes
body = line[5:] if line.startswith("DASH|") else line
cut = min([i for i in (body.find(":"), body.find("|")) if i >= 0], default=len(body))
path = line[:len(line) - len(body) + cut]
rest = body[cut + 1:] if cut < len(body) and body[cut] == ":" else ""
kind = rest.split(":")[0].split("|")[0]
if kind != "none" and path in self._dashboard_lines:
self._dashboard_lines[path] = line
return
for other in [p for p in self._dashboard_lines if p == path or (kind == "none" and p.startswith(path + "/"))]:
del self._dashboard_lines[other]
self._dashboard_lines[path] = line
def _build_packet(self): # (lock held) the next packet: client name, dashboards, descriptions, samples. None: nothing
p = bytearray(struct.pack("<BBH", _MARKER, _VERSION, self._client_id))
start, limit = len(p), _PACKET_SIZE - 2
now = _steady_ms()
every = self._options["describeInterval"] * 1000
if now - self._name_sent_ms >= every:
p += bytes([S_CLIENT_NAME]) + _cstr(self._options["name"][:_MAX_NAME])
self._name_sent_ms = now
if now - self._dashboards_sent_ms >= every: # (the lines of the dashboards again, unless some still wait to be sent)
if not self._dashboards:
self._dashboards.extend(self._dashboard_lines.values())
self._dashboards_sent_ms = now
while self._dashboards and len(self._dashboards[0].encode()) + 2 <= limit - len(p):
p += bytes([S_DASHBOARD]) + _cstr(self._dashboards.popleft())
full = False
waiting = set()
for i, e in enumerate(self._entries):
if full:
break
if not e.dirty and now - e.attrs_sent_ms < every:
continue
if e.attr_cursor == 0: # name first; codes in order: the newer ones (11 and up) last
e.items = [bytes([A_NAME]) + _cstr(e.name)]
for code in sorted(e.attrs):
if code < A_ARGS and code not in (A_NAME,):
e.items.append(bytes([code]) + self._attr_bytes(code, e.attrs[code]))
for arg in e.args:
e.items.append(bytes([A_ARGS]) + arg)
for code in sorted(e.attrs):
if code > A_ARGS:
e.items.append(bytes([code]) + self._attr_bytes(code, e.attrs[code]))
for (kind, _), (ns, values, sent_ms) in list(e.latched.items()): # sent once and not since: again, its own time
key = (S_FLOAT64 << 8) | kind if e.precise and kind in _NUMERIC else kind
if now - sent_ms >= every and not e.queues.get(key):
self._binary_sample(e, kind, ns, values)
while e.attr_cursor < len(e.items):
if limit - len(p) < 4 + len(e.items[e.attr_cursor]):
if len(p) == start:
e.attr_cursor += 1 # (cannot fit even alone: skipped, never sent in a loop)
continue
full = True
break
p += struct.pack("<BH", S_ATTR, e.id)
count_at = len(p)
p.append(0)
count = 0
while e.attr_cursor < len(e.items) and count < 255 and limit - len(p) >= len(e.items[e.attr_cursor]):
p += e.items[e.attr_cursor]
e.attr_cursor += 1
count += 1
p[count_at] = count
if e.attr_cursor >= len(e.items):
e.attr_cursor, e.dirty, e.attrs_sent_ms = 0, False, now
else:
waiting.add(i)
n = len(self._entries)
for k in range(n):
if full:
break
i = (self._rr + k) % n
if i in waiting:
continue
e = self._entries[i]
for key in sorted(e.queues):
q = e.queues[key]
if not q:
continue
f64 = (key >> 8) == S_FLOAT64
header = 12 + (1 if f64 else 0)
reference, first = q[0]
if limit - len(p) < header + 4 + len(first):
if len(p) == start:
q.popleft()
self._queued -= len(first) + 8
self._stats["tooBig"] += 1
continue
full = True
break
p += struct.pack("<BHQ", S_FLOAT64 if f64 else key, e.id, max(0, reference))
count_at = len(p)
p.append(0)
if f64:
p.append(key & 0xFF)
count = 0
while q and count < 255:
ns, payload = q[0]
diff = ns - reference
if diff < 0 or diff > 0xFFFFFFFF: # (TIMEDIFF: an uint32 of ns; out of it, a section of its own)
break
if limit - len(p) < 4 + len(payload):
full = True
break
p += struct.pack("<I", diff) + payload
q.popleft()
self._queued -= len(payload) + 8
count += 1
p[count_at] = count
if full:
break
self._rr += 1
return bytes(p) if len(p) > start else None
def _binary_call(self, r):
telem_id, call_id, count = r.u16(), r.u16(), r.u8()
action = self._actions.get(telem_id)
values = {}
for _ in range(count):
at = r.u8()
if action is None or at >= len(action._args):
return False
spec = action._args[at]
if spec.type == Teleplot.Arg.Bool:
values[spec.name] = r.u8() != 0
elif spec.type == Teleplot.Arg.Text:
values[spec.name] = r.str()
elif spec.type == Teleplot.Arg.XY:
values[spec.name] = [r.f64(), r.f64()]
elif spec.type in (Teleplot.Arg.XYZ, Teleplot.Arg.Pose2D):
values[spec.name] = [r.f64(), r.f64(), r.f64()]
else:
values[spec.name] = r.f64()
if not r.ok:
return False
name = self._entries[self._by_id[telem_id]].name if telem_id in self._by_id else ""
self._run_call(action, Teleplot.Call(name, call_id, telem_id), values)
return True
def _answer(self, telem_id, name, call_id, status, text):
if self._text:
head = "%s#%d" % (name, call_id) if call_id != _CALL_ID_SETTING else name
word = ["ok", "err", "run"][status]
line = "ACK|%s:%s" % (head, word) + (":" + _escape(text, "%\n\r") if text else "")
with self._lock:
self._line(line)
self.flush()
return
packet = struct.pack("<BBHBHHB", _MARKER, _VERSION, self._client_id, S_CALL_ANSWER, telem_id, call_id, status) + _cstr(str(text)[:_MAX_TEXT])
with self._send_lock:
self._send(packet)
# ---------------------------------------------------------------- text
def _line(self, line): # (lock held)
data = (line + "\n").encode()
self._text_queue.append(data)
self._queued += len(data)
while self._queued > self._options["maxQueuedBytes"] and self._text_queue:
self._queued -= len(self._text_queue.popleft())
self._stats["dropped"] += 1
def _text_head(self, entry):
label = entry.attrs.get(A_LABEL)
return entry.name + ("," + label if label else "")
def _text_flags(self, entry, kind):
flags = [kind] if kind else []
if entry.attrs.get(A_AUTOPLOT) is False:
flags.append("np")
return ("|" + ",".join(flags)) if flags else ""
def _text_describe(self, entry): # (lock held) ATTR| and the 3D| lines of a shape's type and frame
entry.dirty = False
a = entry.attrs
keys = []
for code, key in ((A_UNIT, "unit"), (A_DESC, "desc"), (A_COLOR, "color")):
if a.get(code):
keys.append("%s=%s" % (key, _escape(a[code], "%|,=:\n\r")))
if a.get(A_RANGE):
for side, key in zip(a[A_RANGE], ("min", "max")):
if side is not None and not math.isnan(side):
keys.append("%s=%s" % (key, _number_text(side, True)))
if a.get(A_PIXELS):
scale, no_data, depth = a[A_PIXELS]
keys += ["scale=%s" % _number_text(scale, True), "nodata=%s" % ("" if math.isnan(no_data) else _number_text(no_data, True)),
"depth=%d" % (1 if depth else 0)]
if keys:
self._line("ATTR|%s|%s" % (entry.name, "|".join(keys)))
if A_SHAPE in a:
shape_type, url = a[A_SHAPE]
self._line("3D|%s:S:\"%s\"%s" % (entry.name, _SHAPE_NAMES.get(shape_type, "cube"), (":U:\"%s\"" % url) if shape_type == Teleplot.Stl else ""))
if A_FRAME in a:
frame_type, name = a[A_FRAME]
self._line("3D|%s:%s:\"%s\"" % (entry.name, "FPX" if frame_type == 1 else "F", name))
for code, value in ((A_WRITE, a.get(A_WRITE)),):
if value is not None:
self._line(self._text_write_line(entry, value))
for line in entry.text_args:
self._line(line)
entry.attrs_sent_ms = _steady_ms()
def _text_write_line(self, entry, write):
kind, write_type, flags, step, rate, hold, axes = write
a = entry.attrs
if kind == 2:
line = "ATTR|%s|action" % entry.name
for code, key in ((A_TITLE, "title"), (A_DESC, "desc"), (A_COLOR, "color")):
if a.get(code):
line += "|%s=%s" % (key, _escape(a[code], "%|,=:\n\r"))
return line + ("|confirm" if flags & 1 else "") + ("|longpress" if flags & 2 else "") + self._text_inputs(a)
line = "ATTR|%s|write=%s" % (entry.name, _WRITE_TYPES[write_type])
rng = a.get(A_RANGE) or (None, None)
for side, key in zip(rng, ("min", "max")):
if side is not None and not math.isnan(side):
line += "|%s=%s" % (key, _number_text(side, True))
if step is not None:
line += "|step=%s" % _number_text(step, True)
if rate:
line += "|rate=%d" % rate
if hold:
line += "|hold=%d" % hold
if axes:
line += "|axes=" + ",".join(n for bit, n in ((1, "x"), (2, "y"), (4, "yaw")) if axes & bit)
for code, key in ((A_UNIT, "unit"), (A_DESC, "desc")):
if a.get(code):
line += "|%s=%s" % (key, _escape(a[code], "%|,=:\n\r"))
return line + self._text_inputs(a)
@staticmethod
def _text_inputs(a): # keys= and pad= of a command, as given
keys, pad = a.get(A_INPUTS) or ("", "")
return ("|keys=" + keys if keys else "") + ("|pad=" + pad if pad else "")
def _text_sample(self, entry, kind, ns, values): # (lock held) the line of a sample
if entry.dirty:
self._text_describe(entry)
n = lambda v: _number_text(v, entry.precise)
t = _time_text(ns)
if kind == S_NUMBER:
self._line("%s:%s:%s%s" % (self._text_head(entry), t, n(values[0]), self._text_flags(entry, None)))
elif kind in (S_NUMBER_2D, S_NUMBER_3D):
self._line("%s:%s:%s%s" % (self._text_head(entry), ":".join(n(v) for v in values), t, self._text_flags(entry, "xy" if kind == S_NUMBER_2D else "xyz")))
elif kind == S_TEXT:
text = str(values[0]).replace("\n", " ").replace("\r", " ").replace("§", "?")
if len(text.encode()) > _MAX_TEXT:
self._stats["tooBig"] += 1
text = text.encode()[:_MAX_TEXT].decode(errors="ignore")
self._line("%s:%s:%s%s" % (self._text_head(entry), t, text, self._text_flags(entry, "log" if entry.log else "mom" if entry.moment else "stack" if entry.stack else "t")))
elif kind in (S_ENUM, S_EDGES): # name:time:item,item|enum (or |edges), the items as given ("," ";" "|" in them as %XX)
items = ",".join(_escape(item, ",;|\r") for item in str(values[0]).split("\n"))