"""Convert a GREENBOT v1 ROS 1 bag into a v2 ROS 2 MCAP bag (split files, zstd chunk compression). Usage: convert_v2.py [--split-gb 8] calib_dir must contain: greenbot_tf_static_v2.yaml, stereo_left.yaml, stereo_right.yaml, greenbot_timing_v2.yaml """ import shutil import subprocess import sys from pathlib import Path import numpy as np import yaml from rosbags.interfaces import Qos, QosDurability, QosHistory, QosLiveliness, QosReliability, QosTime from rosbags.rosbag1 import Reader from rosbags.rosbag2 import CompressionFormat, CompressionMode, StoragePlugin, Writer from rosbags.typesys import Stores, get_typestore IN = Path(sys.argv[1]) OUT = Path(sys.argv[2]) CAL = Path(sys.argv[3]) SPLIT_BYTES = float(sys.argv[sys.argv.index("--split-gb") + 1] if "--split-gb" in sys.argv else 8) * 1e9 * 1.6 # ~uncompressed SEQ = IN.stem MAX_SECONDS = float(sys.argv[sys.argv.index("--max-seconds") + 1]) if "--max-seconds" in sys.argv else None TS1 = get_typestore(Stores.ROS1_NOETIC) TS2 = get_typestore(Stores.ROS2_HUMBLE) # message definitions identical in Humble/Jazzy for the types used here T2 = TS2.types tf_yaml = yaml.safe_load(open(CAL / "greenbot_tf_static_v2.yaml")) cam_yaml = {s: yaml.safe_load(open(CAL / f"stereo_{s}.yaml")) for s in ("left", "right")} timing = yaml.safe_load(open(CAL / "greenbot_timing_v2.yaml")) tm = timing["sequences"][SEQ] SRC_TO_OUT = {"/Velodyne1_SCAN": ["/velodyne/points"], "/ouster/points": ["/ouster/points"], "/ouster/imu": ["/ouster/imu"], "/ouster/reflec_image": ["/ouster/reflec_image"], "/stereo_camera/left/image_raw": ["/stereo_camera/left/image_raw", "/stereo_camera/left/camera_info"], "/stereo_camera/right/image_raw": ["/stereo_camera/right/image_raw", "/stereo_camera/right/camera_info"]} CAM_FRAME = {"left": "stereo_left_optical_frame", "right": "stereo_right_optical_frame"} VELO_ORIGIN = np.array(timing["velodyne_origin_in_legacy_base_link"]) def Time(t): sec = int(np.floor(t)) return T2["builtin_interfaces/msg/Time"](sec=sec, nanosec=int(round((t - sec) * 1e9)) % 1000000000) def Header(t, frame): return T2["std_msgs/msg/Header"](stamp=Time(t), frame_id=frame) def stamp1(m): return m.header.stamp.sec + m.header.stamp.nanosec * 1e-9 def ouster_time(h): """Ouster sensor clock -> v2 time base (PC clock of the camera driver).""" return h + tm["ouster_offset"] + tm["ouster_slope"] * (h - tm["ouster_h0"]) def tf_static_msg(t): trs = [] for tr in tf_yaml["transforms"]: x, y, z = tr["translation"] qx, qy, qz, qw = tr["rotation_xyzw"] trs.append(T2["geometry_msgs/msg/TransformStamped"]( header=Header(t, tr["parent"]), child_frame_id=tr["child"], transform=T2["geometry_msgs/msg/Transform"]( translation=T2["geometry_msgs/msg/Vector3"](x=x, y=y, z=z), rotation=T2["geometry_msgs/msg/Quaternion"](x=qx, y=qy, z=qz, w=qw)))) return T2["tf2_msgs/msg/TFMessage"](transforms=trs) def camera_info(side, t): c = cam_yaml[side] return T2["sensor_msgs/msg/CameraInfo"]( header=Header(t, CAM_FRAME[side]), height=c["image_height"], width=c["image_width"], distortion_model=c["distortion_model"], d=np.array(c["distortion_coefficients"]["data"], float), k=np.array(c["camera_matrix"]["data"], float), r=np.array(c["rectification_matrix"]["data"], float), p=np.array(c["projection_matrix"]["data"], float), binning_x=0, binning_y=0, roi=T2["sensor_msgs/msg/RegionOfInterest"](x_offset=0, y_offset=0, height=0, width=0, do_rectify=False)) def PF(name, offset, datatype): return T2["sensor_msgs/msg/PointField"](name=name, offset=offset, datatype=datatype, count=1) def velodyne_cloud(m, t_scan_start, period): P = np.frombuffer(m.data, " SPLIT_BYTES and topic != "/tf_static"): if self.t_first is None: self.t_first = t_ns * 1e-9 self._open(t_ns) data = TS2.serialize_cdr(msg, OUT_TOPICS[topic][0]) self.w.write(self.conn[topic], t_ns, data) self.bytes += len(data) def close(self): if self.w: self.w.close() with Reader(IN) as r_: present = {c_.topic for c_ in r_.connections if c_.msgcount > 0} keep = {"/tf_static"} | {o for src, outs in SRC_TO_OUT.items() if src in present for o in outs} OUT_TOPICS = {k: v for k, v in OUT_TOPICS.items() if k in keep} print("output topics:", sorted(OUT_TOPICS)) W = SplitWriter() counts = {} last_velo_hdr = None with Reader(IN) as r: cons = [c for c in r.connections if c.topic != "/tf_static"] for c, t_ns, raw in r.messages(connections=cons): if MAX_SECONDS is not None and t_ns > r.start_time + MAX_SECONDS * 1e9: break m = TS1.deserialize_ros1(raw, c.msgtype) tp = c.topic if tp == "/Velodyne1_SCAN": h = stamp1(m) period = 0.1 if last_velo_hdr is None or not (0.08 < h - last_velo_hdr < 0.12) else h - last_velo_hdr last_velo_hdr = h out_tp, msg = "/velodyne/points", velodyne_cloud(m, h + tm["velodyne_dt"], period) elif tp == "/ouster/points": out_tp, msg = tp, convert_cloud(m, ouster_time(stamp1(m)), "os_sensor") elif tp == "/ouster/imu": h = stamp1(m) out_tp, msg = tp, convert_imu(m, ouster_time(h)) elif tp == "/ouster/reflec_image": out_tp, msg = tp, convert_image(m, ouster_time(stamp1(m)), "os_lidar") elif tp.startswith("/stereo_camera/") and tp.endswith("image_raw"): side = tp.split("/")[2] t = stamp1(m) + tm["camera_dt"] out_tp, msg = tp, convert_image(m, t, CAM_FRAME[side]) W.write(out_tp, t_ns, msg) counts[out_tp] = counts.get(out_tp, 0) + 1 out_tp, msg = f"/stereo_camera/{side}/camera_info", camera_info(side, t) elif tp.endswith("camera_info"): continue # v1 camera_info is empty; regenerated next to each image else: print(f"skipping unexpected topic {tp}") continue W.write(out_tp, t_ns, msg) counts[out_tp] = counts.get(out_tp, 0) + 1 W.close() # gather the split files into one rosbag2 directory and let rosbag2 write the metadata for i, d in enumerate(sorted(tmp.glob("part_*"), key=lambda p: int(p.name.split("_")[1]))): f = next(d.glob("*.mcap")) shutil.move(str(f), OUT / f"{SEQ}_{i}.mcap") shutil.rmtree(tmp) subprocess.run(["bash", "-c", f"source /opt/ros/jazzy/setup.bash && ros2 bag reindex '{OUT}' -s mcap"], check=True) print("messages written:", counts)