|
| 1 | +# Copyright 2024 Tier IV, Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License.sr/bin/env python |
| 14 | + |
| 15 | +from __future__ import print_function |
| 16 | + |
| 17 | +import logging |
| 18 | +from queue import Empty |
| 19 | +from queue import Queue |
| 20 | + |
| 21 | +import carla |
| 22 | +import numpy as np |
| 23 | + |
| 24 | +from .carla_data_provider import CarlaDataProvider |
| 25 | + |
| 26 | + |
| 27 | +# Sensor Wrapper for Agent |
| 28 | +class SensorReceivedNoData(Exception): |
| 29 | + """Exceptions when no data received from the sensors.""" |
| 30 | + |
| 31 | + |
| 32 | +class GenericMeasurement(object): |
| 33 | + def __init__(self, data, frame): |
| 34 | + self.data = data |
| 35 | + self.frame = frame |
| 36 | + |
| 37 | + |
| 38 | +class CallBack(object): |
| 39 | + def __init__(self, tag, sensor, data_provider): |
| 40 | + self._tag = tag |
| 41 | + self._data_provider = data_provider |
| 42 | + |
| 43 | + self._data_provider.register_sensor(tag, sensor) |
| 44 | + |
| 45 | + def __call__(self, data): |
| 46 | + if isinstance(data, carla.Image): |
| 47 | + self._parse_image_cb(data, self._tag) |
| 48 | + elif isinstance(data, carla.LidarMeasurement): |
| 49 | + self._parse_lidar_cb(data, self._tag) |
| 50 | + elif isinstance(data, carla.GnssMeasurement): |
| 51 | + self._parse_gnss_cb(data, self._tag) |
| 52 | + elif isinstance(data, carla.IMUMeasurement): |
| 53 | + self._parse_imu_cb(data, self._tag) |
| 54 | + elif isinstance(data, GenericMeasurement): |
| 55 | + self._parse_pseudo_sensor(data, self._tag) |
| 56 | + else: |
| 57 | + logging.error("No callback method for this sensor.") |
| 58 | + |
| 59 | + # Parsing CARLA physical Sensors |
| 60 | + def _parse_image_cb(self, image, tag): |
| 61 | + self._data_provider.update_sensor(tag, image, image.frame) |
| 62 | + |
| 63 | + def _parse_lidar_cb(self, lidar_data, tag): |
| 64 | + self._data_provider.update_sensor(tag, lidar_data, lidar_data.frame) |
| 65 | + |
| 66 | + def _parse_imu_cb(self, imu_data, tag): |
| 67 | + self._data_provider.update_sensor(tag, imu_data, imu_data.frame) |
| 68 | + |
| 69 | + def _parse_gnss_cb(self, gnss_data, tag): |
| 70 | + array = np.array( |
| 71 | + [gnss_data.latitude, gnss_data.longitude, gnss_data.altitude], dtype=np.float64 |
| 72 | + ) |
| 73 | + self._data_provider.update_sensor(tag, array, gnss_data.frame) |
| 74 | + |
| 75 | + def _parse_pseudo_sensor(self, package, tag): |
| 76 | + self._data_provider.update_sensor(tag, package.data, package.frame) |
| 77 | + |
| 78 | + |
| 79 | +class SensorInterface(object): |
| 80 | + def __init__(self): |
| 81 | + self._sensors_objects = {} |
| 82 | + self._new_data_buffers = Queue() |
| 83 | + self._queue_timeout = 10 |
| 84 | + self.tag = "" |
| 85 | + |
| 86 | + def register_sensor(self, tag, sensor): |
| 87 | + self.tag = tag |
| 88 | + if tag in self._sensors_objects: |
| 89 | + raise ValueError(f"Duplicated sensor tag [{tag}]") |
| 90 | + |
| 91 | + self._sensors_objects[tag] = sensor |
| 92 | + |
| 93 | + def update_sensor(self, tag, data, timestamp): |
| 94 | + if tag not in self._sensors_objects: |
| 95 | + raise ValueError(f"Sensor with tag [{tag}] has not been created") |
| 96 | + |
| 97 | + self._new_data_buffers.put((tag, timestamp, data)) |
| 98 | + |
| 99 | + def get_data(self): |
| 100 | + try: |
| 101 | + data_dict = {} |
| 102 | + while len(data_dict.keys()) < len(self._sensors_objects.keys()): |
| 103 | + sensor_data = self._new_data_buffers.get(True, self._queue_timeout) |
| 104 | + data_dict[sensor_data[0]] = (sensor_data[1], sensor_data[2]) |
| 105 | + except Empty: |
| 106 | + raise SensorReceivedNoData( |
| 107 | + f"Sensor with tag [{self.tag}] took too long to send its data" |
| 108 | + ) |
| 109 | + |
| 110 | + return data_dict |
| 111 | + |
| 112 | + |
| 113 | +# Sensor Wrapper |
| 114 | + |
| 115 | + |
| 116 | +class SensorWrapper(object): |
| 117 | + _agent = None |
| 118 | + _sensors_list = [] |
| 119 | + |
| 120 | + def __init__(self, agent): |
| 121 | + self._agent = agent |
| 122 | + |
| 123 | + def __call__(self): |
| 124 | + return self._agent() |
| 125 | + |
| 126 | + def setup_sensors(self, vehicle, debug_mode=False): |
| 127 | + """Create and attach the sensor defined in objects.json.""" |
| 128 | + bp_library = CarlaDataProvider.get_world().get_blueprint_library() |
| 129 | + |
| 130 | + for sensor_spec in self._agent.sensors["sensors"]: |
| 131 | + bp = bp_library.find(str(sensor_spec["type"])) |
| 132 | + |
| 133 | + if sensor_spec["type"].startswith("sensor.camera"): |
| 134 | + bp.set_attribute("image_size_x", str(sensor_spec["image_size_x"])) |
| 135 | + bp.set_attribute("image_size_y", str(sensor_spec["image_size_y"])) |
| 136 | + bp.set_attribute("fov", str(sensor_spec["fov"])) |
| 137 | + sensor_location = carla.Location( |
| 138 | + x=sensor_spec["spawn_point"]["x"], |
| 139 | + y=sensor_spec["spawn_point"]["y"], |
| 140 | + z=sensor_spec["spawn_point"]["z"], |
| 141 | + ) |
| 142 | + sensor_rotation = carla.Rotation( |
| 143 | + pitch=sensor_spec["spawn_point"]["pitch"], |
| 144 | + roll=sensor_spec["spawn_point"]["roll"], |
| 145 | + yaw=sensor_spec["spawn_point"]["yaw"], |
| 146 | + ) |
| 147 | + |
| 148 | + elif sensor_spec["type"].startswith("sensor.lidar"): |
| 149 | + bp.set_attribute("range", str(sensor_spec["range"])) |
| 150 | + bp.set_attribute("rotation_frequency", str(sensor_spec["rotation_frequency"])) |
| 151 | + bp.set_attribute("channels", str(sensor_spec["channels"])) |
| 152 | + bp.set_attribute("upper_fov", str(sensor_spec["upper_fov"])) |
| 153 | + bp.set_attribute("lower_fov", str(sensor_spec["lower_fov"])) |
| 154 | + bp.set_attribute("points_per_second", str(sensor_spec["points_per_second"])) |
| 155 | + sensor_location = carla.Location( |
| 156 | + x=sensor_spec["spawn_point"]["x"], |
| 157 | + y=sensor_spec["spawn_point"]["y"], |
| 158 | + z=sensor_spec["spawn_point"]["z"], |
| 159 | + ) |
| 160 | + sensor_rotation = carla.Rotation( |
| 161 | + pitch=sensor_spec["spawn_point"]["pitch"], |
| 162 | + roll=sensor_spec["spawn_point"]["roll"], |
| 163 | + yaw=sensor_spec["spawn_point"]["yaw"], |
| 164 | + ) |
| 165 | + |
| 166 | + elif sensor_spec["type"].startswith("sensor.other.gnss"): |
| 167 | + bp.set_attribute("noise_alt_stddev", str(0.0)) |
| 168 | + bp.set_attribute("noise_lat_stddev", str(0.0)) |
| 169 | + bp.set_attribute("noise_lon_stddev", str(0.0)) |
| 170 | + bp.set_attribute("noise_alt_bias", str(0.0)) |
| 171 | + bp.set_attribute("noise_lat_bias", str(0.0)) |
| 172 | + bp.set_attribute("noise_lon_bias", str(0.0)) |
| 173 | + sensor_location = carla.Location( |
| 174 | + x=sensor_spec["spawn_point"]["x"], |
| 175 | + y=sensor_spec["spawn_point"]["y"], |
| 176 | + z=sensor_spec["spawn_point"]["z"], |
| 177 | + ) |
| 178 | + sensor_rotation = carla.Rotation( |
| 179 | + pitch=sensor_spec["spawn_point"]["pitch"], |
| 180 | + roll=sensor_spec["spawn_point"]["roll"], |
| 181 | + yaw=sensor_spec["spawn_point"]["yaw"], |
| 182 | + ) |
| 183 | + |
| 184 | + elif sensor_spec["type"].startswith("sensor.other.imu"): |
| 185 | + bp.set_attribute("noise_accel_stddev_x", str(0.0)) |
| 186 | + bp.set_attribute("noise_accel_stddev_y", str(0.0)) |
| 187 | + bp.set_attribute("noise_accel_stddev_z", str(0.0)) |
| 188 | + bp.set_attribute("noise_gyro_stddev_x", str(0.0)) |
| 189 | + bp.set_attribute("noise_gyro_stddev_y", str(0.0)) |
| 190 | + bp.set_attribute("noise_gyro_stddev_z", str(0.0)) |
| 191 | + sensor_location = carla.Location( |
| 192 | + x=sensor_spec["spawn_point"]["x"], |
| 193 | + y=sensor_spec["spawn_point"]["y"], |
| 194 | + z=sensor_spec["spawn_point"]["z"], |
| 195 | + ) |
| 196 | + sensor_rotation = carla.Rotation( |
| 197 | + pitch=sensor_spec["spawn_point"]["pitch"], |
| 198 | + roll=sensor_spec["spawn_point"]["roll"], |
| 199 | + yaw=sensor_spec["spawn_point"]["yaw"], |
| 200 | + ) |
| 201 | + |
| 202 | + elif sensor_spec["type"].startswith("sensor.pseudo.*"): |
| 203 | + sensor_location = carla.Location( |
| 204 | + x=sensor_spec["spawn_point"]["x"], |
| 205 | + y=sensor_spec["spawn_point"]["y"], |
| 206 | + z=sensor_spec["spawn_point"]["z"], |
| 207 | + ) |
| 208 | + sensor_rotation = carla.Rotation( |
| 209 | + pitch=sensor_spec["spawn_point"]["pitch"] + 0.001, |
| 210 | + roll=sensor_spec["spawn_point"]["roll"] - 0.015, |
| 211 | + yaw=sensor_spec["spawn_point"]["yaw"] + 0.0364, |
| 212 | + ) |
| 213 | + |
| 214 | + # create sensor |
| 215 | + sensor_transform = carla.Transform(sensor_location, sensor_rotation) |
| 216 | + sensor = CarlaDataProvider.get_world().spawn_actor(bp, sensor_transform, vehicle) |
| 217 | + # setup callback |
| 218 | + sensor.listen(CallBack(sensor_spec["id"], sensor, self._agent.sensor_interface)) |
| 219 | + self._sensors_list.append(sensor) |
| 220 | + |
| 221 | + # Tick once to spawn the sensors |
| 222 | + CarlaDataProvider.get_world().tick() |
| 223 | + |
| 224 | + def cleanup(self): |
| 225 | + """Cleanup sensors.""" |
| 226 | + for i, _ in enumerate(self._sensors_list): |
| 227 | + if self._sensors_list[i] is not None: |
| 228 | + self._sensors_list[i].stop() |
| 229 | + self._sensors_list[i].destroy() |
| 230 | + self._sensors_list[i] = None |
| 231 | + self._sensors_list = [] |
0 commit comments