Apollo 11.0
自动驾驶开放平台
simulation_world_service.h
浏览该文件的文档.
1/******************************************************************************
2 * Copyright 2017 The Apollo Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *****************************************************************************/
16
21#pragma once
22
23#include <algorithm>
24#include <list>
25#include <map>
26#include <memory>
27#include <string>
28#include <unordered_map>
29#include <utility>
30#include <vector>
31
32#include <boost/thread/locks.hpp>
33#include <boost/thread/shared_mutex.hpp>
34
35#include "gtest/gtest_prod.h"
36
37#include "nlohmann/json.hpp"
38
39#include "modules/common_msgs/audio_msgs/audio.pb.h"
40#include "modules/common_msgs/audio_msgs/audio_event.pb.h"
41#include "modules/common_msgs/basic_msgs/drive_event.pb.h"
42#include "modules/common_msgs/basic_msgs/pnc_point.pb.h"
43#include "modules/common_msgs/control_msgs/control_cmd.pb.h"
44#include "modules/common_msgs/external_command_msgs/command_status.pb.h"
45#include "modules/common_msgs/external_command_msgs/lane_follow_command.pb.h"
46#include "modules/common_msgs/external_command_msgs/valet_parking_command.pb.h"
47#include "modules/common_msgs/external_command_msgs/action_command.pb.h"
48#include "modules/common_msgs/localization_msgs/gps.pb.h"
49#include "modules/common_msgs/localization_msgs/localization.pb.h"
50#include "modules/common_msgs/perception_msgs/traffic_light_detection.pb.h"
51#include "modules/common_msgs/planning_msgs/planning.pb.h"
52#include "modules/common_msgs/planning_msgs/planning_command.pb.h"
53#include "modules/common_msgs/planning_msgs/planning_internal.pb.h"
54#include "modules/common_msgs/prediction_msgs/prediction_obstacle.pb.h"
55#include "modules/common_msgs/routing_msgs/routing.pb.h"
56#include "modules/common_msgs/storytelling_msgs/story.pb.h"
57#include "modules/common_msgs/task_manager_msgs/task_manager.pb.h"
58#include "modules/common_msgs/dreamview_msgs/simulation_world.pb.h"
59
60#include "cyber/common/log.h"
63
68namespace apollo {
69namespace dreamview {
70
80 public:
81 // The maximum number of monitor message items to be kept in
82 // SimulationWorld.
83 static constexpr int kMaxMonitorItems = 30;
84
90 SimulationWorldService(const MapService *map_service,
91 bool routing_from_file = false);
92
97 inline const SimulationWorld &world() const { return world_; }
98
105 nlohmann::json GetUpdateAsJson(double radius) const;
106
114 void GetWireFormatString(double radius, std::string *sim_world,
115 std::string *sim_world_with_planning_data);
116
123 nlohmann::json GetMapElements(double radius) const;
124
130 void Update();
131
135 void SetToClear() { to_clear_ = true; }
136
142 bool ReadyToPush() const { return ready_to_push_.load(); }
143
152 const std::string &msg);
153
155 const std::shared_ptr<apollo::relative_map::NavigationInfo> &);
156
158 const std::shared_ptr<apollo::external_command::LaneFollowCommand> &);
159
161 const std::shared_ptr<apollo::external_command::ValetParkingCommand> &);
162
164 const std::shared_ptr<apollo::external_command::ActionCommand> &);
165
166 void PublishTask(const std::shared_ptr<apollo::task_manager::Task> &);
167
168 void GetMapElementIds(double radius, MapElementIds *ids) const;
169
170 const apollo::hdmap::Map &GetRelativeMap() const;
171
172 nlohmann::json GetRoutePathAsJson() const;
173
174 void DumpMessages();
175
176 private:
177 void InitReaders();
178 void InitWriters();
179
184 template <typename DataType>
185 void UpdateSimulationWorld(const DataType &data);
186
187 void UpdateMonitorMessages();
188
189 Object &CreateWorldObjectIfAbsent(
191 void CreateWorldObjectFromSensorMeasurement(
193 Object *world_object);
194 void SetObstacleInfo(const apollo::perception::PerceptionObstacle &obstacle,
195 Object *world_object);
196 void SetObstaclePolygon(
198 Object *world_object);
199 void SetObstacleSensorMeasurements(
201 Object *world_object);
202 void SetObstacleSource(const apollo::perception::PerceptionObstacle &obstacle,
203 Object *world_object);
204 void UpdatePlanningTrajectory(
205 const apollo::planning::ADCTrajectory &trajectory);
206 void UpdateRSSInfo(const apollo::planning::ADCTrajectory &trajectory);
207 bool LocateMarker(const apollo::planning::ObjectDecisionType &decision,
208 Decision *world_decision);
209 void FindNudgeRegion(const apollo::planning::ObjectDecisionType &decision,
210 const Object &world_obj, Decision *world_decision);
211 void UpdateDecision(const apollo::planning::DecisionResult &decision_res,
212 double header_time);
213 void UpdateMainStopDecision(
214 const apollo::planning::MainDecision &main_decision,
215 double update_timestamp_sec, Object *world_main_stop);
216
217 template <typename MainDecision>
218 void UpdateMainChangeLaneDecision(const MainDecision &decision,
219 Object *world_main_decision) {
220 if (decision.has_change_lane_type() &&
221 (decision.change_lane_type() == apollo::routing::ChangeLaneType::LEFT ||
222 decision.change_lane_type() ==
224 auto *change_lane_decision = world_main_decision->add_decision();
225 change_lane_decision->set_change_lane_type(decision.change_lane_type());
226
227 const auto &adc = world_.auto_driving_car();
228 change_lane_decision->set_position_x(adc.position_x());
229 change_lane_decision->set_position_y(adc.position_y());
230 change_lane_decision->set_heading(adc.heading());
231 }
232 }
233
234 void CreatePredictionTrajectory(
236 Object *world_object);
237
238 void DownsamplePath(const apollo::common::Path &paths,
239 apollo::common::Path *downsampled_path);
240
241 void UpdatePlanningData(const apollo::planning_internal::PlanningData &data);
242
243 void PopulateMapInfo(double radius);
244
249 template <typename MessageT>
250 void UpdateWithLatestObserved(cyber::Reader<MessageT> *reader,
251 bool logging = true) {
252 if (reader->Empty()) {
253 if (logging) {
254 AINFO_EVERY(100) << "Has not received any data from "
255 << reader->GetChannelName();
256 }
257 return;
258 }
259
260 const std::shared_ptr<MessageT> msg = reader->GetLatestObserved();
261 UpdateSimulationWorld(*msg);
262 }
263
268 template <typename MessageT>
269 void DumpMessageFromReader(cyber::Reader<MessageT> *reader) {
270 if (reader->Empty()) {
271 AWARN << "Has not received any data from " << reader->GetChannelName()
272 << ". Cannot dump message!";
273 return;
274 }
275
276 apollo::common::util::DumpMessage(reader->GetLatestObserved());
277 }
278
279 void ReadPlanningCommandFromFile(const std::string &planning_command_file);
280
281 template <typename MessageT>
282 void UpdateLatency(const std::string &module_name,
283 cyber::Reader<MessageT> *reader) {
284 if (reader->Empty()) {
285 return;
286 }
287
288 const auto header = reader->GetLatestObserved()->header();
289 const double publish_time_sec = header.timestamp_sec();
290 const double sensor_time_sec =
292 std::max({header.lidar_timestamp(), header.camera_timestamp(),
293 header.radar_timestamp()}))
294 .ToSecond();
295
296 Latency latency;
297 latency.set_timestamp_sec(publish_time_sec);
298 latency.set_total_time_ms((publish_time_sec - sensor_time_sec) * 1.0e3);
299 (*world_.mutable_latency())[module_name] = latency;
300 }
301
309 void UpdateDelays();
310
316 void UpdateLatencies();
317
318 template <typename Points>
319 void DownsampleSpeedPointsByInterval(const Points &points,
320 size_t downsampleInterval,
321 Points *downsampled_points) {
322 if (points.empty()) {
323 return;
324 }
325
326 for (int i = 0; i + 1 < points.size(); i += downsampleInterval) {
327 *downsampled_points->Add() = points[i];
328 }
329
330 // add the last point
331 *downsampled_points->Add() = *points.rbegin();
332 }
333
334 std::unique_ptr<cyber::Node> node_;
335
336 // The underlying SimulationWorld object, owned by the
337 // SimulationWorldService instance.
338 SimulationWorld world_;
339
340 // Downsampled route paths to be rendered in frontend.
341 mutable boost::shared_mutex route_paths_mutex_;
342 std::vector<RoutePath> route_paths_;
343
344 // The handle of MapService, not owned by SimulationWorldService.
345 const MapService *map_service_;
346
347 // The map holding obstacle string id to the actual object
348 std::unordered_map<std::string, Object> obj_map_;
349
350 // A temporary cache for all the monitor messages coming in.
351 std::mutex monitor_msgs_mutex_;
352 std::list<std::shared_ptr<common::monitor::MonitorMessage>> monitor_msgs_;
353
354 // The SIMULATOR monitor for publishing messages.
355 apollo::common::monitor::MonitorLogBuffer monitor_logger_buffer_;
356
357 // Whether to clear the SimulationWorld in the next timer cycle, set by
358 // frontend request.
359 bool to_clear_ = false;
360
361 // Relative map used/retrieved in navigation mode
362 apollo::hdmap::Map relative_map_;
363
364 // Whether the sim_world is ready to push to frontend
365 std::atomic<bool> ready_to_push_;
366
367 // Latest rss info
368 double current_real_dist_ = 0.0;
369 double current_rss_safe_dist_ = 0.0;
370
371 // Gear Location
372 apollo::canbus::Chassis_GearPosition gear_location_;
373
374 // Readers.
375 std::shared_ptr<cyber::Reader<apollo::canbus::Chassis>> chassis_reader_;
376 std::shared_ptr<cyber::Reader<apollo::localization::Gps>> gps_reader_;
377 std::shared_ptr<cyber::Reader<apollo::localization::LocalizationEstimate>>
378 localization_reader_;
379 std::shared_ptr<cyber::Reader<apollo::perception::PerceptionObstacles>>
380 perception_obstacle_reader_;
381 std::shared_ptr<cyber::Reader<apollo::perception::TrafficLightDetection>>
382 perception_traffic_light_reader_;
383 std::shared_ptr<cyber::Reader<apollo::prediction::PredictionObstacles>>
384 prediction_obstacle_reader_;
385 std::shared_ptr<cyber::Reader<apollo::planning::ADCTrajectory>>
386 planning_reader_;
387 std::shared_ptr<cyber::Reader<apollo::control::ControlCommand>>
388 control_command_reader_;
389 std::shared_ptr<cyber::Reader<apollo::relative_map::NavigationInfo>>
390 navigation_reader_;
391 std::shared_ptr<cyber::Reader<apollo::relative_map::MapMsg>>
392 relative_map_reader_;
393 std::shared_ptr<cyber::Reader<apollo::audio::AudioEvent>> audio_event_reader_;
394 std::shared_ptr<cyber::Reader<apollo::common::DriveEvent>>
395 drive_event_reader_;
396 std::shared_ptr<cyber::Reader<apollo::common::monitor::MonitorMessage>>
397 monitor_reader_;
398 std::shared_ptr<cyber::Reader<apollo::planning::PlanningCommand>>
399 planning_command_reader_;
400 std::shared_ptr<cyber::Reader<apollo::storytelling::Stories>>
401 storytelling_reader_;
402 std::shared_ptr<cyber::Reader<apollo::audio::AudioDetection>>
403 audio_detection_reader_;
404 std::shared_ptr<cyber::Reader<apollo::task_manager::Task>> task_reader_;
405
406 // Writers.
407 std::shared_ptr<cyber::Writer<apollo::relative_map::NavigationInfo>>
408 navigation_writer_;
409 std::shared_ptr<cyber::Client<apollo::external_command::LaneFollowCommand,
411 lane_follow_command_client_;
412 std::shared_ptr<cyber::Client<apollo::external_command::ValetParkingCommand,
414 valet_parking_command_client_;
415 std::shared_ptr<cyber::Client<apollo::external_command::ActionCommand,
417 action_command_client_;
418 std::shared_ptr<cyber::Writer<apollo::routing::RoutingResponse>>
419 routing_response_writer_;
420 std::shared_ptr<cyber::Writer<apollo::task_manager::Task>> task_writer_;
421
422 FRIEND_TEST(SimulationWorldServiceTest, UpdateMonitorSuccess);
423 FRIEND_TEST(SimulationWorldServiceTest, UpdateMonitorRemove);
424 FRIEND_TEST(SimulationWorldServiceTest, UpdateMonitorTruncate);
425 FRIEND_TEST(SimulationWorldServiceTest, UpdateChassisInfo);
426 FRIEND_TEST(SimulationWorldServiceTest, UpdateLatency);
427 FRIEND_TEST(SimulationWorldServiceTest, UpdateLocalization);
428 FRIEND_TEST(SimulationWorldServiceTest, UpdatePerceptionObstacles);
429 FRIEND_TEST(SimulationWorldServiceTest, UpdatePlanningTrajectory);
430 FRIEND_TEST(SimulationWorldServiceTest, UpdateDecision);
431 FRIEND_TEST(SimulationWorldServiceTest, UpdatePrediction);
432 FRIEND_TEST(SimulationWorldServiceTest, UpdateRouting);
433 FRIEND_TEST(SimulationWorldServiceTest, UpdateGps);
434 FRIEND_TEST(SimulationWorldServiceTest, UpdateControlCommandWithSimpleLonLat);
435 FRIEND_TEST(SimulationWorldServiceTest, UpdateControlCommandWithSimpleMpc);
436 FRIEND_TEST(SimulationWorldServiceTest, DownsampleSpeedPointsByInterval);
437};
438
439} // namespace dreamview
440} // namespace apollo
const std::string & GetChannelName() const
Get Reader's Channel name
Reader subscribes a channel, it has two main functions:
Definition reader.h:69
bool Empty() const override
Query whether the Reader has data to be handled
Definition reader.h:378
virtual std::shared_ptr< MessageT > GetLatestObserved() const
Get the latest message we Observe
Definition reader.h:400
Cyber has builtin time type Time.
Definition time.h:31
double ToSecond() const
convert time to second.
Definition time.cc:77
This is a major component of the Simulation backend, which maintains a SimulationWorld object and kee...
void SetToClear()
Sets the flag to clear the owned simulation world object.
void Update()
The function Update() is periodically called to check for updates from the external messages.
void PublishNavigationInfo(const std::shared_ptr< apollo::relative_map::NavigationInfo > &)
void PublishTask(const std::shared_ptr< apollo::task_manager::Task > &)
nlohmann::json GetMapElements(double radius) const
Returns the json representation of the map element Ids and hash within the given radius from the car.
void PublishLaneFollowCommand(const std::shared_ptr< apollo::external_command::LaneFollowCommand > &)
nlohmann::json GetUpdateAsJson(double radius) const
Returns the json representation of the SimulationWorld object.
bool ReadyToPush() const
Check whether the SimulationWorld object has enough information.
const apollo::hdmap::Map & GetRelativeMap() const
const SimulationWorld & world() const
Get a read-only view of the SimulationWorld.
void GetMapElementIds(double radius, MapElementIds *ids) const
void PublishActionCommand(const std::shared_ptr< apollo::external_command::ActionCommand > &)
void PublishMonitorMessage(apollo::common::monitor::MonitorMessageItem::LogLevel log_level, const std::string &msg)
Publish message to the monitor
void GetWireFormatString(double radius, std::string *sim_world, std::string *sim_world_with_planning_data)
Returns the binary representation of the SimulationWorld object.
void PublishValetParkingCommand(const std::shared_ptr< apollo::external_command::ValetParkingCommand > &)
#define AINFO_EVERY(freq)
Definition log.h:82
#define AWARN
Definition log.h:43
The class of MonitorLogBuffer
bool DumpMessage(const std::shared_ptr< T > &msg, const std::string &dump_dir="/tmp")
class register implement
Definition arena_queue.h:37