diff --git a/BuildInstructions.md b/BuildInstructions.md
index e9d820c0..289602ed 100644
--- a/BuildInstructions.md
+++ b/BuildInstructions.md
@@ -505,6 +505,68 @@ ros2 run waybionic_teleop mks_drive_sim --interface socketcan --channel vcan0
In a second terminal, launch with `drive_interface:=socketcan drive_channel:=vcan0`
and zero as above. CI runs `waybionic_teleop/test/test_can_drives.py` over `vcan0`.
+## Doctor View Camera
+
+Until the doctor's camera is chosen, a USB webcam stands in for it. `camera_bridge`
+captures the webcam on the computer it is plugged into and sends JPEG frames to the
+ground station, each stamped with its capture time. The ground station publishes
+them on `/doctor_view/left/image_raw/compressed` with `/doctor_view/left/camera_info`.
+The diagnostics panel's `camera.doctor_view` entry shows the frame rate and the delay
+from capture to arrival: mean, minimum, maximum and jitter.
+
+**Windows (Docker):** first install OpenCV for the bridge with
+`python -m pip install opencv-python`. Python 3.13 or newer is recommended for the
+bridge: on Windows, older versions read the clock in 15.6 ms steps, which can add up
+to 15.6 ms to the measured delay. Then start the ground station with the camera
+port, from the repository root:
+
+```powershell
+& "$env:LOCALAPPDATA\Programs\DockerDesktop\resources\bin\docker.exe" compose run --rm --build -p 127.0.0.1:47310:47310 wslg ros2 launch waybionic_bringup ground_station.launch.py camera:=true camera_bind:=0.0.0.0
+```
+
+In a second PowerShell window, start the bridge from the repository root:
+
+```powershell
+cd waybionic_camera
+python -m waybionic_camera.camera_bridge
+```
+
+Finally, tick **Doctor View** in RViz's Displays panel.
+
+**Bridge options:**
+
+- `--camera 1` uses another camera.
+- `--width 1280 --height 720` changes the resolution.
+- On Windows, `--backend dshow` often opens a webcam faster.
+
+**Linux (native ROS):** run
+`ros2 launch waybionic_bringup ground_station.launch.py camera:=true`. Then, from
+`waybionic_camera`, run `python3 -m waybionic_camera.camera_bridge`; it needs
+`python3-opencv`.
+
+**Measuring the delay.**
+
+- **What the reported delay covers:** from when OpenCV hands the bridge a frame to
+ when the frame reaches ROS. It leaves out the time spent inside the camera and on
+ the display.
+- **Full delay:** point the camera at a millisecond stopwatch on the same screen as
+ RViz, then compare the live stopwatch with the one in the Doctor View.
+- **Logging each frame:** add `camera_log:=` with a CSV path to the launch command to
+ log every frame's capture time, arrival time and delay. `frame` counts the frames
+ that arrived, so a dropped frame shows as a longer gap in `captured_s`. With native
+ ROS, any path works, such as `camera_log:=/tmp/camera.csv`. In Docker, `--rm`
+ deletes the container and its files when it stops, so log to a Windows folder
+ mounted into the container instead. This writes `camera.csv` to `camera-logs` in
+ your user folder:
+
+ ```powershell
+ & "$env:LOCALAPPDATA\Programs\DockerDesktop\resources\bin\docker.exe" compose run --rm --build -p 127.0.0.1:47310:47310 -v "$HOME\camera-logs:/camera-logs" wslg ros2 launch waybionic_bringup ground_station.launch.py camera:=true camera_bind:=0.0.0.0 camera_log:=/camera-logs/camera.csv
+ ```
+
+- **Clocks:** the bridge stamps frames with the camera computer's clock, so the two
+ clocks must agree. Docker Desktop keeps them within a few milliseconds. If the
+ delay looks negative or keeps growing after the PC sleeps, restart Docker Desktop.
+
## Native Ubuntu Setup for RViz
Only follow this section if you need ROS and RViz outside the container. It is
diff --git a/waybionic_bringup/launch/ground_station.launch.py b/waybionic_bringup/launch/ground_station.launch.py
index 1a01bda1..b7d24fb2 100644
--- a/waybionic_bringup/launch/ground_station.launch.py
+++ b/waybionic_bringup/launch/ground_station.launch.py
@@ -3,8 +3,9 @@
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
-from launch.actions import DeclareLaunchArgument, OpaqueFunction
+from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription, OpaqueFunction
from launch.conditions import IfCondition
+from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import (
AndSubstitution, Command, EqualsSubstitution, LaunchConfiguration, NotSubstitution,
OrSubstitution)
@@ -99,6 +100,18 @@ def generate_launch_description():
'use_sim_time', default_value='false',
description='Use simulation time')
+ camera_arg = DeclareLaunchArgument(
+ 'camera', default_value='false',
+ description='Show the doctor view sent by camera_bridge and report its delay')
+
+ camera_bind_arg = DeclareLaunchArgument(
+ 'camera_bind', default_value='127.0.0.1',
+ description='Address the camera receiver listens on (0.0.0.0 inside Docker)')
+
+ camera_log_arg = DeclareLaunchArgument(
+ 'camera_log', default_value='',
+ description='CSV file for each camera frame: capture time, arrival time and delay')
+
launch_rviz_arg = DeclareLaunchArgument(
'launch_rviz', default_value='true',
description='Launch RViz (set false for headless validation)')
@@ -203,7 +216,19 @@ def generate_launch_description():
]
)
- # Demo mode and teleop report on /diagnostics, so the panel listens to live diagnostics.
+ camera = LaunchConfiguration('camera')
+ camera_launch = IncludeLaunchDescription(
+ PythonLaunchDescriptionSource(os.path.join(
+ get_package_share_directory('waybionic_camera'), 'launch', 'camera.launch.py')),
+ condition=IfCondition(camera),
+ launch_arguments={
+ 'bind_address': LaunchConfiguration('camera_bind'),
+ 'log_csv': LaunchConfiguration('camera_log'),
+ 'diagnostics_topic': LaunchConfiguration('diagnostics_topic'),
+ }.items()
+ )
+
+ # Demo mode, teleop and the camera report on /diagnostics, so the panel listens to them.
rviz_node = Node(
package='rviz2', executable='rviz2', name='rviz2', output='screen',
arguments=['-d', LaunchConfiguration('rvizconfig')],
@@ -211,7 +236,8 @@ def generate_launch_description():
parameters=[
{'use_sim_time': LaunchConfiguration('use_sim_time')},
{'use_mock_diagnostics': AndSubstitution(
- LaunchConfiguration('use_mock_diagnostics'), NotSubstitution(simulated_joints))},
+ LaunchConfiguration('use_mock_diagnostics'),
+ NotSubstitution(OrSubstitution(simulated_joints, camera)))},
{'diagnostics_topic': LaunchConfiguration('diagnostics_topic')}
]
)
@@ -220,8 +246,9 @@ def generate_launch_description():
model_arg, use_mock_diag_arg, diag_topic_arg, start_temp_pub_arg,
use_jsp_gui_arg, demo_mode_arg, demo_speed_arg, teleop_arg, drive_interface_arg,
drive_channel_arg, joy_source_arg,
- joy_udp_bind_arg, joy_udp_port_arg, follow_camera_arg, use_sim_time_arg,
+ joy_udp_bind_arg, joy_udp_port_arg, follow_camera_arg, use_sim_time_arg, camera_arg,
+ camera_bind_arg, camera_log_arg,
launch_rviz_arg, rviz_config_arg, file_check, rsp_node, jsp_gui_node, joint_demo_node,
joy_node, joy_udp_node, teleop_node, drives_node, camera_follower_node,
- temp_diag_pub_node, rviz_node
+ temp_diag_pub_node, camera_launch, rviz_node
])
diff --git a/waybionic_bringup/package.xml b/waybionic_bringup/package.xml
index 70a454a4..8e6d86ed 100644
--- a/waybionic_bringup/package.xml
+++ b/waybionic_bringup/package.xml
@@ -27,6 +27,7 @@
tf2_ros_py
joy
waybionic_teleop
+ waybionic_camera
ament_cmake_ros
ament_lint_auto
diff --git a/waybionic_bringup/rviz/waybionic_unified.rviz b/waybionic_bringup/rviz/waybionic_unified.rviz
index d1ab3460..47796106 100644
--- a/waybionic_bringup/rviz/waybionic_unified.rviz
+++ b/waybionic_bringup/rviz/waybionic_unified.rviz
@@ -125,6 +125,20 @@ Visualization Manager:
Reliability Policy: Reliable
Value: /waybionic/teleop/markers
Value: true
+ - Class: rviz_default_plugins/Image
+ Enabled: false
+ Max Value: 1
+ Median window: 5
+ Min Value: 0
+ Name: Doctor View
+ Normalize Range: true
+ Topic:
+ Depth: 5
+ Durability Policy: Volatile
+ History Policy: Keep Last
+ Reliability Policy: Best Effort
+ Value: /doctor_view/left/image_raw/compressed
+ Value: false
Enabled: true
Global Options:
Background Color: 48; 48; 48
diff --git a/waybionic_camera/launch/camera.launch.py b/waybionic_camera/launch/camera.launch.py
new file mode 100644
index 00000000..1068abc2
--- /dev/null
+++ b/waybionic_camera/launch/camera.launch.py
@@ -0,0 +1,35 @@
+from launch import LaunchDescription
+from launch.actions import DeclareLaunchArgument
+from launch.substitutions import LaunchConfiguration
+from launch_ros.actions import Node
+from launch_ros.parameter_descriptions import ParameterValue
+
+
+def generate_launch_description():
+ return LaunchDescription([
+ DeclareLaunchArgument(
+ 'bind_address', default_value='127.0.0.1',
+ description='Address camera_receiver listens on (0.0.0.0 inside Docker)'),
+ DeclareLaunchArgument(
+ 'port', default_value='47310', description='TCP port for camera_bridge'),
+ DeclareLaunchArgument(
+ 'log_csv', default_value='',
+ description='Log each frame: capture time, arrival time and delay (CSV path)'),
+ DeclareLaunchArgument(
+ 'diagnostics_topic', default_value='/diagnostics',
+ description='Diagnostics topic for the frame rate and delay'),
+ Node(
+ package='waybionic_camera', executable='camera_receiver', name='camera_receiver',
+ output='screen',
+ parameters=[{
+ 'bind_address': LaunchConfiguration('bind_address'),
+ 'port': ParameterValue(LaunchConfiguration('port'), value_type=int),
+ }]),
+ Node(
+ package='waybionic_camera', executable='latency_monitor',
+ name='camera_latency_monitor',
+ parameters=[{
+ 'log_csv': ParameterValue(LaunchConfiguration('log_csv'), value_type=str),
+ 'diagnostics_topic': LaunchConfiguration('diagnostics_topic'),
+ }]),
+ ])
diff --git a/waybionic_camera/package.xml b/waybionic_camera/package.xml
new file mode 100644
index 00000000..13560c83
--- /dev/null
+++ b/waybionic_camera/package.xml
@@ -0,0 +1,25 @@
+
+
+
+ waybionic_camera
+ 0.1.0
+ Doctor view camera feed for the ground station, with frame delay and rate monitoring.
+ Yassin Soliman
+ Apache-2.0
+
+ diagnostic_msgs
+ rclpy
+ sensor_msgs
+
+ compressed_image_transport
+ launch
+ launch_ros
+
+ ament_flake8
+ ament_pep257
+ python3-pytest
+
+
+ ament_python
+
+
diff --git a/waybionic_camera/resource/waybionic_camera b/waybionic_camera/resource/waybionic_camera
new file mode 100644
index 00000000..e69de29b
diff --git a/waybionic_camera/setup.cfg b/waybionic_camera/setup.cfg
new file mode 100644
index 00000000..d9638398
--- /dev/null
+++ b/waybionic_camera/setup.cfg
@@ -0,0 +1,4 @@
+[develop]
+script_dir=$base/lib/waybionic_camera
+[install]
+install_scripts=$base/lib/waybionic_camera
diff --git a/waybionic_camera/setup.py b/waybionic_camera/setup.py
new file mode 100644
index 00000000..59d9fa01
--- /dev/null
+++ b/waybionic_camera/setup.py
@@ -0,0 +1,32 @@
+from glob import glob
+import os
+
+from setuptools import find_packages, setup
+
+package_name = 'waybionic_camera'
+
+setup(
+ name=package_name,
+ version='0.1.0',
+ packages=find_packages(exclude=['test']),
+ data_files=[
+ ('share/ament_index/resource_index/packages', ['resource/' + package_name]),
+ ('share/' + package_name, ['package.xml']),
+ (os.path.join('share', package_name, 'launch'), glob('launch/*.launch.py')),
+ ],
+ install_requires=['setuptools'],
+ zip_safe=True,
+ maintainer='Yassin Soliman',
+ maintainer_email='solimanyassin@gmail.com',
+ description=(
+ 'Doctor view camera feed for the ground station, with frame delay and rate monitoring.'
+ ),
+ license='Apache-2.0',
+ tests_require=['pytest'],
+ entry_points={
+ 'console_scripts': [
+ 'camera_receiver = waybionic_camera.camera_receiver:main',
+ 'latency_monitor = waybionic_camera.latency_monitor:main',
+ ],
+ },
+)
diff --git a/waybionic_camera/test/test_camera_nodes.py b/waybionic_camera/test/test_camera_nodes.py
new file mode 100644
index 00000000..214670af
--- /dev/null
+++ b/waybionic_camera/test/test_camera_nodes.py
@@ -0,0 +1,177 @@
+"""Frames sent like camera_bridge sends them come out as stamped images and a delay report."""
+
+import socket
+import threading
+import time
+
+from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus
+import pytest
+import rclpy
+from rclpy.executors import SingleThreadedExecutor
+from rclpy.parameter import Parameter
+from sensor_msgs.msg import CameraInfo, CompressedImage
+
+from waybionic_camera.camera_receiver import CameraReceiver, READ_TIMEOUT_S
+from waybionic_camera.frames import pack
+from waybionic_camera.latency_monitor import LatencyMonitor
+
+NAMESPACE = '/camera_test'
+DIAGNOSTICS = f'{NAMESPACE}/diagnostics'
+DELAY_NS = 20_000_000
+JPEG = b'\xff\xd8frame\xff\xd9'
+
+
+@pytest.fixture
+def nodes():
+ context = rclpy.Context()
+ rclpy.init(context=context)
+ receiver = CameraReceiver(context=context, namespace=NAMESPACE, parameter_overrides=[
+ Parameter('port', value=0)])
+ monitor = LatencyMonitor(context=context, namespace=NAMESPACE, parameter_overrides=[
+ Parameter('diagnostics_topic', value=DIAGNOSTICS)])
+ collector = rclpy.create_node('camera_test_collector', context=context)
+ received = {'images': [], 'infos': [], 'diagnostics': []}
+ collector.create_subscription(
+ CompressedImage, f'{NAMESPACE}/doctor_view/left/image_raw/compressed',
+ received['images'].append, 50)
+ collector.create_subscription(CameraInfo, f'{NAMESPACE}/doctor_view/left/camera_info',
+ received['infos'].append, 50)
+ collector.create_subscription(DiagnosticArray, DIAGNOSTICS, received['diagnostics'].append,
+ 10)
+ executor = SingleThreadedExecutor(context=context)
+ for node in (receiver, monitor, collector):
+ executor.add_node(node)
+ spinner = threading.Thread(target=executor.spin, daemon=True)
+ spinner.start()
+ yield receiver, received
+ executor.shutdown()
+ receiver.close()
+ monitor.close()
+ for node in (receiver, monitor, collector):
+ node.destroy_node()
+ rclpy.try_shutdown(context=context)
+ spinner.join(timeout=5.0)
+
+
+@pytest.fixture
+def monitor(monkeypatch):
+ context = rclpy.Context()
+ rclpy.init(context=context)
+ node = LatencyMonitor(context=context, namespace=NAMESPACE, parameter_overrides=[
+ Parameter('diagnostics_topic', value=DIAGNOSTICS)])
+ reports = []
+ monkeypatch.setattr(node.publisher, 'publish', reports.append)
+ yield node, reports
+ node.destroy_node()
+ rclpy.try_shutdown(context=context)
+
+
+def wait_for(done, seconds):
+ deadline = time.monotonic() + seconds
+ while not done() and time.monotonic() < deadline:
+ time.sleep(0.05)
+ return done()
+
+
+def stream(sender, stamps, done, seconds):
+ """Send a frame every 20 ms, as a live bridge does, until done() or the time runs out."""
+ deadline = time.monotonic() + seconds
+ while not done() and time.monotonic() < deadline:
+ stamps.append(time.time_ns() - DELAY_NS)
+ sender.sendall(pack(len(stamps), stamps[-1], 640, 480, JPEG))
+ time.sleep(0.02)
+ return done()
+
+
+def statuses(messages, level):
+ return [status for message in messages for status in message.status
+ if status.level == level]
+
+
+def test_bridge_frames_become_stamped_images_and_a_delay_report(nodes):
+ receiver, received = nodes
+ # Give discovery a moment so the first frames are not lost.
+ time.sleep(1.0)
+ stamps = []
+ with socket.create_connection(('127.0.0.1', receiver.port)) as sender:
+ assert stream(sender, stamps, lambda: len(received['images']) >= 35, 5.0)
+ # Keep streaming until a report covers those frames.
+ covered = len(received['diagnostics'])
+ assert stream(sender, stamps, lambda: statuses(
+ received['diagnostics'][covered:], DiagnosticStatus.OK), 3.0)
+ first = received['images'][0]
+ assert first.format == 'jpeg' and bytes(first.data) == JPEG
+ stamp = first.header.stamp.sec * 1_000_000_000 + first.header.stamp.nanosec
+ assert stamp in stamps
+ assert first.header.frame_id == 'doctor_view_left_optical_frame'
+ assert (received['infos'][0].width, received['infos'][0].height) == (640, 480)
+
+ report = statuses(received['diagnostics'], DiagnosticStatus.OK)[-1]
+ values = {item.key: item.value for item in report.values}
+ assert 20.0 <= float(values['mean_ms']) < 60.0
+ assert 30.0 < float(values['fps']) < 60.0
+ assert report.name == 'camera.doctor_view' and 'at 640x480' in report.message
+
+ # Once the frames stop, the report warns within a second or two, long before it goes stale.
+ stopped = len(received['diagnostics'])
+ assert wait_for(lambda: any(
+ status.message.startswith('No frame for')
+ for status in statuses(received['diagnostics'][stopped:], DiagnosticStatus.WARN)), 3.0)
+
+
+def test_a_silent_connection_gives_way_to_the_next_bridge(nodes):
+ receiver, received = nodes
+ # A bridge that vanished without closing its connection, then connected again.
+ silent = socket.create_connection(('127.0.0.1', receiver.port))
+ with silent, socket.create_connection(('127.0.0.1', receiver.port)) as sender:
+ sender.sendall(pack(1, time.time_ns(), 640, 480, JPEG))
+ assert wait_for(lambda: received['images'], READ_TIMEOUT_S + 3.0)
+ silent.settimeout(1.0)
+ assert silent.recv(1) == b''
+
+
+def test_close_wakes_a_receiver_waiting_for_a_bridge(nodes):
+ receiver, _ = nodes
+ receiver.close()
+ assert not receiver.thread.is_alive()
+
+
+def test_close_ends_a_live_connection_at_once(nodes):
+ receiver, received = nodes
+ with socket.create_connection(('127.0.0.1', receiver.port)) as sender:
+ assert stream(sender, [], lambda: received['images'], 5.0)
+ assert receiver.connection.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE)
+ # The bridge goes quiet, so the receiver is waiting for its next frame.
+ time.sleep(0.2)
+ start = time.monotonic()
+ receiver.close()
+ assert time.monotonic() - start < READ_TIMEOUT_S / 2
+ assert not receiver.thread.is_alive()
+ sender.settimeout(1.0)
+ assert sender.recv(1) == b''
+
+
+def test_a_stalled_feed_warns(monitor):
+ node, reports = monitor
+ now = node.get_clock().now().nanoseconds * 1e-9
+ # A second of frames that stopped half a second ago.
+ for index in range(30):
+ received = now - 1.5 + index / 30.0
+ node.stats.add(received - 0.01, received)
+ node.report()
+ status = reports[-1].status[0]
+ assert status.level == DiagnosticStatus.WARN
+ assert status.message.startswith('No frame for')
+
+
+def test_a_negative_delay_warns_of_clock_skew(monitor):
+ node, reports = monitor
+ now = node.get_clock().now().nanoseconds * 1e-9
+ for index in range(30):
+ received = now - 1.0 + index / 30.0
+ # Stamped after it arrived: the camera computer's clock is ahead of this one.
+ node.stats.add(received + 0.005, received)
+ node.report()
+ status = reports[-1].status[0]
+ assert status.level == DiagnosticStatus.WARN
+ assert 'clock skew' in status.message
diff --git a/waybionic_camera/test/test_flake8.py b/waybionic_camera/test/test_flake8.py
new file mode 100644
index 00000000..3d3f045e
--- /dev/null
+++ b/waybionic_camera/test/test_flake8.py
@@ -0,0 +1,11 @@
+"""Style check for the package sources."""
+
+from ament_flake8.main import main_with_errors
+import pytest
+
+
+@pytest.mark.flake8
+@pytest.mark.linter
+def test_flake8():
+ rc, errors = main_with_errors(argv=[])
+ assert rc == 0, '\n'.join(['Found %d code style errors / warnings:' % len(errors)] + errors)
diff --git a/waybionic_camera/test/test_frames.py b/waybionic_camera/test/test_frames.py
new file mode 100644
index 00000000..506cb632
--- /dev/null
+++ b/waybionic_camera/test/test_frames.py
@@ -0,0 +1,39 @@
+"""The camera bridge's frame stream survives the trip through TCP intact."""
+
+import socket
+
+import pytest
+
+from waybionic_camera import frames
+
+
+def test_frames_round_trip_through_a_socket():
+ sender, receiver = socket.socketpair()
+ with sender, receiver:
+ sender.sendall(frames.pack(1, 1_700_000_000_123_456_789, 1920, 1080, b'\xff\xd8one'))
+ sender.sendall(frames.pack(2, 1_700_000_000_156_789_012, 1920, 1080, b'\xff\xd8two!'))
+ sender.close()
+ assert frames.read_frame(receiver) == (1, 1_700_000_000_123_456_789, 1920, 1080,
+ b'\xff\xd8one')
+ assert frames.read_frame(receiver) == (2, 1_700_000_000_156_789_012, 1920, 1080,
+ b'\xff\xd8two!')
+ assert frames.read_frame(receiver) is None
+
+
+def test_a_frame_cut_short_ends_the_stream():
+ sender, receiver = socket.socketpair()
+ with sender, receiver:
+ sender.sendall(frames.pack(1, 0, 640, 480, b'0123456789')[:-3])
+ sender.close()
+ assert frames.read_frame(receiver) is None
+
+
+def test_bad_headers_are_rejected():
+ header = frames.pack(1, 0, 640, 480, b'')
+ with pytest.raises(ValueError):
+ frames.unpack_header(b'XXXX' + header[4:])
+ with pytest.raises(ValueError):
+ frames.unpack_header(frames.HEADER.pack(frames.MAGIC, frames.VERSION, 1, 0, 640, 480,
+ frames.MAX_JPEG_BYTES + 1))
+ with pytest.raises(ValueError):
+ frames.pack(1, 0, 640, 480, bytes(frames.MAX_JPEG_BYTES + 1))
diff --git a/waybionic_camera/test/test_latency.py b/waybionic_camera/test/test_latency.py
new file mode 100644
index 00000000..b1b6bfc0
--- /dev/null
+++ b/waybionic_camera/test/test_latency.py
@@ -0,0 +1,40 @@
+"""Frame rate, delay and jitter over the sliding window."""
+
+import pytest
+
+from waybionic_camera.latency import FrameStats
+
+
+def test_rate_delay_and_jitter_of_a_steady_stream():
+ stats = FrameStats(window_s=5.0)
+ for index in range(90):
+ captured = 100.0 + index / 30.0
+ # Alternating 35 and 45 ms of delay.
+ stats.add(captured, captured + (0.035 if index % 2 else 0.045))
+ summary = stats.summary(103.0)
+ assert summary['fps'] == pytest.approx(30.0, rel=0.02)
+ assert summary['mean_ms'] == pytest.approx(40.0, abs=0.2)
+ assert (summary['min_ms'], summary['max_ms']) == pytest.approx((35.0, 45.0))
+ assert summary['jitter_ms'] == pytest.approx(5.0, abs=0.1)
+ assert stats.total == 90
+
+
+def test_old_frames_leave_the_window():
+ stats = FrameStats(window_s=1.0)
+ stats.add(10.0, 10.5)
+ stats.add(11.6, 11.62)
+ assert stats.summary(11.7)['max_ms'] == pytest.approx(20.0)
+ assert stats.summary(13.0) is None
+
+
+def test_the_rate_falls_as_soon_as_the_frames_stop():
+ stats = FrameStats(window_s=5.0)
+ for index in range(91):
+ stats.add(100.0 + index / 30.0, 100.002 + index / 30.0)
+ # The last frame arrived at 103.002, three seconds after the first.
+ current = stats.summary(103.002)
+ assert current['fps'] == pytest.approx(30.0)
+ assert current['since_last_ms'] == pytest.approx(0.0, abs=1e-6)
+ stopped = stats.summary(104.002)
+ assert stopped['fps'] == pytest.approx(90 / 4.0)
+ assert stopped['since_last_ms'] == pytest.approx(1000.0)
diff --git a/waybionic_camera/test/test_pep257.py b/waybionic_camera/test/test_pep257.py
new file mode 100644
index 00000000..06e19b7b
--- /dev/null
+++ b/waybionic_camera/test/test_pep257.py
@@ -0,0 +1,11 @@
+"""Docstring check for the package sources."""
+
+from ament_pep257.main import main
+import pytest
+
+
+@pytest.mark.linter
+@pytest.mark.pep257
+def test_pep257():
+ rc = main(argv=['.', 'test'])
+ assert rc == 0, 'Found code style errors / warnings'
diff --git a/waybionic_camera/waybionic_camera/__init__.py b/waybionic_camera/waybionic_camera/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/waybionic_camera/waybionic_camera/camera_bridge.py b/waybionic_camera/waybionic_camera/camera_bridge.py
new file mode 100644
index 00000000..6107d491
--- /dev/null
+++ b/waybionic_camera/waybionic_camera/camera_bridge.py
@@ -0,0 +1,108 @@
+"""
+Stream a USB camera to the ground station: capture with OpenCV and send JPEG frames over TCP.
+
+Run it on the computer the camera is plugged into, after ``pip install opencv-python``::
+
+ python -m waybionic_camera.camera_bridge
+
+Each frame carries the time it was captured, so the ground station can measure the delay.
+This file needs only Python 3 and OpenCV, not ROS.
+"""
+
+import argparse
+import os
+import socket
+import sys
+import time
+
+from waybionic_camera.frames import pack
+
+
+def open_camera(cv2, args):
+ source = int(args.camera) if args.camera.isdigit() else args.camera
+ backends = {'any': cv2.CAP_ANY, 'dshow': cv2.CAP_DSHOW, 'msmf': cv2.CAP_MSMF,
+ 'v4l2': cv2.CAP_V4L2, 'avfoundation': cv2.CAP_AVFOUNDATION}
+ capture = cv2.VideoCapture(source, backends[args.backend])
+ if not capture.isOpened():
+ raise SystemExit(f'Could not open camera {args.camera}')
+ # USB 2 webcams only reach 1080p at 30 fps when they send MJPG.
+ capture.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG'))
+ capture.set(cv2.CAP_PROP_FRAME_WIDTH, args.width)
+ capture.set(cv2.CAP_PROP_FRAME_HEIGHT, args.height)
+ capture.set(cv2.CAP_PROP_FPS, args.fps)
+ return capture
+
+
+def main():
+ parser = argparse.ArgumentParser(description='Send a camera to the ground station.')
+ parser.add_argument('--host', default='127.0.0.1', help='ground station address')
+ parser.add_argument('--port', type=int, default=47310, help='camera_receiver port')
+ parser.add_argument('--camera', default='0', help='camera index, video file or stream URL')
+ parser.add_argument('--backend', default='any',
+ choices=('any', 'dshow', 'msmf', 'v4l2', 'avfoundation'))
+ parser.add_argument('--width', type=int, default=1920)
+ parser.add_argument('--height', type=int, default=1080)
+ parser.add_argument('--fps', type=float, default=30.0)
+ parser.add_argument('--quality', type=int, default=80, help='JPEG quality, 1-100')
+ args = parser.parse_args()
+ try:
+ import cv2
+ except ImportError:
+ raise SystemExit('The camera bridge needs OpenCV: pip install opencv-python') from None
+ capture = open_camera(cv2, args)
+ # A local video file can stand in for a camera: it loops at the requested frame rate.
+ video_file = os.path.isfile(args.camera)
+ number, sender, report = 0, None, time.monotonic()
+ next_frame = report
+ resolution = time.get_clock_info('time').resolution
+ if resolution > 1e-3:
+ # Before Python 3.13, time.time_ns() on Windows only advances every 15.6 ms.
+ print(f'Warning: frame times are only precise to {1000 * resolution:.1f} ms with this '
+ 'Python; use Python 3.13 or newer for the bridge', file=sys.stderr)
+ print(f'Sending camera {args.camera} to {args.host}:{args.port} (Ctrl+C to stop)')
+ try:
+ while True:
+ ok, image = capture.read()
+ stamp_ns = time.time_ns()
+ if not ok:
+ if video_file:
+ capture.set(cv2.CAP_PROP_POS_FRAMES, 0)
+ continue
+ raise SystemExit('The camera stopped sending frames')
+ if sender is None:
+ try:
+ sender = socket.create_connection((args.host, args.port), timeout=1.0)
+ sender.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
+ print('Connected to the ground station')
+ except OSError:
+ time.sleep(0.5)
+ continue
+ ok, jpeg = cv2.imencode('.jpg', image, [cv2.IMWRITE_JPEG_QUALITY, args.quality])
+ height, width = image.shape[:2]
+ number += 1
+ try:
+ sender.sendall(pack(number, stamp_ns, width, height, jpeg.tobytes()))
+ except OSError:
+ print('Ground station disconnected; retrying')
+ sender.close()
+ sender = None
+ if number % 30 == 0:
+ now = time.monotonic()
+ print(f'\r{30 / (now - report):5.1f} fps at {width}x{height}', end='',
+ flush=True)
+ report = now
+ if video_file and args.fps > 0:
+ # A camera or stream sets its own pace; a video file plays at the set rate.
+ next_frame += 1.0 / args.fps
+ time.sleep(max(0.0, next_frame - time.monotonic()))
+ except KeyboardInterrupt:
+ pass
+ finally:
+ capture.release()
+ if sender is not None:
+ sender.close()
+ return 0
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/waybionic_camera/waybionic_camera/camera_receiver.py b/waybionic_camera/waybionic_camera/camera_receiver.py
new file mode 100644
index 00000000..6b378461
--- /dev/null
+++ b/waybionic_camera/waybionic_camera/camera_receiver.py
@@ -0,0 +1,101 @@
+"""
+Publish the camera bridge's frames as the doctor view.
+
+Frames arrive over TCP from camera_bridge and are published, still JPEG-compressed, on
+doctor_view/left/image_raw/compressed with doctor_view/left/camera_info, both stamped with
+the time the frame was captured. RViz shows them with the compressed image transport.
+"""
+
+import contextlib
+import socket
+import threading
+
+import rclpy
+from rclpy.executors import ExternalShutdownException
+from rclpy.node import Node
+from sensor_msgs.msg import CameraInfo, CompressedImage
+
+from waybionic_camera.frames import read_frame
+
+# A silent bridge (cable pulled, PC asleep) is dropped after this, so its reconnection is served.
+READ_TIMEOUT_S = 2.0
+
+
+def to_messages(frame_id, stamp_ns, width, height, jpeg):
+ """Return the CompressedImage and CameraInfo for one frame."""
+ image = CompressedImage(format='jpeg', data=jpeg)
+ info = CameraInfo(width=width, height=height)
+ seconds, nanoseconds = divmod(stamp_ns, 1_000_000_000)
+ for message in (image, info):
+ message.header.frame_id = frame_id
+ message.header.stamp.sec, message.header.stamp.nanosec = seconds, nanoseconds
+ return image, info
+
+
+class CameraReceiver(Node):
+ """Accept one camera bridge at a time and republish its frames."""
+
+ def __init__(self, **kwargs):
+ super().__init__('camera_receiver', **kwargs)
+ bind = self.declare_parameter('bind_address', '127.0.0.1').value
+ port = int(self.declare_parameter('port', 47310).value)
+ self.frame_id = self.declare_parameter(
+ 'frame_id', 'doctor_view_left_optical_frame').value
+ self.image_publisher = self.create_publisher(
+ CompressedImage, 'doctor_view/left/image_raw/compressed', 10)
+ self.info_publisher = self.create_publisher(CameraInfo, 'doctor_view/left/camera_info', 10)
+ self.server = socket.create_server((bind, port))
+ self.port = self.server.getsockname()[1]
+ self.connection = None
+ self.running = True
+ self.thread = threading.Thread(target=self.serve, daemon=True)
+ self.thread.start()
+ self.get_logger().info(f'Waiting for camera_bridge on {bind}:{self.port}/tcp')
+
+ def serve(self):
+ while self.running:
+ try:
+ connection, address = self.server.accept()
+ except OSError:
+ return
+ connection.settimeout(READ_TIMEOUT_S)
+ connection.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
+ self.connection = connection
+ self.get_logger().info(f'Camera bridge connected from {address[0]}')
+ with connection:
+ try:
+ while self.running and (frame := read_frame(connection)) is not None:
+ _, stamp_ns, width, height, jpeg = frame
+ image, info = to_messages(self.frame_id, stamp_ns, width, height, jpeg)
+ self.image_publisher.publish(image)
+ self.info_publisher.publish(info)
+ except (OSError, ValueError) as error:
+ self.get_logger().warning(f'Camera stream dropped: {error}')
+ self.get_logger().info('Camera bridge disconnected')
+
+ def close(self):
+ self.running = False
+ # On Linux, closing a socket does not wake a thread blocked on it; shutting it down does.
+ for sock in (self.server, self.connection):
+ if sock is not None:
+ with contextlib.suppress(OSError):
+ sock.shutdown(socket.SHUT_RDWR)
+ self.server.close()
+ self.thread.join(READ_TIMEOUT_S)
+
+
+def main():
+ rclpy.init()
+ node = CameraReceiver()
+ try:
+ rclpy.spin(node)
+ except (KeyboardInterrupt, ExternalShutdownException):
+ pass
+ finally:
+ node.close()
+ node.destroy_node()
+ rclpy.try_shutdown()
+
+
+if __name__ == '__main__':
+ main()
diff --git a/waybionic_camera/waybionic_camera/frames.py b/waybionic_camera/waybionic_camera/frames.py
new file mode 100644
index 00000000..2e37236b
--- /dev/null
+++ b/waybionic_camera/waybionic_camera/frames.py
@@ -0,0 +1,49 @@
+"""The camera bridge's TCP stream: a fixed header, then one JPEG image, for every frame."""
+
+import struct
+
+MAGIC = b'WBCF'
+VERSION = 1
+# Magic, version, frame number, capture time (ns since the epoch, on the camera computer's
+# clock), width, height and the JPEG length.
+HEADER = struct.Struct('<4sB3xQqHHI')
+MAX_JPEG_BYTES = 16 * 1024 * 1024
+
+
+def pack(number, stamp_ns, width, height, jpeg):
+ """Encode one frame for the stream."""
+ if len(jpeg) > MAX_JPEG_BYTES:
+ raise ValueError(f'a {len(jpeg)} byte frame is larger than {MAX_JPEG_BYTES} bytes')
+ return HEADER.pack(MAGIC, VERSION, number, stamp_ns, width, height, len(jpeg)) + jpeg
+
+
+def unpack_header(data):
+ """Return (number, stamp_ns, width, height, length); raise ValueError if malformed."""
+ magic, version, number, stamp_ns, width, height, length = HEADER.unpack(data)
+ if magic != MAGIC or version != VERSION:
+ raise ValueError('not a version 1 WayBionic camera frame')
+ if length > MAX_JPEG_BYTES:
+ raise ValueError(f'frame of {length} bytes is larger than {MAX_JPEG_BYTES} bytes')
+ return number, stamp_ns, width, height, length
+
+
+def read_exactly(stream, size):
+ """Read size bytes from a socket, or return None if it closes first."""
+ chunks, remaining = [], size
+ while remaining:
+ chunk = stream.recv(min(remaining, 1 << 20))
+ if not chunk:
+ return None
+ chunks.append(chunk)
+ remaining -= len(chunk)
+ return b''.join(chunks)
+
+
+def read_frame(stream):
+ """Return (number, stamp_ns, width, height, jpeg) for the next frame, or None at the end."""
+ header = read_exactly(stream, HEADER.size)
+ if header is None:
+ return None
+ number, stamp_ns, width, height, length = unpack_header(header)
+ jpeg = read_exactly(stream, length)
+ return None if jpeg is None else (number, stamp_ns, width, height, jpeg)
diff --git a/waybionic_camera/waybionic_camera/latency.py b/waybionic_camera/waybionic_camera/latency.py
new file mode 100644
index 00000000..0a57e8fa
--- /dev/null
+++ b/waybionic_camera/waybionic_camera/latency.py
@@ -0,0 +1,43 @@
+"""Frame rate and delay over a sliding window (pure logic, no ROS)."""
+
+from collections import deque
+import math
+
+
+class FrameStats:
+ """Keep the frames of the last few seconds: when each was captured and received."""
+
+ def __init__(self, window_s=5.0):
+ self.window = window_s
+ self.frames = deque()
+ self.total = 0
+
+ def add(self, captured_s, received_s):
+ self.frames.append((captured_s, received_s))
+ self.total += 1
+ while self.frames and received_s - self.frames[0][1] > self.window:
+ self.frames.popleft()
+
+ def summary(self, now_s):
+ """
+ Return fps, delay in ms (mean, min, max and jitter) and ms since the last frame.
+
+ Return None without frames.
+ """
+ while self.frames and now_s - self.frames[0][1] > self.window:
+ self.frames.popleft()
+ if not self.frames:
+ return None
+ delays = [1000.0 * (received - captured) for captured, received in self.frames]
+ mean = sum(delays) / len(delays)
+ # The span runs to now, so the rate falls as soon as the frames stop.
+ span = now_s - self.frames[0][1]
+ return {
+ 'fps': (len(self.frames) - 1) / span if span > 0 else 0.0,
+ 'mean_ms': mean,
+ 'min_ms': min(delays),
+ 'max_ms': max(delays),
+ # Jitter is how much the delay varies from frame to frame.
+ 'jitter_ms': math.sqrt(sum((delay - mean) ** 2 for delay in delays) / len(delays)),
+ 'since_last_ms': 1000.0 * (now_s - self.frames[-1][1]),
+ }
diff --git a/waybionic_camera/waybionic_camera/latency_monitor.py b/waybionic_camera/waybionic_camera/latency_monitor.py
new file mode 100644
index 00000000..3a2f3220
--- /dev/null
+++ b/waybionic_camera/waybionic_camera/latency_monitor.py
@@ -0,0 +1,115 @@
+"""
+Report a camera's frame rate and delay on /diagnostics, and optionally log every frame.
+
+The delay is the time a frame arrives minus its header stamp, so it covers capture to arrival
+as long as the camera computer's clock matches this one. Any camera topic works: the camera
+bridge's compressed frames, or a ROS camera driver's raw images.
+"""
+
+import csv
+
+from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue
+import rclpy
+from rclpy.executors import ExternalShutdownException
+from rclpy.node import Node
+from rclpy.qos import qos_profile_sensor_data
+from sensor_msgs.msg import CameraInfo, CompressedImage, Image
+
+from waybionic_camera.latency import FrameStats
+
+
+class LatencyMonitor(Node):
+ """Measure the frames on one image topic."""
+
+ def __init__(self, **kwargs):
+ super().__init__('camera_latency_monitor', **kwargs)
+ topic = self.declare_parameter('topic', 'doctor_view/left/image_raw/compressed').value
+ compressed = self.declare_parameter('compressed', True).value
+ info_topic = self.declare_parameter('info_topic', 'doctor_view/left/camera_info').value
+ self.name = self.declare_parameter('name', 'camera.doctor_view').value
+ self.max_delay = float(self.declare_parameter('max_delay_ms', 100.0).value)
+ self.min_fps = float(self.declare_parameter('min_fps', 25.0).value)
+ # Three frame periods at 25 fps: no frame for longer means the feed has stopped.
+ self.max_gap = float(self.declare_parameter('max_gap_ms', 120.0).value)
+ diagnostics = self.declare_parameter('diagnostics_topic', '/diagnostics').value
+ log_path = self.declare_parameter('log_csv', '').value
+ self.topic = self.resolve_topic_name(topic)
+ self.stats = FrameStats()
+ self.size = None
+ self.log = None
+ if log_path:
+ self.log_file = open(log_path, 'w', newline='', encoding='utf-8')
+ self.log = csv.writer(self.log_file)
+ self.log.writerow(['frame', 'captured_s', 'received_s', 'delay_ms', 'width',
+ 'height'])
+ self.create_subscription(CompressedImage if compressed else Image, topic, self.on_image,
+ qos_profile_sensor_data)
+ self.create_subscription(CameraInfo, info_topic, self.on_info, qos_profile_sensor_data)
+ self.publisher = self.create_publisher(DiagnosticArray, diagnostics, 10)
+ self.create_timer(1.0, self.report)
+
+ def on_info(self, message):
+ self.size = (message.width, message.height)
+
+ def on_image(self, message):
+ if isinstance(message, Image):
+ self.size = (message.width, message.height)
+ stamp = message.header.stamp
+ captured = stamp.sec + stamp.nanosec * 1e-9
+ received = self.get_clock().now().nanoseconds * 1e-9
+ self.stats.add(captured, received)
+ if self.log is not None:
+ width, height = self.size or ('', '')
+ self.log.writerow([self.stats.total, f'{captured:.6f}', f'{received:.6f}',
+ f'{1000.0 * (received - captured):.2f}', width, height])
+
+ def report(self):
+ summary = self.stats.summary(self.get_clock().now().nanoseconds * 1e-9)
+ if summary is None:
+ level, value, text = DiagnosticStatus.STALE, '', f'No frames on {self.topic}'
+ else:
+ problems = []
+ if summary['since_last_ms'] > self.max_gap:
+ problems.append(f'No frame for {summary["since_last_ms"]:.0f} ms')
+ # A frame cannot arrive before it was captured unless the two clocks disagree.
+ if summary['min_ms'] < 0.0:
+ problems.append('Negative delay: possible clock skew')
+ slow = summary['fps'] < self.min_fps or summary['mean_ms'] > self.max_delay
+ level = DiagnosticStatus.WARN if problems or slow else DiagnosticStatus.OK
+ value = f'{summary["mean_ms"]:.0f}'
+ size = f' at {self.size[0]}x{self.size[1]}' if self.size else ''
+ text = '; '.join(problems + [
+ f'{summary["fps"]:.1f} fps, delay {summary["mean_ms"]:.0f} ms (min '
+ f'{summary["min_ms"]:.0f}, max {summary["max_ms"]:.0f}, jitter '
+ f'{summary["jitter_ms"]:.1f}){size}'])
+ values = [KeyValue(key='value', value=value), KeyValue(key='unit', value='ms'),
+ KeyValue(key='frames', value=str(self.stats.total))]
+ if summary is not None:
+ values += [KeyValue(key=key, value=f'{number:.2f}') for key, number in summary.items()]
+ message = DiagnosticArray(status=[DiagnosticStatus(
+ name=self.name, level=level, message=text, hardware_id=self.topic, values=values)])
+ message.header.stamp = self.get_clock().now().to_msg()
+ self.publisher.publish(message)
+ if self.log is not None:
+ self.log_file.flush()
+
+ def close(self):
+ if self.log is not None:
+ self.log_file.close()
+
+
+def main():
+ rclpy.init()
+ node = LatencyMonitor()
+ try:
+ rclpy.spin(node)
+ except (KeyboardInterrupt, ExternalShutdownException):
+ pass
+ finally:
+ node.close()
+ node.destroy_node()
+ rclpy.try_shutdown()
+
+
+if __name__ == '__main__':
+ main()