-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathlcm_foxglove_bridge.py
More file actions
1738 lines (1525 loc) · 76 KB
/
lcm_foxglove_bridge.py
File metadata and controls
1738 lines (1525 loc) · 76 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
#!/usr/bin/env python3
import asyncio
import json
import time
import sys
import os
import re
import threading
import lcm
import base64
import importlib
import logging
import queue
from concurrent.futures import ThreadPoolExecutor
from typing import Dict, List, Any, Set, Optional, Tuple, Callable
from dataclasses import dataclass
import numpy as np
from collections import defaultdict
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger("lcm_foxglove_bridge")
# Import foxglove-websocket
from foxglove_websocket import run_cancellable
from foxglove_websocket.server import FoxgloveServer, FoxgloveServerListener
from foxglove_websocket.types import ChannelId
# Constants
ROS_MSGS_DIR = "ros_msgs"
LCM_PYTHON_MODULES_PATH = "python_lcm_msgs/lcm_msgs"
DEFAULT_THREAD_POOL_SIZE = 8
MESSAGE_BATCH_SIZE = 10
MAX_QUEUE_SIZE = 100
# Hardcoded schemas for Foxglove compatibility
# These are specially formatted to match exactly what Foxglove expects
HARDCODED_SCHEMAS = {
"sensor_msgs.Image": {
"foxglove_name": "sensor_msgs/msg/Image",
"schema": {
"type": "object",
"properties": {
"header": {
"type": "object",
"properties": {
"stamp": {
"type": "object",
"properties": {
"sec": {"type": "integer"},
"nsec": {"type": "integer"}
}
},
"frame_id": {"type": "string"}
}
},
"height": {"type": "integer"},
"width": {"type": "integer"},
"encoding": {"type": "string"},
"is_bigendian": {"type": "boolean"},
"step": {"type": "integer"},
"data": {
"type": "string",
"contentEncoding": "base64"
}
}
}
},
"sensor_msgs.CompressedImage": {
"foxglove_name": "sensor_msgs/msg/CompressedImage",
"schema": {
"type": "object",
"properties": {
"header": {
"type": "object",
"properties": {
"stamp": {
"type": "object",
"properties": {
"sec": {"type": "integer"},
"nsec": {"type": "integer"}
}
},
"frame_id": {"type": "string"}
}
},
"format": {"type": "string"},
"data": {
"type": "string",
"contentEncoding": "base64"
}
}
}
},
"sensor_msgs.JointState": {
"foxglove_name": "sensor_msgs/msg/JointState",
"schema": {
"type": "object",
"properties": {
"header": {
"type": "object",
"properties": {
"stamp": {
"type": "object",
"properties": {
"sec": {"type": "integer"},
"nsec": {"type": "integer"}
}
},
"frame_id": {"type": "string"}
}
},
"name": {
"type": "array",
"items": {"type": "string"}
},
"position": {
"type": "array",
"items": {"type": "number"}
},
"velocity": {
"type": "array",
"items": {"type": "number"}
},
"effort": {
"type": "array",
"items": {"type": "number"}
}
},
"required": ["header", "name", "position", "velocity", "effort"]
}
},
"tf2_msgs.TFMessage": {
"foxglove_name": "tf2_msgs/msg/TFMessage",
"schema": {
"type": "object",
"properties": {
"transforms": {
"type": "array",
"items": {
"type": "object",
"properties": {
"header": {
"type": "object",
"properties": {
"stamp": {
"type": "object",
"properties": {
"sec": {"type": "integer"},
"nsec": {"type": "integer"}
}
},
"frame_id": {"type": "string"}
}
},
"child_frame_id": {"type": "string"},
"transform": {
"type": "object",
"properties": {
"translation": {
"type": "object",
"properties": {
"x": {"type": "number"},
"y": {"type": "number"},
"z": {"type": "number"}
}
},
"rotation": {
"type": "object",
"properties": {
"x": {"type": "number"},
"y": {"type": "number"},
"z": {"type": "number"},
"w": {"type": "number"}
}
}
}
}
}
}
}
}
}
},
"sensor_msgs.PointCloud2": {
"foxglove_name": "sensor_msgs/msg/PointCloud2",
"schema": {
"type": "object",
"properties": {
"header": {
"type": "object",
"properties": {
"stamp": {
"type": "object",
"properties": {
"sec": {"type": "integer"},
"nsec": {"type": "integer"}
},
"required": ["sec", "nsec"]
},
"frame_id": {"type": "string"}
},
"required": ["stamp", "frame_id"]
},
"height": {"type": "integer"},
"width": {"type": "integer"},
"fields": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string"},
"offset": {"type": "integer"},
"datatype": {"type": "integer"},
"count": {"type": "integer"},
},
"required": ["name","offset","datatype","count"]
}
},
"is_bigendian": {"type": "boolean"},
"point_step": {"type": "integer"},
"row_step": {"type": "integer"},
"data": {
"type": "string",
"contentEncoding": "base64"
},
"is_dense": {"type": "boolean"}
},
"required": [
"header","height","width","fields",
"is_bigendian","point_step","row_step",
"data","is_dense"
]
}
}
}
# Mapping of ROS primitive types to JSON schema types
TYPE_MAPPING = {
"bool": {"type": "boolean"},
"int8": {"type": "integer", "minimum": -128, "maximum": 127},
"uint8": {"type": "integer", "minimum": 0, "maximum": 255},
"int16": {"type": "integer", "minimum": -32768, "maximum": 32767},
"uint16": {"type": "integer", "minimum": 0, "maximum": 65535},
"int32": {"type": "integer", "minimum": -2147483648, "maximum": 2147483647},
"uint32": {"type": "integer", "minimum": 0, "maximum": 4294967295},
"int64": {"type": "integer"},
"uint64": {"type": "integer", "minimum": 0},
"float32": {"type": "number"},
"float64": {"type": "number"},
"string": {"type": "string"},
"char": {"type": "integer", "minimum": 0, "maximum": 255},
"byte": {"type": "integer", "minimum": 0, "maximum": 255},
"time": {
"type": "object",
"properties": {
"sec": {"type": "integer"},
"nsec": {"type": "integer"}
},
"required": ["sec", "nsec"]
},
"duration": {
"type": "object",
"properties": {
"sec": {"type": "integer"},
"nsec": {"type": "integer"}
},
"required": ["sec", "nsec"]
},
}
@dataclass
class TopicInfo:
"""Information about an LCM topic with schema"""
name: str # Base topic name (without schema) for Foxglove
full_topic_name: str # Full LCM topic name including schema annotation
schema_type: str # Schema type (e.g., "sensor_msgs.Image")
schema: dict # JSON schema
channel_id: Optional[ChannelId] = None # Foxglove channel ID
lcm_class: Any = None # LCM message class
package: str = "" # ROS package name
msg_type: str = "" # ROS message type
foxglove_schema_name: str = "" # Schema name in Foxglove format
last_sent_timestamp: float = 0.0 # Time the last message was sent (for throttling)
message_count: int = 0 # Number of messages received
is_high_frequency: bool = False # Flag for topics that send many messages
cache_hash: Optional[int] = None # Hash of the last message (for message deduplication)
rate_limit_ms: int = 0 # Rate limit in milliseconds (0 = no limit)
priority: int = 0 # Message priority (higher = more important)
@dataclass
class LcmMessage:
"""Container for an LCM message"""
topic_info: TopicInfo
data: bytes
receive_time: float
priority: int = 0 # Higher priority will be processed first
def __lt__(self, other):
# Compare based on priority (higher priority comes first)
if not isinstance(other, LcmMessage):
return NotImplemented
return self.priority > other.priority # Reversed for higher priority first
def __gt__(self, other):
if not isinstance(other, LcmMessage):
return NotImplemented
return self.priority < other.priority # Reversed for higher priority first
def __eq__(self, other):
if not isinstance(other, LcmMessage):
return NotImplemented
return self.priority == other.priority
class SchemaGenerator:
"""Generates JSON schemas from ROS message definitions"""
def __init__(self):
self.schema_cache = {}
def generate_schema(self, schema_type):
"""Generate a JSON schema for the given schema type (e.g., 'sensor_msgs.Image')"""
# Check if we have a hardcoded schema for this type
if schema_type in HARDCODED_SCHEMAS:
logger.info(f"Using hardcoded schema for {schema_type}")
return HARDCODED_SCHEMAS[schema_type]["schema"]
# Check if schema is already cached
if schema_type in self.schema_cache:
return self.schema_cache[schema_type]
# Parse schema type to get package and message type
if "." not in schema_type:
raise ValueError(f"Invalid schema type format: {schema_type}")
package, msg_type = schema_type.split(".", 1)
# Find the .msg file
msg_file_path = os.path.join(ROS_MSGS_DIR, package, "msg", f"{msg_type}.msg")
if not os.path.exists(msg_file_path):
raise FileNotFoundError(f"Message file not found: {msg_file_path}")
# Parse the .msg file and generate schema
schema = self._parse_msg_file(msg_file_path, package)
self.schema_cache[schema_type] = schema
return schema
def _parse_msg_file(self, msg_file_path, package_name):
"""Parse a ROS .msg file and create a JSON schema"""
with open(msg_file_path, 'r') as f:
msg_content = f.read()
# Create basic schema structure
schema = {
"type": "object",
"properties": {},
"required": []
}
# Parse each line in the .msg file
for line in msg_content.splitlines():
# Remove comments (anything after #)
if '#' in line:
line = line.split('#', 1)[0]
line = line.strip()
if not line:
continue
# Parse field definition (type field_name)
if ' ' not in line:
continue
parts = line.split(None, 1) # Split on any whitespace
if len(parts) < 2:
continue
field_type, field_name = parts
field_name = field_name.strip() # Ensure no trailing whitespace
# Check if it's an array type
is_array = False
array_size = None
if field_type.endswith('[]'):
is_array = True
field_type = field_type[:-2]
elif '[' in field_type and field_type.endswith(']'):
match = re.match(r'(.*)\[(\d+)\]', field_type)
if match:
field_type = match.group(1)
array_size = int(match.group(2))
is_array = True
# Process the field and add to schema
field_schema = self._convert_type_to_schema(field_type, package_name, is_array, array_size)
if field_schema:
schema["properties"][field_name] = field_schema
schema["required"].append(field_name)
return schema
def _lcm_to_schema(self, topic_name, lcm_class):
"""Dynamically generate a schema from an LCM class"""
schema = {
"type": "object",
"properties": {},
"required": []
}
# Get fields from LCM class
slots = getattr(lcm_class, "__slots__", [])
typenames = getattr(lcm_class, "__typenames__", [])
dimensions = getattr(lcm_class, "__dimensions__", [])
if not slots or len(slots) != len(typenames):
logger.error(f"Cannot generate schema for {topic_name}: missing slots or typenames")
return None
# First identify all length fields
length_fields = {}
for i, field in enumerate(slots):
if field.endswith('_length'):
base_field = field[:-7] # Remove '_length' suffix
length_fields[base_field] = field
# Process each field
for i, (field, typename) in enumerate(zip(slots, typenames)):
# Skip length fields, they're handled implicitly
if field.endswith('_length'):
continue
# Get dimension info if available (for arrays)
dimension = dimensions[i] if i < len(dimensions) else None
is_array = dimension is not None and dimension != [None]
# For known array fields, make sure we're marking them properly
if field in length_fields:
is_array = True
# Get the JSON schema for this field
field_schema = self._lcm_type_to_schema(typename, field, is_array, dimension)
if field_schema:
schema["properties"][field] = field_schema
schema["required"].append(field)
return schema
def _lcm_type_to_schema(self, typename, field, is_array=False, dimension=None):
"""Convert an LCM type to a JSON schema"""
# Check for primitive types
primitive_map = {
"int8_t": {"type": "integer"},
"int16_t": {"type": "integer"},
"int32_t": {"type": "integer"},
"int64_t": {"type": "integer"},
"uint8_t": {"type": "integer", "minimum": 0},
"uint16_t": {"type": "integer", "minimum": 0},
"uint32_t": {"type": "integer", "minimum": 0},
"uint64_t": {"type": "integer", "minimum": 0},
"boolean": {"type": "boolean"},
"bool": {"type": "boolean"}, # Add 'bool' as alias for boolean
"float": {"type": "number"},
"double": {"type": "number"},
"string": {"type": "string"},
"bytes": {"type": "string", "contentEncoding": "base64"}
}
# Special check for arrays with common LCM naming patterns
if field in ['axes', 'buttons']:
is_array = True
if typename in primitive_map:
base_schema = primitive_map[typename]
# Handle array type
if is_array:
# Make sure arrays are properly defined - this is crucial for Foxglove
return {
"type": "array",
"items": base_schema,
"description": f"Array of {typename} values"
}
return base_schema
# Handle complex types
if "." in typename:
# This is a complex type reference, like 'std_msgs.Header'
# For these, we'll create a reference to their schema
if is_array:
return {
"type": "array",
"items": {"type": "object"},
"description": f"Array of {typename} objects"
}
return {"type": "object", "description": f"Object of type {typename}"}
# If we get here, we don't know how to handle the type
logger.warning(f"Unknown LCM type {typename} for field {field}")
if is_array:
return {"type": "array", "items": {"type": "object"}, "description": f"Array of unknown type: {typename}"}
return {"type": "object", "description": f"Unknown type: {typename}"} # Fallback
def _convert_type_to_schema(self, field_type, package_name, is_array=False, array_size=None):
"""Convert a ROS field type to a JSON schema type"""
# Check for primitive types
if field_type in TYPE_MAPPING:
field_schema = dict(TYPE_MAPPING[field_type])
if is_array:
schema = {"type": "array", "items": field_schema}
if array_size is not None:
schema["maxItems"] = array_size
schema["minItems"] = array_size
return schema
return field_schema
# Special case for Header
elif field_type == "Header" or field_type == "std_msgs/Header":
header_schema = {
"type": "object",
"properties": {
"seq": {"type": "integer"},
"stamp": {
"type": "object",
"properties": {
"sec": {"type": "integer"},
"nsec": {"type": "integer"} # Use nanosec instead of nsec for Foxglove compatibility
},
"required": ["sec", "nsec"]
},
"frame_id": {"type": "string"}
},
"required": ["seq", "stamp", "frame_id"]
}
if is_array:
schema = {"type": "array", "items": header_schema}
if array_size is not None:
schema["maxItems"] = array_size
schema["minItems"] = array_size
return schema
return header_schema
# Complex type - could be from another package
else:
# Check if type contains a package name
if "/" in field_type:
pkg, msg = field_type.split("/", 1)
complex_schema_type = f"{pkg}.{msg}"
else:
# Assume it's from the same package
complex_schema_type = f"{package_name}.{field_type}"
try:
# Try to recursively generate schema
complex_schema = self.generate_schema(complex_schema_type)
if is_array:
schema = {"type": "array", "items": complex_schema}
if array_size is not None:
schema["maxItems"] = array_size
schema["minItems"] = array_size
return schema
return complex_schema
except Exception as e:
logger.error(f"Error processing complex type {field_type}: {e}")
# Return a placeholder schema
return {"type": "object", "description": f"Error: could not process type {field_type}"}
class LcmTopicDiscoverer:
"""Discovers LCM topics and their schemas"""
def __init__(self, callback, schema_map=None):
"""
Initialize the topic discoverer
Args:
callback: Function to call when a new topic is discovered
schema_map: Optional dict mapping bare topic names to schema types
"""
self.lc = lcm.LCM()
self.callback = callback
self.topics = set()
self.running = True
self.thread = threading.Thread(target=self._discovery_thread)
self.mutex = threading.Lock()
self.schema_map = schema_map or {}
def start(self):
"""Start the discovery thread"""
self.thread.daemon = True
self.thread.start()
def stop(self):
"""Stop the discovery thread"""
self.running = False
if self.thread.is_alive():
self.thread.join(timeout=2.0) # Wait up to 2 seconds for clean shutdown
def _discovery_thread(self):
"""Thread function for discovering topics"""
# Unfortunately LCM doesn't have built-in topic discovery
# We'll use a special handler to catch all messages and extract topic info
# Subscribe to all messages with a wildcard
self.lc.subscribe(".*", self._on_any_message)
while self.running:
try:
# Handle LCM messages with a timeout
self.lc.handle_timeout(100) # 100ms timeout
except Exception as e:
logger.error(f"Error in LCM discovery: {e}")
def _on_any_message(self, channel, data):
"""Callback for any LCM message during discovery"""
with self.mutex:
if channel not in self.topics:
# New topic found
self.topics.add(channel)
logger.info(f"Discovered new LCM topic: {channel}")
# Special debugging for joint states topic
if "joint_state" in channel.lower():
logger.info(f"Found joint states topic: {channel}")
# Check if the topic has schema information
if "#" in channel:
# Topic already has schema info in the name
try:
logger.info(f"Processing topic with embedded schema: {channel}")
self.callback(channel)
except Exception as e:
logger.error(f"Error processing discovered topic {channel}: {e}")
elif channel in self.schema_map:
# We have schema info in our map
schema_type = self.schema_map[channel]
annotated_channel = f"{channel}#{schema_type}"
try:
logger.info(f"Mapping topic {channel} to {annotated_channel}")
self.callback(annotated_channel)
except Exception as e:
logger.error(f"Error processing mapped topic {channel} with schema {schema_type}: {e}")
else:
# No schema information available
logger.warning(f"No schema information for topic: {channel}")
if "joint_state" in channel.lower():
# Auto-map joint states topic for debugging
schema_type = "sensor_msgs.JointState"
annotated_channel = f"{channel}#{schema_type}"
logger.info(f"Auto-mapping joint states topic: {annotated_channel}")
try:
self.callback(annotated_channel)
except Exception as e:
logger.error(f"Error auto-mapping joint states topic: {e}")
class MessageConverter:
"""Handles conversion of LCM messages to JSON format for Foxglove"""
def __init__(self, debug=False):
self.debug = debug
self.conversion_methods = {
"sensor_msgs.image": self._format_image_msg,
"sensor_msgs.compressedimage": self._format_compressed_image_msg,
"tf2_msgs.tfmessage": self._format_tf_msg,
"sensor_msgs.jointstate": self._format_joint_state_msg,
# Fix case sensitivity for JointState message type
"sensor_msgs.JointState": self._format_joint_state_msg,
"sensor_msgs.pointcloud2": self._format_pointcloud2_msg,
"sensor_msgs.PointCloud2": self._format_pointcloud2_msg,
}
# Cache for previously converted messages
self.conversion_cache = {}
# Stats for conversion timing
self.conversion_times = defaultdict(list)
def convert_message(self, topic_info, msg):
"""Convert an LCM message to Foxglove format"""
# Try with exact type first
if topic_info.schema_type in self.conversion_methods:
converter = self.conversion_methods[topic_info.schema_type]
else:
# Fall back to case-insensitive check
schema_type_lower = topic_info.schema_type.lower()
if schema_type_lower in self.conversion_methods:
converter = self.conversion_methods[schema_type_lower]
else:
# Log when we don't have a specialized converter
logger.debug(f"No specialized converter for {topic_info.schema_type}, using generic conversion")
return self._lcm_to_dict(msg)
# Convert using the specialized converter
try:
start_time = time.time()
result = converter(msg, topic_info)
elapsed = time.time() - start_time
# Update stats
schema_key = topic_info.schema_type.lower() # Use lowercase for stats
self.conversion_times[schema_key].append(elapsed)
if len(self.conversion_times[schema_key]) > 100:
self.conversion_times[schema_key] = self.conversion_times[schema_key][-100:]
# Log timing for slow conversions
if elapsed > 0.1: # More than 100ms
avg_time = sum(self.conversion_times[schema_key]) / len(self.conversion_times[schema_key])
logger.warning(f"Slow conversion for {topic_info.name}: {elapsed:.3f}s (avg: {avg_time:.3f}s)")
return result
except Exception as e:
logger.error(f"Error in converter for {topic_info.schema_type}, falling back to generic: {e}")
return self._lcm_to_dict(msg)
def _lcm_to_dict(self, msg):
"""Convert an LCM message to a dictionary"""
if isinstance(msg, (int, float, bool, str, type(None))):
return msg
elif isinstance(msg, bytes):
# Convert bytes to base64
return base64.b64encode(msg).decode("ascii")
elif isinstance(msg, list) or isinstance(msg, tuple):
# Handle array case - this is the key change
# For foxglove visualization, arrays need to have proper format
# Return as a simple array of converted values rather than an object with numeric keys
return [self._lcm_to_dict(item) for item in msg]
elif isinstance(msg, dict):
return {k: self._lcm_to_dict(v) for k, v in msg.items()}
elif isinstance(msg, np.ndarray):
# Handle numpy arrays - convert to list first
return [self._lcm_to_dict(item) for item in msg.tolist()]
else:
# Try to convert a custom LCM message object
result = {}
# First gather all attributes and their types
attribute_info = {}
length_fields = {}
# First pass: identify all length fields and their values
for attr in dir(msg):
if attr.startswith('_') or callable(getattr(msg, attr)):
continue
# Check for length fields
if attr.endswith('_length'):
base_attr = attr[:-7] # Remove '_length' suffix
length_value = getattr(msg, attr)
length_fields[base_attr] = length_value
# Second pass: process all attributes
for attr in dir(msg):
if attr.startswith('_') or callable(getattr(msg, attr)) or attr.endswith('_length'):
continue
value = getattr(msg, attr)
# Handle arrays with corresponding length fields
if attr in length_fields and (isinstance(value, list) or isinstance(value, tuple)):
length = length_fields[attr]
if isinstance(length, int) and length >= 0 and length <= len(value):
# Truncate array to specified length
value = value[:length]
# Recursively convert the value
try:
result[attr] = self._lcm_to_dict(value)
except Exception as e:
logger.error(f"Error converting attribute {attr}: {e}")
result[attr] = None
return result
def _get_header_dict(self, header):
"""Extract a properly formatted header dictionary from a ROS Header"""
try:
# Standard ROS header has seq, stamp, and frame_id
stamp = {}
# Handle stamp which might be a struct or separate sec/nsec fields
if hasattr(header, "stamp") and not isinstance(header.stamp, (int, float)):
if hasattr(header.stamp, "sec") and hasattr(header.stamp, "nsec"):
stamp = {
"sec": int(header.stamp.sec) if hasattr(header.stamp, "sec") else 0,
"nsec": int(header.stamp.nsec) if hasattr(header.stamp, "nsec") else 0
}
else:
# Handle builtin_interfaces/Time which might use nanosec instead of nsec
stamp = {
"sec": int(header.stamp.sec) if hasattr(header.stamp, "sec") else 0,
"nsec": int(
header.stamp.nanosec if hasattr(header.stamp, "nanosec")
else (header.stamp.nsec if hasattr(header.stamp, "nsec") else 0)
)
}
elif hasattr(header, "sec") and hasattr(header, "nsec"):
# Some messages have sec/nsec directly in the header
stamp = {
"sec": int(header.sec),
"nsec": int(header.nsec)
}
else:
# Default to current time if no valid stamp found
now = time.time()
stamp = {
"sec": int(now),
"nsec": int((now % 1) * 1e9)
}
# Ensure frame_id is a string (convert bytes if needed)
frame_id = header.frame_id if hasattr(header, "frame_id") else ""
if isinstance(frame_id, bytes):
frame_id = frame_id.decode('utf-8', errors='replace')
return {
"seq": int(header.seq) if hasattr(header, "seq") else 0,
"stamp": stamp,
"frame_id": frame_id
}
except Exception as e:
logger.error(f"Error formatting header: {e}")
# Return a minimal valid header
now = time.time()
return {
"seq": 0,
"stamp": {"sec": int(now), "nsec": int((now % 1) * 1e9)},
"frame_id": ""
}
def _format_image_msg(self, msg, topic_info=None):
"""Format a sensor_msgs/Image message for Foxglove"""
try:
# Get header
header = self._get_header_dict(msg.header)
# For Image messages, we need to encode the data as base64
data_length = getattr(msg, "data_length", len(msg.data) if hasattr(msg, "data") else 0)
# Convert potentially incompatible encoding
encoding = msg.encoding if hasattr(msg, "encoding") and msg.encoding else "rgb8"
# Foxglove might need rgb8 instead of bgr8
if encoding.lower() == "bgr8":
# Change the encoding string to rgb8
encoding = "rgb8"
if hasattr(msg, "data") and data_length > 0:
# Get image data as bytes
image_data_bytes = msg.data[:data_length]
# Convert to base64
image_data = base64.b64encode(image_data_bytes).decode("ascii")
else:
# If no data, return empty string
image_data = ""
# Return properly formatted message dict for Foxglove
return {
"header": header,
"height": int(msg.height),
"width": int(msg.width),
"encoding": encoding,
"is_bigendian": bool(msg.is_bigendian),
"step": int(msg.step),
"data": image_data
}
except Exception as e:
logger.error(f"Error formatting Image message: {e}")
return self._lcm_to_dict(msg) # Fallback to generic conversion
def _format_compressed_image_msg(self, msg, topic_info=None):
"""Format a sensor_msgs/CompressedImage message for Foxglove"""
try:
# Get header
header = self._get_header_dict(msg.header)
# For CompressedImage messages, format must be jpg or png
image_format = msg.format.lower() if hasattr(msg, "format") and msg.format else "jpeg"
# Convert data to base64
data_length = getattr(msg, "data_length", len(msg.data) if hasattr(msg, "data") else 0)
if hasattr(msg, "data") and data_length > 0:
# Get image data as bytes
image_data_bytes = msg.data[:data_length]
# Convert to base64
image_data = base64.b64encode(image_data_bytes).decode("ascii")
else:
# If no data, return empty string
image_data = ""
# Return properly formatted message for Foxglove
return {
"header": header,
"format": image_format,
"data": image_data
}
except Exception as e:
logger.error(f"Error formatting CompressedImage message: {e}")
return self._lcm_to_dict(msg) # Fallback to generic conversion
def _format_tf_msg(self, msg, topic_info=None):
"""Format a tf2_msgs/TFMessage for Foxglove"""
try:
# Get the transforms array with correct length
transforms_length = getattr(msg, "transforms_length", 0)
transforms = []
# Process each transform in the array
if hasattr(msg, "transforms") and transforms_length > 0:
for i in range(min(transforms_length, len(msg.transforms))):
transform = msg.transforms[i]
transform_dict = self._format_transform_stamped(transform)
if transform_dict:
transforms.append(transform_dict)
# Return properly formatted message
return {"transforms": transforms}
except Exception as e:
logger.error(f"Error formatting TFMessage: {e}")
return {"transforms": []} # Return empty transforms array on error
def _format_transform_stamped(self, transform):
"""Format a geometry_msgs/TransformStamped message for Foxglove"""
try:
# Format header
header = self._get_header_dict(transform.header)
# Check for required attributes
if not hasattr(transform, "transform"):
logger.warning("Warning: TransformStamped missing 'transform' attribute")
return None
if not hasattr(transform.transform, "translation") or not hasattr(transform.transform, "rotation"):
logger.warning("Warning: Transform missing translation or rotation")
return None
# Format translation (defaulting to zeros if missing)
translation = {
"x": float(getattr(transform.transform.translation, "x", 0.0)),
"y": float(getattr(transform.transform.translation, "y", 0.0)),
"z": float(getattr(transform.transform.translation, "z", 0.0))
}
# Format rotation (defaulting to identity if missing)
rotation = {
"x": float(getattr(transform.transform.rotation, "x", 0.0)),
"y": float(getattr(transform.transform.rotation, "y", 0.0)),
"z": float(getattr(transform.transform.rotation, "z", 0.0)),
"w": float(getattr(transform.transform.rotation, "w", 1.0))
}
# Get child frame id
child_frame_id = transform.child_frame_id
if isinstance(child_frame_id, bytes):
child_frame_id = child_frame_id.decode('utf-8', errors='replace')
# Return formatted transform (exactly as Foxglove TF expects)
return {
"header": header,
"child_frame_id": child_frame_id,
"transform": {
"translation": translation,
"rotation": rotation
}
}
except Exception as e:
logger.error(f"Error formatting TransformStamped: {e}")
return None
def _format_joint_state_msg(self, msg, topic_info=None):
"""Format a sensor_msgs/JointState message for Foxglove"""
try:
# Debug log when processing a joint state
logger.info(f"Processing JointState message from {topic_info.name if topic_info else 'unknown'}")
# Format the header
header = self._get_header_dict(msg.header)
# Get array lengths and print debug info
name_length = getattr(msg, "name_length", 0)
position_length = getattr(msg, "position_length", 0)
velocity_length = getattr(msg, "velocity_length", 0)
effort_length = getattr(msg, "effort_length", 0)
logger.info(f"JointState arrays: names={name_length}, positions={position_length}, velocities={velocity_length}, efforts={effort_length}")
# Check if message has required attributes
if not hasattr(msg, "name") or not hasattr(msg, "position"):
logger.warning(f"JointState message missing required attributes name or position")
# Log available attributes
logger.warning(f"JointState available attributes: {[a for a in dir(msg) if not a.startswith('_')]}")
# Format arrays with correct lengths
names = msg.name[:name_length] if hasattr(msg, "name") and name_length > 0 else []
positions = msg.position[:position_length] if hasattr(msg, "position") and position_length > 0 else []
velocities = msg.velocity[:velocity_length] if hasattr(msg, "velocity") and velocity_length > 0 else []
efforts = msg.effort[:effort_length] if hasattr(msg, "effort") and effort_length > 0 else []
# Convert name list items from bytes to strings if needed
names = [name.decode('utf-8', errors='replace') if isinstance(name, bytes) else name for name in names]