repo_id
stringlengths
19
138
file_path
stringlengths
32
200
content
stringlengths
1
12.9M
__index_level_0__
int64
0
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/06_Perception/how_to_add_a_gps_receiver_cn.md
# 如何添加新的GPS接收器 ## 简介 GPS接收器是一种从GPS卫星上接收信息,然后根据这些信息计算设备地理位置、速度和精确时间的设备。这种设备通常包括一个接收器,一个IMU(Inertial measurement unit,惯性测量单元),一个针对轮编码器的接口以及一个将各传感器获取的数据融合到一起的融合引擎。Apollo系统中默认使用Novatel 板卡,该说明详细介绍如何添加并使用一个新的GPS接收器。 ## 添加GPS新接收器的步骤 请按照下面的步骤添加新的GPS接收器. 1. 通过继承基类“Parser”,实现新GPS接收器的数据解析器 2. 在Parser类中为新GPS接收器添加新接口 3. 在文件`config.proto`中, 为新GPS接收器添加新数据格式 4. 在函数`create_parser`(见文件data_parser.cpp), 为新GPS接收器添加新解析器实例 下面让我们用上面的方法来添加u-blox GPS接收器。 ### 步骤 1 通过继承类“Parser”,为新GPS接收器实现新的数据解析器: ```cpp class UbloxParser : public Parser { public: UbloxParser(); virtual MessageType get_message(MessagePtr& message_ptr); private: bool verify_checksum(); Parser::MessageType prepare_message(MessagePtr& message_ptr); // The handle_xxx functions return whether a message is ready. bool handle_esf_raw(const ublox::EsfRaw* raw, size_t data_size); bool handle_esf_ins(const ublox::EsfIns* ins); bool handle_hnr_pvt(const ublox::HnrPvt* pvt); bool handle_nav_att(const ublox::NavAtt *att); bool handle_nav_pvt(const ublox::NavPvt* pvt); bool handle_nav_cov(const ublox::NavCov *cov); bool handle_rxm_rawx(const ublox::RxmRawx *raw); double _gps_seconds_base = -1.0; double _gyro_scale = 0.0; double _accel_scale = 0.0; float _imu_measurement_span = 0.0; int _imu_frame_mapping = 5; double _imu_measurement_time_previous = -1.0; std::vector<uint8_t> _buffer; size_t _total_length = 0; ::apollo::drivers::gnss::Gnss _gnss; ::apollo::drivers::gnss::Imu _imu; ::apollo::drivers::gnss::Ins _ins; }; ``` ### 步骤 2 在Parser类中,为新GPS接收器添加新的接口: 在Parser类中添加函数‘create_ublox‘: ```cpp class Parser { public: // Return a pointer to a NovAtel parser. The caller should take ownership. static Parser* create_novatel(); // Return a pointer to a u-blox parser. The caller should take ownership. static Parser* create_ublox(); virtual ~Parser() {} // Updates the parser with new data. The caller must keep the data valid until get_message() // returns NONE. void update(const uint8_t* data, size_t length) { _data = data; _data_end = data + length; } void update(const std::string& data) { update(reinterpret_cast<const uint8_t*>(data.data()), data.size()); } enum class MessageType { NONE, GNSS, GNSS_RANGE, IMU, INS, WHEEL, EPHEMERIDES, OBSERVATION, GPGGA, }; // Gets a parsed protobuf message. The caller must consume the message before calling another // get_message() or update(); virtual MessageType get_message(MessagePtr& message_ptr) = 0; protected: Parser() {} // Point to the beginning and end of data. Do not take ownership. const uint8_t* _data = nullptr; const uint8_t* _data_end = nullptr; private: DISABLE_COPY_AND_ASSIGN(Parser); }; Parser* Parser::create_ublox() { return new UbloxParser(); } ``` ### 步骤 3 在config.proto文件中, 为新的GPS接收器添加新的数据格式定义: 在配置文件(modules/drivers/gnss/proto/config.proto)中添加`UBLOX_TEXT` and `UBLOX_BINARY` ```txt message Stream { enum Format { UNKNOWN = 0; NMEA = 1; RTCM_V2 = 2; RTCM_V3 = 3; NOVATEL_TEXT = 10; NOVATEL_BINARY = 11; UBLOX_TEXT = 20; UBLOX_BINARY = 21; } ... ... ``` ### 步骤 4 在函数`create_parser`(见data_parser.cpp), 为新GPS接收器添加新解析器实例. 我们将通过添加处理`config::Stream::UBLOX_BINARY`的代码实现上面的步骤,具体如下。 ``` cpp Parser* create_parser(config::Stream::Format format, bool is_base_station = false) { switch (format) { case config::Stream::NOVATEL_BINARY: return Parser::create_novatel(); case config::Stream::UBLOX_BINARY: return Parser::create_ubloxl(); default: return nullptr; } } ```
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/15_FAQS/Calibration_FAQs_cn.md
# 传感器标定 FAQs ## 如何查看传感器是否有数据输出? 使用 rostopic 命令。例如,查看 HDL-64ES3 的输出,可以在终端中输入: ```bash rostopic echo /apollo/sensor/velodyne64/VelodyneScanUnified ``` 若该 topic 的数据会显示在终端上,则激光雷达工作正常。 ## 如何查看车辆的定位状态? 以使用 Novatel 组合惯导为例,在终端中输入: ```bash rostopic echo /apollo/sensor/gnss/ins_stat ``` 找到“pos_type”字段,若该字段的值为 56,则表示进入了良好的定位状态 (RTK_FIXED), 可以用于标定。若不为 56,则无法获得可靠的标定结果。 ## 如何进行质检? 目前进行质检方法主要通过人工来完成。标定完成后,页面会提供标定过程中拼接得到的点 云。若标定结果良好,会得到锐利和清晰的拼接点云,可反映出标定场地的细节。通常质检 的参照物有平整的建筑立面、路灯和电线杆以及路沿等。若标定质量较差,则会使拼接点云 出现一些模糊、重影的效果。图 1 是两张不同标定质量的拼接点云对比。 ![](../quickstart/images/calibration/lidar_calibration/good_calib.png) <p align="center"> (a) </p> ![](../quickstart/images/calibration/lidar_calibration/poor_calib.png) <p align="center"> (b) </p> <p align="center"> 图1. (a) 高质量的标定结果 (b) 质量较差的标定结果。 </p> ## 如何解决标定程序权限错误? Output path 需要`write`权限来创建文件夹以及保存标定结果,若缺少相关权限,则会出 现如下错误: ```bash terminate called after throwing an instance of ‘boost::filesystem::filesystem_error’ what(): boost::filesystem::create_directories: permission denied: "***" ``` 输入以下命令,来为 Output path 添加`write`权限: ```bash # 为output path(如:/apollo/modules/calibration/data/mkz8)添加write权限 sudo chmod a+w /apollo/modules/calibration/data/mkz8 -R ``` ## 如何解决执行 sensor_calibration.sh 时出现的权限错误? Log 存储文件夹需要`write`权限来创建日志,若缺少相关权限,则会出现如下错误: ```bash tee: /apollo/data/log/***.out: permission denied ``` 输入以下命令,来为脚本添加`write`权限: ```bash sudo chmod a+x /apollo/data/log ```
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/15_FAQS/Hardware_FAQs_cn.md
# 硬件 FAQs: ### Apollo 需要什么硬件支持? Apollo 各个版本所必须用的硬件可以在一下的链接中找到: - [Hardware for Apollo 1.0](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_1_0_hardware_system_installation_guide.md) - [Hardware for Apollo 1.5](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_1_5_hardware_system_installation_guide.md) - [Hardware for Apollo 2.0](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_2_0_hardware_system_installation_guide_v1.md) - [Hardware for Apollo 2.5](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_2_5_hardware_system_installation_guide_v1.md) ## Apollo 可以在什么样的车上使用? 目前,Apollo 的控制算法只在林肯 MKZ 中配置(我们的默认车辆)。如果你想使用不同的 车辆类型,请访问[这里](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%80%82%E9%85%8D/how_to_add_a_new_vehicle.md). ## Apollo 支持哪种 LiDAR? 在 Apollo 1.5 中,只支持 Velodyne 64。但欢迎开发者在 ROS 中加入驱动以便支持其他 类型的 LiDAR。
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/15_FAQS/Dreamview_FAQs.md
# DreamView FAQs ## I had difficulty connecting to <http://localhost:8888> (Dreamview Web UI). The Dreamview web server is provided by the dreamview node (A node is an executable in CyberRT terminology). Before accessing Dreamview Web UI, make sure Apollo is built within Apollo development Docker container following [Apollo Software Installation Guide](../01_Installation%20Instructions/apollo_software_installation_guide.md). Once built, dreamview node will be started by running `bash scripts/bootstrap.sh`. So if you can not access Dreamview, please check: - Make sure you have the Dreamview process running correctly. In the latest version, `bash scripts/bootstrap.sh` will report `dreamview: ERROR (spawn error)` if dreamview fails to start. You can also check with command: `ps aux | grep dreamview`. - Make sure the address and port are not blocked by the firewall. - Make sure you're using `<apollo_host_ip>:8888` instead of `localhost:8888` if you are accessing the Dreamview UI through another host. --- ## Dreamview does not open up if I install more than 1 version of Apollo? This issue occured because of port conflict error. Even though you setup two different docker environments, both of them are still trying to use port 8888 on your machine, therefore causing a port conflict issue. If you'd like to run both versions at the same time, please make sure different ports are set. To do so, 1. Open `dreamview.conf` file under modules/dreamview/conf add `--server_ports=<PORT_NUMBER>` to the end of the file. Ex: --flagfile=modules/common/data/global_flagfile.txt --server_ports=5555 2. Restart apollo This way, dreamview can be accessed from http://localhost:<PORT_NUMBER> (http://localhost:5555 for this example) --- ## Dreamview is too slow. How do I resolve it? If you feel Dreamview is taking too long to load/work, please run both the [WebGL reports](http://webglreport.com/?v=1). If there are any missing drivers, please install them --- ## How to draw anything in Dreamview (e.g. an arrow) Dreamview uses https://github.com/mrdoob/three.js as graphics library. You can modify the frontend code to draw an arrow using the corresponding API of the library. After that you need to run a `./apollo.sh build_fe` to compile. --- ## How can I test planning algorithms offline? Use dreamview and enable sim_control on dreamview to test your planning algorithm. --- ## Adding a new point of interest permanently in the Dreamview interface There's a default_end_way_point file for each map to specify point of interest, you can refer to [the following file](../../modules/map/data/demo/default_end_way_point.txt). --- ## What's the function of sim_control in the backend of dreamview It simulates a SDC's control module, and moves the car based on planning result. This is a really convenient way to visualize and test planning module --- ## How do I turn on Sim Control? Purpose of sim control: drive the car based on the planning trajectory. Good for debugging planning algorithms. **Apollo 2.5 or after**: simply turning on the SimControl switch as seen in the image below: ![](images/sim_control_2.5.png) **Apollo 2.0 or older**: you would need to enable the sim control manually, which can be performed as follows: 1. Open `modules/dreamview/conf/dreamview.conf` 2. Add **“--enable_sim_control=true”** to the second line of the file 3. Restart apollo using our bootstrap script ```bash bash scripts/bootstrap.sh stop bash scripts/bootstrap.sh start ``` **Please note**, planning and routing modules (see image below) should be ON while using SimControl. To navigate the ego-car, select either “route editing” or “default routing” from the side bar to define a route. You can turn the sim_control on and off from the toggle. However, a new routing request is needed each time the sim_control is restarted. ![](images/sim_control_2.0.png) --- ## I want to plot my own graphs for my algorithms, where should I go? Go to the PnC Monitor section in [Dreamview Doc](../13_Apollo%20Tool/%E5%8F%AF%E8%A7%86%E5%8C%96%E4%BA%A4%E4%BA%92%E5%B7%A5%E5%85%B7Dremview/dreamview_usage_table.md). --- ## What is Dreamland? Dreamland is Apollo's web-based simulation platform. Based on an enormous amount of driving scenario data and large-scale cloud computing capacity, Apollo simulation engine creates a powerful testing environment for the development of an autonomous driving system, from algorithms to grading, and then back to improved algorithms. It enables the developers and start-ups to run millions of miles of simulation daily, which dramatically accelerates the development cycle. To access Dreamland, please visit [our Simulation website](http://apollo.auto/platform/simulation.html) and join now! --- **More DreamView FAQs to follow.**
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/15_FAQS/Hardware_FAQs.md
# Hardware FAQs ### What hardware is needed for Apollo? The required hardware for each version of Apollo can be found at the following links: - [Hardware for Apollo 1.0](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_1_0_hardware_system_installation_guide.md) - [Hardware for Apollo 1.5](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_1_5_hardware_system_installation_guide.md) - [Hardware for Apollo 2.0](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_2_0_hardware_system_installation_guide_v1.md) - [Hardware for Apollo 2.5](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_2_5_hardware_system_installation_guide_v1.md) --- ### Which types of vehicles can Apollo be run on? Currently, the Apollo control algorithm is configured for our default vehicle, which is a Lincoln MKZ. If you would like to use a different vehicle type, please visit [this](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%80%82%E9%85%8D/how_to_add_a_new_vehicle.md) page. --- ### Which types of LiDAR are supported by Apollo? In Apollo 1.5, only Velodyne 64 is supported. Users are welcome to add drivers to ROS in order to support other models of LiDAR. --- ### Do you have a list of Hardware devices that are compatible with Apollo Refer to the [Hardware Installation Guide 3.0](../quickstart/apollo_3_0_hardware_system_installation_guide.md) for information on all devices that are compatible with Apollo 3.0. If you are looking for a different version of Apollo, refer to that version's Hardware Installation guide found under `docs/quickstart` --- ### What is the difference between Apollo Platform Supported devices and Apollo Hardware Development Platform Supported device? 1. Apollo Platform Supported means - The device is part of the Apollo hardware reference design - One or more device(s) has/have been tested and passed to become a fully functional module of the corresponding hardware category, which provides adequate support for upper software layers 2. Apollo Hardware Development Platform supported means one or more device(s) has/have been tested and passed for data collection purpose only. Please note, that in order to collect useful data, it is required for the device to work with the rest of necessary hardware devices listed in the Apollo Reference Design. In order to achieve the same performance in Perception and other upper software modules, it would require extra effort from the developers’ side, including the creation of new model(s), annotation of the data, training the new models, etc. --- ### I do not have an IMU, now what? Without an IMU, the localization would depend on GPS system which only updates once per second. On top of that, you wouldn't have velocity and heading information of your vehicle. That is probably not a good idea unless you have other solutions. --- ### I have only VLP16, can I work with it? The documentation advises me to use HDL64 HDL64 provides a much denser point cloud than VLP-16 can. It gives a further detection range for obstacles. That is why we recommend it in the reference design. Whether VLP-16 works for your project, you will need to find out. --- ### Is HDL32 (Velodyne 32 line LiDAR) compatible with Apollo? Apollo can work successfully for HDL32 Lidars. You could follow the [Puck Series Guide](../specs/Lidar/VLP_Series_Installation_Guide.md) alongwith the following [modification](https://github.com/ApolloAuto/apollo/commit/df37d2c79129434fb90353950a65671278a4229e#diff-cb9767ab272f7dc5b3e0d870a324be51). However, please note that you would need to change the intrinsics for HDL32 in order to avoid [the following error](https://github.com/ApolloAuto/apollo/issues/5244). --- ### How to set the USB cameras to provide valid time stamp? First use time_sync.sh script to sync the system clock to NTP servers. Then reset UVCVideo module with clock set to realtime with root access. ``` rmmod UVCVideo; modprobe UVCVideo clock=realtime ``` --- **More Hardware FAQs to follow.**
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/15_FAQS/Calibration_FAQs.md
# Calibration FAQs ## How to Check Sensor Output? Use the `rostopic` command. For example, type the following command to check the output of HDL-64ES3: ```bash rostopic echo /apollo/sensor/velodyne64/VelodyneScanUnified ``` If the topic data is displayed on the terminal, the LiDAR works normally. ## How to Check INS Status? Using Novatel INS as an example, type the following command to check the INS status: ```bash rostopic echo /apollo/sensor/gnss/ins_stat ``` Find the `pos_type` field: If the value is 56, it has entered a good positioning status (RTK_FIXED) and can be used for calibration. If it is not 56, reliable calibration results cannot be obtained. ## How to Complete a Quality Inspection? At present, you complete the quality verification manually with a visual inspection of the results. When the calibration is completed, the point cloud stitched during the calibration process is provided. In the point cloud, details of the calibration field can be easily identified. Assess the calibration quality for clarity. Look at objects such as building facades, street lights, poles and road curbs. If the point cloud is blurry and a ghosting effect can be found, the calibration is poor. If the calibration result is good, a sharp and clear stitched point cloud is shown. Figure 1 shows the comparison between the stitched point clouds with good (a) and insufficient(b) calibration quality. ![](../quickstart/images/calibration/lidar_calibration/good_calib.png) <p align="center"> (a) </p> ![](../quickstart/images/calibration/lidar_calibration/poor_calib.png) <p align="center"> (b) </p> <p align="center"> Figure 1. (a) a high quality calibration result (b) an insufficient one. </p> ## How to solve the permission error of calibration tools? Output path needs `write` permission to be created folders and saved results. If the path is missing the relevant permissions, you will receive the following error: ```bash terminate called after throwing an instance of 'boost::filesystem::filesystem_error' what(): boost::filesystem::create_directories: permission denied: "***" ``` Enter the following command to add `write` permission: ```bash # add write permission to output path(e.g. /apollo/modules/calibration/data/mkz8) sudo chmod a+w /apollo/modules/calibration/data/mkz8 -R ``` ## How to solve permission error when running sensor_calibration.sh? Log path needs `write` permission to be created log files. If it is missing the relevant permissions, you will receive the following error: ```bash tee: /apollo/data/log/***.out: permission denied ``` Enter the following command to add `write` permission: ```bash sudo chmod a+w /apollo/data/log ```
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/15_FAQS/README.md
# FAQs Index - [General FAQs](General_FAQs.md) - [General FAQs 中文版](General_FAQs_cn.md) - [Calibration FAQs](Calibration_FAQs.md) - [Calibration FAQs 中文版](Calibration_FAQs_cn.md) - [Perception FAQs](Perception_FAQs.md) - [Dreamview FAQs](Dreamview_FAQs.md) - [Hardware FAQs](Hardware_FAQs.md) - [Hardware FAQs 中文版](Hardware_FAQs_cn.md) - [Software FAQs](Software_FAQs.md) - [Software FAQs 中文版](Software_FAQs_cn.md) - [Cyber RT FAQs](CyberRT_FAQs.md)
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/15_FAQS/Perception_FAQs.md
# Perception FAQs ## How many typer of sensors calibrations are present? There are 5 types of calibration: - Camera - Camera - Camera - LiDAR - Radar - Camera - LiDAR - GNSS - IMU - Vehicle For additional information on Sensor Calibration, please refer to our [calibration guide](../10Hardware%20Integration%20and%20Calibration/%E4%BC%A0%E6%84%9F%E5%99%A8%E6%A0%87%E5%AE%9A/apollo_2_0_sensor_calibration_guide.md) For additional information on LiDAR - GNSS calibration please refer to our [LiDAR - GNSS calibration guide](https://github.com/ApolloAuto/apollo/blob/r1.5.0/docs/quickstart/apollo_1_5_lidar_calibration_guide.md) --- ## Is the order of sensor calibration important at all ? Can I do IMU - vehicle before Radar - Camera ? Yes it is important, but you could calibrate the IMU - Vehicle before Radar - Camera --- ## Are you going to release the source code for the calibration tools ? No, we currently have not released the source code for our calibration tools. --- ## How do you ensure that the right calibration files are loaded for the perception module ? In each car, specific Camera parameters should be saved and the default parameters will be replaced by the saved parameters when you install the release version. When user select a vehicle, we'll copy files from calibration/data/[vehicle]/[src_data] to target places. The code is at [Link](../../modules/dreamview/backend/hmi/vehicle_manager.cc). This action is totally configurable, see the [example here](../../modules/dreamview/conf/vehicle_data.pb.txt) --- ## I am trying to run the extrinsic sensor calibration tools and they seem to complain about the INS_STAT not being 56. But when I echo the /apollo/sensor/gnss/ins_stat topic I can see that the position type is 56. What could be the problem? The error log occurs (stat=-1) whenever the tool has not received any GNSS message or the image stamp is not correct. Please check the topic of GNSS message or image stamp. --- **More Perception FAQs to follow**
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/15_FAQS/Software_FAQs_cn.md
# 软件 FAQ ## 除了 Ubuntu 之外,能用其它操作系统吗? 我们只对 Ubuntu 进行了测试,这意味着它是我们目前正式支持的唯一操作系统。欢迎开发 者尝试不同的操作系统,如果能够成功地使用它们,可以分享补丁与社区。 ## 在链接到 localhost:8888(DreamView)时有问题 Dreamview 网页服务器由 Dreamview 节点提供。在访问 Dreamview 页面之前,您需要按 照[Apollo 软件安装指南](../01_Installation%20Instructions/apollo_software_installation_guide.md) 编 译 DOCKER 容器内的系统(包括 Dreamview 节点)。一旦编译成功,Dreamview 节点将在 步骤 `bash scripts/bootstrap.sh` 中启动。 因此,如果你不能访问 Dreamview,请检查: - 确保您的 Dreamview 进程正确运行。在最新版本中,如果 Dreamview 无法启动 ,`bash scripts/bootstrap.sh`会报告`dreamview: ERROR (spawn error)`。或使用命 令检查: `ps aux | grep dreamview`。 - 确保地址和端口不被防火墙拦截。 - 如果您是通过其它主机访问 Dreamview 页面,确保您使用的是 `<apollo_host_ip>:8888` 而不是 `localhost:8888`。 ## 我如何进行分步调试? 大多数 bug 可以通过日志记录找到(使用 AERROR, AINFO, ADEBUG)。如果需要一步一步 的调试,我们建议使用 GDB.
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/15_FAQS/CyberRT_FAQs.md
Please refer to [Apollo CyberRT FAQ](../04_CyberRT/CyberRT_FAQs.md) under the `docs/cyber` directory.
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/15_FAQS/General_FAQs.md
# General FAQs ## I am new to the Apollo project, where do I start? You have several options: - To build apollo on your computer, start by reviewing [Apollo Software Installation Guide](../01_Installation%20Instructions/apollo_software_installation_guide.md) - To run the Apollo demo offline, go to: [Apollo README.md](../02_Quick%20Start/demo_guide/README.md). - To install and build Apollo on a vehicle, go to: [Apollo 1.0 quick start](../02_Quick%20Start/apollo_1_0_quick_start.md). - To build the Apollo Kernel, the Robot Operating System (ROS), and Apollo, go to: [apollo/docs/quickstart/apollo_1_0_quick_start_developer.md](../02_Quick%20Start/apollo_1_0_quick_start_developer.md) and refer to [build kernel](../02_Quick%20Start/apollo_1_0_quick_start_developer.md#build-the-apollo-kernel). --- ## How do I send a pull request? Sending a pull request is simple. 1. Fork the Apollo Repository into your GitHub. 2. Create a Developer Branch in your Repository. 3. Commit your change in your Developer Branch. 4. Send the pull request from your GitHub Repository Webpage. --- ## Do comments need to be made in Doxygen? Yes, currently all comments need to be made in Doxygen. --- ## How to debug build problems? 1. Carefully review the instructions in the documentation for the option that you selected to get started with the Apollo project. 2. Make sure that you follow the steps in the document exactly as they are written. 3. Use Ubuntu 14.04 as the build can only be implemented using Linux. 4. Verify that the Internet setting is correct on your computer. 5. Allocate more than 1GB of memory, at the recommended minimum, for your computer. 6. If roscore cannot start in apollo docker, you may need to tune the master start timeout value in ROS. You may want to check a related user-reported [issue](https://github.com/ApolloAuto/apollo/issues/2500) for more details. --- ## If I cannot solve my build problems, what is the most effective way to ask for help? Many build problems are related to the environment settings. 1. Run the script to get your environment: `bash scripts/env.sh >& env.txt` 2. Post the content of env.txt to our Github issues page and someone from our team will get in touch with you. --- ## Which ports must be whitelisted to run Apollo in a public cloud instance? Use these ports for HMI and Dreamview: - 8888: Dreamview --- ## Why there is no ROS environment in dev docker? The ROS package is downloaded when you start to build apollo: `bash apollo.sh build`. 1. Run the following command inside Docker to set up the ROS environment after the build is complete: `source /apollo/scripts/apollo_base.sh` 2. Run ROS-related commands such as rosbag, rostopic and so on. --- ## How do I clean the existing build output? Follow these steps: 1. Log into Docker using the command: `bash docker/scripts/dev_into.sh` 2. Run the command: `bash apollo.sh clean` --- ## How do I delete the downloaded third party dependent packages? Follow these steps: 1. Log into Docker using the command: `bash docker/scripts/dev_into.sh` 2. Run the command: `bazel clean --expunge` The build command, `bash apollo.sh build`, then downloads all of the dependent packages according to the _WORKSPACE_ file. **More General FAQs to follow.**
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/15_FAQS/General_FAQs_cn.md
# General FAQs_cn ## 请问我怎么样使用pull request? 使用pull request非常简单。 1. 将Apollo Repository fork到你自己的Github中。 2. 在你的Repository中建立一个开发者 Branch。 3. 在开发者Branch中commit你做的任何的改变 4. 在你的github网页中使用pull request ## 注释需要写在Doxygen中吗? 目前所有的注释都应写在Doxygen中。 **参考更多的FAQs**
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/15_FAQS/Software_FAQs.md
# Software FAQs ## Can other operating systems besides Ubuntu be used? We have only tested on Ubuntu which means it's the only operating system we currently officially support. Users are always welcome to try different operating systems and can share their patches with the community if they are successfully able to use them. --- ## How can I perform step-by-step debugging? The majority of bugs can be found through logging (using AERROR, AINFO, ADEBUG). If step-by-step debugging is needed, we recommend using gdb. --- ## How do I add a new module Apollo currently functions as a single system, therefore before adding a module to it, understand that there would be a lot of additional work to be done to ensure that the module functions perfectly with the other modules of Apollo. Simply add your module to the `modules/` folder. You can use `modules/routing` as an example, which is a relatively simple module. Write the BUILD files properly and apollo.sh will build your module automatically --- ## Build error "docker: Error response from daemon: failed to copy files: userspace copy failed": An error message like this means that your system does not have enough space to build Apollo. To resolve this issue, run the following command to free up some space on your host: ``` docker/setup_host/cleanup_resources.sh ``` Run `bash apollo.sh clean -a` inside Docker to free more. --- ## Bootstrap error: unix:///tmp/supervisor.sock refused connection There could be a number of reasons why this error occurs. Please follow the steps recommended in the [following thread](https://github.com/ApolloAuto/apollo/issues/5344). There are quite a few suggestions. If it still does not work for you, comment on the thread mentioned above. --- ## My OS keeps freezing when building Apollo 3.5? If you see an error like this, you do not have enough memory to build Apollo. Please ensure that you have at least **16GB** memory available before building Apollo. You could also find `--jobs=$(nproc)` in apollo.sh file and replace it with `--jobs=2`. This will make build process to use only 2 cores. Building will be longer, but will use less memory. --- **More Software FAQs to follow.**
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/10_Control/how_to_add_a_new_control_algorithm_cn.md
# 如何添加新的控制算法 Apollo中的控制算法由一个或多个控制器组成,可以轻松更改或替换为不同的算法。 每个控制器将一个或多个控制命令输出到`CANbus`。 Apollo中的默认控制算法包含横向控制器(LatController)和纵向控制器(LonController)。 它们分别负责横向和纵向的车辆控制。 新的控制算法不必遵循默认模式,例如,一个横向控制器+一个纵向控制器。 它可以是单个控制器,也可以是任意数量控制器的组合。 添加新的控制算法的步骤: 1. 创建一个控制器 2. 在文件`control_config` 中添加新控制器的配置信息 3. 注册新控制器 为了更好的理解,下面对每个步骤进行详细的阐述: ## 创建一个控制器 所有控制器都必须继承基类`Controller`,它定义了一组接口。 以下是控制器实现的示例: ```c++ namespace apollo { namespace control { class NewController : public Controller { public: NewController(); virtual ~NewController(); Status Init(const ControlConf* control_conf) override; Status ComputeControlCommand( const localization::LocalizationEstimate* localization, const canbus::Chassis* chassis, const planning::ADCTrajectory* trajectory, ControlCommand* cmd) override; Status Reset() override; void Stop() override; std::string Name() const override; }; } // namespace control } // namespace apollo ``` ## 在文件`control_config` 中添加新控制器的配置信息 按照下面的步骤添加新控制器的配置信息: 1. 根据算法要求为新控制器配置和参数定义`proto`。作为示例,可以参考以下位置的`LatController`的`proto`定义:`modules/control/proto/ lat_controller_conf.proto` 2. 定义新的控制器`proto`之后,例如`new_controller_conf.proto`,输入以下内容: ```protobuf syntax = "proto2"; package apollo.control; message NewControllerConf { double parameter1 = 1; int32 parameter2 = 2; } ``` 3. 参考如下内容更新 `modules/control/proto/control_conf.proto`文件: ```protobuf optional apollo.control.NewControllerConf new_controller_conf = 15; ``` 4. 参考以内容更新 `ControllerType`(在`modules/control/proto/control_conf.proto` 中): ```protobuf enum ControllerType { LAT_CONTROLLER = 0; LON_CONTROLLER = 1; NEW_CONTROLLER = 2; }; ``` 5. `protobuf`定义完成后,在`modules/control/conf/control_conf.pb.txt`中相应更新控制配置文件。 ``` 注意:上面的"control/conf"文件是Apollo的默认文件。您的项目可能使用不同的控制配置文件. ``` ## 注册新控制器 要激活Apollo系统中的新控制器,请在如下文件中的“ControllerAgent”中注册新控制器: > modules/control/controller/controller_agent.cc 按照如下示例添加注册信息: ```c++ void ControllerAgent::RegisterControllers() { controller_factory_.Register( ControlConf::NEW_CONTROLLER, []() -> Controller * { return new NewController(); }); } ``` 在完成以上步骤后,您的新控制器便可在Apollo系统中生效。
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/10_Control/how_to_add_a_new_can_card_cn.md
# 如何添加新的CAN卡 ## 简介 控制器区域网络(CAN)是在许多微控制器和设备中密集使用的网络,用于在没有主计算机帮助的情况下在设备之间传输数据。 Apollo中使用的默认CAN卡是 **ESD CAN-PCIe卡**。您可以使用以下步骤添加新的CAN卡: ## 添加新CAN卡 添加新的CAN卡需要完成以下几个步骤: 1. 实现新CAN卡的`CanClient`类。 2. 在`CanClientFactory`中注册新的CAN卡。 3. 更新配置文件。 以下步骤展示了如何添加新的CAN卡 - 示例添加CAN卡到您的工程。 ### 步骤 1 实现新CAN卡的CanClient类 下面的代码展示了如何实现 `CANClient` 类: ```cpp #include <string> #include <vector> #include "hermes_can/include/bcan.h" #include "modules/canbus/can_client/can_client.h" #include "modules/canbus/common/canbus_consts.h" #include "modules/common/proto/error_code.pb.h" /** * @namespace apollo::canbus::can * @brief apollo::canbus::can */ namespace apollo { namespace canbus { namespace can { /** * @class ExampleCanClient * @brief The class which defines a Example CAN client which inherits CanClient. */ class ExampleCanClient : public CanClient { public: /** * @brief Initialize the Example CAN client by specified CAN card parameters. * @param parameter CAN card parameters to initialize the CAN client. * @return If the initialization is successful. */ bool Init(const CANCardParameter& parameter) override; /** * @brief Destructor */ virtual ~ExampleCanClient() = default; /** * @brief Start the Example CAN client. * @return The status of the start action which is defined by * apollo::common::ErrorCode. */ apollo::common::ErrorCode Start() override; /** * @brief Stop the Example CAN client. */ void Stop() override; /** * @brief Send messages * @param frames The messages to send. * @param frame_num The amount of messages to send. * @return The status of the sending action which is defined by * apollo::common::ErrorCode. */ apollo::common::ErrorCode Send(const std::vector<CanFrame>& frames, int32_t* const frame_num) override; /** * @brief Receive messages * @param frames The messages to receive. * @param frame_num The amount of messages to receive. * @return The status of the receiving action which is defined by * apollo::common::ErrorCode. */ apollo::common::ErrorCode Receive(std::vector<CanFrame>* const frames, int32_t* const frame_num) override; /** * @brief Get the error string. * @param status The status to get the error string. */ std::string GetErrorString(const int32_t status) override; private: ... ... }; } // namespace can } // namespace canbus } // namespace apollo ``` ### 步骤 2 在CanClientFactory中注册新CAN卡, 在 `CanClientFactory`中添加如下代码: ```cpp void CanClientFactory::RegisterCanClients() { Register(CANCardParameter::ESD_CAN, []() -> CanClient* { return new can::EsdCanClient(); }); // register the new CAN card here. Register(CANCardParameter::EXAMPLE_CAN, []() -> CanClient* { return new can::ExampleCanClient(); }); } ``` ### 步骤 3 接下来,需要更新配置文件 在`/modules/canbus/proto/can_card_parameter.proto`添加 EXAMPLE_CAN ```proto message CANCardParameter { enum CANCardBrand { FAKE_CAN = 0; ESD_CAN = 1; EXAMPLE_CAN = 2; // add new CAN card here. } ... ... } ``` Update `/modules/canbus/conf/canbus_conf.pb.txt` ```txt ... ... can_card_parameter { brand:EXAMPLE_CAN type: PCI_CARD // suppose the new can card is PCI_CARD channel_id: CHANNEL_ID_ZERO // suppose the new can card has CHANNEL_ID_ZERO } ... ... ```
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/10_Control/how_to_tune_control_parameters_cn.md
# 如何调节控制参数 ## 引言 控制模块的目标是基于计划轨迹和当前车辆状态生成控制命令给车辆。 ## 背景 ### 输入/输出 #### 输入 * 规划轨迹 * 当前的车辆状态 * HMI驱动模式更改请求 * 监控系统 #### 输出 输出控制命令管理`canbus`中的转向、节流和制动等功能。 ### 控制器介绍 控制器包括管理转向指令的横向控制器和管理节气门和制动器命令的纵向控制器。 #### 横向控制器 横向控制器是基于LQR的最优控制器。 该控制器的动力学模型是一个简单的带有侧滑的自行车模型。它被分为两类,包括闭环和开环。 - 闭环提供具有4种状态的离散反馈LQR控制器: - 横向误差 - 横向误差率 - 航向误差 - 航向误差率 - 开环利用路径曲率信息消除恒定稳态航向误差。 #### 纵向控制器 纵向控制器配置为级联PID +校准表。它被分为两类,包括闭环和开环。 - 闭环是一个级联PID(站PID +速度PID),它将以下数据作为控制器输入: - 站误差 - 速度误差 - 开环提供了一个校准表,将加速度映射到节气门/制动百分比。 ## 控制器调谐 ### 实用工具 类似于[诊断](../../modules/tools/diagnostics) 和 [realtime_plot](../../modules/tools/realtime_plot) 可用于控制器调优,并且可以在`apollo/modules/tools/`中找到. ### 横向控制器的整定 横向控制器设计用于最小调谐力。“所有”车辆的基础横向控制器调谐步骤如下: 1. 将`matrix_q` 中所有元素设置为零. 2. 增加`matrix_q`中的第三个元素,它定义了航向误差加权,以最小化航向误差。 3. 增加`matrix_q`的第一个元素,它定义横向误差加权以最小化横向误差。 #### 林肯MKZ调谐 对于Lincoln MKZ,有四个元素指的是状态加权矩阵Q的对角线元素: - 横向误差加权 - 横向误差率加权 - 航向误差加权 - 航向差错率加权 通过在横向控制器调谐中列出的基本横向控制器调整步骤来调整加权参数。下面是一个例子。 ``` lat_controller_conf { matrix_q: 0.05 matrix_q: 0.0 matrix_q: 1.0 matrix_q: 0.0 } ``` #### 调谐附加车辆类型 当调整除林肯MKZ以外的车辆类型时,首先更新车辆相关的物理参数,如下面的示例所示。然后,按照上面列出的基本横向控制器调整步骤*横向控制器调谐*和定义矩阵Q参数。 下面是一个例子. ``` lat_controller_conf { cf: 155494.663 cr: 155494.663 wheelbase: 2.85 mass_fl: 520 mass_fr: 520 mass_rl: 520 mass_rr: 520 eps: 0.01 steer_transmission_ratio: 16 steer_single_direction_max_degree: 470 } ``` ### 纵控制器的调谐 纵向控制器由级联的PID控制器组成,该控制器包括一个站控制器和一个具有不同速度增益的高速/低速控制器。Apollo管理开环和闭环的调谐通过: - 开环: 校准表生成。请参阅[how_to_update_vehicle_calibration.md](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E6%A0%87%E5%AE%9A/how_to_update_vehicle_calibration.md)的详细步骤 - 闭环: 基于高速控制器->低速控制器->站控制器的顺序。 #### 高/低速控制器的调谐 高速控制器代码主要用于跟踪高于某一速度值的期望速度。例如: ``` high_speed_pid_conf { integrator_enable: true integrator_saturation_level: 0.3 kp: 1.0 ki: 0.3 kd: 0.0 } ``` 1. 首先将`kp`, `ki`, 和 `kd` 的值设为0. 2. 然后开始增加`kp`的值,以减小阶跃响应对速度变化的上升时间。 3. 最后,增加`ki`以降低速度控制器稳态误差。 一旦获得较高速度的相对准确的速度跟踪性能,就可以开始从起点开始调整低速PID控制器以获得一个舒适的加速率。 ``` low_speed_pid_conf { integrator_enable: true integrator_saturation_level: 0.3 kp: 0.5 ki: 0.3 kd: 0.0 } ``` *注意:* 当设备切换到 *Drive*时,Apollo 通常将速度设置为滑行速度。 #### 站控制器调谐 Apollo 使用车辆的站控制器来跟踪车辆轨迹基准与车辆位置之间的站误差。 一个站控制器调谐示例如下所示。 ``` station_pid_conf { integrator_enable: true integrator_saturation_level: 0.3 kp: 0.3 ki: 0.0 kd: 0.0 } ``` ## 参考文献 1. "Vehicle dynamics and control." Rajamani, Rajesh. Springer Science & Business Media, 2011. 2. "Optimal Trajectory generation for dynamic street scenarios in a Frenet Frame", M. Werling et., ICRA2010
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/10_Control/how_to_add_a_new_can_card.md
# How to Add a New CAN Card ## Introduction The Controller Area Network (CAN) is a network used intensively in many microcontrollers and devices to transfer data between devices without the assistance of a host computer. The default CAN card used in Apollo is the **ESD CAN-PCIe card**. You can add a new CAN card using the steps below: ## Adding a New CAN Card Complete the following required task sequence to add a new CAN card: 1. Implement the `CanClient` class of the new CAN card. 2. Register the new CAN card in `CanClientFactory`. 3. Update the config file. The steps below show how you can add a new CAN card -- EXAMPLE CAN card to your stack. ### Step 1 Let us Implement the CanClient Class of the New CAN Card Use the following code to implement the specific `CANClient` class: ```cpp #include <string> #include <vector> #include "hermes_can/include/bcan.h" #include "modules/canbus/can_client/can_client.h" #include "modules/canbus/common/canbus_consts.h" #include "modules/common/proto/error_code.pb.h" /** * @namespace apollo::canbus::can * @brief apollo::canbus::can */ namespace apollo { namespace canbus { namespace can { /** * @class ExampleCanClient * @brief The class which defines an Example CAN client which inherits CanClient. */ class ExampleCanClient : public CanClient { public: /** * @brief Initialize the Example CAN client by specified CAN card parameters. * @param parameter CAN card parameters to initialize the CAN client. * @return If the initialization is successful. */ bool Init(const CANCardParameter& parameter) override; /** * @brief Destructor */ virtual ~ExampleCanClient() = default; /** * @brief Start the Example CAN client. * @return The status of the start action which is defined by * apollo::common::ErrorCode. */ apollo::common::ErrorCode Start() override; /** * @brief Stop the Example CAN client. */ void Stop() override; /** * @brief Send messages * @param frames The messages to send. * @param frame_num The amount of messages to send. * @return The status of the sending action which is defined by * apollo::common::ErrorCode. */ apollo::common::ErrorCode Send(const std::vector<CanFrame>& frames, int32_t* const frame_num) override; /** * @brief Receive messages * @param frames The messages to receive. * @param frame_num The amount of messages to receive. * @return The status of the receiving action which is defined by * apollo::common::ErrorCode. */ apollo::common::ErrorCode Receive(std::vector<CanFrame>* const frames, int32_t* const frame_num) override; /** * @brief Get the error string. * @param status The status to get the error string. */ std::string GetErrorString(const int32_t status) override; private: ... ... }; } // namespace can } // namespace canbus } // namespace apollo ``` ### Step 2 To register the New CAN Card in CanClientFactory, add the following code to `CanClientFactory`: ```cpp void CanClientFactory::RegisterCanClients() { Register(CANCardParameter::ESD_CAN, []() -> CanClient* { return new can::EsdCanClient(); }); // register the new CAN card here. Register(CANCardParameter::EXAMPLE_CAN, []() -> CanClient* { return new can::ExampleCanClient(); }); } ``` ### Step 3 Next, you would need to update the config File Add the EXAMPLE_CAN into `/modules/drivers/canbus/proto/can_card_parameter.proto` ```proto message CANCardParameter { enum CANCardBrand { FAKE_CAN = 0; ESD_CAN = 1; EXAMPLE_CAN = 2; // add new CAN card here. } ... ... } ``` Update `/modules/canbus/conf/canbus_conf.pb.txt` ```txt ... ... can_card_parameter { brand:EXAMPLE_CAN type: PCI_CARD // suppose the new can card is PCI_CARD channel_id: CHANNEL_ID_ZERO // suppose the new can card has CHANNEL_ID_ZERO } ... ... ``` If you use radar, like Conti radar in apollo, its' canbus configuration file should alse be modified. Update `/modules/drivers/radar/conti_radar/conf/conti_radar_conf.pb.txt` ```txt ... ... can_card_parameter { brand:EXAMPLE_CAN type: PCI_CARD // suppose the new can card is PCI_CARD channel_id: CHANNEL_ID_ZERO // suppose the new can card has CHANNEL_ID_ZERO } ... ... ```
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/10_Control/how_to_tune_control_parameters.md
# How to Tune Control Parameters ## Introduction The objective of the control module is to generate control commands to the vehicle based on planning trajectory and the current car status. ## Background ### Input / Output #### Input * Planning trajectory * Current car status * HMI driving mode change request * Monitor System #### Output The output control command governs functions such as steering, throttle, and brake in the `canbus`. ### Controller Introduction The controllers include a lateral controller that manages the steering commands and a longitudinal controller that manages the throttle and brakes commands . #### Lateral Controller The lateral controller is an LQR-Based Optimal Controller. The dynamic model of this controller is a simple bicycle model with side slip. It is divided into two categories, including a closed loop and an open loop. - The closed loop provides discrete feedback LQR controller with 4 states: - Lateral Error - Lateral Error Rate - Heading Error - Heading Error Rate - The open loop utilizes the path curvature information to cancel the constant steady state heading error. #### Longitudinal Controller The longitudinal controller is configured as a cascaded PID + Calibration table. It is divided into two categories, including a closed loop and an open loop. - The closed loop is a cascaded PID (station PID + Speed PID), which takes the following data as controller input: - Station Error - Speed Error - The open loop provides a calibration table which maps acceleration onto throttle/brake percentages. ## Controller Tuning ### Useful tools Tool like [diagnostics](../../modules/tools/diagnostics) and [realtime_plot](../../modules/tools/realtime_plot) are useful for controller tuning and can be found under `apollo/modules/tools/`. ### Lateral Controller Tuning The lateral controller is designed for minimal tuning effort. The basic lateral controller tuning steps for *all* vehicles are: 1. Set all elements in `matrix_q` to zero. 2. Increase the third element of `matrix_q`, which defines the heading error weighting, to minimize the heading error. 3. Increase the first element of `matrix_q`, which defines the lateral error weighting to minimize the lateral error. #### Tune a Lincoln MKZ For a Lincoln MKZ, there are four elements that refer to the diagonal elements of the state weighting matrix Q: - Lateral error weighting - Lateral error rate weighting - Heading error weighting - Heading error rate weighting Tune the weighting parameters by following the basic lateral controller tuning steps listed above in *Lateral Controller Tuning*. An example is shown below. ``` lat_controller_conf { matrix_q: 0.05 matrix_q: 0.0 matrix_q: 1.0 matrix_q: 0.0 } ``` #### Tune Additional Vehicle Types When tuning a vehicle type that is other than a Lincoln MKZ, first update the vehicle-related physical parameters as shown in the example below. Then, follow the basic lateral controller tuning steps listed above in *Lateral Controller Tuning* and define the matrix Q parameters. An example is shown below. ``` lat_controller_conf { cf: 155494.663 cr: 155494.663 wheelbase: 2.85 mass_fl: 520 mass_fr: 520 mass_rl: 520 mass_rr: 520 eps: 0.01 steer_transmission_ratio: 16 steer_single_direction_max_degree: 470 } ``` ### Longitudinal Controller Tuning The longitudinal controller is composed of Cascaded PID controllers that include one station controller and a high/low speed controller with different gains for different speeds. Apollo manages tuning in open loop and closed loop by: - OpenLoop: Calibration table generation. Please refer to [how_to_update_vehicle_calibration.md](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E6%A0%87%E5%AE%9A/how_to_update_vehicle_calibration.md) for detailed steps. - Closeloop: Based on the order of High Speed Controller -> Low Speed Controller -> Station Controller. #### High/Low Speed Controller Tuning The high speed controller code is used mainly to track the desired speed above a certain speed value. For example: ``` high_speed_pid_conf { integrator_enable: true integrator_saturation_level: 0.3 kp: 1.0 ki: 0.3 kd: 0.0 } ``` 1. First set the values for `kp`, `ki`, and `kd` to zero. 2. Then start to increase `kp` to reduce the rising time of step response to velocity changes. 3. Finally, increase `ki` to reduce velocity controller steady state error. Once you obtain relatively accurate speed tracking performance for the higher speed, you can start tuning the low speed PID controller for a comfortable acceleration rate from the start point. ``` low_speed_pid_conf { integrator_enable: true integrator_saturation_level: 0.3 kp: 0.5 ki: 0.3 kd: 0.0 } ``` *Note:* Apollo usually sets the switch speed to be a coasting speed when the gear switches to *Drive*. #### Station Controller Tuning Apollo uses the station controller for the vehicle to track the station error between the vehicle trajectory reference and the vehicle position. A station controller tuning example is shown below. ``` station_pid_conf { integrator_enable: true integrator_saturation_level: 0.3 kp: 0.3 ki: 0.0 kd: 0.0 } ``` ## References 1. "Vehicle dynamics and control." Rajamani, Rajesh. Springer Science & Business Media, 2011. 2. "Optimal Trajectory generation for dynamic street scenarios in a Frenet Frame", M. Werling et., ICRA2010
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/10_Control/how_to_add_a_new_control_algorithm.md
# How to Add a New Control Algorithm The control algorithm in Apollo consists of one or more controllers that can be easily changed or replaced with different algorithms. Each controller outputs one or more control commands to `CANbus`. The default control algorithm in Apollo contains a lateral controller (LatController) and a longitudinal controller (LonController). They are responsible for the vehicle control in the lateral and longitudinal directions respectively. The new control algorithm does not have to follow the default pattern, e.g., one lateral controller + one longitudinal controller. It could be a single controller or a combination of any number of controllers. Complete the following task sequence to add a new control algorithm: 1. Create a controller 2. Add the new controller configuration into the `control_config` file 3. Register the new controller The steps are elaborated below for better understanding: ## Create a Controller All controllers must inherit the base class `Controller`, which defines a set of interfaces. Here is an example of a controller implementation: ```c++ namespace apollo { namespace control { class NewController : public Controller { public: NewController(); virtual ~NewController(); Status Init(const ControlConf* control_conf) override; Status ComputeControlCommand( const localization::LocalizationEstimate* localization, const canbus::Chassis* chassis, const planning::ADCTrajectory* trajectory, ControlCommand* cmd) override; Status Reset() override; void Stop() override; std::string Name() const override; }; } // namespace control } // namespace apollo ``` ## Add a New Controller Configuration to the control_config File To add the new controller configuration complete the following steps: 1. Define a `proto` for the new controller configurations and parameters based on the algorithm requirements. An example `proto` definition of `LatController` can be found at: `modules/control/proto/lat_controller_conf.proto` 2. After defining the new controller `proto`, e.g., `new_controller_conf.proto`, type the following: ```protobuf syntax = "proto2"; package apollo.control; message NewControllerConf { double parameter1 = 1; int32 parameter2 = 2; } ``` 3. Update `control_conf.proto` at `modules/control/proto/control_conf.proto`: ```protobuf optional apollo.control.NewControllerConf new_controller_conf = 15; ``` 4. Update `ControllerType` in this file: ```protobuf enum ControllerType { LAT_CONTROLLER = 0; LON_CONTROLLER = 1; NEW_CONTROLLER = 2; }; ``` 5. When the `protobuf` definition is complete, update the control configuration file accordingly at `modules/control/conf/control_conf.pb.txt` ``` Note: The above `control/conf` file is the default for Apollo. Your project may use a different control configuration file. ``` ## Register the New Controller To activate a new controller in the Apollo system, register the new controller in `ControllerAgent`. Go to: > modules/control/controller/controller_agent.cc Type your registration information in the shell. For example: ```c++ void ControllerAgent::RegisterControllers() { controller_factory_.Register( ControlConf::NEW_CONTROLLER, []() -> Controller * { return new NewController(); }); } ``` After this code update sequence is complete, you new controller should take effect in the Apollo system.
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/10_Control/dynamic_model.md
# Dynamic Model - Control-in-loop Simulation ## Introduction Simulation is a vital part of autonomous driving especially in Apollo where most of the testing happens via our simulation platform. In order to have a more accurate approach to our testing environment, Apollo 5.0 introduces Dynamic model which is used to achieve Control-in-loop Simulation to represent the ego car's actual dynamic characteristics. It is possible to gauge the how the ego car would actually perform while driving in autonomous mode, but virtually using the Control-in-loop simulation making it secure and efficient. It can also accelerate your development cycle as you can maximize your testing and enhance your algorithms even before entering the vehicle. The architecture diagram for how Dynamic model works is included below: ![](images/architecture.png) The Control module receives input via planning and the vehicle and uses it effectively to generate the output path which is then fed into the Dynamic model. ## Examples The simulation platform - [Dreamland](http://apollo.auto/platform/simulation.html) can be used to test various control parameters, three parameters are shown below: ``` Note: The green lines in the graph below are the actual planning trajectories for those scenarios, and they blue lines are the computed results from Dynamic Model combined with output from the control module. ``` 1. **Longitudinal Control** A pedestrian walk across the road and the ego car needs to stop by applying the brake ![](images/Longitudinal.png) 2. **Lateral Control** The ego car has to make a wide-angle U-turn in this scenario. As seen in the image below, the steering turn is at 64%. You can also monitor the performance of the dynamic model on the right against the actual planned trajectory. 3. **Backward Behavior** The ego car has to park itself in a designated spot. This scenario is complex as it requires a mixture of forward and backward (reverse) driving and requires a high level of accuracy from the control module. As you can see in the image below, the steering turn required is at `-92%`. Additional details on this example can be seen in the planning module's Park scenario. ![](images/Backward.png) ## References The algorithm behind this learning based control-in-loop simulation has been published at IROS 2019, please cite us at: Xu, Jiaxuan, Qi Luo, Kecheng Xu, Xiangquan Xiao, Siyang Yu, Jiangtao Hu, Jinghao Miao, and Jingao Wang. "An Automated Learning-Based Procedure for Large-scale Vehicle Dynamics Modeling on Baidu Apollo Platform." In 2019 IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS), pp. 5049-5056. IEEE, 2019.
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/10_Control/how_to_troubleshoot_esdcan_cn.md
## 如何解决ESD CAN设备的故障? ### 问题 不能通过ESD卡进行通信。 ### 故障排除步骤: 1. 确保CAN驱动程序(内核模块)被加载,运行:```lsmod |grep can```; 如果驱动程序已经加载,您应该看到关于内核驱动程序的信息,例如版本号。 2. 确保CAN设备存在并具有正确的权限集,运行:```ls -l /dev/can0```. 3. 检查内核日志(运行 ```dmesg |grep -i can```) 和系统日志 (运行 ```grep -i can /var/log/syslog```), 查看是否存在与CAN相关的错误消息。 4. 运行Apollo程序 ```esdcan_test_app``` (在```monitor/hwmonitor/hw/tools/```下), 它将列出详细统计数据和状态信息。 * 了解这个工具,运行 ```esdcan_test_app --help```. * 列举其他详细信息, 运行 ```sudo esdcan_test_app --details=true```. 5. [可选] 保存内核日志,系统日志(步骤4),并从步骤5的输出中进行离线分析。 6. 必要时,检查系统环境温度。ESD CAN卡(CAN-PCIe/402-FD)的工作温度范围为0~75摄氏度,在该温度范围外可能无法工作。您还可以在ESD CAN(Altera FPGA芯片)上附加一个温度传感器到主IC芯片的表面,以监测芯片的表面温度,以确保其不会过热。
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/10_Control/how_to_troubleshoot_esdcan.md
## How to troubleshoot ESD CAN device? ### Problem Can’t communicate through ESD CAN card. ### Troubleshooting Steps: 1. Make sure CAN driver (kernel module) is loaded, run: ```lsmod |grep can```; you should see information regarding the kernel driver such as version number if CAN driver has been loaded. 2. Make sure CAN device is present and has the right permission set, run: ```ls -l /dev/can0```. 3. Check kernel log (run ```dmesg |grep -i can```) and syslog (run ```grep -i can /var/log/syslog```), see if there are error messages related to CAN. 4. Run the Apollo program ```esdcan_test_app``` (under ```monitor/hwmonitor/hw/tools/```), which will print out detailed stats and status information. * To learn about this tool, run ```esdcan_test_app --help```. * To print additional detailed stats, run ```sudo esdcan_test_app --details=true``. 5. [Optional] Save the kernel log, syslog (Step 4) and output from Step 5 for offline analysis. 6. If necessary, check system ambient temperature. ESD CAN card (CAN-PCIe/402-FD) has a working temperature range of 0-75 degree Celsius; it may not work outside of this temperature range. You may also attach a temperature sensor to the surface of the main IC chip on ESD CAN (an Altera FPGA chip) to monitor the surface temperature of the chip to make sure it is not overheating.
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/02_Quick Start/apollo_5_5_quick_start.md
# Apollo 5.5 Quick Start Guide The following guide serves as a user manual for launching the Apollo upgraded software and hardware stack on vehicle. The latest Apollo upgrade, Quick Start Guide focuses on the new features. For general Apollo concepts, please refer to [Apollo 3.5 Quick Start](../02_Quick%20Start/apollo_3_5_quick_start.md) ## Contents - [Calibration Guide](#calibration-guide) - [Hardware and Software Installation](#hardware-and-software-installation) - [Dreamview Usage Table](#dreamview-usage-table) - [Onboard Test](#onboard-test) ## Calibration Guide Apollo currently offers a robust calibration service to support your calibration requirements from LiDARs to IMU to Cameras. This service is currently being offered to select partners only as part of our Data Pipeline service offering. If you would like to learn more about the calibration service, please reach out to us via email: **apollopartner@baidu.com** ## Hardware and Software Installation The Hardware setup for Apollo 5.5 remains the same as Apollo 3.5, please refer to [Apollo 3.5 Hardware and System Installation Guide](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_3_5_hardware_system_installation_guide.md) for the steps to install the hardware components and the system software, as well as [Apollo Software Installation Guide](../01_Installation%20Instructions/apollo_software_installation_guide.md). ## Dreamview Usage Table For questions regarding Dreamview icons refer to the [Dreamview Usage Table](../13_Apollo%20Tool/%E5%8F%AF%E8%A7%86%E5%8C%96%E4%BA%A4%E4%BA%92%E5%B7%A5%E5%85%B7Dremview/dreamview_usage_table.md). For questions regarding Dreamland and the scenario editor, please visit our [Dreamland Introduction guide](../13_Apollo%20Tool/%E4%BA%91%E5%B9%B3%E5%8F%B0Apollo%20Studio/Dreamland_introduction.md) ## Onboard Test 1. Plug-in an external hard-drive to any available USB port in the host machine 2. Turn on the vehicle, and then the host machine 3. Launch the Dev Docker Container 4. Launch DreamView Note\: Use your favorite browser to access Dreamview web service in your host machine browser with URL <http://localhost:8888> ![dreamview_2_5](images/dreamview_2_5.png) 5. Select Mode, Vehicle and Map ![dreamview_2_5_setup_profile](images/dreamview_2_5_setup_profile.png) Note\: You'll be required to setup profile before doing anything else. Click the dropdown menu to select **Navigation** mode, the HDMap and vehicle you want to use. The lists are defined in [HMI config file](https://raw.githubusercontent.com/ApolloAuto/apollo/master/modules/dreamview/conf/hmi.conf) Note\: It's also possible to change the profile on the right panel of the HMI, but just remember to click `Reset All` on the top-right corner to restart the system 6. Start the Modules. Click the `Setup` button ![dreamview_2_5_setup](images/dreamview_2_5_setup.png) Go to **Module Controller** tab, check if all modules and hardware are ready (Note\: In your offline environment, the hardware modules such as GPS, CANBus, Velodyne, Camera and Radar cannot be brought up) (Note\: You may need to drive around a bit to get a good GPS signal) ![dreamview_2_5_module_controller](images/dreamview_2_5_module_controller.png) 7. Under `Default Routing` select your desired route 8. Under Tasks click `Start Auto`. (Note: Be cautious when starting the autonomous driving, you should now be in autonomous mode) ![dreamview_2_5_start_auto](images/dreamview_2_5_start_auto.png) 9. After the autonomous testing is complete, under `Tasks` click `Reset All`, close all windows and shutdown the machine 10. Remove the hard drive
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/02_Quick Start/apollo_1_5_quick_start.md
# Apollo 1.5 Quick Start Guide This quick start focuses on Apollo 1.5 new features. For general Apollo concepts, please refer to [Apollo 1.0 Quick Start](../02_Quick%20Start/apollo_1_0_quick_start.md) and [Apollo Software Installation Guide](../01_Installation Instructions/apollo_software_installation_guide.md). # Onboard Test 1. For vehicle onboard test, make sure you have calibrated the extrinsic parameters between the LiDAR and the GNSS/INS. For sensor calibration, please refer to [Apollo 1.5 LiDAR calibration guide](../11_Hardware%20Integration%20and%20Calibration/传感器标定/apollo_lidar_imu_calibration_guide.md) before you proceed. 2. Launch Docker Release Container 3. Launch HMI Use your favorite browser to access HMI web service in your host machine browser with URL http://localhost:8887 4. Select Vehicle and Map You'll be required to setup profile before doing anything else. Click the dropdown menu to select your HDMap and vehicle in use. The list are defined in [HMI config file](https://raw.githubusercontent.com/ApolloAuto/apollo/master/modules/hmi/conf/config.pb.txt). *Note: It's also possible to change profile on the right panel of HMI, but just remember to click "Reset All" on the top-right corner to restart the system.* ![](images/start_hmi.png) 5. Start Modules Set up the system by clicking the "Setup" button on left panel. ![](images/hmi_setup_1.5.png) 6. (*New!*) Be Cautious When Starting Autonomous Driving Make sure all modules are on and hardware is ready, and the vehicle is in a good state which is safe to enter auto mode to follow the traffic to destination. Click the "Start Auto" button, then it will drive you there! ![](images/hmi_start_auto_following.png)
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/02_Quick Start/apollo_1_0_quick_start.md
# Apollo 1.0 Quick Start Guide ## Contents * [About This Guide](#about-this-guide) * [Document Conventions](#document-conventions) * [Overview of Apollo](#overview-of-apollo) * [Description of the Vehicle Environment](#description-of-the-vehicle-environment) * [Hardware Installation](#hardware-installation) * [Apollo Software Installation](#apollo-software-installation) * [Run the Demo on Vehicle](#run-the-demo-on-vehicle) * [Launch the Local Release Docker Image](#launch-the-local-release-env-docker-image) * [Record the Driving Trajectory](#record-driving-trajectory) * [Perform Autonomous Driving](#perform-autonomous-driving) * [Shut Down](#shut-down) * [Run Offline Demo](#run-offline-demo) # About This Guide The _Apollo 1.0 Quick Start Guide_ provides all of the basic instructions to understand, install, and build Apollo. ## Document Conventions The following table lists the conventions that are used in this document: | **Icon** | **Description** | | ----------------------------------- | ---------------------------------------- | | **Bold** | Emphasis | | `Mono-space font` | Code, typed data | | _Italic_ | Titles of documents, sections, and headings Terms used | | ![info](images/info_icon.png) | **Info** Contains information that might be useful. Ignoring the Info icon has no negative consequences. | | ![tip](images/tip_icon.png) | **Tip**. Includes helpful hints or a shortcut that might assist you in completing a task. | | ![online](images/online_icon.png) | **Online**. Provides a link to a particular web site where you can get more information. | | ![warning](images/warning_icon.png) | **Warning**. Contains information that must **not** be ignored or you risk failure when you perform a certain task or step. | # About Apollo 1.0 Apollo 1.0, also referred to as the _Automatic GPS Waypoint Following_, works in an enclosed venue such as a test track or parking lot. It accurately replays a trajectory and the speed of that trajectory that a human driver has traveled in an enclosed, flat area on solid ground. At this stage of development, Apollo 1.0 **cannot** perceive obstacles in close proximity, drive on public roads, or drive in areas without GPS signals. # Description of the Vehicle Environment The Lincoln MKZ, enhanced by Autonomous Stuff, provides users with an accessible autonomous vehicle platform. The platform supplies users with a comprehensive stack of hardware and software solutions. Users gain direct access to vehicle controls such as gear selection, speed, and indicator lights. Software interfaces have been created for steering, braking, acceleration, and gear selection to provide Developers with a workable user interface. Additional features include: - Power distributor terminals - Integrated PC with ROS pre-installed and configured - Emergency Stop using a drive-by-wire system - Ethernet network and USB connections (to PC) # Hardware Installation Please refer to [Apollo 1.0 Hardware and System Installation Guide](../11_Hardware%20Integration%20and%20Calibration/车辆集成/硬件安装hardware installation/apollo_1_0_hardware_system_installation_guide.md) for the steps to install the hardware components and the system software. # Apollo Software Installation Please refer to [Apollo Software Installation Guide](../01_Installation Instructions/apollo_software_installation_guide.md). # Run Demo on Vehicle This section provides the instructions to run the Apollo 1.0 Demo on Vehicle. 1. Set up the hardware: - Power-on the platform vehicle. - Power-on the Industrial PC (IPC). ![](images/ipc_power_on.png) - Power-on the modem by pressing and holding the power button until the lights turn on. - Set up the network configuration for the IPC: static IP (for example, 192.168.10.6), subnet mask (for example, 255.255.255.0), and gateway (for example, 192.168.10.1) - Configurate your DNS server IP (for example, 8.8.8.8). - Use a tablet to access **Settings** and connect to MKZ wifi: ![](images/ipad_config_wifi.png) 2. Start the HMI in Docker **using Chrome only**: ![warning](images/warning_icon.png)**Warning:** Make sure that you are not starting HMI from two Docker containers concurrently. ## Launch the Local release env Docker Image Run the following commands: ``` cd $APOLLO_HOME bash docker/scripts/release_start.sh local_release ``` When Docker starts, it creates a port mapping, which maps the Docker internal port 8887 to the host port 8887. You can then visit the HMI web service in your host machine browser: Open the Chrome browser and start the Apollo HMI by going to **192.168.10.6:8887**. ![](images/start_hmi.png) ## Record the Driving Trajectory Follow these steps to record the driving trajectory: 1. In the Apollo HMI, under Quick Record, click **Setup** to start all modules and perform the hardware health check. ![](images/hmi_record_setup.png) 2. If the hardware health check passes, click the **Start** button to start to record the driver trajectory. ![](images/hmi_record_start.png) 3. After arriving at a destination, click the **Stop** button to stop recording. ![](images/hmi_record_stop.png) 4. If you want to record a *different* trajectory, click the **New** button to initiate recording again. ![](images/hmi_record_reset.png) ## Perform Autonomous Driving Follow these steps to perform autonomous driving: 1. In the Apollo HMI, under Quick Play, click **Setup** to start all modules and perform a hardware health check. ![](images/hmi_play_setup.png) 2. If the vehicle successfully passes the Setup step, it is ready to enter the Autonomous mode. **MAKE SURE DRIVER IS READY!** Click the **Start** button to start the autonomous driving. ![](images/hmi_play_start.png) 3. After arriving at your destination, click the **Stop** button to stop replaying the recorded trajectory. ![](images/hmi_play_stop.png) ## Shut Down 1. Shut down the system from a terminal: ```sudo shutdown now``` 2. Power-off the IPC (locate the icon on the top right of the desktop to click **Shut Down**). 3. Turn off the modem by pressing and holding the power button until the lights turn off. 4. Turn off the car. # Run Offline Demo See [Offline Demo Guide](../02_Quick%20Start/demo_guide/README.md)
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/02_Quick Start/apollo_5_0_quick_start.md
# Apollo 5.0 Quick Start Guide The following guide serves as a user manual for launching the Apollo upgraded software and hardware stack on vehicle. This Quick Start Guide focuses on the new features. For general Apollo concepts, please refer to [Apollo 3.5 Quick Start](../02_Quick%20Start/apollo_3_5_quick_start.md) ## Contents - [Calibration Guide](#calibration-guide) - [Hardware and Software Installation](#hardware-and-software-installation) - [Dreamview Usage Table](#dreamview-usage-table) - [Onboard Test](#onboard-test) ## Calibration Guide Apollo currently offers a robust calibration service to support your calibration requirements from LiDARs to IMU to Cameras. This service is being offered to selected partners only. If you would like to learn more about the calibration service, please reach out to us via email: **apollopartner@baidu.com** ## Hardware and Software Installation The Hardware setup for Apollo 5.0 remains the same as Apollo 3.5, please refer to [Apollo 3.5 Hardware and System Installation Guide](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_3_5_hardware_system_installation_guide.md) for the steps to install the hardware components and the system software, as well as [Apollo Software Installation Guide](../01_Installation%20Instructions/apollo_software_installation_guide.md). ## Dreamview Usage Table For questions regarding Dreamview icons refer to the [Dreamview Usage Table](../13_Apollo%20Tool/%E5%8F%AF%E8%A7%86%E5%8C%96%E4%BA%A4%E4%BA%92%E5%B7%A5%E5%85%B7Dremview/dreamview_usage_table.md). For questions regarding Dreamland and the scenario editor, please visit our [Dreamland Introduction guide](../13_Apollo%20Tool/云平台Apollo Studio/Dreamland_introduction.md) ## Onboard Test 1. Plug-in an external hard-drive to any available USB port in the host machine 2. Turn on the vehicle, and then the host machine 3. Launch the Dev Docker Container 4. Launch DreamView Note\: Use your favorite browser to access Dreamview web service in your host machine browser with URL <http://localhost:8888> ![dreamview_2_5](images/dreamview_2_5.png) 5. Select Mode, Vehicle and Map ![dreamview_2_5_setup_profile](images/dreamview_2_5_setup_profile.png) Note\: You'll be required to setup profile before doing anything else. Click the dropdown menu to select **Navigation** mode, the HDMap and vehicle you want to use. The lists are defined in [HMI config file](https://raw.githubusercontent.com/ApolloAuto/apollo/master/modules/dreamview/conf/hmi.conf) Note\: It's also possible to change the profile on the right panel of the HMI, but just remember to click `Reset All` on the top-right corner to restart the system 6. Start the Modules. Click the `Setup` button ![dreamview_2_5_setup](images/dreamview_2_5_setup.png) Go to **Module Controller** tab, check if all modules and hardware are ready (Note\: In your offline environment, the hardware modules such as GPS, CANBus, Velodyne, Camera and Radar cannot be brought up) (Note\: You may need to drive around a bit to get a good GPS signal) ![dreamview_2_5_module_controller](images/dreamview_2_5_module_controller.png) 7. Under `Default Routing` select your desired route 8. Under Tasks click `Start Auto`. (Note: Be cautious when starting the autonomous driving, you should now be in autonomous mode) ![dreamview_2_5_start_auto](images/dreamview_2_5_start_auto.png) 9. After the autonomous testing is complete, under `Tasks` click `Reset All`, close all windows and shutdown the machine 10. Remove the hard drive
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/02_Quick Start/apollo_1_0_quick_start_developer.md
# Apollo 1.0 Quick Start Guide for Developers ## Contents * [About This Guide](#about-this-guide) * [Introduction](#introduction) * [Build the Apollo Kernel](#build-the-apollo-kernel) * [Access the Apollo Dev Container](#access-the-apollo-dev-container) * [Build the Apollo ROS](#build-the-apollo-ros) * [Build Apollo](#build-apollo) * [Release](#release) # About This Guide *The Apollo 1.0 Quick Start for Developers* provides the basic instructions to all Developers who want to build the Apollo Kernel, the Robot Operating System (ROS), and Apollo. ## Document Conventions The following table lists the conventions that are used in this document: | **Icon** | **Description** | | ----------------------------------- | ---------------------------------------- | | **Bold** | Emphasis | | `Mono-space font` | Code, typed data | | _Italic_ | Titles of documents, sections, and headingsTerms used | | ![info](images/info_icon.png) | **Info** Contains information that might be useful. Ignoring the Info icon has no negative consequences. | | ![tip](images/tip_icon.png) | **Tip**. Includes helpful hints or a shortcut that might assist you in completing a task. | | ![online](images/online_icon.png) | **Online**. Provides a link to a particular web site where you can get more information. | | ![warning](images/warning_icon.png) | **Warning**. Contains information that must **not** be ignored or you risk failure when you perform a certain task or step. | # Introduction It is assumed that you have read and performed the instructions in the companion guide, the *Apollo 1.0 Quick Start Guide*, to set up the basic environment. Use this guide to build your own version of the Apollo Kernel, the ROS, and Apollo. There are also instructions on how to release your own Apollo container to others who might want to build on what you have developed. It is strongly recommended that you build all of the components (Apollo Kernel, ROS, and Apollo) in the Apollo pre-specified dev Docker container. # Build the Apollo Kernel The Apollo runtime in the vehicle requires the [Apollo Kernel](https://github.com/ApolloAuto/apollo-kernel). You are strongly recommended to install the pre-built kernel. ## Use pre-built Apollo Kernel. You get access and install the pre-built kernel with the following commands. 1. Download the release packages from the release section on github ``` https://github.com/ApolloAuto/apollo-kernel/releases ``` 2. Install the kernel After having the release package downloaded: ``` tar zxvf linux-4.4.32-apollo-1.0.0.tar.gz cd install sudo ./install_kernel.sh ``` 3. Reboot your system by the `reboot` command 4. Build the ESD CAN driver source code Now you need to build the ESD CAN driver source code according to [ESDCAN-README.md](https://github.com/ApolloAuto/apollo-kernel/blob/master/linux/ESDCAN-README.md) ## Build your own kernel. If have modified the kernel, or the pre-built kernel is not the best for your platform, you can build your own kernel with the following steps. 1. Clone the code from repository ``` git clone https://github.com/ApolloAuto/apollo-kernel.git cd apollo-kernel ``` 2. Build the ESD CAN driver source code according to [ESDCAN-README.md](https://github.com/ApolloAuto/apollo-kernel/blob/master/linux/ESDCAN-README.md) 3. Build the kernel with the following command. ``` bash build.sh ``` 4. Install the kernel the same way as using a pre-built Apollo Kernel. # Access the Apollo Dev Container 1. Please follow the [Quick Start Guide](../02_Quick%20Start/apollo_1_0_quick_start.md) to clone the Apollo source code. ![tip](images/tip_icon.png) In the following sections, it is assumed that the Apollo directory is located in `$APOLLO_HOME`. 2. Apollo provides a build environment Docker image: `dev-latest`. Run the following command to start a container with the build image: ``` cd $APOLLO_HOME bash docker/scripts/dev_start.sh ``` 3. Run the following command to log into the container: ``` bash docker/scripts/dev_into.sh ``` In the container, the default directory lives in `/apollo` , which contains the mounted source code repo. # Build the Apollo ROS Check out Apollo ROS from [github source](https://github.com/ApolloAuto/apollo-platform): ```bash git clone https://github.com/ApolloAuto/apollo-platform.git apollo-platform cd apollo-platform/ros bash build.sh build ``` # Build Apollo Before your proceed to build, please obtain ESD CAN library according to instructions in [ESD CAN README](https://github.com/ApolloAuto/apollo/blob/master/third_party/can_card_library/esd_can/README.md). Run the following command: ```bash cd $APOLLO_HOME bash apollo.sh build ``` # Release Apollo uses Docker images to release packages. **For advanced developers**: you can generate a new Docker image to test in an actual vehicle. Apollo has set up a base Docker image environment to test the Apollo build. The image is called: `run-env-latest`. 1. Run the following command: ``` bash apollo.sh release ``` The release command generates a release directory, which contains: - ROS environment - Running scripts - Binaries - Dependent shared libraries (`.so` files) 2. Open a new terminal and run the following command in an Apollo source directory outside of Docker: ``` cd $APOLLO_HOME bash apollo_docker.sh gen ``` The command creates a new Docker image using the release directory. The release image tag will be named:`release-yyyymmdd_hhmm`. The existing release image tag, `release-latest`, is always pointing to the most current release. 3. Push your release image online using your own Docker registry set up from outside of the container: ``` cd $APOLLO_HOME bash apollo_docker.sh push ``` The command pushes the newly built Docker image to the release Docker registry. To set up a new Docker registry, see [this page](https://docs.docker.com/registry).
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/02_Quick Start/README.md
# Quick Start Guides ## Apollo 8.0 - [Apollo 8.0 quick start](./apollo_8_0_quick_start.md) - [Apollo software installation guide - package method](../01_Installation%20Instructions/apollo_software_installation_guide_package_method.md) New method to install apollo - [Apollo 3.5 hardware system installation guide](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_3_5_hardware_system_installation_guide.md) - Since there are no changes in our Hardware setup, please refer to the Apollo 3.5 guide ## Apollo 6.0 - [Apollo 6.0 quick start](./apollo_6_0_quick_start.md) - [Apollo 6.0 quick start cn](./apollo_6_0_quick_start_cn.md) - [Apollo 3.5 hardware system installation guide](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_3_5_hardware_system_installation_guide.md) - Since there are no changes in our Hardware setup, please refer to the Apollo 3.5 guide ## Apollo 5.5 - [Apollo 5.5 quick start](./apollo_5_5_quick_start.md) - [Apollo 3.5 hardware system installation guide](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_3_5_hardware_system_installation_guide.md) - Since there are no changes in our Hardware setup, please refer to the Apollo 3.5 guide - [Apollo 5.5 technical guide](../14_Others/%E7%89%88%E6%9C%AC%E4%BB%8B%E7%BB%8D/apollo_5.5_technical_tutorial.md) - Everything you need to know about Apollo 5.5 ## Apollo 5.0 - [Apollo 5.0 quick start](./apollo_5_0_quick_start.md) - [Apollo 3.5 hardware system installation guide](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_3_5_hardware_system_installation_guide.md) - Since there are no changes in our Hardware setup, please refer to the Apollo 3.5 guide - [Apollo 5.0 technical guide](../14_Others/%E7%89%88%E6%9C%AC%E4%BB%8B%E7%BB%8D/apollo_5.0_technical_tutorial.md) - Everything you need to know about Apollo 5.0 ## Apollo 3.5 - [Apollo 3.5 quick start](./apollo_3_5_quick_start.md) - [Apollo 3.5 hardware system installation guide](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_3_5_hardware_system_installation_guide.md) - [Apollo 3.5 map collection guide](../12_Map%20acquisition/apollo_3_5_map_collection_guidelines.md) - [Apollo 3.5 technical guide](../14_Others/%E7%89%88%E6%9C%AC%E4%BB%8B%E7%BB%8D/apollo_3.5_technical_tutorial.md) - Everything you need to know about Apollo 3.5 ## Apollo 3.0 - [Apollo 3.0 quick start](./apollo_3_0_quick_start.md) - [Apollo 3.0 hardware system installation guide](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_3_0_hardware_system_installation_guide.md) - [Apollo 3.0 calibration guide](../06_Perception/multiple_lidar_gnss_calibration_guide.md) - [Apollo 3.0 technical guide](../14_Others/%E7%89%88%E6%9C%AC%E4%BB%8B%E7%BB%8D/apollo_3.0_technical_tutorial.md) - Everything you need to know about Apollo 3.0 ## Apollo 2.5 - [Apollo 2.5 quick start](./apollo_2_5_quick_start.md) - [Apollo 2.5 quick start cn](./apollo_2_5_quick_start_cn.md) - [Apollo 2.5 hardware system installation guide](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_2_5_hardware_system_installation_guide_v1.md) - [Apollo 2.5 map collection guide](../12_Map%20acquisition/apollo_2_5_map_collection_guide.md) - [Apollo 2.5 map collection guide cn](../12_Map%20acquisition/apollo_2_5_map_collection_guide_cn.md) - [Apollo 2.5 technical guide](../14_Others/%E7%89%88%E6%9C%AC%E4%BB%8B%E7%BB%8D/apollo_2.5_technical_tutorial.md) - Everything you need to know about Apollo 2.5 ## Apollo 2.0 - [Apollo 2.0 quick start](./apollo_2_0_quick_start.md) - [Apollo 2.0 quick start cn](./apollo_2_0_quick_start_cn.md) - [Apollo 2.0 hardware system installation guide](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_2_0_hardware_system_installation_guide_v1.md) - [Apollo 2.0 sensor calibration guide](../10Hardware%20Integration%20and%20Calibration/%E4%BC%A0%E6%84%9F%E5%99%A8%E6%A0%87%E5%AE%9A/apollo_2_0_sensor_calibration_guide.md) - [Apollo 2.0 sensor calibration guide cn](../10Hardware%20Integration%20and%20Calibration/%E4%BC%A0%E6%84%9F%E5%99%A8%E6%A0%87%E5%AE%9A/apollo_2_0_sensor_calibration_guide_cn.md) ## Apollo 1.5 - [Apollo 1.5 quick start](./apollo_1_5_quick_start.md) - [Apollo 1.5 quick start cn](./apollo_1_5_quick_start_cn.md) - [Apollo 1.5 hardware system installation guide](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_1_5_hardware_system_installation_guide.md) - [Apollo 1.5 hardware system installation guide cn](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_1_5_hardware_system_installation_guide_cn.md) - [Apollo 1.5 lidar calibration guide](../10Hardware%20Integration%20and%20Calibration/%E4%BC%A0%E6%84%9F%E5%99%A8%E6%A0%87%E5%AE%9A/apollo_lidar_imu_calibration_guide.md) - [Apollo 1.5 lidar calibration guide cn](../10Hardware%20Integration%20and%20Calibration/%E4%BC%A0%E6%84%9F%E5%99%A8%E6%A0%87%E5%AE%9A/apollo_1_5_lidar_calibration_guide_cn.md) ## Apollo 1.0 - [Apollo 1.0 quick start](./apollo_1_0_quick_start.md) - [Apollo 1.0 quick start cn](./apollo_1_0_quick_start_cn.md) - [Apollo 1.0 hardware system installation guide](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_1_0_hardware_system_installation_guide.md) - [Apollo 1.0 quick start developer](../02_Quick%20Start/apollo_1_0_quick_start_developer.md) ## Others - [Apollo software installation guide](../01_Installation%20Instructions/apollo_software_installation_guide.md) - [Apollo software installation guide cn](../01_Installation%20Instructions/apollo_software_installation_guide_cn.md) - [Apollo software installation guide - package method](../01_Installation%20Instructions/apollo_software_installation_guide_package_method.md)
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/02_Quick Start/apollo_6_0_quick_start_cn.md
# Apollo 6.0 快速入门指南 以下指南是用于在车辆上启动Apollo软硬件套件的用户手册, 整体内容与Apollo 5.5类似。本快速入门指南重点介绍新功能,对于 Apollo 的一般概念,请参阅[Apollo 5.5 快速入门指南](./apollo_5_5_quick_start.md) ## 内容 - [Apollo 6.0 快速入门指南](#apollo-60-快速入门指南) - [内容](#内容) - [紧急车辆音频检测](#紧急车辆音频检测) - [硬件和软件安装](#硬件和软件安装) - [Dreamview的使用](#dreamview的使用) - [上车测试](#上车测试) ## 紧急车辆音频检测 Apollo目前通过音频设备集成了紧急车辆检测功能。在自动驾驶车辆上安装麦克风采集周围的音频信号,并对记录的音频进行分析和处理,以检测周围的紧急车辆。模块详细信息在[这里](../../modules/audio)。 Apollo集成了新的深度学习模型,包括使用PointPillars进行障碍物检测、使用语义地图进行行人预测以及基于学习的轨迹规划。请在对应的模块中寻找详细的信息。 ## 硬件和软件安装 Apollo 6.0的硬件设置与Apollo 3.5相同,请参阅[Apollo 3.5 硬件与系统安装指南](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_3_5_hardware_system_installation_guide.md)获取安装硬件组件的步骤,参阅[Apollo软件安装指南](../01_Installation%20Instructions/apollo_software_installation_guide_cn.md)获取软件安装步骤。 ## Dreamview的使用 关于Dreamview图标的问题,请参考[Dreamview用法介绍](../13_Apollo%20Tool/%E5%8F%AF%E8%A7%86%E5%8C%96%E4%BA%A4%E4%BA%92%E5%B7%A5%E5%85%B7Dremview/dreamview_usage_table_cn.md)。关于Dreamland和场景编辑器的问题,请参考[Dreamland简介](../13_Apollo%20Tool/%E4%BA%91%E5%B9%B3%E5%8F%B0Apollo%20Studio/Dreamland_introduction.md)。 ## 上车测试 1. 将一个外部磁盘驱动器接入主机任一可用USB接口。 2. 首先启动车辆,然后启动主机。 3. 启动Dev版本的Docker容器。 4. 启动Dreamview。 打开浏览器(譬如Chrome)然后在地址栏输入 <http://localhost:8888> ![launch_dreamview](images/dreamview_2_5.png) 5. 选择模式、车辆和地图。 ![select_mode](images/dreamview_2_5_setup_profile.png) 附注\: 在进行任何测试前会要求使用者设置参数。点击下拉列表并选择想要使用的导航模式,高清地图和车辆。该列表数据在[HMI配置文件目录](../../modules/dreamview/conf/hmi_modes)中定义。 附注\: 允许使用者在HMI的右侧面板中更改参数,但是需要点击右上角的`Reset All`按钮重启该系统以使参数生效。 6. 启动模块。 点击`Setup`按钮 ![start_module](images/dreamview_2_5_setup.png) 进入**Module Controller** 面板,检查是否所有的模块和硬件已经准备好(在离线环境中,某些硬件模块如GPS、CANBus、Velodyne、Camera和Radar不会显示)(为了获得良好的GPS信号,可能需要车辆运行一段距离。) ![module_controller](images/dreamview_2_5_module_controller.png) 7. 在`Default Routing`中选择期望的路线。 8. 在`Tasks`面板中,点击`Start Auto`。(将要进入自动驾驶模式时需要十分小心谨慎)。 ![start_auto](images/dreamview_2_5_start_auto.png) 9. 自动驾驶测试结束后,在`Tasks`面板中点击`Reset All`,关闭所有窗口,关闭主机。 10. 移除磁盘驱动器。
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/02_Quick Start/apollo_2_0_quick_start.md
# Apollo 2.0 Quick Start Guide In Apollo 2.0, we have released auto driving on simple urban roads. The following guide serves as a user manual for launching the Apollo 2.0 software and hardware stack on vehicle. The Apollo 2.0 Quick Start Guide focuses on Apollo 2.0 new features. For general Apollo concepts, please refer to [Apollo 1.0 Quick Start](../02_Quick%20Start/apollo_1_0_quick_start.md). ## Contents * [Calibration Guide](#calibration-guide) * [Hardware and Software Installation](#hardware-and-software-installation) * [Dreamview Usage Table](#dreamview-usage-table) * [Onboard Test](#onboard-test) ## Calibration Guide For vehicle onboard testing make sure you have calibrated all sensors. For sensor calibration, please refer to [Apollo 2.0 Sensor Calibration Guide](../11_Hardware%20Integration%20and%20Calibration/传感器标定/apollo_2_0_sensor_calibration_guide.md) before you proceed. ## Hardware and Software Installation Please refer to [Apollo 2.0 Hardware and System Installation Guide](../11_Hardware%20Integration%20and%20Calibration/车辆集成/硬件安装hardware installation/apollo_2_0_hardware_system_installation_guide_v1.md) for the steps to install the hardware components and the system software, as well as [Apollo Software Installation Guide](../01_Installation Instructions/apollo_software_installation_guide.md). ## Dreamview Usage Table For questions regarding Dreamview icons refer to the [Dreamview Usage Table]( https://github.com/ApolloAuto/apollo/blob/master/docs/specs/dreamview_usage_table.md). ## Onboard Test 1. Plug-in an external hard-drive to any available USB port in the host machine. 2. Turn on the vehicle, and then the host machine. 3. Launch Docker Release Container. 4. Launch DreamView. Note: Use your favorite browser to access HMI web service in your host machine browser with URL http://localhost:8888. ![](images/dreamview.png) 5. Select Vehicle and Map. Note: You'll be required to setup profile before doing anything else. Click the dropdown menu to select your HDMap and vehicle in use. The list are defined in [HMI config file](https://raw.githubusercontent.com/ApolloAuto/apollo/master/modules/dreamview/conf/hmi.conf). Note: It's also possible to change the profile on the right panel of the HMI, but just remember to click "Reset All" on the top-right corner to restart the system. 6. Start Modules. Click the "Setup" button. ![](images/dreamview_setup.png) Go to **Module Controller** tab, check if all modules and hardware are ready. (Note: In your offline environment, the hardware modules such as GPS, CANBus, Velodyne, Camera and Radar cannot be brought up.) (Note:You may need to drive around a bit to get a good GPS signal.) ![](https://github.com/ApolloAuto/apollo/blob/master/docs/quickstart/images/dreamview_module_controller.png?raw=true) 7. Under Default Routing select your desired route. 8. Under Tasks click Start Auto. (Note: Be cautious when starting autonomous driving, you should now be in autonomous mode.) ![](images/dreamview_start_auto.png) 9. After autonomous testing is complete, under Tasks click Reset All, close all windows and shutdown the machine. 10. Remove the hard drive.
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/02_Quick Start/apollo_3_0_quick_start_cn.md
# Apollo 3.0 快速入门指南 该指南是帮助使用者在车辆上安装和启动Apollo 3.0软硬件套件的用户手册。 这个快速入门指南专注于Apollo 3.0新功能的介绍。对于Apollo的通用概念,请参考[Apollo 1.0 快速入门指南](../02_Quick%20Start/apollo_1_0_quick_start_cn.md)。 ## 内容 - [Apollo 3.0 快速入门指南](#apollo-30-快速入门指南) - [内容](#内容) - [车辆校准指南](#车辆校准指南) - [硬件和软件安装](#硬件和软件安装) - [DreamView的使用](#dreamview的使用) - [上车测试](#上车测试) ## 车辆校准指南 在进行车辆测试前必须确保已经校准了所有的传感器,关于传感器校准,请参考[Apollo 2.0 传感器标定方法使用指南](../11_Hardware%20Integration%20and%20Calibration/传感器标定/apollo_2_0_sensor_calibration_guide_cn.md)。 ## 硬件和软件安装 请参考[Apollo 3.0 硬件与系统安装指南](../11_Hardware%20Integration%20and%20Calibration/车辆集成/硬件安装hardware installation/apollo_3_0_hardware_system_installation_guide_cn.md)获取安装硬件组件的步骤,参考[Apollo软件安装指南](https://github.com/ApolloAuto/apollo/blob/r3.0.0/docs/quickstart/apollo_software_installation_guide_cn.md)获取软件安装步骤。 ## DreamView的使用 关于DreamView使用时的相关问题请参考[DreamView用法介绍](../13_Apollo%20Tool/可视化交互工具Dremview/dreamview_usage_table_cn.md)。 ## 上车测试 1. 将一个外部磁盘驱动器接入主机任一可用USB接口。 2. 首先启动车辆,然后启动主机。 3. 启动发布版本的Docker容器。 4. 启动DreamView。 打开浏览器(譬如Chrome)然后在地址栏输入 <http://localhost:8888> ![dreamview_2_5](images/dreamview_2_5.png) 5. 选择模式、车辆和地图。 ![dreamview_2_5_setup_profile](images/dreamview_2_5_setup_profile.png) 附注:在进行任何测试前会要求使用者设置参数。点击下拉列表并选择想要使用的导航模式,高清地图和车辆。该列表数据在[HMI config file](https://raw.githubusercontent.com/ApolloAuto/apollo/master/modules/dreamview/conf/hmi.conf)中定义。 附注:允许使用者在HMI的右侧面板中更改参数,但是需要点击右上角的Reset All按钮重启该系统以使参数生效。 6. 启动模块。 点击 `Setup`按钮。 ![dreamview_2_5_setup](images/dreamview_2_5_setup.png) 附注:进入 **Module Controller** 面板,检查是否所有的模块和硬件已经准备好(在离线环境中,某些硬件模块如GPS, CANBus, Velodyne,Camera和Radar不会显示)(为了获得更佳的GPS信号,可能需要车辆运行一段距离。) 7. 在 `Default Routing`中选择期望的路线。 8. 在Tasks面板中,点击 `Start Auto`(将要进入自动驾驶模式时需要十分小心谨慎)。 ![dreamview_2_5_start_auto](images/dreamview_2_5_start_auto.png) 9. 自动驾驶测试结束后,在Tasks面板中点击 `Reset All`,关闭所有窗口,关闭主机。 10. 移除磁盘驱动器。
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/02_Quick Start/apollo_6_0_quick_start.md
# Apollo 6.0 Quick Start Guide The following guide serves as a user manual for launching the Apollo upgraded software and hardware stack on vehicle, which is similar to Apollo 5.5. This Quick Start Guide focuses on the new features. For general Apollo concepts, please refer to [Apollo 5.5 Quick Start](./apollo_5_5_quick_start.md) ## Contents - [Apollo 6.0 Quick Start Guide](#apollo-60-quick-start-guide) - [Contents](#contents) - [Emergency Audio Detection](#emergency-audio-detection) - [New Deep Learning Models](#new-deep-learning-models) - [Hardware and Software Installation](#hardware-and-software-installation) - [Dreamview Usage Table](#dreamview-usage-table) - [Onboard Test](#onboard-test) ## Emergency Audio Detection Apollo currently integrates emergency vehicle detection through audio devices. Microphones are installed on the vehicle to collect audio signals around the autonomous vehicle, and the recorded soundtracks will be analized and processed to detect emergency vehicles in the surroundings. The module detail is [here](../../modules/audio). ## New Deep Learning Models Apollo integrates new deep learning models including obstacle detection with PointPillars, pedestrian prediction with semantic map and learning based trajectory planning. Please find details in corresponding modules ## Hardware and Software Installation The Hardware setup for Apollo 6.0 remains the same as Apollo 3.5, please refer to [Apollo 3.5 Hardware and System Installation Guide](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_3_5_hardware_system_installation_guide.md) for the steps to install the hardware components and the system software, as well as [Apollo Software Installation Guide](../01_Installation%20Instructions/apollo_software_installation_guide.md). ## Dreamview Usage Table For questions regarding Dreamview icons refer to the [Dreamview Usage Table](../13_Apollo%20Tool/%E5%8F%AF%E8%A7%86%E5%8C%96%E4%BA%A4%E4%BA%92%E5%B7%A5%E5%85%B7Dremview/dreamview_usage_table.md). For questions regarding Dreamland and the scenario editor, please visit our [Dreamland Introduction guide](../13_Apollo%20Tool/%E4%BA%91%E5%B9%B3%E5%8F%B0Apollo%20Studio/Dreamland_introduction.md) ## Onboard Test 1. Plug-in an external hard-drive to any available USB port in the host machine 2. Turn on the vehicle, and then the host machine 3. Launch the Dev Docker Container 4. Launch DreamView Open URL <http://localhost:8888> to launch Dreamview web service onyour host ![launch_dreamview](images/dreamview_2_5.png) 5. Select Mode, Vehicle and Map ![select_mode](images/dreamview_2_5_setup_profile.png) Note\: You'll be required to setup profile before doing anything else. Click the dropdown menu to select **Navigation** mode, the HDMap and vehicle you want to use. The lists are defined in [HMI config file](../../modules/dreamview/conf/hmi_modes) Note\: It's also possible to change the profile on the right panel of the HMI, but just remember to click `Reset All` on the top-right corner to restart the system 6. Start the Modules. Click the `Setup` button ![start_module](images/dreamview_2_5_setup.png) Go to **Module Controller** tab, check if all modules and hardware are ready (Note\: In your offline environment, the hardware modules such as GPS, CANBus, Velodyne, Camera and Radar cannot be brought up) (Note\: You may need to drive around a bit to get a good GPS signal) ![module_controller](images/dreamview_2_5_module_controller.png) 7. Under `Default Routing` select your desired route 8. Under Tasks click `Start Auto`. (Note: Be cautious when starting the autonomous driving, you should now be in autonomous mode) ![start_auto](images/dreamview_2_5_start_auto.png) 9. After the autonomous testing is complete, under `Tasks` click `Reset All`, close all windows and shutdown the machine 10. Remove the hard drive
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/02_Quick Start/apollo_1_5_quick_start_cn.md
# Apollo 1.5 快速入门指南 这个快速入门指南专注于Apollo 1.5新功能的介绍。对于Apollo的一般概念,请参考 [Apollo 1.0 快速入门指南](../02_Quick%20Start/apollo_1_0_quick_start_cn.md)和[Apollo软件安装指南](https://github.com/ApolloAuto/apollo/blob/r3.0.0/docs/quickstart/apollo_software_installation_guide_cn.md)。 # 上车测试 1. 上车测试,请确认你已经调试了LiDAR与GNSS/INS之间的外部参数。关于传感器标定,请参考[Apollo 1.5 LiDAR calibration guide](../11_Hardware%20Integration%20and%20Calibration/传感器标定/apollo_1_5_lidar_calibration_guide_cn.md)。 2. 启动发布的环境的Docker镜像 3. 启动HMI 打开浏览器(譬如Chrome)然后在地址栏输入**localhost:8887**来开始Apollo的HMI。 ![](images/hmi_setup_profile.png) 4. 选择车辆和地图 单击右上角下拉菜单选择车辆和地图。这个列表是在[HMI config file](https://raw.githubusercontent.com/ApolloAuto/apollo/master/modules/hmi/conf/config.pb.txt)中定义的。 *注意:你也可以在HMI的右侧界面来更改个人配置。只要记得点击右上角的“Reset All”来重启系统就好* ![](images/start_hmi.png) 5. 启动所有模块 ![](images/hmi_setup_1.5.png) 6. 谨慎启动自动驾驶模式 确定硬件已经齐备,所有模块已经打开并且汽车状态良好,可以安全进入自动模式自动跟车到达目的地。 ![](images/hmi_start_auto_following.png)
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/02_Quick Start/apollo_2_0_quick_start_cn.md
# Apollo 2.0 快速入门指南 这个快速入门指南专注于Apollo 2.0新功能的介绍。对于Apollo的一般概念,请参考 [Apollo 1.0 快速入门指南](../02_Quick%20Start/apollo_1_0_quick_start_cn.md)和[Apollo软件安装指南](https://github.com/ApolloAuto/apollo/blob/r3.0.0/docs/quickstart/apollo_software_installation_guide_cn.md)。 # 上车测试 1. 上车测试,请确认你已经调试了所有传感器之间的外部参数。关于传感器标定,请参考[Apollo 2.0 Sensor Calibration Guide](../11_Hardware%20Integration%20and%20Calibration/传感器标定/apollo_2_0_sensor_calibration_guide_cn.md). 2. 启动发布的环境的Docker镜像 3. 启动DreamView 打开浏览器(譬如Chrome)然后在地址栏输入**localhost:8887**来开始Apollo的HMI。 ![](images/dreamview.png) 4. 选择车辆和地图 单击右上角下拉菜单选择车辆和地图。这个列表是在[HMI config file](ttps://raw.githubusercontent.com/ApolloAuto/apollo/master/modules/dreamview/conf/hmi.conf)中定义的。 5. 启动所有模块 点击左侧的"Setup"按钮来设置。 ![](images/dreamview_setup.png) 跳转到*Module Controller*页面,检查所有的软硬件都已正常工作。 ![](images/dreamview_module_controller.png) 6. 谨慎启动自动驾驶模式 确定硬件已经齐备,所有模块已经打开并且汽车状态良好,环境安全,点击"Start Auto"按钮,然后它就会自动带你走! ![](images/dreamview_start_auto.png)
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/02_Quick Start/apollo_3_5_quick_start.md
# Apollo 3.5 Quick Start Guide The following guide serves as a user manual for launching the Apollo 3.5 software and hardware stack on vehicle. The Apollo 3.5 Quick Start Guide focuses on new features available in Apollo 3.5. For general Apollo concepts, please refer to [Apollo 1.0 Quick Start](apollo_1_0_quick_start.md). ## Contents - [Calibration Guide](#calibration-guide) - [Hardware and Software Installation](#hardware-and-software-installation) - [Dreamview Usage Table](#dreamview-usage-table) - [Onboard Test](#onboard-test) ## Calibration Guide For the vehicle's onboard testing make sure you have calibrated all the sensors. For sensor calibration, please refer to [Apollo 2.0 Sensor Calibration Guide](../10Hardware%20Integration%20and%20Calibration/%E4%BC%A0%E6%84%9F%E5%99%A8%E6%A0%87%E5%AE%9A/apollo_2_0_sensor_calibration_guide.md) before you proceed. ## Hardware and Software Installation Please refer to [Apollo 3.5 Hardware and System Installation Guide](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_3_5_hardware_system_installation_guide.md) for the steps to install the hardware components and the system software, as well as [Apollo Software Installation Guide](../01_Installation%20Instructions/apollo_software_installation_guide.md). ## Dreamview Usage Table For questions regarding Dreamview icons refer to the [Dreamview Usage Table](../13_Apollo%20Tool/%E5%8F%AF%E8%A7%86%E5%8C%96%E4%BA%A4%E4%BA%92%E5%B7%A5%E5%85%B7Dremview/dreamview_usage_table.md). ## Onboard Test 1. Plug-in an external hard-drive to any available USB port in the host machine. 2. Turn on the vehicle, and then the host machine. 3. Launch Docker Release Container. 4. Launch DreamView. Note\: Use your favorite browser to access Dreamview web service in your host machine browser with URL <http://localhost:8888>. ![launch_dreamview](images/dreamview_2_5.png) 5. Select Mode, Vehicle and Map. ![setup_profile](images/dreamview_2_5_setup_profile.png) Note\: You'll be required to setup profile before doing anything else. Click the dropdown menu to select **Navigation** mode, the HDMap and vehicle you want to use. The lists are defined in [HMI config file](https://raw.githubusercontent.com/ApolloAuto/apollo/r3.0.0/modules/dreamview/conf/hmi.conf). Note\: It's also possible to change the profile on the right panel of the HMI, but just remember to click `Reset All` on the top-right corner to restart the system. 6. Start the Modules. Click the `Setup` button. ![start_modules](images/dreamview_2_5_setup.png) Go to **Module Controller** tab, check if all modules and hardware are ready. (Note\: In your offline environment, the hardware modules such as GPS, CANBus, Velodyne, Camera and Radar cannot be brought up.) (Note\: You may need to drive around a bit to get a good GPS signal.) ![controller](images/dreamview_2_5_module_controller.png) 7. Under `Default Routing` select your desired route. 8. Under Tasks click `Start Auto`. (Note: Be cautious when starting the autonomous driving, you should now be in autonomous mode.) ![start_auto](images/dreamview_2_5_start_auto.png) 9. After the autonomous testing is complete, under Tasks click `Reset All`, close all windows and shutdown the machine. 10. Remove the hard drive.
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/02_Quick Start/apollo_1_0_quick_start_cn.md
# Apollo 快速入门指南 1.0 ## 目录 - [Apollo 快速入门指南 1.0](#apollo-快速入门指南-10) - [目录](#目录) - [关于这个文档](#关于这个文档) - [文档规约](#文档规约) - [概览](#概览) - [车辆环境描述](#车辆环境描述) - [硬件安装](#硬件安装) - [软件安装](#软件安装) - [在车辆上运行示例](#在车辆上运行示例) - [启动本地版本Docker映像](#启动本地版本docker映像) - [记录驾驶轨迹](#记录驾驶轨迹) - [执行自动驾驶](#执行自动驾驶) - [关闭](#关闭) - [运行离线演示](#运行离线演示) # 关于这个文档 _Apollo 快速入门指南 1.0_ 提供了所有关于了解、安装以及构建Apollo的基本说明 ## 文档规约 下表列出了本文档中使用的归约: | **Icon** | **描述** | | ----------------------------------- | ---------------------------------------- | | **粗体** | 重要 | | `等宽字体` | 代码,类型数据 | | _斜体_ | 文件标题,章节和标题使用的术语 | | ![info](images/info_icon.png) | **Info** 包含可能有用的信息。忽略信息图标没有消极的后果 | | ![tip](images/tip_icon.png) | **Tip**. 包括有用的提示或可能有助于您完成任务的捷径。 | | ![online](images/online_icon.png) | **Online**. 提供指向特定网站的链接,您可以在其中获取更多信息 | | ![warning](images/warning_icon.png) | **Warning**. 包含**不**能忽略的信息,或者执行某个任务或步骤时,您将面临失败风险 | # 概览 Apollo 1.0, 也被称为 _Automatic GPS Waypoint Following(自动GPS跟随)_, 使用在封闭的区域内,如测试轨道或停车场。它可以准确地以人类驾驶员在封闭的平坦区域的速度复现一个驾驶轨迹。 在这个开发阶段, Apollo 1.0 **无法** 察觉到邻近的障碍物, **不要**在公共道路或没有GPS信号的区域行驶。 # 车辆环境描述 The Lincoln MKZ, enhanced by Autonomous Stuff, 为用户提供了一个无障碍的自动车辆平台。该平台为用户提供了一整套硬件和软件解决方案。 用户可以直接获得车辆某些模块控制权限,如档位,速度和指示灯。平台已经为转向,刹车,加速和档位创建了接口,为开发人员提供了可使用的用户界面。 包含的其他功能: - 电源分配器终端 - 集成PC与ROS预安装和配置 - 线控驱动的紧急停止系统 - 以太网和USB连接 (to PC) # 硬件安装 请参考 [Apollo 1.0 Hardware and System Installation Guide](https://github.com/ApolloAuto/apollo/blob/r1.0.0/docs/quickstart/apollo_1_0_hardware_system_installation_guide.md) 中的步骤来安装硬件组件以及系统软件 # 软件安装 请参考[Apollo软件安装指南](https://github.com/ApolloAuto/apollo/blob/r3.0.0/docs/quickstart/apollo_software_installation_guide_cn.md) # 在车辆上运行示例 本节提供运行Apollo 1.0 Demo on Vehicle的说明。 1. 设置硬件: - 打开平台车辆 - 打开工业PC机(IPC). ![](images/IPC_powerbutton.png) - 通过按住电源按钮打开调制解调器电源,直到指示灯亮起 - 设置IPC的网络配置:静态IP(例如192.168.10.6),子网掩码(例如255.255.255.0)和网关(例如192.168.10.1) - 配置您的DNS服务器IP(例如,8.8.8.8)。 - 使用平板电脑访问**设置**并连接到MKZ wifi 热点: ![](images/ipad_config_wifi.png) 2. 在Docker中使用**Chrome(只能使用Chrome)** 启动HMI: ![warning](images/warning_icon.png)**Warning:** 确保您不是同时从两个Docker容器启动HMI。 ## 启动本地版本Docker映像 运行以下命令: ``` cd $APOLLO_HOME bash docker/scripts/release_start.sh local_release ``` 当Docker启动时,它创建一个端口映射,将Docker内部端口8887映射到主机端口8887.然后,您可以在主机浏览器中访问HMI Web服务: 打开Chrome浏览器并启动阿波罗人机界面,转到 **192.168.10.6:8887**. ![](images/start_hmi.png) ## 记录驾驶轨迹 按照以下步骤记录驾驶轨迹: 1. 在Apollo HMI中,在**Quick Record**下,单击**Setup**以启动所有模块并执行硬件运行状况检查。 ![](images/hmi_record_setup.png) 2. 如果硬件健康检查通过,单击 **Start** 按钮开始记录驱动程序轨迹。 ![](images/hmi_record_start.png) 3. 到达目的地后,点击**Stop** 按钮停止录制。 ![](images/hmi_record_stop.png) 4. 如果要记录不同的轨迹,请单击**New** 按钮再次开始录制。 ![](images/hmi_record_reset.png) ## 执行自动驾驶 按照以下步骤执行自主驾驶: 1. 在Apollo HMI中,在Quick Play下,单击 **Setup** 启动所有模块并执行硬件运行状况检查。 ![](images/hmi_play_setup.png) 2. 如果车辆顺利通过Setup这一步, 它已经准备好进入自动模式了。 **确保驾驶员准备好了!** 点击 **Start**按钮开始自动驾驶。 ![](images/hmi_play_start.png) 3. 到达目的地后,点击 **Stop** 按钮停止重放录制的轨迹。 ![](images/hmi_play_stop.png) ## 关闭 1. 从终端关闭系统: ```sudo shutdown now``` 2. 关闭IPC(找到桌面右上角的图标点击 **Shut Down**). 3. 按住电源按钮关闭调制解调器,直到指示灯熄灭。 4. 关掉车子 # 运行离线演示 参考 [Offline Demo Guide](https://github.com/ApolloAuto/apollo/blob/r1.0.0/docs/demo_guide/README.md)
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/02_Quick Start/apollo_2_5_quick_start_cn.md
# Apollo 2.5 快速入门指南 这个快速入门指南专注于Apollo 2.5新功能的介绍。对于Apollo的一般概念,请参考 [Apollo 1.0 快速入门指南](../02_Quick%20Start/apollo_1_0_quick_start_cn.md) 和 [Apollo软件安装指南](https://github.com/ApolloAuto/apollo/blob/r3.0.0/docs/quickstart/apollo_software_installation_guide_cn.md)。 # 上车测试 1. 上车测试,请确认你已经调试了所有传感器之间的外部参数。关于传感器标定,请参考 [Apollo 2.0 Sensor Calibration Guide](../11_Hardware%20Integration%20and%20Calibration/传感器标定/apollo_2_0_sensor_calibration_guide_cn.md). 1. 启动发布的环境的Docker镜像 1. 启动DreamView 打开浏览器(譬如Chrome)然后在地址栏输入**http://localhost:8888**来启动Apollo Dreamview。 ![](images/dreamview_2_5.png) 1. 选择模式、车辆和地图 ![](images/dreamview_2_5_setup_profile.png) 单击右上角下拉菜单选择车辆和地图。这个列表是在 [HMI config file](ttps://raw.githubusercontent.com/ApolloAuto/apollo/master/modules/dreamview/conf/hmi.conf) 中定义的。 1. 启动所有模块 点击左侧的"Setup"按钮来设置。 ![](images/dreamview_2_5_setup.png) 跳转到*Module Controller*页面,检查所有的软硬件都已正常工作。 ![](images/dreamview_2_5_module_controller.png) 1. 在Default Routing下选择想要的路线。 1. 在Tasks下谨慎启动自动驾驶模式 确定硬件已经齐备,所有模块已经打开并且汽车状态良好,环境安全,点击"Start Auto"按钮。 [](images/dreamview_2_5_start_auto.png) 1. 测试完成后,点击Reset All,关闭所有窗口,关闭工控机。
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/02_Quick Start/apollo_8_0_quick_start.md
# Apollo 8.0 Quick Start Guide This document is based on four typical scenarios, from simple to complex, to introduce how to use the package in a typical way, so that developers can quickly get started using Apollo. ## Prerequisites Before reading this document, make sure you have installed the Apollo environment manager tool and launch apollo env container successfully according to the installation documentation. ## Demo <video src="https://apollo-pkg-beta.cdn.bcebos.com/e2e/QuickStartDemo_v0.4_en.mp4" width="700px" height="400px" controls="controls"></video> ### Scenario 1: Using Dreamview to View Records This scenario describes how to use Dreamview to play records and provides a foundation for developers to become familiar with the Apollo platform. You can use Dreamview to play the records provided by Apollo to further observe and learn about Apollo autonomous driving. This article explains the installation and simple usage steps of Dreamview. For the detailed documentation of Dreamview, see the Dreamview documentation. #### Step 1: Enter the Apollo Docker environment 1. Create workspace ```shell mkdir application-demo cd application-demo ``` 2. Start Apollo env container ```shell aem start ``` 3. Enter Apollo env container ```shell aem enter ``` > Note: If you want to force the container to be recreated you can specify the `-f` option and If you are using multiple containers at the same time, it is helpful to specify the container name with the `--name` option 4. Initialize workspace ```shell aem init ``` #### Step 2: Install DreamView In the same terminal, enter the following command to install Apollo's DreamView program. ```sudo apt install apollo-neo-dreamview-dev apollo-neo-monitor-dev sudo apt install apollo-neo-dreamview-dev apollo-neo-monitor-dev ``` #### Step 3: Launch Dreamview In the same terminal, enter the following command to start Apollo's DreamView program. ```shell aem bootstrap start ``` #### Step 4: Download the Apollo demo record A file with .record suffix is what we call a record. > The Record file is used to record messages sent/received to/from channels in Cyber RT. Reply record files can help reproduce the behavior of previous operations of Cyber RT. From the command line, type the following command to download the record package. ```shell wget https://apollo-system.cdn.bcebos.com/dataset/6.0_edu/demo_3.5.record ``` #### Step 5: Play the Apollo demo record ```shell cyber_recorder play -f demo_3.5.record --loop ``` > Note: The --loop option is used to set the loop playback mode. #### Step 6: Use DreamView to view the record Enter https://localhost:8888 in your browser to access Apollo DreamView: ![dv_page][dv_page.png] If all is well, you can see a car moving forward in DreamView. The car and road conditions you see now are simply a playback of the data from the record by DreamView, just like playing back a recorded video. #### Step 7: Stop DreamView Enter the following command to end the DreamView process: ```shell aem bootstrap stop ``` ### Scenario 2: Cyber Component Extensions This document describes how to develop and compile and run a Cyber component as a simple extension to example-component to provide a foundation for developers to become familiar with the Apollo platform. You can observe and learn more about the Apollo compilation process by compiling and running example-component. The source code of example-component in the QuickStart Project is a demo based on Cyber RT extending Apollo functional components. If you are interested in how to write a component, dag file and launch file, you can find the full source code of example-component in the QuickStart Project. The directory structure of demo/example-component is shown below: ```shell demo/example_components/ |-- src | |-- common_component_example.cc | |-- common_component_example.h | |-- BUILD |-- proto | |--examples.proto | |--BUILD |-- BUILD |-- cyberfile.xml |-- example.dag |-- example.launch ``` #### Step 1: Download quickstart project Clone demo project ```shell git clone https://github.com/ApolloAuto/application-demo.git ``` and enter project directory ```shell cd application-demo ``` #### Step 2: Enter the Apollo Docker environment Start apollo env container. ```shell aem start ``` > Note: If you want to force the container to be recreated you can specify the `-f` option and If you are using multiple containers at the same time, it is helpful to specify the container name with the `--name` option. Enter apollo env container. ```shell aem enter ``` #### Step 3: Compile the component Enter the following command to compile the component. ```shell buildtool build --packages example_components ``` > The --packages argument specifies the path to the package specified in the compilation workspace, in this case example_components. > For more detailed usage of `buildtool`, please refer to the [Apollo buildtool](../03_Package%20Management/apollo_buildtool.md) documentation When you call the script build command, the current directory is the workspace directory, so be sure to use the script build command in the workspace. Apollo's compilation tool will automatically analyze all the required dependencies, download and generate the necessary dependency information files automatically. ![example_building][example_building.png] If the compiler needs to pass in arguments, you can use --builder_args to specify them. #### Step 4: Run the component Run the following command: ```shell cyber_launch start example_components/example.launch ``` If everything works, the terminal will display as follows: ![example_launched][example_launched.png] At this point, you can open another terminal, run cyber_monitor, and observe the data in channels: ```shell cyber_monitor ``` ### Scenario 3: Learning and experimenting with the planning module This scenario describes how to learn and adjust the planning module, compile and debug the planning module, and help developers get familiar with the Apollo 8.0 development model. The planning_customization module is an End-2-End solution (i.e. you can run through the entire contents of Routing Request within the simulation environment), but it does not contain any source code but a cyberfile.xml file. The cyberfile.xml file describes all the component packages (planning-dev, dreamview-dev, routing-dev, task_manager, and monitor-dev) that are dependent on the scenario and how they have been imported. Since the planning source code needs to be extended, the planning-dev package is introduced as "src", and the planning source code is automatically downloaded and copied to the workspace when the module is compiled. The cyberfile for planning_customization is shown as follows: ```xml <package> <name>planning-customization</name> <version>1.0.0</version> <description> planning_customization </description> <maintainer email="apollo-support@baidu.com">apollo-support</maintainer> <type>module</type> <src_path>//planning_customization</src_path> <license>BSD</license> <author>Apollo</author> <depend>bazel-extend-tools-dev</depend> <depend type="binary" repo_name="dreamview">dreamview-dev</depend> <depend type="binary" repo_name="routing">routing-dev</depend> <depend type="binary" repo_name="task-manager">task-manager-dev</depend> <depend type="binary" repo_name="monitor">monitor-dev</depend> <depend type="src" repo_name="planning">planning-dev</depend> <depend expose="False">3rd-rules-python-dev</depend> <depend expose="False">3rd-grpc-dev</depend> <depend expose="False">3rd-bazel-skylib-dev</depend> <depend expose="False">3rd-rules-proto-dev</depend> <depend expose="False">3rd-py-dev</depend> <depend expose="False">3rd-gpus-dev</depend> <builder>bazel</builder> </package> ``` #### Step 1: Download quickstart project Clone demo project ```shell git clone https://github.com/ApolloAuto/application-demo.git ``` and enter project directory ```shell cd application-demo ``` #### Step 2: Enter the Apollo Docker environment Start apollo env container. ```shell aem start ``` > Note: If you want to force the container to be recreated you can specify the `-f` option and If you are using multiple containers at the same time, it is helpful to specify the container name with the `--name` option. Enter apollo env container. ```shell aem enter ``` #### Step 3: Compile the planning source code package ```shell buildtool build --packages planning_customization ``` The --packages argument specifies the path to the package specified in the compilation workspace, in this case planning_customization, and defaults to all packages in the workspace if not specified. When script compile command is called, the current directory is the workspace directory, so be sure to use the script compile command under the workspace. Apollo's compilation tool will automatically analyze all the required dependencies, download and generate the necessary dependency information files automatically. The first time you build, you need to pull some dependency packages from the Internet, which takes about 13 minutes depending on the speed and configuration of your computer. ![planning_build_finish][planning_build_finish.png] #### Step 4: Debug planning Enter the following command to run dreamview: ```shell aem bootstrap start ``` If you have already started Dreamview, enter the following command to restart the Dreamview process: ```shell aem bootstrap restart ``` At this point, DreamView and monitor will be started automatically, and you can enter localhost:8888 in your browser to open DreamView: ![dv_page_2][dv_page_2.png] #### Step 5: Enter sim control simulation mode for debugging 1. Select the mode, model and map. - Select MKz Standard Debug in the upper menu bar. - Select MkzExample for the vehicle model. - Select Sunnyvale Big Loop for the map. 2. Click Tasks, and in the Others module, select Sim Control to enter the simulation control, as shown in the following figure. ![start_simcontrol][start_simcontrol.png] 3. Click the Module Controller column on the left to start the process of the module to be debugged, and select the Planning, Routing modules. ![dv_modules][dv_modules_page.png] 4. Set the vehicle simulation driving path, click Route Editing on the left side, drag and click the mouse to set the vehicle driving path in the map, as shown in the following figure: ![route_request][route_request.png] 5. After you set the point position, click Send Routing Request. As shown in the following figure, the red path is found in the map by the Routing module, and the blue path is the local path planned by the Planning module at real time. ![dv_running_page][dv_running_page.png] 6. At this point, if you want to debug the planning module, you can directly modify the planning source code in the workspace, which is located in the modules/planning directory, and re-run the compilation script after the changes are made: ```shell buildtool build --packages planning_customization ``` 7. Re-run the planning module in Dreamview. ### Scenario 4: Awareness LIDAR Functionality Testing This scenario describes how to start the Lidar Perception module using a package to help developers get familiar with the Apollo Perception module. You can observe the results of the Lidar Perception run by playing the record provided by Apollo. #### Prerequisites This document assumes that you have followed the Installation - Package Method > Installing Apollo environment manager tool to complete Steps 1 and 2. Compared to the three examples above, testing the sensing module functionality requires the use of the GPU, so you should obtain the GPU image of the package for testing and verification. #### Step 1: Start Apollo Docker environment and enter 1. Create workspace ```shell mkdir application-demo cd application-demo ``` 2. Enter the following command to start in GPU mode: ```shell aem start_gpu -f ``` 3. Enter the following command to access the container: ```shell aem enter ``` 4. Initialize workspace ```shell aem init ``` #### Step 2: Download the record 1. Enter the following command to download the record: ```shell wget https://apollo-system.bj.bcebos.com/dataset/6.0_edu/sensor_rgb.tar.xz ``` 2. Create a directory and extract the downloaded record to the directory: ```shell sudo mkdir -p ./data/bag/ sudo tar -xzvf sensor_rgb.tar.xz -C ./data/bag/ ``` #### Step 3: Install DreamView > Note: Apollo core can only be installed inside the container, do not perform this step on the host! In the same terminal, enter the following command to install the DreamView program. ```shell buildtool install --legacy dreamview-dev monitor-dev ``` #### Step 4: Install transform, perception and localization 1. In the same terminal, enter the following command to install the perception program. ```shell buildtool install --legacy perception-dev ``` 2. Enter the following command to install localization, v2x and transform programs. ```shell buildtool install --legacy localization-dev v2x-dev transform-dev ``` #### Step 5: Run the module 1. Modify the pointcloud_topic flag in `/apollo/modules/common/data/global_flagfile.txt` (or add the pointcloud_topic flag if it doesn't exist) to specify the channel for point cloud data. ```shell --pointcloud_topic=/apollo/sensor/velodyne64/compensator/PointCloud2 ``` ![package-configuration2][package-configuration2.png] 2. In the same terminal, enter the following command to start Apollo's DreamView program. ```shell aem bootstrap ``` Enter localhost:8888 in the browser to open the DreamView page, then select the correct mode, model, and map. ![package-dreamview2][package-dreamview2.png] Click the Module Controller module in the status bar on the left side of the page to start the transform module. ![package-transform][package-transform.png] 3. Start the LIDAR module using the mainboard method: ```shell mainboard -d /apollo/modules/perception/production/dag/dag_streaming_perception_lidar.dag ``` #### Step 6: Result verification 1. Play the record: you need to mask out the perception channel data contained in the record with -k parameter. ```shell cyber_recorder play -f ./data/bag/sensor_rgb.record -k /perception/vehicle/obstacles /apollo/perception/obstacles /apollo/perception/traffic_light /apollo/perception ``` 2. Verify the detection result: click the LayerMenu in the left toolbar of DreamView and turn on Point Cloud in Perception. ![package-results1][package-results1.png] To view the results. ![package-results2][package-results2.png] #### Step 7: Model Replacement The following describes the parameter configuration and replacement process for the MASK_PILLARS_DETECTION, CNN_SEGMENTATION, and CENTER_POINT_DETECTION models in the lidar detection process. You can easily replace these in lidar_detection_pipeline.pb.txt configuration to load and run a different model. **MASK_PILLARS_DETECTION Model Replacement** Modify the contents of the configuration file in lidar_detection_pipeline.pb.txt ```shell vim /apollo/modules/perception/pipeline/config/lidar_detection_pipeline.pb.txt ``` Replace stage_type with MASK_PILLARS_DETECTION ```shell stage_type: MASK_PILLARS_DETECTION ``` ![mask1][mask1.png] and change the content of the configuration file information of the corresponding stage to ```shell stage_config: { stage_type: MASK_PPILLARS_DETECTION enabled: true } ``` ![mask2][maske2.png] After saving the configuration file changes, start the LIDAR module and play the record to verify the detection results. ![mask3][mask3.png] **CNN_SEGMENTATION model replacement** Modify the content of the configuration file in lidar_detection_pipeline.pb.txt: replace stage_type with CNN_SEGMENTATION and modify the content of the configuration file of the corresponding stage. ```shell stage_type: CNN_SEGMENTATION ``` ```shell stage_config: { stage_type: CNN_SEGMENTATION enabled: true cnnseg_config: { sensor_name: "velodyne128" param_file: "/apollo/modules/perception/production/data/perception/lidar/models/cnnseg/velodyne64/cnnseg_param.conf" proto_file: "/apollo/modules/perception/production/data/perception/lidar/models/cnnseg/velodyne64/deploy.prototxt" weight_file: "/apollo/modules/perception/production/data/perception/lidar/models/cnnseg/velodyne64/deploy.caffemodel" engine_file: "/apollo/modules/perception/production/data/perception/lidar/models/cnnseg/velodyne64/engine.conf" } } ``` Start the lidar module and play the record to verify the detection result. ![cnn1][cnn1.png] **CENTER_POINT_DETECTION model replacement** Replace stage_type with CENTER_POINT_DETECTION: ```shell stage_type: CENTER_POINT_DETECTION ``` and change the content of the configuration file information of the corresponding stage to ```shell stage_config: { stage_type: CENTER_POINT_DETECTION enabled: true } ``` Start the LIDAR module and play the record to verify the detection result: ![centor1][centor1.png] ## Install Apollo module source code This section describes how to install the Apollo modules' source code under the workspace after installing the package. ### Step 1: Start and enter apollo env container Download demo project ```shell git clone https://github.com/ApolloAuto/application-demo.git ``` Enter project directory ```shell cd application-demo ``` > the folder will be mounted to /apollo_workspace Start apollo env container ```bash aem start ``` Enter apollo env container ```shell aem enter ``` ### Step 2: Install source code Execute the following command to install the source code ```bash buildtool install cyber-dev audio-dev bridge-dev canbus-dev canbus-vehicle-lincoln-dev common-dev control-dev dreamview-dev drivers-dev guardian-dev localization-dev map-dev monitor-dev perception-dev planning-gpu-dev prediction-dev routing-dev storytelling-dev task-manager-dev third-party-perception-dev transform-dev v2x-dev ``` > A series of warnings may appear during the installation process, which is normal and can be ignored. ![install-warning][install-warning.png] [dv_page.png]: <https://bce.bdstatic.com/doc/Apollo-Homepage-Document/Apollo_Doc_CN_8_0/dv_page_6334353.jpeg> [example_building.png]: <https://bce.bdstatic.com/doc/Apollo-Homepage-Document/Apollo_Doc_CN_8_0/example_buiding_8617536.png> [example_launched.png]: <https://bce.bdstatic.com/doc/Apollo-Homepage-Document/Apollo_Doc_CN_8_0/example_launched_07bcf7b.png> [planning_build_finish.png]: <https://bce.bdstatic.com/doc/Apollo-Homepage-Document/Apollo_Doc_CN_8_0/planning_build_finish_1ac5b1e.png> [dv_page_2.png]: <https://bce.bdstatic.com/doc/Apollo-Homepage-Document/Apollo_Doc_CN_8_0/dv_page_2_bdc05e7.png> [start_simcontrol.png]: <https://bce.bdstatic.com/doc/Apollo-Homepage-Document/Apollo_Doc_CN_8_0/start_simcontrol_ee8eaf7.png> [dv_modules_page.png]: <https://bce.bdstatic.com/doc/Apollo-Homepage-Document/Apollo_Doc_CN_8_0/dv_modules_page_cf16a28.png> [route_request.png]: <https://bce.bdstatic.com/doc/Apollo-Homepage-Document/Apollo_Doc_CN_8_0/route_request_ba8694d.png> [dv_running_page.png]: <https://bce.bdstatic.com/doc/Apollo-Homepage-Document/Apollo_Doc_CN_8_0/dv_running_page_e346da7.png> [package-configuration2.png]: <https://bce.bdstatic.com/doc/Apollo-Homepage-Document/Apollo_Doc_CN_8_0/%E5%8C%85-%E9%85%8D%E7%BD%AE2_f5ce968.png> [package-dreamview2.png]: <https://bce.bdstatic.com/doc/Apollo-Homepage-Document/Apollo_Doc_CN_8_0/%E5%8C%85-dreamview2_3d6fa5c.png> [package-transform.png]: <https://bce.bdstatic.com/doc/Apollo-Homepage-Document/Apollo_Doc_CN_8_0/%E5%8C%85-%20transform_e13afb6.png> [package-results1.png]: <https://bce.bdstatic.com/doc/Apollo-Homepage-Document/Apollo_Doc_CN_8_0/%E5%8C%85-%E7%BB%93%E6%9E%9C1_32f3f86.png> [package-results2.png]: <https://bce.bdstatic.com/doc/Apollo-Homepage-Document/Apollo_Doc_CN_8_0/%E5%8C%85-%E7%BB%93%E6%9E%9C2_1be66a4.png> [mask1.png]: <https://bce.bdstatic.com/doc/Apollo-Homepage-Document/Apollo_Doc_CN_8_0/mask1_f067520.png> [maske2.png]: <https://bce.bdstatic.com/doc/Apollo-Homepage-Document/Apollo_Doc_CN_8_0/mask2_f5373a5.png> [mask3.png]: <https://bce.bdstatic.com/doc/Apollo-Homepage-Document/Apollo_Doc_CN_8_0/mask3_7d0d0bd.png> [cnn1.png]: <https://bce.bdstatic.com/doc/Apollo-Homepage-Document/Apollo_Doc_CN_8_0/cnn1_8d22d9f.png> [centor1.png]: <https://bce.bdstatic.com/doc/Apollo-Homepage-Document/Apollo_Doc_CN_8_0/centor1_edea96e.png> [install-warning.png]: <https://bce.bdstatic.com/doc/Apollo-Homepage-Document/Apollo_Doc_CN_8_0/%E6%88%AA%E5%B1%8F2022-12-09%20%E4%B8%8A%E5%8D%8811.12.22_1da6ba9.png>
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/02_Quick Start/apollo_3_0_quick_start.md
# Apollo 3.0 Quick Start Guide The following guide serves as a user manual for launching the Apollo 3.0 software and hardware stack on vehicle. The Apollo 3.0 Quick Start Guide focuses on Apollo 3.0's new features. For general Apollo concepts, please refer to [Apollo 1.0 Quick Start](../02_Quick%20Start/apollo_1_0_quick_start.md). ## Contents - [Calibration Guide](#calibration-guide) - [Hardware and Software Installation](#hardware-and-software-installation) - [Dreamview Usage Table](#dreamview-usage-table) - [Onboard Test](#onboard-test) ## Calibration Guide For the vehicle's onboard testing make sure you have calibrated all the sensors. For sensor calibration, please refer to [Apollo 2.0 Sensor Calibration Guide](../11_Hardware%20Integration%20and%20Calibration/传感器标定/apollo_2_0_sensor_calibration_guide.md) before you proceed. ## Hardware and Software Installation Please refer to [Apollo 3.0 Hardware and System Installation Guide](../11_Hardware%20Integration%20and%20Calibration/车辆集成/硬件安装hardware installation/apollo_3_0_hardware_system_installation_guide.md) for the steps to install the hardware components and the system software, as well as [Apollo Software Installation Guide](../01_Installation Instructions/apollo_software_installation_guide.md). ## Dreamview Usage Table For questions regarding Dreamview icons refer to the [Dreamview Usage Table](../13_Apollo%20Tool/可视化交互工具Dremview/dreamview_usage_table.md). ## Onboard Test 1. Plug-in an external hard-drive to any available USB port in the host machine. 2. Turn on the vehicle, and then the host machine. 3. Launch Docker Release Container. 4. Launch DreamView. Note\: Use your favorite browser to access Dreamview web service in your host machine browser with URL <http://localhost:8888.> ![dreamview_2_5](images/dreamview_2_5.png) 5. Select Mode, Vehicle and Map. ![dreamview_2_5_setup_profile](images/dreamview_2_5_setup_profile.png) Note\: You'll be required to setup profile before doing anything else. Click the dropdown menu to select **Navigation** mode, the HDMap and vehicle you want to use. The lists are defined in [HMI config file](https://raw.githubusercontent.com/ApolloAuto/apollo/master/modules/dreamview/conf/hmi.conf). Note\: It's also possible to change the profile on the right panel of the HMI, but just remember to click `Reset All` on the top-right corner to restart the system. 6. Start the Modules. Click the `Setup` button. ![dreamview_2_5_setup](images/dreamview_2_5_setup.png) Go to **Module Controller** tab, check if all modules and hardware are ready. (Note\: In your offline environment, the hardware modules such as GPS, CANBus, Velodyne, Camera and Radar cannot be brought up.) (Note\: You may need to drive around a bit to get a good GPS signal.) ![dreamview_2_5_module_controller](images/dreamview_2_5_module_controller.png) 7. Under `Default Routing` select your desired route. 8. Under Tasks click `Start Auto`. (Note: Be cautious when starting the autonomous driving, you should now be in autonomous mode.) ![dreamview_2_5_start_auto](images/dreamview_2_5_start_auto.png) 9. After the autonomous testing is complete, under Tasks click `Reset All`, close all windows and shutdown the machine. 10. Remove the hard drive.
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/02_Quick Start/apollo_2_5_quick_start.md
# Apollo 2.5 Quick Start Guide The following guide serves as a user manual for launching the Apollo 2.5 software and hardware stack on vehicle. The Apollo 2.5 Quick Start Guide focuses on Apollo 2.5 new features. For general Apollo concepts, please refer to [Apollo 1.0 Quick Start](../02_Quick%20Start/apollo_1_0_quick_start.md). ## Contents - [Calibration Guide](#calibration-guide) - [Hardware and Software Installation](#hardware-and-software-installation) - [Dreamview Usage Table](#dreamview-usage-table) - [Onboard Test](#onboard-test) ## Calibration Guide For vehicle onboard testing make sure you have calibrated all sensors. For sensor calibration, please refer to [Apollo 2.0 Sensor Calibration Guide](../11_Hardware%20Integration%20and%20Calibration/传感器标定/apollo_2_0_sensor_calibration_guide.md) before you proceed. ## Hardware and Software Installation Please refer to [Apollo 2.5 Hardware and System Installation Guide](../11_Hardware%20Integration%20and%20Calibration/车辆集成/硬件安装hardware installation/apollo_2_5_hardware_system_installation_guide_v1.md) for the steps to install the hardware components and the system software, as well as [Apollo Software Installation Guide](../01_Installation Instructions/apollo_software_installation_guide.md). ## Dreamview Usage Table For questions regarding Dreamview icons refer to the [Dreamview Usage Table]( https://github.com/ApolloAuto/apollo/blob/master/docs/specs/dreamview_usage_table.md). ## Onboard Test 1. Plug-in an external hard-drive to any available USB port in the host machine. 2. Turn on the vehicle, and then the host machine. 3. Launch Docker Release Container. 4. Launch DreamView. Note\: Use your favorite browser to access Dreamview web service in your host machine browser with URL http://localhost:8888. ![](images/dreamview_2_5.png) 5. Select Mode, Vehicle and Map. ![](images/dreamview_2_5_setup_profile.png) Note\: You'll be required to setup profile before doing anything else. Click the dropdown menu to select **Navigation** mode, the HDMap and vehicle you want to use. The lists are defined in [HMI config file](https://raw.githubusercontent.com/ApolloAuto/apollo/master/modules/dreamview/conf/hmi.conf). Note\: It's also possible to change the profile on the right panel of the HMI, but just remember to click "Reset All" on the top-right corner to restart the system. 6. Start Modules. Click the "Setup" button. ![](images/dreamview_2_5_setup.png) Go to **Module Controller** tab, check if all modules and hardware are ready. (Note\: In your offline environment, the hardware modules such as GPS, CANBus, Velodyne, Camera and Radar cannot be brought up.) (Note\: You may need to drive around a bit to get a good GPS signal.) ![](images/dreamview_2_5_module_controller.png) 7. Under Default Routing select your desired route. 8. Under Tasks click Start Auto. (Note: Be cautious when starting autonomous driving, you should now be in autonomous mode.) ![](images/dreamview_2_5_start_auto.png) 9. After autonomous testing is complete, under Tasks click Reset All, close all windows and shutdown the machine. 10. Remove the hard drive.
0
apollo_public_repos/apollo/docs/02_Quick Start
apollo_public_repos/apollo/docs/02_Quick Start/demo_guide/record_helper.py
#!/usr/bin/env python3 ############################################################################### # Copyright 2018 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### """ A script for downloading Apollo record files """ import os import sys import argparse import subprocess DOWNLOAD_LINK_PREFIX = "https://github.com/ApolloAuto/apollo/releases/download" URL_LISTING = [ "v1.0.0/demo_1.0.bag", "v1.5.0/demo_1.5.bag", "v2.0.0/demo_2.0.bag", "v2.0.0/apollo_2.0_camera_sample.bag", "v2.5.0/demo_2.5.bag", "v3.5.0/demo_3.5.record", ] def build_urls(): urls = {} for u in URL_LISTING: urls[os.path.basename(u)] = "{}/{}".format(DOWNLOAD_LINK_PREFIX, u) return urls def download_record(record_name, urls): """ Match and download record from urls, and save it locally """ if record_name not in urls: print( "Unknown record: {}. Type \"{} --help\" on available records.".format( record_name, sys.argv[0])) return False url = urls[record_name] print("Downloading {}".format(url)) result = subprocess.run(["wget", url, "-O", record_name]) return result.returncode == 0 if __name__ == "__main__": urls = build_urls() name_desc = "record name. Available records: {}".format( ", ".join(u for u in urls)) parser = argparse.ArgumentParser( description="A script for downloading Apollo demo records") parser.add_argument( "name", type=str, help=name_desc) args = parser.parse_args() requested_record = args.name success = download_record(requested_record, urls) if success: print("Successfully downloaded {}".format(requested_record)) else: print("Bad luck, failed to download {}".format(requested_record))
0
apollo_public_repos/apollo/docs/02_Quick Start
apollo_public_repos/apollo/docs/02_Quick Start/demo_guide/README.md
# Run Simulation with Offline Record This document provides a step-by-step guide on how to run simulation with a demo offline record, in case you don't have the required hardware. ## Preparation Work Suppose you have followed the [Apollo Software Installation Guide](../../01_Installation%20Instructions/apollo_software_installation_guide.md). You have cloned Apollo's GitHub repo, all the software pre-requisites were installed correctly. ## Start and enter Apollo development Docker container The following commands are assumed to run from `$APOLLO_ROOT_DIR`. ``` bash docker/scripts/dev_start.sh bash docker/scripts/dev_into.sh ``` ## Build Apollo Run the following command to build Apollo inside Docker: ``` ./apollo.sh build ``` Note: > The script will auto-detect whether it was a CPU only build or a GPU build. ## Start Dreamview To start the Monitor module and Dreamview backend, run: ``` bash scripts/bootstrap.sh ``` ## Download and play the demo record ``` python3 docs/demo_guide/record_helper.py demo_3.5.record cyber_recorder play -f demo_3.5.record --loop ``` Note: > The `--loop` option enables record to keep playing in a loop playback mode. ## Open <http://127.0.0.1:8888> in your favorite browser (e.g. Chrome) to access Apollo Dreamview The following screen should be shown to you and the car in Dreamview now moves around! ![](images/dv_trajectory.png) Congratulations!
0
apollo_public_repos/apollo/docs/02_Quick Start
apollo_public_repos/apollo/docs/02_Quick Start/demo_guide/README_cn.md
# 运行线下演示 如果您没有车辆及车载硬件,Apollo 提供了用于演示和调试代码的模拟环境。 ## 准备工作 假设您已经按照 [Apollo 软件安装指南](../../01_Installation%20Instructions/apollo_software_installation_guide.md) 的说明准备搭建好 Apollo 的运行环境。即,您已经克隆了 Apollo 在 GitHub 上的 代码库,并安装了所有必需的软件。 下面是 Apollo 演示的设置步骤: ## 启动并进入 Apollo Docker 环境 ``` bash docker/scripts/dev_start.sh bash docker/scripts/dev_into.sh ``` ## 在 Docker 中编译 Apollo: ``` bash apollo.sh build ``` 备注: > 上述命令会通过检测 GPU 环境是否就绪来自动判断是执行 CPU 构建还是 GPU 构建。 ## 启动 Dreamview ``` bash scripts/bootstrap.sh ``` ## 下载并播放 Apollo 的演示包 ``` python docs/demo_guide/record_helper.py demo_3.5.record cyber_recorder play -f docs/demo_guide/demo_3.5.record --loop ``` 选项 `--loop` 用于设置循环回放模式. ## 在浏览器中输入 <http://localhost:8888> 访问 Apollo Dreamview 如下图所示: ![](images/dv_trajectory.png) 如果一切正常,现在您应该能看到一辆汽 车在模拟器里移动。 恭喜您完成了 Apollo 的演示步骤!
0
apollo_public_repos/apollo/docs/02_Quick Start/demo_guide
apollo_public_repos/apollo/docs/02_Quick Start/demo_guide/images/README.md
![](docs/02_Quick%20Start/demo_guide/images/Apollo_logo.png) [![Build Status](http://180.76.142.62:8111/app/rest/builds/buildType:Apollo_Build/statusIcon)](http://180.76.142.62:8111/viewType.html?buildTypeId=Apollo_Build&guest=1) [![Simulation Status](https://azure.apollo.auto/dailybuildstatus.svg)](https://azure.apollo.auto/daily-build/public) ``` We choose to go to the moon in this decade and do the other things, not because they are easy, but because they are hard. -- John F. Kennedy, 1962 ``` Welcome to Apollo's GitHub page! [Apollo](http://apollo.auto) is a high performance, flexible architecture which accelerates the development, testing, and deployment of Autonomous Vehicles. For business and partnership, please visit [our website](http://apollo.auto). ## Table of Contents 1. [Introduction](#introduction) 2. [Prerequisites](#prerequisites) 3. [Individual Versions](#individual-versions) 4. [Architecture](#architecture) 5. [Installation](#installation) 6. [Quick Starts](#quick-starts) 7. [Documents](#documents) ## Introduction Apollo is loaded with new modules and features but needs to be calibrated and configured perfectly before you take it for a spin. Please review the prerequisites and installation steps in detail to ensure that you are well equipped to build and launch Apollo. You could also check out Apollo's architecture overview for a greater understanding of Apollo's core technology and platforms. ## Prerequisites **[New 2021-01]** The Apollo platform (stable version) is now upgraded with software packages and library dependencies of newer versions including: 1. CUDA upgraded to version 11.1 to support Nvidia Ampere (30x0 series) GPUs, with NVIDIA driver >= 455.32 2. LibTorch (both CPU and GPU version) bumped to version 1.7.0 accordingly. We do not expect a disruption to your current work, but to ease your life of migratation, you would need to: 1. Update NVIDIA driver on your host to version >= 455.32. ([Web link](https://www.nvidia.com/Download/index.aspx?lang=en-us)) 2. Pull latest code and run the following commands after restarting and logging into Apollo Development container: ```bash # Remove Bazel output of previous builds rm -rf /apollo/.cache/{bazel,build,repos} # Re-configure bazelrc. ./apollo.sh config --noninteractive ``` --- * The vehicle equipped with the by-wire system, including but not limited to brake-by-wire, steering-by-wire, throttle-by-wire and shift-by-wire (Apollo is currently tested on Lincoln MKZ) * A machine with a 8-core processor and 16GB memory minimum * NVIDIA Turing GPU is strongly recommended * Ubuntu 18.04 * NVIDIA driver version 455.32.00 and above ([Web link](https://www.nvidia.com/Download/index.aspx?lang=en-us)) * Docker-CE version 19.03 and above ([Official doc](https://docs.docker.com/engine/install/ubuntu/)) * NVIDIA Container Toolkit ([Official doc](https://github.com/NVIDIA/nvidia-docker)) **Please note**, it is recommended that you install the versions of Apollo in the following order: **1.0 -> whichever version you would like to test out**. The reason behind this recommendation is that you need to confirm whether individual hardware components and modules are functioning correctly, and clear various version test cases before progressing to a higher and more capable version for your safety and the safety of those around you. ## Individual Versions: The following diagram highlights the scope and features of each Apollo release: ![](docs/02_Quick%20Start/demo_guide/images/Apollo_Roadmap_6_0.png) [**Apollo 1.0:**](docs/Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_1_0_hardware_system_installation_guide.md) Apollo 1.0, also referred to as the Automatic GPS Waypoint Following, works in an enclosed venue such as a test track or parking lot. This installation is necessary to ensure that Apollo works perfectly with your vehicle. The diagram below lists the various modules in Apollo 1.0. ![](docs/02_Quick%20Start/demo_guide/images/Apollo_1.png) [**Apollo 1.5:**](docs/Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_1_5_hardware_system_installation_guide.md) Apollo 1.5 is meant for fixed lane cruising. With the addition of LiDAR, vehicles with this version now have better perception of its surroundings and can better map its current position and plan its trajectory for safer maneuvering on its lane. Please note, the modules highlighted in Yellow are additions or upgrades for version 1.5. ![](docs/02_Quick%20Start/demo_guide/images/Apollo_1_5.png) [**Apollo 2.0:**](docs/Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_2_0_hardware_system_installation_guide_v1.md#key-hardware-components) Apollo 2.0 supports vehicles autonomously driving on simple urban roads. Vehicles are able to cruise on roads safely, avoid collisions with obstacles, stop at traffic lights, and change lanes if needed to reach their destination. Please note, the modules highlighted in Red are additions or upgrades for version 2.0. ![](docs/demo_guide/images/Apollo_2.png) [**Apollo 2.5:**](docs/quickstart/apollo_2_5_hardware_system_installation_guide_v1.md) Apollo 2.5 allows the vehicle to autonomously run on geo-fenced highways with a camera for obstacle detection. Vehicles are able to maintain lane control, cruise and avoid collisions with vehicles ahead of them. ``` Please note, if you need to test Apollo 2.5; for safety purposes, please seek the help of the Apollo Engineering team. Your safety is our #1 priority, and we want to ensure Apollo 2.5 was integrated correctly with your vehicle before you hit the road. ``` ![](docs/demo_guide/images/Apollo_2_5.png) [**Apollo 3.0:**](docs/quickstart/apollo_3_0_quick_start.md) Apollo 3.0's primary focus is to provide a platform for developers to build upon in a closed venue low-speed environment. Vehicles are able to maintain lane control, cruise and avoid collisions with vehicles ahead of them. ![](docs/demo_guide/images/Apollo_3.0_diagram.png) [**Apollo 3.5:**](docs/quickstart/apollo_3_5_quick_start.md) Apollo 3.5 is capable of navigating through complex driving scenarios such as residential and downtown areas. The car now has 360-degree visibility, along with upgraded perception algorithms to handle the changing conditions of urban roads, making the car more secure and aware. Scenario-based planning can navigate through complex scenarios, including unprotected turns and narrow streets often found in residential areas and roads with stop signs. ![](docs/demo_guide/images/Apollo_3_5_Architecture.png) [**Apollo 5.0:**](docs/quickstart/apollo_3_5_quick_start.md) Apollo 5.0 is an effort to support volume production for Geo-Fenced Autonomous Driving. The car now has 360-degree visibility, along with upgraded perception deep learning model to handle the changing conditions of complex road scenarios, making the car more secure and aware. Scenario-based planning has been enhanced to support additional scenarios like pull over and crossing bare intersections. ![](docs/demo_guide/images/Apollo_5_0_diagram1.png) [**Apollo 5.5:**](docs/quickstart/apollo_5_5_quick_start.md) Apollo 5.5 enhances the complex urban road autonomous driving capabilities of previous Apollo releases, by introducing curb-to-curb driving support. With this new addition, Apollo is now a leap closer to fully autonomous urban road driving. The car has complete 360-degree visibility, along with upgraded perception deep learning model and a brand new prediction model to handle the changing conditions of complex road and junction scenarios, making the car more secure and aware. ![](docs/demo_guide/images/Apollo_5_5_Architecture.png) [**Apollo 6.0:**](docs/quickstart/apollo_6_0_quick_start.md) Apollo 6.0 incorporates new deep learning models to enhance the capabilities for certain Apollo modules. This version works seamlessly with new additions of data pipeline services to better serve Apollo developers. Apollo 6.0 is also the first version to integrate certain features as a demonstration of our continuous exploration and experimentation efforts towards driverless technology. ![](docs/demo_guide/images/Apollo_6_0.png) **Apollo 7.0:** Apollo 7.0 incorporates 3 brand new deep learning models to enhance the capabilities for Apollo Perception and Prediction modules. Apollo Studio is introduced in this version, combining with Data Pipeline, to provide a one-stop online development platform to better serve Apollo developers. Apollo 7.0 also publishes the PnC reinforcement learning model training and simulation evaluation service based on previous simulation service. ![](docs/demo_guide/images/Apollo_7_0.png) ## Architecture * **Hardware/ Vehicle Overview** ![](docs/demo_guide/images/Hardware_overview_3_5.png) * **Hardware Connection Overview** ![](docs/demo_guide/images/Hardware_connection_3_5_1.png) * **Software Overview** ![](docs/demo_guide/images/Apollo_3_5_software_architecture.png) ## Installation * [Hardware installation guide](docs/quickstart/apollo_3_5_hardware_system_installation_guide.md) * [Software installation guide](docs/quickstart/apollo_software_installation_guide.md) - **This step is required** * [Launch and run Apollo](docs/howto/how_to_launch_and_run_apollo.md) Congratulations! You have successfully built out Apollo without Hardware. If you do have a vehicle and hardware setup for a particular version, please pick the Quickstart guide most relevant to your setup: ## Quick Starts: * [Apollo 6.0 QuickStart Guide](docs/quickstart/apollo_6_0_quick_start.md) * [Apollo 5.5 QuickStart Guide](docs/quickstart/apollo_5_5_quick_start.md) * [Apollo 5.0 QuickStart Guide](docs/quickstart/apollo_5_0_quick_start.md) * [Apollo 3.5 QuickStart Guide](docs/quickstart/apollo_3_5_quick_start.md) * [Apollo 3.0 QuickStart Guide](docs/quickstart/apollo_3_0_quick_start.md) * [Apollo 2.5 QuickStart Guide](docs/quickstart/apollo_2_5_quick_start.md) * [Apollo 2.0 QuickStart Guide](docs/quickstart/apollo_2_0_quick_start.md) * [Apollo 1.5 QuickStart Guide](docs/quickstart/apollo_1_5_quick_start.md) * [Apollo 1.0 QuickStart Guide](docs/quickstart/apollo_1_0_quick_start.md) ## Documents * [Technical Tutorials](docs/technical_tutorial/README.md): Everything you need to know about Apollo. Written as individual versions with links to every document related to that version. * [How-To Guides](docs/howto/README.md): Brief technical solutions to common problems that developers face during the installation and use of the Apollo platform * [Specs](docs/specs/README.md): A Deep dive into Apollo's Hardware and Software specifications (only recommended for expert level developers that have successfully installed and launched Apollo) * [FAQs](docs/15_FAQS/README.md) ## Questions You are welcome to submit questions and bug reports as [GitHub Issues](https://github.com/ApolloAuto/apollo/issues). ## Copyright and License Apollo is provided under the [Apache-2.0 license](https://github.com/ApolloAuto/apollo/blob/master/LICENSE). ## Disclaimer Apollo open source platform only has the source code for models, algorithms and processes, which will be integrated with cybersecurity defense strategy in the deployment for commercialization and productization. Please refer to the Disclaimer of Apollo in [Apollo's official website](http://apollo.auto/docs/disclaimer.html). ## Connect with us * [Have suggestions for our GitHub page?](https://github.com/ApolloAuto/apollo/issues) * [Twitter](https://twitter.com/apolloplatform) * [YouTube](https://www.youtube.com/channel/UC8wR_NX_NShUTSSqIaEUY9Q) * [Blog](https://www.medium.com/apollo-auto) * [Newsletter](http://eepurl.com/c-mLSz) * Interested in our turnKey solutions or partnering with us Mail us at: apollopartner@baidu.com
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/03_Package Management/apollo_buildtool.md
# Apollo buildtool ## Summary Apollo buildtool is a command line tool, providing functions such as compiling, testing, installing or running Apollo modules. Based on buildtool, not only can you easily install the binary packages of each module in Apollo, but you can also perform secondary development, compilation, and testing on these source code without downloading the whole Apollo. buildtool allows developers to only focus on the modules that need to be developed to improve overall development efficiency. ## Installation buildtool currently only supports running in the Apollo container environment. If you haven't started the container, you can use apollo enviromnent tool: **aem** to start or enter an Apollo container environment. Or you can also use the traditional way: Apollo scripts setup. The Apollo container environment has pre-installed Apollo core and Apollo buildtool. When you enter the container, you can enter the following command to check whether buildtool has been installed correctly: ```shell buildtool -h ``` If all goes well, you will see a prompt similar to the image below: ```shell usage: buildtool [-h] {pack,build,test,init,install,bootstrap,info,reinstall,clean,create} ... build tools of apollo positional arguments: {pack,build,test,init,install,bootstrap,info,reinstall,clean,create} sub-command pack verify the packaging process build build module test perform the unit test init init a single workspace with cyber example component install install specific package bootstrap start or stop module info list package depends infomation based on a specific compilation parameter reinstall reinstall specific package clean clean build cache and build tool generated files create create specific package optional arguments: -h, --help show this help message and exit ``` ## buildtool action The buildtool action is a single entry point for all the functions provided by buildtool. The invocation of the buildtool action follows the following form: ```shell buildtool <action> [action arguments or options] ``` The different functions of buildtool are organized into different action, similar to common command-line tools such as git or apt. Action covers all functions of buildtool, such as **build** responsible for compiling, **install** responsible for installation, and **clean** responsible for cleaning up compilation cache, etc. Some parameters may be required after the action, you can enter -h, --help after the action to view the detailed parameters. ## builtin buildtool action * build - compile the source code in the Apollo workspace * test - perform the unit test for each package in the Apollo workspace * install - install the source code of a package to Apollo workspace * clean - clear the compilation cache of the Apollo workspace * init - creates a simple Apollo workspace * info - view the dependency information of the specified package * bootstrap - bootstrap Apollo specific modules * reinstall - reinstall the specific package * create - initialize a user-defined package The specific usage of each action will be introduced in detail next. ### build The build action compiles the source code of one or more software packages in the workspace, and build can only be executed in the root directory of the workspace. The build action will throw an error if executed outside the workspace or in a non-root directory within the workspace. #### Basic usage ##### Compile the source code of all packages under the workspace ```shell buildtool build ``` When there is no parameter, buildtool will compile all source codes in the workspace. During compilation, buildtool will automatically create dev, modules, third_party, tools folders to save compilation information. ##### Compile the source code of the package in a specified folder under the workspace When receiving the -p or --packages parameter, buildtool can compile the source code in a specified folder separately: ```shell $ mkdir demo && cd demo $ buildtool init $ tree |-- WORKSPACE `-- example_components |-- BUILD |-- cyberfile.xml |-- example-components.BUILD |-- example.dag |-- example.launch |-- proto | |-- BUILD | `-- examples.proto `-- src |-- BUILD |-- common_component_example.cc |-- common_component_example.h |-- timer_common_component_example.cc `-- timer_common_component_example.h $ buildtool build --packages example_components ``` The above command compiles the source code in example_components. If everything gone well, you will see the following prompt: ```shell [buildtool] INFO PostProcess example-components-dev [buildtool] INFO Done, Enjoy! [buildtool] INFO apollo build tool exit. ``` #### Advanced usage ##### Specify gpu compilation ```shell $ buildtool build --gpu ``` ##### Pass compilation parameters to bazel ```shell $ buildtool build --arguments "--linkopts=-lz4" ``` ##### Clear the previous compilation cache and compile ```shell $ buildtool build --expunge ``` ##### Specify the number of compilation threads and the percentage of memory used ```shell $ buildtool build --jobs 2 --memories 0.5 ``` ##### detailed parameters ```shell usage: buildtool build [-h] [-p [* [* ...]]] [-a [* [* ...]]] [--gpu] [--cpu] [--dbg] [--opt] [--prof] [--teleop] [--expunge] [-j JOBS] [-m MEMORIES] optional arguments: -h, --help show this help message and exit -p [* [* ...]], --packages [* [* ...]] Specify the package path. -a [* [* ...]], --arguments [* [* ...]] Pass arguments to the build system. --gpu Run build in GPU mode --cpu Run build in cpu mode --dbg Build with debugging enabled --opt Build with optimization enabled --prof Build with profiler enabled --teleop Run build with teleop enabled --expunge Expunge the building cache before build -j JOBS, --jobs JOBS Specifies the number of threads to compile in parallel -m MEMORIES, --memories MEMORIES Specifies the percentage of memory used by compilation ``` ### test The test action performs unit testing for the source code of the workspace, and actually executes all cc_test defined in the source code BUILD file. #### Basic usage Perform the unit-test of module: ```shell $ buildtool init $ buildtool install planning-dev $ buildtool test --package_paths modules/planning ``` The above operation buildtool will download the planning module, copy the source code of the planning module to the workspace, and finally compile and test it. ##### Specify gpu mode to compile and test ```shell $ buildtool test --gpu --package_paths modules/planning ``` ##### Pass the parameters to bazel ```shell $ buildtool test --arguments "--linkopts=-llz4" --package_paths modules/planning ``` ##### detailed parameters ```shell usage: buildtool test [-h] [-p [* [* ...]]] [--gpu] [--cpu] [--arguments [* [* ...]]] optional arguments: -h, --help show this help message and exit -p [* [* ...]], --package_paths [* [* ...]] Specify the package path. --gpu Run build in gpu mode" --cpu Run build in cpu mode" --arguments [* [* ...]] Pass arguments to the build system. ``` ### install This action installs the source code of a specified module into the workspace. #### usage ```shell $ buildtool init $ buildtool install planning-dev ``` The above operation buildtool will download the planning module, copy the source code of the planning module to the workspace. ```shell $ buildtool init $ buildtool install --legacy planning-dev ``` The above operation buildtool will only download the planning module, and will not copy the source code to workspace. ##### detailed parameters ```shell usage: buildtool install [-h] [--legacy] [packages [packages ...]] positional arguments: packages Install the packages optional arguments: -h, --help show this help message and exit --legacy legacy way to install package ``` ### clean This action is used to clear the compilation cache and output from the workspace source code. #### usage The clean action clears all compilation caches of the workspace when it does not accept any parameters, which is equivalent to executing bazel clean --expunge ```shell $ buildtool clean ``` The packages_path parameter can specify to delete the compiled output of the module source code under the corresponding path: ```shell $ buildtool clean --packages_path modules/planning ``` The above operation will delete the compilation output of the planning module. The expunge parameter will delete the compiled output of all module source codes on the machine: ```shell $ buildtool clean --expunge ``` ##### detailed parameters ```shell usage: buildtool clean [-h] [--packages_path [* [* ...]]] [--expunge] optional arguments: -h, --help show this help message and exit --packages_path [* [* ...]] clean specified module build production. --expunge clean the build cache including production ``` ### init This action is used to initialize a single workspace. #### usage The init action creates a basic workspace in the current directory when it accepts no arguments: ```shell buildtool init ``` Of course, you can also bring example_component in the workspace. ```shell buildtool init -w ``` The path parameter can specify the creation path in the workspace: ```shell $ buildtool init --path ~/demo ``` ##### detailed parameters ```shell usage: buildtool init [-h] [-p PATH] [-w] optional arguments: -h, --help show this help message and exit -p PATH, --path PATH specify workspace path -w, --with-examples init workspace with example component and lib ``` ### info This action is used to list the dependencies of the specified package. #### usage List the direct dependencies of the requested package: ```shell $ buildtool info planning-dev [buildtool] INFO Reconfigure apollo enviroment setup [buildtool] INFO Compile parameters: [buildtool] INFO using gpu: False [buildtool] INFO using debug mode: False [buildtool] INFO According parameters above to analysis depends of planning-dev [buildtool] INFO Analyzing dependencies topological graph... [buildtool] INFO planning-dev directly depends on the following packages: [buildtool] INFO (3rd-gflags-dev|1.0.0.1), (3rd-absl-dev|1.0.0.1), (3rd-osqp-dev|1.0.0.1), (3rd-glog-dev|1.0.0.1) [buildtool] INFO (3rd-proj-dev|1.0.0.1), (libtinyxml2-dev|None), (3rd-boost-dev|1.0.0.1), (3rd-opencv-dev|1.0.0.1) [buildtool] INFO (3rd-ipopt-dev|1.0.0.1), (3rd-eigen3-dev|1.0.0.1), (libadolc-dev|None), (3rd-ad-rss-lib-dev|1.0.0.1) [buildtool] INFO (cyber-dev|1.0.0.1), (common-dev|1.0.0.1), (map-dev|1.0.0.2), (common-msgs-dev|1.0.0.1) [buildtool] INFO (bazel-extend-tools-dev|1.0.0.1), (3rd-mkl-dev|1.0.0.1), (3rd-libtorch-cpu-dev|1.0.0.1), (3rd-protobuf-dev|1.0.0.1) [buildtool] INFO (3rd-rules-python-dev|1.0.0.1), (3rd-grpc-dev|1.0.0.1), (3rd-bazel-skylib-dev|1.0.0.1), (3rd-rules-proto-dev|1.0.0.1) [buildtool] INFO (3rd-py-dev|1.0.0.1), (3rd-gpus-dev|1.0.0.1), (3rd-gtest-dev|1.0.0.1) [buildtool] INFO Done, Enjoy! [buildtool] INFO apollo build tool exit. ``` List all dependencies of the requested package: ```shell $ buildtool info --with-indirect planning-dev [buildtool] INFO Reconfigure apollo enviroment setup [buildtool] INFO Compile parameters: [buildtool] INFO using gpu: False [buildtool] INFO using debug mode: False [buildtool] INFO According parameters above to analysis depends of planning-dev [buildtool] INFO Analyzing dependencies topological graph... [buildtool] INFO planning-dev depends on these following packages: [buildtool] INFO (3rd-gflags-dev|1.0.0.1), (3rd-absl-dev|1.0.0.1), (3rd-osqp-dev|1.0.0.1), (3rd-glog-dev|1.0.0.1) [buildtool] INFO (3rd-proj-dev|1.0.0.1), (libtinyxml2-dev|None), (3rd-boost-dev|1.0.0.1), (3rd-opencv-dev|1.0.0.1) [buildtool] INFO (3rd-ipopt-dev|1.0.0.1), (3rd-eigen3-dev|1.0.0.1), (libadolc-dev|None), (3rd-ad-rss-lib-dev|1.0.0.1) [buildtool] INFO (cyber-dev|1.0.0.1), (libncurses5-dev|None), (libuuid1|None), (3rd-rules-python-dev|1.0.0.1) [buildtool] INFO (3rd-grpc-dev|1.0.0.1), (3rd-rules-proto-dev|1.0.0.1), (3rd-py-dev|1.0.0.1), (3rd-bazel-skylib-dev|1.0.0.1) [buildtool] INFO (3rd-protobuf-dev|1.0.0.1), (3rd-fastrtps-dev|1.0.0.1), (common-msgs-dev|1.0.0.1), (bazel-extend-tools-dev|1.0.0.1) [buildtool] INFO (common-dev|1.0.0.1), (libsqlite3-dev|None), (3rd-gtest-dev|1.0.0.1), (3rd-nlohmann-json-dev|1.0.0.1) [buildtool] INFO (map-dev|1.0.0.2), (3rd-mkl-dev|1.0.0.1), (3rd-libtorch-cpu-dev|1.0.0.1), (3rd-gpus-dev|1.0.0.1) [buildtool] INFO Done, Enjoy! [buildtool] INFO apollo build tool exit. ``` List the dependency information of the package source code in the specified path: ```shell $ buildtool info --directory example_components/ [buildtool] INFO Reconfigure apollo enviroment setup [buildtool] INFO Compile parameters: [buildtool] INFO using gpu: False [buildtool] INFO using debug mode: False [buildtool] INFO According parameters above to analysis depends of example-components-dev [buildtool] INFO Analyzing dependencies topological graph... [buildtool] INFO example-components-dev directly depends on the following packages: [buildtool] INFO (cyber-dev|1.0.0.1), (bazel-extend-tools-dev|1.0.0.1), (3rd-protobuf-dev|1.0.0.1) [buildtool] INFO Done, Enjoy! [buildtool] INFO apollo build tool exit. ``` ##### detailed parameters ```shell usage: buildtool info [-h] [--depends-on] [--with-indirect] [--directory] [--gpu] [--cpu] [--dbg] [query] positional arguments: [query] the package name or stored path of which package's depends you want to list optional arguments: -h, --help show this help message and exit --depends-on list those packages information which are directly dependent on the package --with-indirect list the package all depends, direct and indirect --directory list the package infomation which stored in the directory --gpu with compilation in GPU parameter --cpu with compilation in CPU parameter --dbg with compilation in debugging parameter ``` ### bootstrap bootstrap is used to boot the latest version of a specific package. The latest version refers to the version corresponding to the last operation of the software package. If the last operation of the package is compilation, then bootstrap will start the output of the compiled package. If the last operation of the package is installation or reinstallation, for example, if you execute a command such as sudo apt install --reinstall, then bootstrap will start the binary file or dynamic link library of the installed or reinstalled package. > Note: Currently, the modules that bootstrap can start are: dreamview-dev, monitor-dev. #### usage ##### boot dreamview: ```shell buildtool bootstrap start dreamview-dev ``` ##### stop dreamview: ```shell buildtool bootstrap stop dreamview-dev ``` ##### detailed parameters ```shell usage: buildtool bootstrap [-h]{start,stop}... positional arguments: {start,stop} options start start module stop stop module optional arguments: -h, --help show this help message and exit ``` ### reinstall This action is used to reinstall the package, which is equivalent to executing apt install --reinstall. ##### detailed parameters ```shell usage: buildtool reinstall [-h] [packages [packages ...]] positional arguments: packages Reinstall the packages optional arguments: -h, --help show this help message and exit ``` ### create This action is used to initialize the cyberfile of the user defined package. ##### detailed parameters ```shell usage: buildtool create [-h] [--name NAME] --type {src,binary,wrapper} [--author AUTHOR] [--email EMAIL] package_path positional arguments: package_path specify the path of this package needed to create optional arguments: -h, --help show this help message and exit --name NAME specify the name of this package --type {src,binary,wrapper} specify the type of this package --author AUTHOR specify this 3rd package author --email EMAIL specify the contacted email ``` ### pack This action is used to pack deb file for a package from building output. #### usage ```shell $ buildtool pack -d package.json ``` among them, package.json is releasing description file, you can refer to "Introduction to package of Apollo" to see the detailed example.
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/03_Package Management/introduction_to_package_of_apollo.md
# Introduction to package of Apollo ## Overview This article briefly introduces how to develop an Apollo extension module, with a simple example of how to create the project code of an extension module and the role of the necessary files contained in it. It alos explains how to use the buildtool to compile the extension module. To read this article you need a preliminary grasp of - How to use Bazel to build C++ projects https://docs.bazel.build/versions/5.1.0/tutorial/cpp.html - Introduction to using Apollo buildtool ## Broad concept of package The package is not just a .deb file in a broad sense, but contains a variety of forms throughout the cycle, from code to dependencies. The package can be divided into 5 types: source, local compilation, packaging, remote, and local installation. |Forms |Role |Generation method/Time |Storage Location |Usage |Remarks | |:-|:-|:-|:-|:-|:-| |source |Create the source code files for the package |Developed by developers |git code repository |Ordinary source code files containing some of the file contents necessary for the specification | | |local compilation |Compile and generated content ready for packaging and distribution |Compile and install |local repository (located in /opt/apollo/neo/packages) |Generated by local code compiled in the local environment, containing local modifications |Can also be used as a dependency, component | |packaging |Make a .deb package ready for release |Packing Production |Generally in the packing tool working directory |The deb package is the same as other deb packages and can be installed using the system's dpkg and other tools. | | |remote |Deb packages published to remote repositories and made available to developers across the network |release |apt source |Download and install via apt (or buildtool) | | |local installation |Packages installed locally using the apt tool, which can be loaded as dependencies or components |apt install or buildtool install |local repository(located in /opt/apollo/neo/packages) |Used as a Cyber component to load, used as a general dynamic library SO, etc. | | ## Module Extensions Module extension is the process of creating new or modifying the code of an existing module and publishing the module. The following figure shows the workflow of module extension: Next, we will introduce the complete workflow of the module extension project and the considerations of each node through the demo project. ### Step 1. Initialize workspace First install Docker and start the Apollo Env container, then use buildtool to initialize a demo project: ```shell buildtool init -w ``` The demo project directory structure is as follows: ```shell . |-- WORKSPACE `-- example_components |-- BUILD |-- cyberfile.xml |-- example-components.BUILD |-- example.dag |-- example.launch |-- proto | |-- BUILD | `-- examples.proto `-- src |-- BUILD |-- common_component_example.cc |-- common_component_example.h |-- timer_common_component_example.cc `-- timer_common_component_example.h ``` The demo project is described in detail next: - src: holds all the source code of the demo project. - proto: holds the proto message format definition of the demo project. - component launch files: example.dag and example.launch, which define how to launch example-component. - BUILD: bazel compilation description file, which will be further described in the compilation description file section. - cyberfile.xml: package description file, similar to package.xml in ros, which will be described in the module description file section. - example-components.BUILD: Through this file, other modules can use the symbols and functions of example-components, which will be further described in the section on dependency description files. - WORKSPACE: Bazel workspace markup file, further described in the section WORKSPACE files and workspaces. ### Step 2. Writing Code #### WORKSPACE files and workspace WORKSPACE i.e. Bazel's workspace, it is a directory, the Demo project directory is a workspace which contains all the files of the extension module (including source files and build output, etc.), which also contains some special files such as WORKSPACE, BUILD, cyberfile.xml, etc. The WORKSPACE file, Bazel's WORKSPACE file, identifies the directory and its contents as a Bazel workspace and is located in the root directory of the project directory structure. The WORKSPACE file can be an empty file, but it can also define space names or download and initialize dependencies. when Bazel builds a project, all inputs and dependencies must be located in the same workspace. Unless linked, files in different workspaces are independent of each other. Apollo buildtool will process the WORKSPACE file, injecting common dependency tools and initializing the dependency packages declared in the cyberfile.xml file (see Appendix: WORKSPACE File Injection for details). #### Source code Writing the source code is the actual module development process. Demo projects already come with example-component source code, so there is no need to write and modify any source code for demo projects. In the actual development, the developer needs to write the code of the module to be developed or develop it based on the existing module source code. For developing modules from scratch, buildtool provides a useful command to initialize the module. ```shell buildtool create --type src $YOU_MODULE_PATH ``` For secondary development scenarios, buildtool provides a useful command to copy the source code into a workspace: ```shell buildtool install planning-dev ``` This command copies the source code of the planning module to the workspace, which is stored in the module/planning folder. > Note: The above command needs to be run under the workspace. #### Compiling description file For bazel, developers need to write BUILD files according to bazel's specifications in order to compile the modules, which can be found in the official bazel tutorial or in the Appendix: BUILD Files and Package Dependencies. In addition to the bazel specification, in order to achieve Apollo package management, the following Apollo specifications should be followed when writing BUILD files. - Add two additional Apollo custom rules: install, install_src_files to the BUILD file in the root directory of the module (For example, the root directory of the planning module is modules/planning) install and install_src are two extension rules that serve to install build output into the local repository of Apollo packages (i.e. /opt/apollo/neo/packages directory). install rule installs build output into the local repository, while install_src rule installs the source code to the local repository, and the installation result supports preserving the source code directory structure. These two rules mainly serve the package approach to use Apollo. Using buildtool to compile must define these two extended rules in the BUILD file at the top level of the module, otherwise the compilation will fail. Use as shown in the demo: ```bazel install( name = "install", data = [ "//example_components/proto:examples_cc_proto", ":cyberfile.xml" ], data_dest = "example-components", library_dest = "example-components/lib", library_strip_prefix = ["src", "proto"], targets = [ "//example_components/src:libcomponent_examples.so", "//example_components/proto:examples_cc_proto" ], deps = [ ":pb_headers", ":dag", ":launch" ] ) install_src_files( name = "install_src", src_dir = ["."], dest = "example-components/src", filter = "*", deps = [ ":headers" ] ) ``` - install - data: install as data file - data_dest: the installation directory of the data file, the installation directory is /opt/apollo/neo/package/ relative directory, and the installation directory (xxx_dest) should be set to be the same as the package name. data_dest in the demo is set to example-components, which is the same as the package name. In demo example, data is directly installed in the package directory. - library_dest: the installation directory of dynamic library files (*.so), same as data_dest specification. library_dest in the demo is set to example-components/lib. In demo example, .so files are installed in the lib directory of the package. - targets: the list of installed target files. - deps: other targets that the rule depends on. - install_src_files - src_dir: the directory where the target source code is installed. - dest: the location of the source code installation, again, the installation directory should be set to the src directory under the package name directory (header files should be set to the include directory of the package directory). For example, the demo is set to example-components/src. - filter: filtering target files by file name, "*" means all files. - deps: other targets that the rule depends on. Note: The first-level directory of the above dest-related properties should be consistent with the name in cyberfile.xml. For example, the name in cyberfile.xml in the demo project is example-components, so the install and install_src_files rules in the dest related properties in the install and install_src_files rule have example-components as the first level directory. Failure to follow this rule can lead to problems with the module not being imported as a dependency. - When the output of a module is a dynamic library that needs to be loaded dynamically, additional options need to be added to the native cc_library and cc_binary rules. A component is a dynamic library loaded by Apollo middleware cyber-rt, e.g., perception, location, etc. Developers who want to extend new functionality based on their own scenario generally create a new component. The main content of the component is the compiled output dynamic library SO file, and is different from the dependency library SO files, so they are generally not used as compiled dependencies by other modules/packages. To successfully build a component into a package the following items need to be noted when writing the BUILD file: ```bazel cc_binary( name = "libcomponent_examples.so", linkshared = True, linkstatic = True, deps = [ ":timer_common_component_example_lib", ":common_component_example_lib" ], ) cc_library( name = "timer_common_component_example_lib", srcs = ["timer_common_component_example.cc"], hdrs = ["timer_common_component_example.h"], visibility = ["//visibility:private"], alwayslink = True, deps = [ "//cyber", "//example_components/proto:examples_cc_proto", ], ) ``` - Use cc_binary to compile dynamic libraries, and the name should be in the format of libxxxxx.so, i.e. starting with lib and ending with .so. - The linkshared and linksstatic attributes are set to True. - If the dependent target is compiled by cc_library, then alwayslink must be set to True. - When there is a specific part of the module that needs to be depended on by other modules (i.e. the module is used as a dependency library), the BUILD file needs to be written according to a specific specification. Dependency libraries are packages that will be depended on by other modules/packages when they are compiled. Under the Bazel compilation system, cc_library is generally used to write targets for other rules to use as dependencies, while Apollo packages need to make these dependencies into packages for distribution. Bazel's cc_library rules cannot meet the demand by default, so it needs to be combined with cc_binary rules and the necessary attribution to make a complete SO library. Take cyber_core as an example: ```bazel cc_binary( name = "libcyber_core.so", srcs = glob([ "cyber.cc", "cyber.h", ]), linkshared = True, linkstatic = True, linkopts = ["-lrt"], deps = [ "//cyber:binary", "//cyber:init", ... ], visibility = ["//visibility:public"], ) cc_library( name = "cyber_core", srcs = ["libcyber_core.so"], hdrs = ["cyber.h"], linkopts = ["-lrt"], visibility = ["//visibility:public"], deps = [ "@com_github_google_glog//:glog", "@com_google_protobuf//:protobuf", "@fastrtps", "@com_github_gflags_gflags//:gflags", "//cyber/proto:run_mode_conf_cc_proto", ... ], includes = ["."], ) ``` - First write a dynamic SO library using cc_binary with reference to the configuration of the component SO. Pay attention to the name and linkshared, linkstatic properties settings. - Then use cc_library to "wrap" the SO - The srcs property is set to the target of the previous cc_binary, i.e. libcyber_core.so. - hdrs contains the header files that need to be exposed to other modules. - includes is also recommended to contain the headers that need to be exposed to other modules. - deps contains the secondary dependencies to be passed. The BUILD file of the demo project follows the above Apollo specification, and developers can refer to the BUILD file of the demo project. #### Module description file cyberfile.xml is a module description file used to describe the information related to a module made into a package, such as package name, version number, dependent packages, etc. cyberfile.xml is located in the root directory of the module in the workspace. The directory containing the cyberfile.xml file is the source form of a package (as shown in the demo source structure above), and its subdirectories are not allowed to have cyberfile.xml files, i.e. packages do not support nesting. After compilation and installation, the package is installed in the local repository (i.e. /opt/apollo/neo/packages directory) and becomes a local installation, see Local repository and package installation form for details. The package directory must have a BUILD file in addition to the required cyberfile.xml file (i.e., the directory is also a Bazel module). The writing of the dependency information needs to be focused on, such as the cyberfile.xml shown in the demo. ```xml <package> <name>example-components</name> <version>1.0.0.0</version> <description> example component </description> <maintainer email="apollo-support@baidu.com">apollo-support</maintainer> <type>module</type> <src_path>//example_components</src_path> <license>BSD</license> <author>Apollo</author> <depend type="binary" src_path="//cyber" repo_name="cyber">cyber-dev</depend> <depend>bazel-extend-tools-dev</depend> <depend lib_names="protobuf" repo_name="com_google_protobuf">3rd-protobuf-dev</depend> <depend expose="False" condition="gpu">3rd-gpus-dev</depend> <builder>bazel</builder> </package> ``` - name: the name of the package, Apollo global unique, if you need to publish the package to the official web, it is better to add a specific identifier to prevent conflicts when naming. - version: package version number, strictly follow Ubuntu package naming convention: <1><2>-<3><4>.deb. - <1>Package Name: omitted, use the name field to take the value directly. - <2>Version Number: three numbers separated by dots are recommended, such as 1.0.1. - <3>Build Number: one number is recommended, such as 1. - <4>Architecture: omitted, need to be configured when releasing the package. - src_path: the location of the module source code in the workspace. - depend: dependency package information, i.e. the name of the declared dependency package, e.g. cyber-dev. Because of the type of dependency package and how it is used, this field also supports the configuration of the following attributes. - type: the way the module is introduced, binary means using a compiled binary dependency from the package, src means using a binary dependency compiled from the workspace source code. - src_path: the path where the source code of the dependency is stored in the workspace, usually no need to specify. - repo_name: generally the package name, some third-party packages may have a specific name. - lib_names: the name in the cc_library of the dependency xxx.BUILD file. - expose: whether to expose the dependency to the rest of the modules as a secondary dependency. - condition: the dependency is used only when compiled under certain conditions. The attributes in the depend tag above are more complex. Each package released on the apollo website has a default value for the depend attribute, so you don't need to modify it, you can just use it. - builder: the compilation system type, currently supports bazel. #### Dependency Description File xxx.BUILD file is not needed in the scenario of a new extension of a component, it is only needed when making dependent packages (i.e. packages that can be used as dependencies for other modules), such as the cyber package. So its main role is to be introduced as a dependency to other modules to form the description file of Bazel's dependency. Take cyber.BUILD as an example: ```bazel load("@rules_cc//cc:defs.bzl", "cc_library")  cc_library( name = "cyber", includes = ["include"], hdrs = glob(["include/**/*"]), srcs = glob(["lib/**/lib*.so*"]), include_prefix = "cyber", strip_include_prefix = "include", visibility = ["//visibility:public"], ) ``` Some of the points to note are: - name: lib name. When used as a dependency library, the name needs to be configured on the lib_names attribute in the depend sticky in cyberfile.xml (package name is used by default). Thus this field needs to be updated with great care, which may cause the compilation of the dependent parties to fail. - includes: (system library) header search directory, generally contains "include", that is, the soft package directory of the include directory, install specification requires the installation of header files to the package's include directory. - hdrs: (sandbox environment) the imported of the header files, here imported all the header files under the include folder. - srcs: contains the dynamic library SO files of the package. - include_prefix: configured according to the actual situation. - strip_include_prefix: configured according to the actual situation. in demo, demo include a cyber headers according to: ```shell #include "cyber/component/component.h" ``` while component.h is stored in "include/component/component.h". thus include_prefix is "cyber" while strip_include_prefix is "include". - visibility: must be set to public. ### Step 3. Compilation As you can see above, the Apollo extension project adds support for Apollo package dependencies to the Bazel project specification, so it cannot be compiled directly using the Bazel command (mainly because of the lack of package dependencies), and requires some manual operations or configurations, such as downloading packages, converting packages into Bazel dependencies library into the project, etc. So to simplify the whole process, use buildtool to quickly compile. Just execute the following command to compile the extension project code into the local installation form of the package (for details of the local installation form and local libraries, please refer to Appendix: Local Repositories and Installation Form). ```shell buildtool build --packages example_components ``` ### Step 4. Producing package Take the common module as an example of how to compile, make packages and verify its functionality. Developers need to: - Download the common source code to the workspace, - Compile, - Write the release description file, - Call buildtool to package the compiled output, - Verify whether the package is available. Next, each step will be described in detail. #### 1. Download the source code to the workspace In the workspace enter the following command: ```shell buildtool install common-dev ``` #### 2. Build use buildtool to build: ```shell buildtool build --p modules/common ``` #### 3. Write the release description file In this case, we use the following release description file: ```json { "linux_distribution": "Ubuntu 18.04.5 LTS", "kernal": "Linux 5.4.0-42-generic", "arch": "x86_64", "image": "registry.baidubce.com/apollo/apollo-env-gpu:0.0.4-dev", "apollo_distribution": "neo", "package_info": { "type": "local", "source": "/apollo_workspace/modules/common", "build_ops": [] }, "release_detail": { "name": "common", "ver": "1.0.0.1", "arch": "amd64", "description": "Apollo common module.", "deps": [ "3rd-rules-python-dev", "3rd-grpc-dev", "3rd-gflags-dev", "3rd-absl-dev", "libsqlite3-dev", "3rd-rules-proto-dev", "3rd-eigen3-dev", "3rd-osqp-dev", "3rd-boost-dev", "3rd-gtest-dev", "cyber-dev", "cyber-dev", "3rd-py-dev", "3rd-nlohmann-json-dev", "common-msgs-dev", "latency-proto-dev", "3rd-bazel-skylib-dev" ], "preinst_extend_ops": [], "postinst_extend_ops": [ # create conf dir and grant permission "mkdir -p /apollo/modules/common", "chmod a+rw /apollo/modules/common", # delete old config file "if [ ! -f /apollo/LICENSE ]; then rm -rf /apollo/modules/common/data; fi", "if [ ! -f /apollo/LICENSE ]; then rm -rf /apollo/modules/common/vehicle_model; fi", # ln output config file to config dir "if [ ! -f /apollo/LICENSE ]; then ln -snf /opt/apollo/neo/packages/common-dev/latest/data /apollo/modules/common/data; fi", "if [ ! -f /apollo/LICENSE ]; then ln -snf /opt/apollo/neo/packages/common-dev/latest/vehicle_model /apollo/modules/common/vehicle_model; fi" ], "prerm_extend_ops":[], "postrm_extend_ops":[] "data": [ { "src": "common-dev/local", "des": "-" } ] } } ``` Next, the meaning of each field is explained. linux_distribution: the linux distribution used, currently this field can only be filled with Ubuntu 18.04.5 LTS, which does not affect the packaging behavior. kernal: linux kernel version, usually Linux 5.4.0-42-generic, this field currently does not affect the packaging behavior. arch: cpu architecture, currently only supports x86_64. image: the Apollo image used when compiling the source code, fill in the actual value based on the actual situation. apollo_distribution: Apollo version code, currently only neo. package_info: information related to the source code of the package to be compiled. type: source code type, currently only supports local storage, that is, the source code is stored locally. source: source code storage path, fill in the actual path. build_ops: compile command set, a field reserved for future extensions, currently left empty. release_detail: information related to the release. name: the name of the package, must be consistent with the cyberfile.xml in the source code. For example, the name of cyberfile.xml in this example is "common", so the name of the release description file is also "common". ver: package version, defined by the developer. arch: architecture, currently only amd64 can be used. description: the description of the package, the developer can fill in as needed. deps: the dependency of the package. Strictly speaking it should be the same as the dependency in cyberfile.xml, but it is not mandatory. If the release description file is not exactly the same as the dependency in cyberfile.xml, it may cause errors in the actual use. preinst_extend_ops: a shell operation to be executed before the package is installed. postinst_extend_ops: the shell operation that will be executed after the package is installed. prerm_extend_ops: the shell operation that will be executed before the package is removed. postrm_extend_ops: the shell operation that will be executed after package deletion. > Note: The above four options can be filled in by the developer as needed. For all current apollo modules, all configuration files are read under /apollo, and the current package installation location is /opt/apollo/neo/packages. Therefore, it is necessary to softlink the package configuration files to the corresponding path of /apollo, and this operation postinst_extend_ops is performed. At the same time, since the package is compatible with the source image, the full amount of Apollo source code already exists in the source image, and the configuration file and source code under /apollo cannot be deleted. For detailed information about implementation, please refer to the description file in this example. data: the file to be wrapped into a package. src: path to the output file. dst: the path to which the output file will be installed after the package is installed. For example, in the above example src is common-dev/local, which is a relative path, corresponding to /opt/apollo/neo/packages/common-dev/local. src can also be specified as an absolute path, e.g. directly into /opt/apollo/neo/packages/common-dev/local. dst refers to the path where the files or folders in src will be installed after the package is installed by other users. This example uses the default value of "-", which means that everything in /opt/apollo/neo/packages/common-dev/local will be installed to /opt/apollo/neo/packages/common-dev/${version}, where ${version} is the value corresponding to the vec field of the release description file. #### 4. Call buildtool to package the compiled output Assuming that the release description file written in the previous step is named common.json. Simply enter the following command: ```shell buildtool pack -d common.json ``` The packed package is located in the .deb_local folder under the path of the execute package command. Verify whether the package is available. There are two types of modules, public dependency modules that provide the base interface (e.g. common module in this example) and modules that can be loaded or run independently (e.g. planning, perception, v2x). For the public dependency modules, after installation, let other modules (e.g. planning) depend on the module in cyberfile.xml and compile it to verify that the public dependency module functions properly. For modules that can be loaded or run independently, execute the binaries directly after installation, or launch the corresponding dag file or launch file to verify functionality. Using v2x as an example: - Install the already packed package. ```shell cd .deblocal && sudo apt install -y ./apollo-neo-v2x-dev_1.0.0.2_amd64.deb ``` - Access the module installation location. ```shell cd /opt/apollo/neo/packages/v2x/1.0.0.2 ``` - Start the dag or run the binary executable directly. ```shell mainboard -d dag/v2x_perception_fusion.dag ./bin/v2x ``` ## Appendix ### BUILD files and package dependencies BUILD file that is Bazel's file, a WORKSPACE can contain one or more BUILD files. These files tell Bazel how to build different parts of the project. Bazel will contain the BUILD file directory as a Bazel module processing, and support nesting. That is, the subdirectory containing the BUILD file directory can also contain BUILD files, and Bazel will be treated as two modules. A BUILD file contains several different types of instructions for Bazel. The most important type is a build rule, which tells Bazel how to build the desired output, such as an executable binary or library. Each instance of a build rule in a BUILD file is called a target and points to a specific set of source files and dependencies. A target can also point to other targets. Dependent packages can be declared in the cyberfile.xml file, and when building with buildtool, buildtool automatically injects the dependent modules declared in cyberfile.xml as dependencies into the deps attribute of the three build rules in cc_binary cc_libary cc_test (if the deps attribute already contains the dependency, it will be overwritten automatically) to implement the package dependency. For example, the demo has a dependency on the cyber package. First add the cyber package dependency in the cyberfile.xml file (see the cyberfile.xml description for details of the fields), and then use //cyber directly in the deps attribute of the cc_library rule of the target that depends on the cyber module to introduce the cyber dependency, just like the source code of cyber is used as if it were located directly in WORKSPACE. The rules commonly used in BUILD files are: - cc_binary: There are two main scenarios, one is to compile executable files, such as mainboard, etc. The other is used when compiling dynamic libraries, especially when compiling dynamic libraries that depend on other modules, you need to use together with cc_library, see Component SO and Dependency SO for details. - cc_libary: Bazel dependency. - cc_test: unit test. - install: extension rules, install output to local repository, see install rules and install_src rules for details. - install_src: extension rules, install source files to local repository, see install rules and install_src rules for details. ### WORKSPACE file and configuration injection The WORKSPACE file is the configuration file of the Bazel workspace. In order to simplify the configuration of some of the necessary dependencies in the Apollo component extension scenario, the buildtool will modify the WORKSPACE file under the workspace during compilation and inject the relevant configuration, so you can see the following addition to the WORKSPACE file after compilation: ```bazel #######################################APOLLO####################################### load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") http_archive( name = "build_bazel_rules_apple", sha256 = "0052d452af7742c8f3a4e0929763388a66403de363775db7e90adecb2ba4944b", urls = [ "https://apollo-system.cdn.bcebos.com/archive/8.0/rules_apple.0.31.3.tar.gz", "https://github.com/bazelbuild/rules_apple/releases/download/0.31.3/rules_apple.0.31.3.tar.gz", ], ) http_archive( name = "rules_foreign_cc", sha256 = "6041f1374ff32ba711564374ad8e007aef77f71561a7ce784123b9b4b88614fc", strip_prefix = "rules_foreign_cc-0.8.0", urls = [ "https://apollo-system.bj.bcebos.com/archive/6.0/rules_foreign_cc-0.8.0.tar.gz", "https://github.com/bazelbuild/rules_foreign_cc/archive/0.8.0.tar.gz", ], ) load("@rules_foreign_cc//foreign_cc:repositories.bzl", "rules_foreign_cc_dependencies") rules_foreign_cc_dependencies() http_archive( name = "rules_cc", urls = ["https://apollo-system.cdn.bcebos.com/archive/8.0/rules_cc-0.0.1.tar.gz", "https://github.com/bazelbuild/rules_cc/releases/download/0.0.1/rules_cc-0.0.1.tar.gz"], sha256 = "4dccbfd22c0def164c8f47458bd50e0c7148f3d92002cdb459c2a96a68498241", patches = ["//tools/package:rules_cc.patch"], ) load("//dev/bazel:deps.bzl", "init_deps") init_deps() load("@bazel_skylib//:workspace.bzl", "bazel_skylib_workspace") bazel_skylib_workspace() load("@com_github_grpc_grpc//bazel:grpc_deps.bzl", "grpc_deps") grpc_deps() load("@com_github_grpc_grpc//bazel:grpc_extra_deps.bzl", "grpc_extra_deps") grpc_extra_deps() load("@rules_proto//proto:repositories.bzl", "rules_proto_dependencies", "rules_proto_toolchains") rules_proto_dependencies() rules_proto_toolchains() #######################################APOLLO####################################### ``` - All modifications are made by a pair of "##... .APOLLO... ##" fields, and buildtool checks them to prevent duplicate injections. It is also recommended not to modify this section. - It contains some typical tools that Bazel depends on when compiling, such as build_bazel_rules_apple, rules_foreign_cc, rules_cc and other rules and dependencies. - init_deps(): this function is the entry function to load the package into the Bazel dependency. ### Local repository and installation form A brief description of the organization of the package in the local repository after installation. The so-called entity of the local repository is a directory, and the contents of the directory need to be organized in a way that conforms to the package specification. The details are as follows: ```shell /opt/apollo/neo/ |-- bin | |-- cyber_channel -> /opt/apollo/neo/packages/cyber-dev/latest/bin/cyber_channel ... | |-- mainboard -> /opt/apollo/neo/packages/cyber-dev/latest/bin/mainboard | `-- mainboard.py -> /opt/apollo/neo/packages/buildtool-dev/latest/bin/mainboard.py |-- conf |-- dag |-- data | |-- bag | |-- core | `-- log |-- include | |-- adapters -> /opt/apollo/neo/packages/common-dev/latest/include/adapters ... | `-- vehicle_state -> /opt/apollo/neo/packages/common-dev/latest/include/vehicle_state |-- launch |-- lib | |-- 3rd-fastrtps-dev -> /opt/apollo/neo/packages/3rd-fastrtps-dev/latest/lib ... | `-- cyber-dev -> /opt/apollo/neo/packages/cyber-dev/latest/lib |-- packages | |-- 3rd-fastrtps-dev | | |-- 1.0.0.1 | | `-- latest -> /opt/apollo/neo/packages/3rd-fastrtps-dev/1.0.0.1 ... | |-- cyber -> /opt/apollo/neo/packages/cyber-dev/latest | `-- cyber-dev | |-- 1.0.0.1 | `-- latest -> /opt/apollo/neo/packages/cyber-dev/1.0.0.1 |-- setup.sh -> /opt/apollo/neo/packages/buildtool-dev/latest/setup.sh |-- share `-- update_dylib.sh -> /opt/apollo/neo/packages/buildtool-dev/latest/scripts/update_dylib.sh ``` - bin directory: executable file unified entry, the software that stores executable files, the specific target is distributed within each package. - conf directory: configuration file (reserved directory). - dag directory: (reserved directory). - data directory: data files (reserved directory). - include directory: dependency package header file summary directory, through the software of the way each package include directory (or a level of subdirectory) link to the directory, need to pay attention to the name of the self-built dependency package, the way the same name conflict. - launch directory: (reserved directory). - lib directory: the unified entrance of dynamic SO, the lib directory of each package is linked to this directory by means of a soft chain. - packages directory: the actual storage directory of packages. - Each subdirectory is a package, and the different versions in the packages directory are stored separately using the version number, while using the latest softlink to link to the latest installed (or compiled) version. It is recommended to use the latest version directly, so that you can use the latest version. - share directory: (reserved directory). - setup.sh file: set environment variables. - update_dylib.sh file: update the system dynamic libraries, add apollo packages to the system libraries.
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/03_Package Management/launch_and_run_apollo_package_method.md
# Launch and Run Apollo This document describes how to install and run Apollo via the package method. This article assumes that you have followed [Installation - Package Method](../01_Installation%20Instructions/apollo_software_installation_guide_package_method.md) and completed the installation of the apollo environment manager tool. > Make sure Nvidia GPU is available and that you have installed the appropriate Nvidia driver if you want to run the entire system. ## Step 1. Create an end-2-end project 1. Create workspace. ```shell mkdir application-urban ``` ```shell cd application-urban ``` > Note: You can also check out the demo code from https://github.com/ApolloAuto/application-urban 2. Start Apollo Env Container. ```shell aem start_gpu ``` > Note: For more detailed usage of `aem`, please refer to the [Apollo Environment Manager](../03_Package%20Management/apollo_env_manager.md) documentation.. 3. Enter Apollo Env Container. ```shell aem enter ``` 4. Initialize workspace. ```shell aem init ``` ## Step 2. Create an end-2-end package 1. Create package path and `cyberfile.xml` ```shell mkdir mkz ``` ```shell touch mkz/cyberfile.xml ``` 2. Add necessary packages. ```shell vim mkz/cyberfile.xml ``` ```xml <?xml version='1.0' encoding='utf-8'?> <package> <name>mkz</name> <version>1.0.0</version> <description> mkz is end to end project, providing a quick setup for Apollo. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <type>module</type> <src_path>//mkz</src_path> <license>BSD</license> <author>Apollo</author> <builder>bazel</builder> <depend repo_name="audio" type="binary">audio-dev</depend> <depend repo_name="bridge" type="binary">bridge-dev</depend> <depend repo_name="canbus" type="binary">canbus-dev</depend> <depend repo_name="control" type="binary">control-dev</depend> <depend repo_name="dreamview" type="binary">dreamview-dev</depend> <depend repo_name="drivers" type="binary">drivers-dev</depend> <depend repo_name="guardian" type="binary">guardian-dev</depend> <depend repo_name="localization" lib_names="localization" type="binary">localization-dev</depend> <depend repo_name="map" type="binary">map-dev</depend> <depend repo_name="monitor" type="binary">monitor-dev</depend> <depend repo_name="perception" type="binary">perception-dev</depend> <depend repo_name="planning" type="binary">planning-gpu-dev</depend> <depend repo_name="prediction" type="binary">prediction-dev</depend> <depend repo_name="routing" type="binary">routing-dev</depend> <depend repo_name="storytelling" type="binary">storytelling-dev</depend> <depend repo_name="task-manager" type="binary">task-manager-dev</depend> <depend repo_name="tools" type="binary">tools-dev</depend> <depend repo_name="transform" type="binary">transform-dev</depend> <depend repo_name="v2x" type="binary">v2x-dev</depend> <depend expose="False">3rd-rules-python-dev</depend> <depend expose="False">3rd-grpc-dev</depend> <depend expose="False">3rd-bazel-skylib-dev</depend> <depend expose="False">3rd-rules-proto-dev</depend> <depend expose="False">3rd-py-dev</depend> <depend expose="False">3rd-gpus-dev</depend> </package> ``` > Note: For more information about `cyberfile.xml`, please refer to the [Introduction to Pakcage of Apollo](../03_Package%20Management/introduction_to_package_of_apollo.md) documentation. > Note: if Nvidia GPU is not available, you should remove the CUDA-based module (such as perception). 3. Add compiling description file. ```shell vim mkz/BUILD ``` ```bazel load("//tools/install:install.bzl", "install", "install_src_files") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) install( name = "install", data = [":cyberfile.xml"], data_dest = "mkz" ) install_src_files( name = "install_src", src_dir = ["."], dest = "mkz", filter = "*", ) ``` > Note: For more information about `mkz/BUILD`, please refer to the [Introduction to Pakcage of Apollo](../03_Package%20Management/introduction_to_package_of_apollo.md) documentation 4. Add dependency description file ```shell touch mkz/mkz.BUILD ``` > Note: For more information about `mkz.BUILD`, please refer to the [Introduction to Pakcage of Apollo](../03_Package%20Management/introduction_to_package_of_apollo.md) documentation ## Step 3. Build Use `buildtool` to build the end-2-end package, and it will download and install all required packages automatically. ```shell buildtool build --packages mkz ``` For more detailed usage of `buildtool`, please refer to the [Apollo buildtool](../03_Package%20Management/apollo_buildtool.md) documentation. ## Step 4. Run Apollo ### 1. Start Apollo ```shell aem bootstrap ``` This command will start Dreamview backend with the monitor module enabled. ### 2. Access Dreamview Web UI Open [http://localhost:8888](http://localhost:8888) in your browser, e.g. Chrome, and you can see this screen. However, no module(s) except monitor is running in the background at this moment. ![Access Dreamview](../01_Installation%20Instructions/images/apollo_bootstrap_screen.png) ### 3. Select Driving Mode and Map From the dropdown box of Mode Setup, select "Mkz Standard Debug" mode. From the dropdown box of Map, select "Sunnyvale with Two Offices". ![Drive Mode and Map Selection](../01_Installation%20Instructions/images/dreamview_6_0_setup_profile.png) ### 4. Replay Demo Record To see if the system works, use the demo record to "feed" the system. ``` # You need to download the demo record using the following commands wget -c https://apollo-system.cdn.bcebos.com/dataset/6.0_edu/demo_3.5.record # You can now replay this demo "record" in a loop with the '-l' flag cyber_recorder play -f demo_3.5.record -l ``` Dreamview shows a vehicle running forward. (The following image might be different due to frontend code changes.) ![Dreamview with Trajectory](../01_Installation%20Instructions/images/dv_trajectory_6.0.png) ### Congrats! You have successfully built Apollo! Now you can revisit [Apollo Readme](../../README.md) for additional guidelines on the necessary hardware setup.
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/03_Package Management/apollo_env_manager.md
# Apollo Environment Manager ## Summary Apollo environment manager, aem is a command line tool, providing the ability to manage Apollo containers. With aem, there is no need to run Apollo scripts to start and enter the container, avoiding the problem of Apollo scripts polluting the code in the workspace. ## Installation To install aem, you first need to add apt source of Apollo: ```shell $ sudo -i $ echo "deb https://apollo-pkg-beta.cdn.bcebos.com/neo/beta bionic main" >> /etc/apt/sources.list && wget -O - https://apollo-pkg-beta.cdn.bcebos.com/neo/beta/key/deb.gpg.key | apt-key add - $ exit ``` Then, use apt to install aem: ```shell $ sudo apt install apollo-neo-env-manager-dev ``` When the installation is completed, you can enter the following command to check whether buildtool has been installed correctly: ```shell aem -h ``` If all goes well, you will see a prompt similar to the image below: ```shell Usage: aem [OPTION] Options: start : start a docker container with apollo development image. start_gpu : start a docker container with apollo gpu support development image. enter : enter into the apollo development container. stop : stop all apollo development container. install_core : install the core module of apollo. bootstrap : run dreamview and monitor module. build : build package in workspace. install : install package in workspace. init: init single workspace. update: update core modules of apollo. ``` ## subcommand Similar to common command-line tools such as **git** or **apt**, the functionality of **aem** is organized into subcommands, such as **start** responsible for starting a container, **enter** responsible for entering a started container, etc. Some parameters may be required after the action, you can enter -h, --help after the action to view the detailed parameters. ## start, start_gpu This subcommand start a Apollo env container. This command will check whether the apollo container has been started. If the container has been started or stopped, it will use the started container; and if the container has never been started, it will start a new container. ### usage Start a normal container: ```shell aem start ``` Start a gpu-enabled container where you can build or run modules that require gpu support: ```shell aem start_gpu ``` > Note: NVIDIA graphics driver and nvidia toolkit must be installed correctly Start a container using local image: ```shell aem start_gpu -l ``` Force to start a new container: ```shell aem start_gpu -f ``` > Note: this command will completely delete current container. Give the container a name: ```shell aem start_gpu -n apollo_container ``` Specify the mount point: ```shell aem start_gpu -m /home/apollo/workspace:/apollo_workspace ``` ### detailed parameters ```shell OPTIONS: -h, --help Display this help and exit. -f, --force force to restart the container. -n, --name specify container name to start a container. -m, --mount specify the mount point in container, such as /home/apollo/workspace:/apollo_workspace -t, --tag <TAG> Specify docker image with tag <TAG> to start. -y Agree to Apollo License Agreement non-interactively. --shm-size <bytes> Size of /dev/shm . Passed directly to "docker run" --gpu Use gpu image instead of cpu image. ``` ## enter This subcommand enters an Apollo env container. ### usage Enter a container: ```shell aem enter ``` Specify the container name: ```shell aem enter -n apollo_container ``` ## bootstrap This subcommand is used to boot Dreamview and monitor. ### usage boot Dreamview and monitor in container. ```shell aem bootstrap ``` stop Dreamview and monitor in container ```shell aem bootstrap stop ``` restart Dreamview and monitor in container ```shell aem bootstrap restart ``` ## build This subcommand is a simple wrapper of buildtool build action. For detailed usage, please refer to the buildtool documentation. ## install This subcommand is a simple wrapper of buildtool install action. For detailed usage, please refer to the buildtool documentation. ## init This subcommand is a simple wrapper of buildtool init action. For detailed usage, please refer to the buildtool documentation. ## update This subcommand is used to update preinstalled buildtool and apollo-core modules in the image ### usage ```shell aem update ```
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/12_Map acquisition/apollo_2_5_map_collection_guide.md
# Apollo 2.5 map collection guide This guide is mainly used to explain how to use map collection in Apollo 2.5. ## Hardware and Software Requirement 1. Please refer to [Apollo 2.5 Hardware and System Installation Guide](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_2_5_hardware_system_installation_guide_v1.md) for the steps to install the hardware components. 2. Please refer to [Apollo Software Installation Guide](../01_Installation Instructions/apollo_software_installation_guide.md) for steps to install system software. 3. Please refer to [Apollo Sensor Calibration Guide](../Perception/multiple_lidar_gnss_calibration_guide.md) for Sensor Calibration. 4. NVMe SSD. In order to avoid the possible data loss caused by IO bottleneck, it is recommended to install NVME SSD hard disk in IPC. 5. Satelliate Base Station. In order to get accurate mapping results, satellite base stations need to be set up to ensure the RTK can work properly. ## Data Collection Steps 1.Enter Into Map Collection Mode. Please refer to [Apollo 2.5 Quick Start](../02_Quick%20Start/apollo_2_5_quick_start.md) for launching the Apollo 2.5 software and hardware stack on vehicle. Choose [Module Controller] tab, select [Map Collection] mode, and switch on [GPS]、[Camera]、[Velodyne]、[Velodyne16]. ![](images/map_collection_sensor_open.png) confirm whether the sensors are ready. ![](images/map_collection_sensor_check.png) 2. After sensors are all ready, switch on [Record Bag] to start recording the map data. ![](images/map_collection_sensor_start_record.png) Before the map collection, the vehicle needs to be stationary for five minutes, and then circles the ribbon in figure eight for five minutes. During the map collection, we should ensure the same road can be covered more than five times in the speed below 60KM/h. and take different lanes as far as possible in every cycle. You don't need to stop at the intersection area, you can pass it slowly. Besides, at the intersection area, it is necessary to collect at least 50m of roads in all directions to ensure the traffic lights and lane lines in all directions are complete and clear. After the map collection is completed, the vehicle also needs to circle the ribbon in figure eight for five minutes, and to remain stationary for five minutes. 3. After the collection is finished, switch off [Record Bag] firstly, and then switch off [GPS], [Camera], [Velodyne] and [Velodyne16]. ![](images/map_collection_sensor_stop_record.png) 4. Data Upload The collected map data is placed in the /apollo/data/bag/(start time of collection, e.g.,2018-04-14-21-20-24) directory by default, package them as tar.gz compressed file and upload them to the [Apollo Data Official Website](http://data.apollo.auto/hd_map_intro/?locale=en-us). ## Map Production Service 1、Permission Application First, you need to register a Baidu account, log into the account, and apply for permission to use map production service (only need to apply once, skip this step if you have already applied). ![](images/map_collection_request_en.png) 2. Map technical service Users can create new areas, create mapping tasks, manage map data, track progress of cartography, and download map data on this page. ![](images/map_collection_Area_en.png) 3, Data management After clicking “Management”, users can open the data management page. On this page, you can view the description of data upload. After all the data is uploaded, the data can be submitted.And then the drawing process is entered, the data can no longer be edited. ![](images/map_collection_Management_en.png) 4, Data download When the demand status is "Published", click "Download" to download the map data. If you need to update the map, please click "Update Data" to initiate the mapping process, and you need to re-upload the data and the drawing process. ![](images/map_collection_Download_en.png)
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/12_Map acquisition/how_to_run_map_verification_tool.md
# How to run the Map Data Verification Tool The Map Data Verification tool is designed to help Apollo developers detect any issues in their map data collection process before the data is used for HD Map creation. The benefit of using this tool is to ensure that all issues are detected prior to map creation and also ensures that data can be efficiently recollected based on the suggestions in the tool. ## Running the tool In order to run your data on this tool, please follow the steps below: 1. Build Apollo as recommended in the [Build Guide](../01_Installation%20Instructions/apollo_software_installation_guide.md) until the `./apollo.sh build` step. 2. Once instde dev docker and after running `./apollo.sh build` please go to the folder `modules/tools/map_datachecker/` 3. Starting the server: ```bash bash server.sh start ``` Note: You should see the following message displayed `Server has been started successfully`. If not, please resolve the errors before trying again 4. Start the record verification: ```bash bash client.sh --stage record_check --cmd start --record_path path_to_record ``` Note: Do not close your terminal window throughout this process. If the verification is successful, you will not see any error messages. 5. Static alignment verification: ```bash bash client.sh --stage static_align --cmd start ``` Note: The window will display the progress of the static alignment. 6. Figure 8 verification: ```bash bash client.sh --stage eight_route --cmd start ``` Note: Your window displays the progress of the Figure 8 verification 7. Laps verification: ```bash bash client.sh --stage loops_check --cmd start ``` Note: Run this command post data collection to check the number of laps 8. Figure 8 verification: This is repeated to verify that the extrinsic parameters have not been changed 9. Static alignment verification: Similar to 5, it is preferable to repeat this verification to ensure high accuracy 10. Stop record verification: ```bash bash client.sh --stage record_check --cmd stop ``` 11. Clean the intermediate results ```bash bash client.sh --stage clean ``` ## Tips 1. The default value of `cmd` is `start` 2. All error messages will be printed to help better prepare your map data. Please follow the error messages exactly as recommended
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/12_Map acquisition/apollo_3_5_map_collection_guidelines.md
# Apollo 3.5 Map Collection Guide This guide describes the process of map data collection and best practices for Apollo 3.5. ## Prerequisites ### Hardware requirements Hardware installed as mentioned in this guide - [https://github.com/ApolloAuto/apollo/blob/master/docs/quickstart/apollo_3_5_hardware_system_installation_guide.md] In order to proceed with Data collection, we need to use a single 16-Line LiDAR for traffic light detection placed on top of the car, tilted upwards as described below: #### Installation of VLP-16 lidar In Apollo 2.5, map creation services became a part of Apollo Open Source project. To acquire the data necessary for map creation, one would need to install an additional VLP-16 LiDAR on the vehicle. The purpose of this LiDAR is to collect point cloud information for objects above the FOV of the HDL-64 S3 LiDAR, such as traffic lights and signs. It requires a customized rack to mount the VLP-16 Lidar on top of the vehicle. The figure below shows one of the possible configurations: ![VLP_16_installation](images/lidar_mount1.jpeg) Another possible mounting is: ![VLP_16_installation](images/lidar_mount.jpeg) In this specific configuration, the VLP-16 LiDAR is mounted with an upward tilt of **20±2°**. The power cable of the VLP-16 is connected to the DataSpeed power panel. The ethernet connection is connected to the IPC (possibly through an ethernet switch). Similar to HDL-64 S3 LiDAR, the VLP-16 GPRMC and PPS receive input from the GPS receiver. Ideally, additional hardware should be installed to duplicate the GPRMC and PPS signal from the GPS receiver sent to HDL-64 and VLP-16 respectively. However, a simple Y-split cable may also provide adequate signal for both LiDARs. To distinguish from the HDL-64 S3 LiDAR, please follow the VLP-16 manual and configure the IP of VLP-16 to **192.168.20.14**, the data port to **2369**, and the telemetry port to **8309**. The pinout for the signal input from GPS receiver can also be found in the manual if you need customized cable. For additional reference, please visit: [http://velodynelidar.com/vlp-16.html](http://velodynelidar.com/vlp-16.htmll) ### Software requirements Apollo 3.5 installed without any errors - [How to Build Apollo](../01_Installation%20Instructions/how_to_launch_and_run_apollo.md) ### Calibration requirement Refer to the [Apollo Sensor Calibration Guide](../Perception/multiple_lidar_gnss_calibration_guide.md) for Sensor Calibration information. ### Additional requirements 1. **NVMe SSD Installation:** In order to avoid possible data loss caused by IO bottleneck, it is recommended to install NVME SSD hard disk in IPC. 2. **Satellite Base Station:** In order to get accurate mapping results, satellite base stations are needed to be set up to ensure the RTK can work properly. ## Good to know - Data Collection 1. **Weather condition:** Do not collect data when it is either raining or snowing. Please wait for the road to be as clean and dry as possible. You could collect data when there is a slight drizzle as the reflectance of the road would not change too much but it is still highly recommended to collect data in clear weather conditions. 2. Please make sure that the camera lens' are clean. 3. **Driving speed:** Try to keep you speed below 60 km/h (~ 37 mph). For roads with a higher speed limit, drive additional laps of the route (at least 2 or 3 more) to ensure accurate data collection. ## Data Collection Steps Once all the prerequisites are met, follow the steps below: 1. Inside the Dreamview environment, Choose **Module Control** tab, select [Map Collection] mode, and switch on [GPS]、[Camera]、[Velodyne]、[Velodyne16]. ![](images/map_collection_sensor_open.png) Confirm whether the sensors are ready. The button should be `Green` ![](images/map_collection_sensor_check.png) The only special case is that the additional front lidar 16 (which is facing upwards) which is installed for traffic lights, is not Green – this can be ignored when traffic light information is not being collected ![](images/map1.png) 2. Go into your terminal, - Enter `dev_docker` on your terminal and type `cyber_monitor` - If all the topics are green, then they are working correctly - Once inspected, go to the next page, shortcut `fn + up/down arrow key` - Verify that all necessary topics are green Topic list for mapping: ``` /apollo/monitor/system_status /apollo/sensor/gnss/best_pose /apollo/sensor/gnss/gnss_status /apollo/sensor/gnss/imu /apollo/sensor/gnss/ins_stat /apollo/sensor/gnss/odometry /apollo/sensor/gnss/raw_data /tf /tf_static /apollo/sensor/camera/front_12mm/image/compressed /apollo/sensor/camera/front_6mm/image/compressed /apollo/sensor/lidar16/front/up/Scan /apollo/sensor/lidar16/front/up/compensator/PointCloud2 /apollo/sensor/lidar128/Scan /apollo/sensor/lidar128/compensator/PointCloud2 ``` 3. Sync Localization module with your GPS signal, - Go outside the garage where the GPS signal is good, you can confirm that the strength of the GPS signal is good when it turns green in Dreamview as mentioned in Step 1. - Once you see the topic `gnss/best_pose` in cyber_monitor, then you know GPS is working. Inside the topic gnss/best_pose: click on it, if the `sol_type` specifies `narrow int` then it confirms that the signal is good enough to use - Check for topic called `tf` in cyber_monitor to see if the Localization module is up and running - Note, Localization takes time to warm up - If the map in Dreamview has jiggly lines as seen in the image below, please restart dreamview or rebuild Apollo ![](images/map3.png) 4. Data collection, Once the localization module has warmed up and you see the topic `tf` in cyber_monitor, you are now ready for map data collection. - After confirming GPS is working, you can start the data collection process, click on the `Recorder` button as seen in the image below ![](images/map2.png) - **[IMPORTANT]** Stay stationary for 3~5 minutes for the GPS signal to sync - Drive around in figure 8 shape to warm up the localization module. - While collecting map date, we should ensure the same route can be covered more than five times in the speed under 60KM/h. Try to include as many lanes as possible while covering the route. - You do not need to stop at any intersections, you can pass it slowly. But remember that at the intersection, it is necessary to collect at least 50m of all the lanes that enter the intersection in all directions to ensure the traffic lights and lane lines in all directions are captured completely and clearly. 5. Once you are done with data collection, - Go to an area where the GPS signal is good - **[IMPORTANT]** Stay stationary for 3~5 minutes - Shut down the `Recorder` button and close sensor types like Lidar, Camera, GPS ![](images/map_collection_sensor_stop_record.png) ## Data Verification - Check if the point cloud of VLS 128 covers all obstacles surrounding the vehicle like trees, other vehicles - `cyber_visualizer` - Check that the framerate of VLS 128 is at least 10Hz `cyber_monitor` - Check that the LiDAR’s generated noise is moderate (not to high) `cyber_visualizer` - Check whether the IMU coordinates are correct and not rotated on a different axis `cyber_monitor` - **[IMPORTANT]** If data is collected for the first time, or the extrinsic parameters between multiple-lidars and GNSS are changed or if a new vehicle is used to install Apollo 3.5 and data is being collected on this new vehicle, we would need to verify your map data. In order to verify your data, we would need you to collect the data of a small route and upload it as mentioned in the steps above. ## Data Size Management 1. Set your camera frame rate to 10Hz (this will drastically lower the data size) 2. For Lidar topics: - For the vehicles that are needed for map data verification, all the LiDAR related point cloud topics (velodynescan, pointcloud2, compenstator/pointcloud2) must be saved and sent to us - After the vehicle passes the map verification, only velodynescan & pointcloud2 are needed for map creation 3. In order to ensure a smooth upload process: - If you are currently collecting data on Apollo 3.5, then Apollo Cyber will take care of reducing the size of the data files via a splitter - If you are currently collecting data on Apollo 3.0 or lower based on ROS, you could split the file to a maximum size of 4GB per file. Please refer to the following [ROS guide](http://wiki.ros.org/rosbag/Commandline) and look for the keyword --split to learn how to split your bag. ## Data Upload The collected map data is placed in the */apollo/data/bag/(start time of collection, e.g.,2018-04-14-21-20-24)* directory by default, package the data as tar.gz compressed file and contact the team (wuzhenni01@baidu.com) to learn how to mail/upload your data to us for map generation. ``` Note: Please follow the aforementioned data collection guide to acquire data for a small area and upload it to use for verification purposes. This step is vital to understand if your sensors have captured the right data for our map generation process. ``` ## FAQs - If localization doesn’t warm up and if the topic `tf` is not visible, then the best way to kickstart the module is by going to an area where you already have a map and start driving through it. Note: this will not work if you are collecting data for the first time. If you are collecting for the first time, keep driving in a loop in an area with good GPS signal - If the map has jiggly lines, restart Dreamview or rebuild Apollo
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/12_Map acquisition/apollo_2_5_map_collection_guide_cn.md
# Apollo 2.5 地图采集功能使用指南 本文档主要用来说明如何在 Apollo2.5 中使用地图数据采集的功能.重点介绍了数据采集所 需的软硬件环境,数据采集的流程和注意事项. ## 软硬件环境准备 1、硬件安装方法参 见[Apollo 2.5 硬件安装指南](../10Hardware%20Integration%20and%20Calibration/%E8%BD%A6%E8%BE%86%E9%9B%86%E6%88%90/%E7%A1%AC%E4%BB%B6%E5%AE%89%E8%A3%85hardware%20installation/apollo_2_5_hardware_system_installation_guide_v1.md) 2、软件安装方法参 见[Apollo 软件安装指南](../01_Installation%20Instructions/apollo_software_installation_guide.md) 3、传感器标定方法参 见[Apollo 传感器标定方法使用指南](../06_Perception/multiple_lidar_gnss_calibration_guide.md) 4、NVMe SSD 硬盘。为了解决由于 IO 瓶颈导致可能的数据丢帧问题,建议工控机中安装 NVME SSD 硬盘。 5、卫星基站。为了得到精确的制图结果,需要搭建卫星基站,并且保证整个采集过程中采 集车的 RTK 可以正常工作。 ## 数据采集流程 1、启动地图采集模式 Apollo 环境启动参 见[Apollo 2.5 快速上手指南](../02_Quick%20Start/apollo_2_5_quick_start_cn.md) 选择[Module Controller]、[Map Collection],打 开[GPS]、[Camera]、[Velodyne]、[Velodyne16]开关。 ![](images/map_collection_sensor_open.png) 确认各个传感器状态是否 OK。 ![](images/map_collection_sensor_check.png) 2、待确认各个传感器状态 OK 后,打开[Record Bag]开关,开始录制地图数据。 ![](images/map_collection_sensor_start_record.png) 正式采集数据之前,需要车辆静止 5 分钟,8 字绕行 5 分钟。采集过程中需要保证双向车 道全覆盖采集五圈以上,车速 60KM/h 以下,尽量每圈走不同的车道,覆盖完全。在路口区 域无需刻意停留,慢速通过即可。路口区域需对各方向道路外延采集至少 50m,保障道路各 方向的红绿灯及车道线完整清晰。数据采集完成后,需要 8 字绕行五分钟,然后再静止五 分钟。 3、所有采集完成后,关闭[Record Bag]开关结束采集,然后关 闭[GPS]、[Camera]、[Velodyne]、[Velodyne16]开关。 ![](images/map_collection_sensor_stop_record.png) 4、数据上传 采集的数据放置在/apollo/data/bag/(采集开始时间,例如 2018-04-14-21-20-24)目录,把 该目录下的数据打包为 tar.gz 压缩文件, 到[Apollo 数据官网](http://data.apollo.auto/hd_map_intro/?locale=zh-cn)进行数据 上传。 ## 地图数据生产服务 1、数据权限申请 首先需要注册一个百度账号,登陆百度账号,申请地图制作服务使用权限(仅需申请一次), 如果已经申请过,跳过此步。 ![](images/map_collection_request_ch.png) 2、地图技术服务 用户可以在该页面进行新建区域、创建制图任务、管理地图数据、跟踪制图进度,下载地图 数据。 ![](images/map_collection_Area_ch.png) 3、数据管理 用户点击“采集数据管理”后可以进入采集数据管理页面,在该页面可以上传多份采集数据, 所有数据上传上传后可以提交采集数据,之后进入制图流程,不能再对数据进行编辑操作。 ![](images/map_collection_Management_ch.png) 4、数据下载 当需求状态是"已发布"时,点击“下载地图”可进行地图数据下载。如果需要更新地图,请点 击“更新地图数据”发起制图流程,需重新进行数据上传及制图流程。 ![](images/map_collection_Download_ch.png)
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/04_CyberRT/CyberRT_Terms.md
# Apollo Cyber RT Terminologies This page describes the definitions of the most commonly used terminologies in Cyber RT. ## Component In an autonomous driving system, modules(like perception, localization, control systems...) exist in the form of components under Cyber RT. Each component communicates with the others through Cyber channels. The component concept not only decouples modules but also provides the flexibility for modules to be divided into components based individual module design. ## Channel Channels are used to manage data communication in Cyber RT. Users can publish/subscribe to the same channel to achieve p2p communication. ## Task Task is the abstract description of an asynchronous computation task in Cyber RT. ## Node Node is the fundamental building block of Cyber RT; every module contains and communicates through the node. A module can have different types of communication by defining read/write and/or service/client in a node. ## Reader/Writer Message read/write class from/to channel. Reader/Writer are normally created within a node as the major message transfer interface in Cyber RT. ## Service/Client Besides Reader/writer, Cyber RT also provides service/client pattern for module communication. It supports two-way communication between nodes. A client node will receive a response when a request is made to a service. ## Parameter Parameter service provides a global parameter access interface in Cyber RT. It's built based on the service/client pattern. ## Service discovery As a decentralized design framework, Cyber RT does not have a master/central node for service registration. All nodes are treated equally and can find other service nodes through `service discovery`. `UDP` is used in Service discovery. ## CRoutine Referred to as Coroutine concept, Cyber RT implemented CRoutine to optimize thread usage and system resource allocation. ## Scheduler To better support autonomous driving scenarios, Cyber RT provides different kinds of resource scheduling algorithms for developers to choose from. ## Message Message is the data unit used in Cyber RT for data transfer between modules. ## Dag file Dag file is the config file of module topology. You can define components used and upstream/downstream channels in the dag file. ## Launch files The Launch file provides an easy way to start modules. By defining one or multiple dag files in the launch file, you can start multiple modules at the same time. ## Record file The Record file is used to record messages sent/received to/from channels in Cyber RT. Reply record files can help reproduce the behavior of previous operations of Cyber RT.
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/04_CyberRT/CyberRT_Scheduler_cn.md
## 1. 调度策略 调度系统调度策略分为classic策略和choreography策略。 classic策略是一个较为通用的调度策略,如果对当前车上dag结构不清楚,建议用此策略。 choreography策略是基于对车上任务足够熟悉,根据任务的依赖执行关系、任务的执行时长、任务cpu消耗情况、消息频率等,对任务进行编排。 ## 2. classic策略 ### 2.1 classic策略配置示例 cyber/conf/example_classic_sched.conf: ```bash scheduler_conf { policy: "classic" process_level_cpuset: "0-7,16-23" threads: [ { name: "async_log" cpuset: "1" policy: "SCHED_OTHER" prio: 0 }, { name: "shm" cpuset: "2" policy: "SCHED_FIFO" prio: 10 } ] classic_conf { groups: [ { name: "group1" processor_num: 16 affinity: "range" cpuset: "0-7,16-23" processor_policy: "SCHED_OTHER" processor_prio: 0 tasks: [ { name: "E" prio: 0 } ] },{ name: "group2" processor_num: 16 affinity: "1to1" cpuset: "8-15,24-31" processor_policy: "SCHED_OTHER" processor_prio: 0 tasks: [ { name: "A" prio: 0 },{ name: "B" prio: 1 },{ name: "C" prio: 2 },{ name: "D" prio: 3 } ] } ] } } ``` ### 2.2 配置属性说明 每个配置属性的含义、影响: - groups:如2.1的配置示例,classic策略可以配置多个group,主要为了实现资源隔离、跨numa问题,比如一个进程产生的所有task在0-31号cpu上执行,内核的调度会将线程在0-31号cpu上切换,跨numa节点会给系统带来额外的开销,这里可以通过group将numa节点进行隔离,一个numa节点下的0-7,16-23号cpu划分到一个group中,另外一个numa节点下的8-15,24-31号cpu划分到另一个group,这样既保证了资源利用,也能避免跨numa节点带来的开销。 - process_level_cpuset: 控制mainboard进程使用哪些cpu - affinity: 取值为range或者1to1,如第一个group,创建16个线程,在0-7,16-23号cpu上设置亲和性,每个线程都可以在0-7,16-23号核上执行。第二个group中,affinity为1to1,表示16个线程对应8-15,24-31号cpu,每个线程和一个cpu进行亲和性设置,能减少线程在cpu之间切换带来的开销,但是前提是开启的线程数和cpu数必须一致。 - processor_policy和processor_prio: 这两个一般成对出现,processor_policy指设置线程的调度策略,取值为SCHED_FIFO(实时调度策略,先到先服务), SCHED_RR(实时调度策略,时间片轮转), SCHED_OTHER(分时调度策略,为默认策略),对于设置了SCHED_FIFO或者SCHED_RR的线程会更优先的得到cpu执行, 调度模型中设置processor_policy背景:为了保证主链路的任务或者其他一些实时task的优先执行。如果processor_policy设置为SCHED_FIFO/SCHED_RR,processor_prio取值为(1-99),值越大,表明优先级越高,抢到cpu概率越大。如果processor_policy设置为SCHED_OTHER,processor_prio取值为(-20-19,0为默认值),这里为nice值,nice值不影响分配到cpu的优先级,但是影响分到cpu时间片的大小,如果nice值越小,分到的时间片越多。 - tasks:这里是对task任务进行配置,name表示task的名字,prio表示任务的优先级,为了提高性能,减小任务队列锁的粒度,调度模型中采用的是多优先级队列,也就是同一优先级的task在同一个队列里面,系统调度时会优先执行优先级高的任务。 ### 2.3 配置案例详解 例如拓扑结构为下图所示,对应2.1中的配置文件,那么A、B、C、D任务在第一个group中执行,E在第二个group中执行,对于没有出现在配置中的任务,比如F默认会放到第一个group中执行。 而且配置中我们对于任务进行了优先级设置,A、B、C、D优先级依次增大,正好对应下图的拓扑依赖关系,在链路中越靠后的任务优先级越高。这样设置的目的是解决任务优先级反转的问题。 <img src="images/topo_sched.png" width="30%" height="30%" /> ## 3. choreography策略 ### 3.1 choreography策略配置示例 cyber/conf/example_choreography_sched.conf: ```bash scheduler_conf { policy: "choreography" process_level_cpuset: "0-7,16-23" threads: [ { name: "lidar" cpuset: "1" policy: "SCHED_RR" prio: 10 }, { name: "shm" cpuset: "2" policy: "SCHED_FIFO" prio: 10 } ] choreography_conf { choreography_processor_num: 8 choreography_affinity: "range" choreography_cpuset: "0-7" choreography_processor_policy: "SCHED_FIFO" choreography_processor_prio: 10 pool_processor_num: 8 pool_affinity: "range" pool_cpuset: "16-23" pool_processor_policy: "SCHED_OTHER" pool_processor_prio: 0 tasks: [ { name: "A" processor: 0 prio: 1 }, { name: "B" processor: 0 prio: 2 }, { name: "C" processor: 1 prio: 1 }, { name: "D" processor: 1 prio: 2 }, { name: "E" } ] } } ``` ### 3.2 配置属性说明 choreography策略,主要是对主链路上的任务进行编排(choreography开头的配置),将非主链路的任务放到线程池中由classic策略(pool开头的配置)执行,choreography策略中classic线程池存在的意义:主链路的任务执行先后关系比较明确,但是存在一些其他链路的任务在不清楚前后拓扑关系的情况下,或者说未被编排的任务(包括Async创建的异步task),会被放到classic线程池中执行。 关于配置属性: - affinity: 在2.2中进行了解释说明。 - choreography_processor_policy和choreography_processor_prio是设置编排线程的调度策略和优先级,这里设置SCHED_FIFO是为了保证主链路能够及时抢占cpu执行, pool_processor_policy和pool_processor_prio是设置classic线程的调度策略和优先级。 ### 3.3 配置案例详解 用2.3中的拓扑图来进行说明 A、B、C、D是主链路任务,都设置了processor属性,那么A、B在0号cpu上执行,C、D在1号cpu上执行。在同一个核上,A和B还设置了优先级,所以优先执行B,再执行A。 没有配置processor属性的任务E以及没有出现在task配置中的任务如F,则默认进入classic线程池中执行。 考虑到任务优先级、执行时长、频率与调度之间的关系,任务编排有如下几个依据: - 同一个path的任务尽量编排在同一个processor,如果processor负载过高,将部分任务拆分到另外其他processor - 同一个path上的任务从开始到结束,优先级逐级升高 - 不同path上的任务尽量不混排 - 高频&短耗时任务尽量排放同一processor ## 4. 默认配置说明 如果进程没有对应的调度配置文件,默认采用classic调度策略,开启调度任务线程数值为conf/cyber.pb.conf中default_proc_num设置的值 ## 5. 进程加载调度配置文件示例 modules/dreamview/conf/hmi_modes/mkz_close_loop.pb.txt中,设置了两个process_group,分别为compute_sched/control_sched,也就是这两个进程启动时候,分别加载compute_sched.conf/control_sched.conf的调度配置文件。 另外要注意的是dreamview进程的process_group:dreamview_sched 是在modules/dreamview/backend/main.cc 中进行设置的,加载对应的调度配置文件dreamview_sched.conf。 ## 6. 调度策略切换 默认调度策略采用classic策略,compute_sched.conf和control_sched.conf两个软链分别指向compute_sched_classic.conf和control_sched_classic.conf文件。可以通过将软链指向compute_sched_choreography.conf和control_sched_choreography.conf配置文件来切换到choreography策略。
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/04_CyberRT/README.md
Please refer to the [Apollo Cyber RT README](https://github.com/ApolloAuto/apollo/tree/master/cyber/README.md) under cyber directory.
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/04_CyberRT/CyberRT_Quick_Start_cn.md
# 如何使用 Cyber RT 创建新的组件 Apollo 的 Cyber RT 框架是基于组件概念来构建的。每个组件都是 Cyber RT 框架的一个 特定的算法模块, 处理一组输入并产生其输出数椐。 要创建并启动一个算法组件,需要通过以下 4 个步骤: - 初如化组件的目录结构 - 实现组件类 - 设置配置文件 - 启动组件 下面的例子展示了如何创建、编译和运行一个组件。想更深入地探索 Cyber RT 框架,了解 其各种功能,可参考`cyber/examples/`目录下的更多示例。 _Note: 这些例子必须运行在 Apollo Docker 环境内, 且需要通过 Bazel 来编译。_ ## 初始化组件的目录结构 以`cyber/examples/common_component_example/`目录下的样例程序为例: - C++头文件: common_component_example.h - C++源文件: common_component_example.cc - Bazel 构建文件: BUILD - DAG 文件: common.dag - Launch 文件: common.launch ## 实现组件类 ### 头文件 如何实现`common_component_example.h`: - 继承 Component 类 - 定义自己的 `Init` 和 `Proc` 函数。Proc 需要指定输入数椐类型。 - 使用`CYBER_REGISTER_COMPONENT`宏定义把组件类注册成全局可用。 ```cpp #include <memory> #include "cyber/component/component.h" #include "cyber/examples/proto/examples.pb.h" using apollo::cyber::Component; using apollo::cyber::ComponentBase; using apollo::cyber::examples::proto::Driver; class CommonComponentSample : public Component<Driver, Driver> { public: bool Init() override; bool Proc(const std::shared_ptr<Driver>& msg0, const std::shared_ptr<Driver>& msg1) override; }; CYBER_REGISTER_COMPONENT(CommonComponentSample) ``` ### 源文件 对于源文件 `common_component_example.cc`, `Init` 和 `Proc` 这两个函数需要实现。 ```cpp #include "cyber/examples/common_component_example/common_component_example.h" bool CommonComponentSample::Init() { AINFO << "Commontest component init"; return true; } bool CommonComponentSample::Proc(const std::shared_ptr<Driver>& msg0, const std::shared_ptr<Driver>& msg1) { AINFO << "Start common component Proc [" << msg0->msg_id() << "] [" << msg1->msg_id() << "]"; return true; } ``` ### 创建 BUILD 文件 ```python load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_binary( name = "libcommon_component_example.so", linkshared = True, linkstatic = False, deps = [":common_component_example_lib"], ) cc_library( name = "common_component_example_lib", srcs = ["common_component_example.cc"], hdrs = ["common_component_example.h"], visibility = ["//visibility:private"], deps = [ "//cyber", "//cyber/examples/proto:examples_cc_proto", ], ) cpplint() ``` ## 设置配置文件 ### 配置 DAG 文件 在 DAG 依赖配置文件 (例如 common.dag) 中配置如下项: - Channel names: 输入 Channel 的名称 - Library path: 该组件生成的共享库路径 - Class name: 此组件类的名称 ```bash # Define all components in DAG streaming. module_config { module_library : "/apollo/bazel-bin/cyber/examples/common_component_example/libcommon_component_example.so" components { class_name : "CommonComponentSample" config { name : "common" readers { channel: "/apollo/prediction" } readers { channel: "/apollo/test" } } } } ``` ### 配置 Launch 启动文件 在 launch 启动文件中 (`common.launch`), 配置下面的项: - 组件的名字 - 上一步配置的 DAG 文件路径 - 运行组件时的进程名 ```xml <cyber> <component> <name>common</name> <dag_conf>/apollo/cyber/examples/common_component_example/common.dag</dag_conf> <process_name>common</process_name> </component> </cyber> ``` ## 启动这个组件 通过下面的命令来编译组件: ```bash cd /apollo bash apollo.sh build ``` 然后配置环境: ```bash source cyber/setup.bash # 从终端观察输出 export GLOG_alsologtostderr=1 ``` 有两种方法来启动组件: - 使用 Launch 文件启动(推荐) ```bash cyber_launch start cyber/examples/common_component_example/common.launch ``` - 使用 DAG 文件启动 ```bash mainboard -d cyber/examples/common_component_example/common.dag ``` ### 提供通道数据给组件处理 打开另一终端, 运行: ```bash source cyber/setup.bash export GLOG_alsologtostderr=1 /apollo/bazel-bin/cyber/examples/common_component_example/channel_test_writer ``` 再打开一个终端并运行: ```bash source cyber/setup.bash export GLOG_alsologtostderr=1 /apollo/bazel-bin/cyber/examples/common_component_example/channel_prediction_writer ``` 这时,如果成功,你会看到第一个终端有如下的输出: ``` I0331 16:49:34.736016 1774773 common_component_example.cc:25] [mainboard]Start common component Proc [1094] [766] I0331 16:49:35.069005 1774775 common_component_example.cc:25] [mainboard]Start common component Proc [1095] [767] I0331 16:49:35.402289 1774783 common_component_example.cc:25] [mainboard]Start common component Proc [1096] [768] ``` 此即验证第一个样例组件已经跑通。
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/04_CyberRT/CyberRT_Developer_Tools.md
# Apollo Cyber RT Developer Tools Apollo Cyber RT framework comes with a collection of useful tools for daily development, including one visualization tool cyber_visualizer and two command line tools cyber_monitor and cyber_recorder. *Note: apollo docker environment is required to use the tools, please follow apollo wiki to enter docker* All the tools from Apollo Cyber RT rely on Apollo Cyber RT library, so you must source the setup.bash file for environment setup before using any Apollo Cyber RT tools, shown as below: ```bash username@computername:~$: source /your-path-to-apollo-install-dir/cyber/setup.bash ``` ## Cyber_visualizer ### Install and run `cyber_visualizer` is a visualization tool for displaying the channel data in Apollo Cyber RT. ```bash username@computername:~$: source /your-path-to-apollo-install-dir/cyber/setup.bash username@computername:~$: cyber_visualizer ``` ### Interacting with cyber_visualizer - After launching cyber_visualizer, you will see the following interface: ![interface](images/cyber_visualizer1.png) - When data flow through channels in Apollo Cyber RT, the list of all channels are displayed under `ChannelNames` as seen in the figure below. For example, you can use the record tool(cyber_recorder) of Apollo Cyber RT to replay data from another terminal, then `cyber_visualizer` will receive information of all active channels(from replay data) and display it. ![channel information](images/cyber_visualizer2.png) - By clicking on options in toolbar, you can enable reference grid, display point clouds, add images, or display multiple camera's data at the same time. If you have `Show Grid` option enabled, you can set the color of the grid by double-clicking the `Color` item of the `Grid` list below `ChannelNames`. The default color is gray. You can also edit the value of `CellCount` to adjust the number of cells in the grid. As for a point cloud or an image, you can select the source channel through its `ChannelName` sub-item, and `Action` sub-item to play or stop the data from the corresponding channel. As shown in figure below, three cameras' channel data on the button sections and one point cloud channel data on the top section are displayed simultaneously. ![visualization](images/cyber_visualizer3.png) - To adjust the virtual camera in the 3D point cloud scene, you can right click on the point cloud display section. A dialog box will pop up as shown in figure below. ![visualization](images/cyber_visualizer4.png) The point cloud scene supports two types of cameras: Free and Target.(select Type from pop up dialog above) - **Free type Camera**: For this type of camera in the point cloud scene, you can change the pose of the camera by holding down either left or right mouse button and move it. To change the pitch of camera, you can scroll the mouse wheel. - **Target type Camera**: For this type of camera in the point cloud scene, to change the camera's viewing angle, you can hold down the left mouse button and then move it. To change the distance of the camera to the observed point (the default observation point is the coordinate system origin (0, 0,0)), you can scroll the mouse wheel. You can also modify the camera information directly in the dialog box to change the camera's observation status in the point cloud scene. And the "Step" item is the step value from the dialog box. Place the mouse on the image of the camera channel, you can double-click the left button to highlight the corresponding data channel on the left menu bar. Right click on the image to bring up menu for deleting the camera channel. Play and Pause buttons: when clicking the `Play` button, all channels will be shown. While when clicking the `Pause` button, all channels will stop showing on the tool. ## Cyber_monitor ### Install and run The command line tool `cyber_monitor` provides a clear view of the list of real time channel information Apollo Cyber RT in the terminal. ```bash username@computername:~$: source /your-path-to-apollo-install-dir/cyber/setup.bash username@computername:~$: cyber_monitor ``` ### Useful commands #### Display help information Use the -h option to get help for cyber_monitor ```bash username@computername:~$: cyber_monitor -h ``` #### Specify the channel With the -c option, you can have cyber_monitor to monitor only a specified channel, such as: ```bash username@computername:~$: cyber_monitor -c ChannelName ``` ## Get familiar with UI of cyber_monitor After launching the command line tool, you will notice it is similar to cyber_visualizer. It automatically collects the information of all the channels through the topology and displays them in two columns (channel name, channel data type). The default display for channel information is in red. However, if there is data flowing through the a channel, the corresponding line of the channel is displayed in green. As shown in the image below: ![monitor](images/cyber_monitor.png) ### Interacting with cyber_monitor #### Common commands ``` ESC | q key ---- Exit Backspace ---- Back h | H ---- Show help page ``` #### Common command for topology and channel ``` PageDown | Ctrl+d --- Next PageUp | Ctrl+u --- Previous Up, down or w, s keys ---- Move the current highlight line up and down Right arrow or d key ---- Enter highlight line, display highlighted line data in detail Left arrow or a key ------ Return to the previous layer from the current Enter key ----- Same as d key ``` #### Commands only for topology ``` f | F ----- Display frame rate t | T ----- Display channel message type Space ----- Close|Open channel (only valid for channels with data arrival; yellow color after channel is closed) ``` #### Commands only for channel ``` i | I ----- Display channel Reader and Writer information b | B ------ Display channel message content ``` #### View the repeated data field in a channel ``` n | N ---- Repeat the next data in the domain m | M ---- Repeat one data on the domain ``` ## Cyber_recorder `cyber_recorder` is a record/playback tool provided by Apollo Cyber RT. It provides many useful functions, including recording a record file, playing back a record file, splitting a record file, checking the information of record file and etc. ### Install and run Launch cyber_recorder: ```bash $ source /your-path-to-apollo-install-dir/cyber/setup.bash $ cyber_recorder usage: cyber_recorder <command>> [<args>] The cyber_recorder commands are: info Show information of an exist record. play Play an exist record. record Record same topic. split Split an exist record. recover Recover an exist record. ``` ### Commands of cyber_recorder - To view the information of a record file: ``` $ cyber_recorder info -h usage: cyber_recorder info [options] -h, --help show help message ``` - To record a record file ``` $ cyber_recorder record -h usage: cyber_recorder record [options] -o, --output <file> output record file -a, --all all channels -c, --white-channel <name> only record the specified channel -k, --black-channel <name> not record the specified channel -i, --segment-interval <seconds> record segmented every n second(s) -m, --segment-size <MB> record segmented every n megabyte(s) -h, --help show help message ``` - To play back a record file: ``` $ cyber_recorder play -h usage: cyber_recorder play [options] -f, --file <file> input record file -a, --all play all -c, --white-channel <name> only play the specified channel -k, --black-channel <name> not play the specified channel -l, --loop loop play -r, --rate <1.0> multiply the play rate by FACTOR -b, --begin <2018-07-01 00:00:00> play the record begin at -e, --end <2018-07-01 00:01:00> play the record end at -s, --start <seconds> play started at n seconds -d, --delay <seconds> play delayed n seconds -p, --preload <seconds> play after trying to preload n second(s) -h, --help show help message ``` - To split a record file: ``` $ cyber_recorder split -h usage: cyber_recorder split [options] -f, --file <file> input record file -o, --output <file> output record file -a, --all all channels -c, --white-channel <name> only split the specified channel -k, --black-channel <name> not split the specified channel -b, --begin <2018-07-01 00:00:00> begin at assigned time (in the form of String, e.g. "2018-07-01 00:00:00") -e, --end <2018-07-01 01:00:00> end at assigned time (in the form of String, e.g. "2018-07-01 00:00:00") ``` - To repair a record file: ``` $ cyber_recorder recover -h usage: cyber_recorder recover [options] -f, --file <file> input record file -o, --output <file> output record file ``` ### Examples of using cyber_recorder #### Check the details of a record file ``` $ cyber_recorder info demo.record record_file: demo.record version: 1.0 duration: 19.995227 Seconds begin_time: 2018-04-17 06:25:36 end_time: 2018-04-17 06:25:55 size: 28275479 Bytes (26.965598 MB) is_complete: true message_number: 15379 channel_number: 16 channel_info: /apollo/localization/pose 2000 messages : apollo.localization.LocalizationEstimate /tf 4000 messages : apollo.transform.TransformStampeds /apollo/control 2000 messages : apollo.control.ControlCommand /apollo/sensor/gnss/odometry 2000 messages : apollo.localization.Gps /apollo/canbus/chassis 2000 messages : apollo.canbus.Chassis /apollo/sensor/gnss/imu 1999 messages : apollo.drivers.gnss.Imu /apollo/sensor/gnss/rtk_obs 41 messages : apollo.drivers.gnss.EpochObservation /apollo/sensor/gnss/ins_stat 20 messages : apollo.drivers.gnss.InsStat /apollo/sensor/gnss/best_pose 20 messages : apollo.drivers.gnss.GnssBestPose /apollo/perception/obstacles 400 messages : apollo.perception.PerceptionObstacles /apollo/prediction 400 messages : apollo.prediction.PredictionObstacles /apollo/sensor/conti_radar 270 messages : apollo.drivers.ContiRadar /apollo/planning 200 messages : apollo.planning.ADCTrajectory /apollo/monitor/static_info 1 messages : apollo.data.StaticInfo /apollo/sensor/gnss/rtk_eph 25 messages : apollo.drivers.gnss.GnssEphemeris /apollo/monitor 3 messages : apollo.common.monitor.MonitorMessage ``` #### Record a record file ``` $ cyber_recorder record -a [RUNNING] Record : total channel num : 1 total msg num : 5 ... ``` #### Replay a record file ``` $ cyber_recorder play -f 20180720202307.record file: 20180720202307.record, chunk_number: 1, begin_time: 1532089398663399667, end_time: 1532089404688079759, message_number: 75 please wait for loading and playing back record... Hit Ctrl+C to stop replay, or Space to pause. [RUNNING] Record Time: 1532089404.688080 Progress: 6.024680 / 6.024680 play finished. file: 20180720202307.record ``` ## rosbag_to\_record `rosbag_to_record` is a tool which can convert rosbag to recorder file provided by Apollo Cyber RT. Now the tool support following channel: ``` /apollo/perception/obstacles /apollo/planning /apollo/prediction /apollo/canbus/chassis /apollo/control /apollo/guardian /apollo/localization/pose /apollo/perception/traffic_light /apollo/drive_event /apollo/sensor/gnss/odometry /apollo/monitor/static_info /apollo/monitor /apollo/canbus/chassis_detail /apollo/control/pad /apollo/navigation /apollo/routing_request /apollo/routing_response /tf /tf_static /apollo/sensor/conti_radar /apollo/sensor/delphi_esr /apollo/sensor/gnss/best_pose /apollo/sensor/gnss/imu /apollo/sensor/gnss/ins_stat /apollo/sensor/gnss/rtk_eph /apollo/sensor/gnss/rtk_obs /apollo/sensor/velodyne64/compensator/PointCloud2 ``` ### Install and run Launch rosbag_to\_record: ```bash $ source /your-path-to-apollo-install-dir/cyber/setup.bash $ rosbag_to_record Usage: rosbag_to_record input.bag output.record ``` ### Example We can convert [Apollo2.5 demo bag](https://github.com/ApolloAuto/apollo/releases/download/v2.5.0/demo_2.5.bag) to record file. ```bash $ rosbag_to_record demo_2.5.bag demo.record record_file: demo.record version: 1.0 duration: 19.995227 Seconds begin_time: 2018-04-17 06:25:36 end_time: 2018-04-17 06:25:55 size: 28275479 Bytes (26.965598 MB) is_complete: true message_number: 15379 channel_number: 16 channel_info: /apollo/localization/pose 2000 messages : apollo.localization.LocalizationEstimate /tf 4000 messages : apollo.transform.TransformStampeds /apollo/control 2000 messages : apollo.control.ControlCommand /apollo/sensor/gnss/odometry 2000 messages : apollo.localization.Gps /apollo/canbus/chassis 2000 messages : apollo.canbus.Chassis /apollo/sensor/gnss/imu 1999 messages : apollo.drivers.gnss.Imu /apollo/sensor/gnss/rtk_obs 41 messages : apollo.drivers.gnss.EpochObservation /apollo/sensor/gnss/ins_stat 20 messages : apollo.drivers.gnss.InsStat /apollo/sensor/gnss/best_pose 20 messages : apollo.drivers.gnss.GnssBestPose /apollo/perception/obstacles 400 messages : apollo.perception.PerceptionObstacles /apollo/prediction 400 messages : apollo.prediction.PredictionObstacles /apollo/sensor/conti_radar 270 messages : apollo.drivers.ContiRadar /apollo/planning 200 messages : apollo.planning.ADCTrajectory /apollo/monitor/static_info 1 messages : apollo.data.StaticInfo /apollo/sensor/gnss/rtk_eph 25 messages : apollo.drivers.gnss.GnssEphemeris /apollo/monitor 3 messages : apollo.common.monitor.MonitorMessage Conversion finished! Took 0.505623051 seconds in total. ```
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/04_CyberRT/CyberRT_Docker.md
# How to Develop Cyber RT inside Docker on Both x86_64 and ARM64 To make life easier, Apollo maintains Cyber Docker images and a number of scripts to help developers build and play with Cyber RT framework. Cyber Docker images are built upon Ubuntu 18.04, and comes with full support for Cyber RT framework. For those who are interested in Cyber RT only, this would be the ideal point to start with. **Note: Apollo team also maintains ARM64 Cyber Docker images which was tested on Jetson AGX Xavier. The same set of scripts are provided to run both on x86_64 and ARM64 platforms.** In the next section, we will show you how to play with Cyber Docker images. ## Build and Test Cyber RT inside Docker Run the following command to start Cyber Docker container: ```bash bash docker/scripts/cyber_start.sh ``` Or if you are in China, run: ```bash bash docker/scripts/cyber_start.sh -g cn ``` A Docker container named `apollo_cyber_$USER` will be started. **Note**: You will lose all your previous changes in the container if you have ran this command before. Unless you would like to start a fresh Docker environment. To log into the newly started Cyber container: ```bash bash docker/scripts/cyber_into.sh ``` **Note**: you can login and logout Cyber container multiple times as you wish, the Docker environment will stay there until the next time you start another Cyber container. To build Cyber RT only and run unit tests: ```bash ./apollo.sh build cyber ./apollo.sh test cyber ``` Or run with `--config=opt` for an optimized build/test. ```bash ./apollo.sh build --config=opt cyber ./apollo.sh test --config=opt cyber ``` You should be able to see that all the testcases passed.
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/04_CyberRT/CyberRT_Python_API.md
## 1. Background The core functions of Cyber RT are developed in C++. We also provide more python interfaces to help developers build their own utilities for specific projects. ## 2. Cyber RT Python Interfaces The python interfaces of Cyber RT are wrapper the corresponding C++ interfaces. The implementation doesn't rely on other third-party tools, e.g. swig, which makes it easier to maintain. ## 3. Overview of Python Interfaces in Cyber RT So far, the python interfaces covers: * access the information of channels * server/client communication * query informatoin in record files * read and write from/to record files * Time/Duration/Rate related operations * Timer ### 3.1 Read/Write of Channels Steps shown as below: 1. First create a Node; 2. Create corresponding reader or writer; 3. If write to a channel, use write interface in writer. 4. If read from a channel, use the spin interface in the node, and process the messages in your callback function The interfaces are shown below: ```python class Node: """ Class for cyber Node wrapper. """ def create_writer(self, name, data_type, qos_depth=1): """ create a topic writer for send message to topic. @param self @param name str: topic name @param data_type proto: message class for serialization """ def create_reader(self, name, data_type, callback, args=None): """ create a topic reader for receive message from topic. @param self @param name str: topic name @param data_type proto: message class for serialization @callback fn: function to call (fn(data)) when data is received. If args is set, the function must accept the args as a second argument, i.e. fn(data, args) @args any: additional arguments to pass to the callback """ def create_client(self, name, request_data_type, response_data_type): """ """ def create_service(self, name, req_data_type, res_data_type, callback, args=None): def spin(self): """ spin in wait and process message. @param self """ class Writer(object): """ Class for cyber writer wrapper. """ def write(self, data): """ writer msg string """ ``` ### 3.2 Record Interfaces Read from record: 1. Create a RecordReader; 2. Read messages from Record; Write to record: 1. Create a RecordWriter 2. Write messages to record; The interfaces are shown below: ```python class RecordReader(object): """ Class for cyber RecordReader wrapper. """ def read_messages(self, start_time=0, end_time=18446744073709551615): """ read message from bag file. @param self @param start_time: @param end_time: @return: generator of (message, data_type, timestamp) """ def get_messagenumber(self, channel_name): """ return message count. """ def get_messagetype(self, channel_name): """ return message type. """ def get_protodesc(self, channel_name): """ return message protodesc. """ def get_headerstring(self): """ return message header string. """ def reset(self): """ return reset. """ return _CYBER_RECORD.PyRecordReader_Reset(self.record_reader) def get_channellist(self): """ return channel list. """ return _CYBER_RECORD.PyRecordReader_GetChannelList(self.record_reader) class RecordWriter(object): """ Class for cyber RecordWriter wrapper. """ def open(self, path): """ open record file for write. """ def write_channel(self, channel_name, type_name, proto_desc): """ writer channel by channelname,typename,protodesc """ def write_message(self, channel_name, data, time, raw = True): """ writer msg:channelname,data,time,is data raw """ def set_size_fileseg(self, size_kilobytes): """ return filesegment size. """ def set_intervaltime_fileseg(self, time_sec): """ return file interval time. """ def get_messagenumber(self, channel_name): """ return message count. """ def get_messagetype(self, channel_name): """ return message type. """ def get_protodesc(self, channel_name): """ return message protodesc. """ ``` ### 3.3 Time Interfaces ```python class Time(object): @staticmethod def now(): time_now = Time(_CYBER_TIME.PyTime_now()) return time_now @staticmethod def mono_time(): mono_time = Time(_CYBER_TIME.PyTime_mono_time()) return mono_time def to_sec(self): return _CYBER_TIME.PyTime_to_sec(self.time) def to_nsec(self): return _CYBER_TIME.PyTime_to_nsec(self.time) def sleep_until(self, nanoseconds): return _CYBER_TIME.PyTime_sleep_until(self.time, nanoseconds) ``` ### 3.4 Timer Interfaces ```python class Timer(object): def set_option(self, period, callback, oneshot=0): """ set the option of timer. @param period The period of the timer, unit is ms. @param callback The tasks that the timer needs to perform. @param oneshot 1:perform the callback only after the first timing cycle 0:perform the callback every timed period """ def start(self): def stop(self): ``` ## 4. Examples ### 4.1 Read from Channel (in cyber/python/cyber_py3/examples/listener.py) ```python from cyber_py3 import cyber from cyber.proto.unit_test_pb2 import ChatterBenchmark def callback(data): """ Reader message callback. """ print("=" * 80) print("py:reader callback msg->:") print(data) print("=" * 80) def test_listener_class(): """ Reader message. """ print("=" * 120) test_node = cyber.Node("listener") test_node.create_reader("channel/chatter", ChatterBenchmark, callback) test_node.spin() if __name__ == '__main__': cyber.init() test_listener_class() cyber.shutdown() ``` ### 4.2 Write to Channel(in cyber/python/cyber_py3/examples/talker.py) ```python import time from cyber_py3 import cyber from cyber.proto.unit_test_pb2 import ChatterBenchmark def test_talker_class(): """ Test talker. """ msg = ChatterBenchmark() msg.content = "py:talker:send Alex!" msg.stamp = 9999 msg.seq = 0 print(msg) test_node = cyber.Node("node_name1") g_count = 1 writer = test_node.create_writer("channel/chatter", ChatterBenchmark, 6) while not cyber.is_shutdown(): time.sleep(1) g_count = g_count + 1 msg.seq = g_count msg.content = "I am python talker." print("=" * 80) print("write msg -> %s" % msg) writer.write(msg) if __name__ == '__main__': cyber.init("talker_sample") test_talker_class() cyber.shutdown() ``` ### 4.3 Read and Write Messages from/to Record File(in cyber/python/cyber_py3/examples/record.py) ```python """ Module for example of record. Run with: bazel run //cyber/python/cyber_py3/examples:record """ import time from google.protobuf.descriptor_pb2 import FileDescriptorProto from cyber.proto.unit_test_pb2 import Chatter from cyber.python.cyber_py3 import record from modules.common.util.testdata.simple_pb2 import SimpleMessage MSG_TYPE = "apollo.common.util.test.SimpleMessage" MSG_TYPE_CHATTER = "apollo.cyber.proto.Chatter" def test_record_writer(writer_path): """ Record writer. """ fwriter = record.RecordWriter() fwriter.set_size_fileseg(0) fwriter.set_intervaltime_fileseg(0) if not fwriter.open(writer_path): print('Failed to open record writer!') return print('+++ Begin to writer +++') # Writer 2 SimpleMessage msg = SimpleMessage() msg.text = "AAAAAA" file_desc = msg.DESCRIPTOR.file proto = FileDescriptorProto() file_desc.CopyToProto(proto) proto.name = file_desc.name desc_str = proto.SerializeToString() print(msg.DESCRIPTOR.full_name) fwriter.write_channel( 'simplemsg_channel', msg.DESCRIPTOR.full_name, desc_str) fwriter.write_message('simplemsg_channel', msg, 990, False) fwriter.write_message('simplemsg_channel', msg.SerializeToString(), 991) # Writer 2 Chatter msg = Chatter() msg.timestamp = 99999 msg.lidar_timestamp = 100 msg.seq = 1 file_desc = msg.DESCRIPTOR.file proto = FileDescriptorProto() file_desc.CopyToProto(proto) proto.name = file_desc.name desc_str = proto.SerializeToString() print(msg.DESCRIPTOR.full_name) fwriter.write_channel('chatter_a', msg.DESCRIPTOR.full_name, desc_str) fwriter.write_message('chatter_a', msg, 992, False) msg.seq = 2 fwriter.write_message("chatter_a", msg.SerializeToString(), 993) fwriter.close() def test_record_reader(reader_path): """ Record reader. """ freader = record.RecordReader(reader_path) time.sleep(1) print('+' * 80) print('+++ Begin to read +++') count = 0 for channel_name, msg, datatype, timestamp in freader.read_messages(): count += 1 print('=' * 80) print('read [%d] messages' % count) print('channel_name -> %s' % channel_name) print('msgtime -> %d' % timestamp) print('msgnum -> %d' % freader.get_messagenumber(channel_name)) print('msgtype -> %s' % datatype) print('message is -> %s' % msg) print('***After parse(if needed),the message is ->') if datatype == MSG_TYPE: msg_new = SimpleMessage() msg_new.ParseFromString(msg) print(msg_new) elif datatype == MSG_TYPE_CHATTER: msg_new = Chatter() msg_new.ParseFromString(msg) print(msg_new) if __name__ == '__main__': test_record_file = "/tmp/test_writer.record" print('Begin to write record file: {}'.format(test_record_file)) test_record_writer(test_record_file) print('Begin to read record file: {}'.format(test_record_file)) test_record_reader(test_record_file) ```
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/04_CyberRT/CyberRT_FAQs.md
# Apollo Cyber RT FAQs ## What is Apollo Cyber RT? Apollo's Cyber RT is an open source runtime framework designed specifically for autonomous driving scenarios. Based on a centralized computing model, it is highly optimized for performance, latency, and data throughput. --- ## Why did we decide to work on a new runtime framework? - During years of development of autonomous driving technologies, we have learned a lot from our previous experience with Apollo. In autonomous driving scenarious, we need an effective centralized computing model, with demands for high performance, including high concurrency, low latency and high throughput。 - The industry is evolving, so does Apollo. Going forward, Apollo has already moved from development to productization, with volume deployments in the real world, we see the demands for the highest robustness and high performance. That’s why we spent years of building Apollo Cyber RT, which addresses that requirements of autonomous driving solutions. --- ## What are the advantages of the new runtime framework? - Accelerate development - Well defined task interface with data fusion - Array of development tools - Large set of sensor drivers - Simplify deployment - Efficient and adaptive message communication - Configurable user level scheduler with resource awareness - Portable with fewer dependencies - Empower your own autonomous vehicles - The default open source runtime framework - Building blocks specifically designed for autonomous driving - Plug and play your own AD system --- ## Can we still use the data that we have collected? - If the data you have collected is compatible with the previous versions of Apollo, you could use our recommended conversion tools to make the data compliant with our new runtime framework - If you created a customized data format, then the previously generated data will not be supported by the new runtime framework --- ## Will you continue to support ROS? We will continue to support previous Apollo releases (3.0 and before) based on ROS. We do appreciate you continue growing with us and highly encourage you to move to Apollo 3.5. While we know that some of our developers would prefer to work on ROS, we do hope you will understand why Apollo as a team cannot continue to support ROS in our future releases as we strive to work towards developing a more holistic platform that meets automotive standards. --- ## Will Apollo Cyber RT affect regular code development? If you have not modified anything at runtime framework layer and have only worked on Apollo's module code base, you will not be affected by the introduction of our new runtime framework as most of time you would only need to re-interface the access of the input and output data. --- ## Recommended setup for Apollo Cyber RT - The runtime framework also uses apollo's docker environment - It is recommended to run source setup.bash when opening a new terminal - Fork and clone the Apollo repo with the new framework code which can be found at [apollo/cyber](../../cyber/) ## How to enable SHM to decrease the latency? To decrease number of threads, the readable notification mechanism of shared memory was changed in CyberRT. The default mechanism is UDP multicast, and system call(sendto) will cause some latency. So, to decrease the latency, you can change the mechanism, The steps are listed as following: 1. update the CyberRT to the latest version; 2. uncomment the transport_conf in [cyber.pb.conf](../../cyber/conf/cyber.pb.conf); 3. change **notifier_type** of **shm_conf** from "multicast" to "condition"; 4. build CyberRT with opt like `bazel build -c opt --copt=-fpic //cyber/...`; 5. run talker and listener; Note:You can select the corresponding transmission method according to the relationship between nodes.For example, the default configuration is **INTRA** in the process, **SHM** between the host process, and **RTPS** across the host. Of course you can change all three to RTPS. Or change `same_proc` and `diff_proc` to **SHM**; ## How to use the no serialization message? The message types supported by Cyber RT include both serializable structured data like protobuf and raw sequence of bytes. You can refer the sample code: - apollo::cyber::message::RawMessage - talker: https://github.com/gruminions/apollo/blob/record/cyber/examples/talker.cc - listener: https://github.com/gruminions/apollo/blob/record/cyber/examples/listener.cc ## How to configure multiple hosts communication? Make sure the two hosts(or more) are under the same network segment of the local area network, Like `192.168.10.6` and `192.168.10.7`. You just need to modify `CYBER_IP` of `/apollo/cyber/setup.bash` ```bash export CYBER_IP=127.0.0.1 ``` Suppose you have two hosts A and B,the ip of A is `192.168.10.6`, and the ip of B is `192.168.10.7`. Then set `CYBER_IP` to `192.168.10.6` on host A, and set `CYBER_IP` to `192.168.10.7` on host B. Now host A can communicate with host B. --- More FAQs to follow...
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/04_CyberRT/CyberRT_API_for_Developers.md
# Cyber RT API for Developers This document provides an extensive technical deep dive into how to create, manipulate and use Cyber RT's API. ## Table of Contents - [Talker-Listener](#Talker-Listener) - [Service Creation and Use](#Service-Creation-and-Use) - [Param parameter service](#Param-parameter-service) - [Log API](#LOG-API) - [Building a module based on Component](#Building-a-module-based-on-Component) - [Launch](#Launch) - [Timer](#timer) - [Time API](#use-of-time) - [Record file: Read and Write](#Record-file-Read-and-Write) - [C++ API Directory](##API-Directory) - [Node](#node-api) - [Writer](#writer-api) - [Client](#client-api) - [Parameter](#parameter-api) - [Timer](#timer-api) - [Time](#timer-api) - [Duration](#duration-api) - [Rate](#rate-api) - [RecordReader](#recordreader-api) - [RecordWriter](#recordwriter-api) ## Talker-Listener The first part of demonstrating CyberRT API is to understand the Talker/Listener example. Following are three essential concepts: node (basic unit), reader(facility to read message) and writer(facility to write message) of the example. ### Create a node In the CyberRT framework, the node is the most fundamental unit, similar to the role of a `handle`. When creating a specific functional object (writer, reader, etc.), you need to create it based on an existing node instance. The node creation interface is as follows: ```cpp std::unique_ptr<Node> apollo::cyber::CreateNode(const std::string& node_name, const std::string& name_space = ""); ``` - Parameters: - node_name: name of the node, globally unique identifier - name_space: name of the space where the node is located > name_space is empty by default. It is the name of the space concatenated with node_name. The format is `/namespace/node_name` - Return value - An exclusive smart pointer to Node - Error Conditions - when `cyber::Init()` has not called, the system is in an uninitialized state, unable to create a node, return nullptr ### Create a writer The writer is the basic facility used in CyberRT to send messages. Every writer corresponds to a channel with a specific data type. The writer is created by the `CreateWriter` interface in the node class. The interfaces are listed as below: ```cpp template <typename MessageT> auto CreateWriter(const std::string& channel_name) -> std::shared_ptr<Writer<MessageT>>; template <typename MessageT> auto CreateWriter(const proto::RoleAttributes& role_attr) -> std::shared_ptr<Writer<MessageT>>; ``` - Parameters: - channel_name: the name of the channel to write to - MessageT: The type of message to be written out - Return value - Shared pointer to the Writer object ### Create a reader The reader is the basic facility used in cyber to receive messages. Reader has to be bound to a callback function when it is created. When a new message arrives in the channel, the callback will be called. The reader is created by the `CreateReader` interface of the node class. The interfaces are listed as below: ```cpp template <typename MessageT> auto CreateReader(const std::string& channel_name, const std::function<void(const std::shared_ptr<MessageT>&)>& reader_func) -> std::shared_ptr<Reader<MessageT>>; template <typename MessageT> auto CreateReader(const ReaderConfig& config, const CallbackFunc<MessageT>& reader_func = nullptr) -> std::shared_ptr<cyber::Reader<MessageT>>; template <typename MessageT> auto CreateReader(const proto::RoleAttributes& role_attr, const CallbackFunc<MessageT>& reader_func = nullptr) -> std::shared_ptr<cyber::Reader<MessageT>>; ``` - Parameters: - MessageT: The type of message to read - channel_name: the name of the channel to receive from - reader_func: callback function to process the messages - Return value - Shared pointer to the Reader object ### Code Example #### Talker (cyber/examples/talker.cc) ```cpp #include "cyber/cyber.h" #include "cyber/proto/chatter.pb.h" #include "cyber/time/rate.h" #include "cyber/time/time.h" using apollo::cyber::Rate; using apollo::cyber::Time; using apollo::cyber::proto::Chatter; int main(int argc, char *argv[]) { // init cyber framework apollo::cyber::Init(argv[0]); // create talker node std::shared_ptr<apollo::cyber::Node> talker_node( apollo::cyber::CreateNode("talker")); // create talker auto talker = talker_node->CreateWriter<Chatter>("channel/chatter"); Rate rate(1.0); while (apollo::cyber::OK()) { static uint64_t seq = 0; auto msg = std::make_shared<apollo::cyber::proto::Chatter>(); msg->set_timestamp(Time::Now().ToNanosecond()); msg->set_lidar_timestamp(Time::Now().ToNanosecond()); msg->set_seq(seq++); msg->set_content("Hello, apollo!"); talker->Write(msg); AINFO << "talker sent a message!"; rate.Sleep(); } return 0; } ``` #### Listener (cyber/examples/listener.cc) ```cpp #include "cyber/cyber.h" #include "cyber/proto/chatter.pb.h" void MessageCallback( const std::shared_ptr<apollo::cyber::proto::Chatter>& msg) { AINFO << "Received message seq-> " << msg->seq(); AINFO << "msgcontent->" << msg->content(); } int main(int argc, char *argv[]) { // init cyber framework apollo::cyber::Init(argv[0]); // create listener node auto listener_node = apollo::cyber::CreateNode("listener"); // create listener auto listener = listener_node->CreateReader<apollo::cyber::proto::Chatter>( "channel/chatter", MessageCallback); apollo::cyber::WaitForShutdown(); return 0; } ``` #### Bazel BUILD file(cyber/samples/BUILD) ```python cc_binary( name = "talker", srcs = [ "talker.cc", ], deps = [ "//cyber", "//cyber/examples/proto:examples_cc_proto", ], ) cc_binary( name = "listener", srcs = [ "listener.cc", ], deps = [ "//cyber", "//cyber/examples/proto:examples_cc_proto", ], ) ``` #### Build and Run - Build: bazel build cyber/examples/… - Run talker/listener in different terminals: - ./bazel-bin/cyber/examples/talker - ./bazel-bin/cyber/examples/listener - Examine the results: you should see message printing out on listener. ## Service Creation and Use ### Introduction In an autonomous driving system, there are many scenarios that require more from module communication than just sending or receiving messages. Service is another way of communication between nodes. Unlike channel, service implements `two-way` communication, e.g. a node obtains a response by sending a request. This section introduces the `service` module in CyberRT API with examples. ### Demo - Example Problem: create a client-server model that pass Driver.proto back and forth. When a request is sent in by the client, the server parses/processes the request and returns the response. The implementation of the demo mainly includes the following steps. #### Define request and response messages All messages in cyber are in the `protobuf` format. Any protobuf message with serialize/deserialize interfaces can be used as the service request and response message. `Driver` in examples.proto is used as service request and response in this example: ```protobuf // filename: examples.proto syntax = "proto2"; package apollo.cyber.examples.proto; message Driver { optional string content = 1; optional uint64 msg_id = 2; optional uint64 timestamp = 3; }; ``` #### Create a service and a client ```cpp // filename: cyber/examples/service.cc #include "cyber/cyber.h" #include "cyber/examples/proto/examples.pb.h" using apollo::cyber::examples::proto::Driver; int main(int argc, char* argv[]) { apollo::cyber::Init(argv[0]); std::shared_ptr<apollo::cyber::Node> node( apollo::cyber::CreateNode("start_node")); auto server = node->CreateService<Driver, Driver>( "test_server", [](const std::shared_ptr<Driver>& request, std::shared_ptr<Driver>& response) { AINFO << "server: I am driver server"; static uint64_t id = 0; ++id; response->set_msg_id(id); response->set_timestamp(0); }); auto client = node->CreateClient<Driver, Driver>("test_server"); auto driver_msg = std::make_shared<Driver>(); driver_msg->set_msg_id(0); driver_msg->set_timestamp(0); while (apollo::cyber::OK()) { auto res = client->SendRequest(driver_msg); if (res != nullptr) { AINFO << "client: response: " << res->ShortDebugString(); } else { AINFO << "client: service may not ready."; } sleep(1); } apollo::cyber::WaitForShutdown(); return 0; } ``` #### Bazel build file ```python cc_binary( name = "service", srcs = [ "service.cc", ], deps = [ "//cyber", "//cyber/examples/proto:examples_cc_proto", ], ) ``` #### Build and run - Build service/client: bazel build cyber/examples/… - Run: ./bazel-bin/cyber/examples/service - Examining result: you should see content below in apollo/data/log/service.INFO ``` txt I1124 16:36:44.568845 14965 service.cc:30] [service] server: i am driver server I1124 16:36:44.569031 14949 service.cc:43] [service] client: response: msg_id: 1 timestamp: 0 I1124 16:36:45.569514 14966 service.cc:30] [service] server: i am driver server I1124 16:36:45.569932 14949 service.cc:43] [service] client: response: msg_id: 2 timestamp: 0 I1124 16:36:46.570627 14967 service.cc:30] [service] server: i am driver server I1124 16:36:46.571024 14949 service.cc:43] [service] client: response: msg_id: 3 timestamp: 0 I1124 16:36:47.571566 14968 service.cc:30] [service] server: i am driver server I1124 16:36:47.571962 14949 service.cc:43] [service] client: response: msg_id: 4 timestamp: 0 I1124 16:36:48.572634 14969 service.cc:30] [service] server: i am driver server I1124 16:36:48.573030 14949 service.cc:43] [service] client: response: msg_id: 5 timestamp: 0 ``` ### Precautions - When registering a service, note that duplicate service names are not allowed - The node name applied when registering the server and client should not be duplicated either ## Parameter Service The Parameter Service is used for shared data between nodes, and provides basic operations such as `set`, `get`, and `list`. The Parameter Service is based on the `Service` implementation and contains service and client. ### Parameter Object #### Supported Data types All parameters passed through cyber are `apollo::cyber::Parameter` objects, the table below lists the 5 supported parameter types. Parameter type | C++ data type | protobuf data type :------------- | :------------- | :-------------- apollo::cyber::proto::ParamType::INT | int64_t | int64 apollo::cyber::proto::ParamType::DOUBLE | double | double apollo::cyber::proto::ParamType::BOOL | bool |bool apollo::cyber::proto::ParamType::STRING | std::string | string apollo::cyber::proto::ParamType::PROTOBUF | std::string | string apollo::cyber::proto::ParamType::NOT_SET | - | - Besides the 5 types above, Parameter also supports interface with protobuf object as incoming parameter. Post performing serialization processes the object and converts it to the STRING type for transfer. #### Creating the Parameter Object Supported constructors: ```cpp Parameter(); // Name is empty, type is NOT_SET explicit Parameter(const Parameter& parameter); explicit Parameter(const std::string& name); // type为NOT_SET Parameter(const std::string& name, const bool bool_value); Parameter(const std::string& name, const int int_value); Parameter(const std::string& name, const int64_t int_value); Parameter(const std::string& name, const float double_value); Parameter(const std::string& name, const double double_value); Parameter(const std::string& name, const std::string& string_value); Parameter(const std::string& name, const char* string_value); Parameter(const std::string& name, const std::string& msg_str, const std::string& full_name, const std::string& proto_desc); Parameter(const std::string& name, const google::protobuf::Message& msg); ``` Sample code of using Parameter object: ```cpp Parameter a("int", 10); Parameter b("bool", true); Parameter c("double", 0.1); Parameter d("string", "cyber"); Parameter e("string", std::string("cyber")); // proto message Chatter Chatter chatter; Parameter f("chatter", chatter); std::string msg_str(""); chatter.SerializeToString(&msg_str); std::string msg_desc(""); ProtobufFactory::GetDescriptorString(chatter, &msg_desc); Parameter g("chatter", msg_str, Chatter::descriptor()->full_name(), msg_desc); ``` #### Interface and Data Reading Interface list: ```cpp inline ParamType type() const; inline std::string TypeName() const; inline std::string Descriptor() const; inline const std::string Name() const; inline bool AsBool() const; inline int64_t AsInt64() const; inline double AsDouble() const; inline const std::string AsString() const; std::string DebugString() const; template <typename Type> typename std::enable_if<std::is_base_of<google::protobuf::Message, Type>::value, Type>::type value() const; template <typename Type> typename std::enable_if<std::is_integral<Type>::value && !std::is_same<Type, bool>::value, Type>::type value() const; template <typename Type> typename std::enable_if<std::is_floating_point<Type>::value, Type>::type value() const; template <typename Type> typename std::enable_if<std::is_convertible<Type, std::string>::value, const std::string&>::type value() const; template <typename Type> typename std::enable_if<std::is_same<Type, bool>::value, bool>::type value() const; ``` An example of how to use those interfaces: ```cpp Parameter a("int", 10); a.Name(); // return int a.Type(); // return apollo::cyber::proto::ParamType::INT a.TypeName(); // return string: INT a.DebugString(); // return string: {name: "int", type: "INT", value: 10} int x = a.AsInt64(); // x = 10 x = a.value<int64_t>(); // x = 10 x = a.AsString(); // Undefined behavior, error log prompt f.TypeName(); // return string: chatter auto chatter = f.value<Chatter>(); ``` ### Parameter Service If a node wants to provide a Parameter Service to other nodes, then you need to create a `ParameterService`. ```cpp /** * @brief Construct a new ParameterService object * * @param node shared_ptr of the node handler */ explicit ParameterService(const std::shared_ptr<Node>& node); ``` Since all parameters are stored in the parameter service object, the parameters can be manipulated directly in the ParameterService without sending a service request. **Setting parameters:** ```cpp /** * @brief Set the Parameter object * * @param parameter parameter to be set */ void SetParameter(const Parameter& parameter); ``` **Getting parameters:** ```cpp /** * @brief Get the Parameter object * * @param param_name * @param parameter the pointer to store * @return true * @return false call service fail or timeout */ bool GetParameter(const std::string& param_name, Parameter* parameter); ``` **Getting the list of parameters:** ```cpp /** * @brief Get all the Parameter objects * * @param parameters pointer of vector to store all the parameters * @return true * @return false call service fail or timeout */ bool ListParameters(std::vector<Parameter>* parameters); ``` ### Parameter Client If a node wants to use parameter services of other nodes, you need to create a `ParameterClient`. ```cpp /** * @brief Construct a new ParameterClient object * * @param node shared_ptr of the node handler * @param service_node_name node name which provide a param services */ ParameterClient(const std::shared_ptr<Node>& node, const std::string& service_node_name); ``` You could also perform `SetParameter`, `GetParameter` and `ListParameters` mentioned under [Parameter Service](#Parameter-Service). ### Demo - example ```cpp #include "cyber/cyber.h" #include "cyber/parameter/parameter_client.h" #include "cyber/parameter/parameter_server.h" using apollo::cyber::Parameter; using apollo::cyber::ParameterServer; using apollo::cyber::ParameterClient; int main(int argc, char** argv) { apollo::cyber::Init(*argv); std::shared_ptr<apollo::cyber::Node> node = apollo::cyber::CreateNode("parameter"); auto param_server = std::make_shared<ParameterServer>(node); auto param_client = std::make_shared<ParameterClient>(node, "parameter"); param_server->SetParameter(Parameter("int", 1)); Parameter parameter; param_server->GetParameter("int", &parameter); AINFO << "int: " << parameter.AsInt64(); param_client->SetParameter(Parameter("string", "test")); param_client->GetParameter("string", &parameter); AINFO << "string: " << parameter.AsString(); param_client->GetParameter("int", &parameter); AINFO << "int: " << parameter.AsInt64(); return 0; } ``` #### Build and run - Build: bazel build cyber/examples/… - Run: ./bazel-bin/cyber/examples/paramserver ## Log API ### Log library Cyber log library is built on top of glog. The following header files need to be included: ```cpp #include "cyber/common/log.h" #include "cyber/init.h" ``` ### Log configuration Default global config path: cyber/setup.bash The configs below could be modified by devloper: ``` export GLOG_log_dir=/apollo/data/log export GLOG_alsologtostderr=0 export GLOG_colorlogtostderr=1 export GLOG_minloglevel=0 ``` ### Log initialization Call the Init method at the code entry to initialize the log: ```cpp++ apollo::cyber::cyber::Init(argv[0]) is initialized. If no macro definition is made in the previous component, the corresponding log is printed to the binary log. ``` ### Log output macro Log library is encapsulated in Log printing macros. The related log macros are used as follows: ```cpp ADEBUG << "hello cyber."; AINFO << "hello cyber."; AWARN << "hello cyber."; AERROR << "hello cyber."; AFATAL << "hello cyber."; ``` ### Log format The format is `<MODULE_NAME>.log.<LOG_LEVEL>.<datetime>.<process_id>` ### About log files Currently, the only different output behavior from default glog is that different log levels of a module will be written into the same log file. ## Building a module based on Component ### Key concepts #### 1. Component The component is the base class that Cyber RT provides to build application modules. Each specific application module can inherit the Component class and define its own `Init` and `Proc` functions so that it can be loaded into the Cyber framework. #### 2. Binary vs Component There are two options to use Cyber RT framework for applications: - Binary based: the application is compiled separately into a binary, which communicates with other cyber modules by creating its own `Reader` and `Writer`. - Component based: the application is compiled into a Shared Library. By inheriting the Component class and writing the corresponding dag description file, the Cyber RT framework will load and run the application dynamically. ##### The essential Component interface - The component's `Init()` function is like the main function that does some initialization of the algorithm. - Component's `Proc()` function works like Reader's callback function that is called by the framework when a message arrives. ##### Advantages of using Component - Component can be loaded into different processes through the launch file, and the deployment is flexible. - Component can change the received channel name by modifying the dag file without recompiling. - Component supports receiving multiple types of data. - Component supports providing multiple fusion strategies. #### 3. Dag file format An example dag file: ```protobuf # Define all coms in DAG streaming. module_config { module_library : "lib/libperception_component.so" components { class_name : "PerceptionComponent" config { name : "perception" readers { channel: "perception/channel_name" } } } timer_components { class_name : "DriverComponent" config { name : "driver" interval : 100 } } } ``` - **module_library**: If you want to load the .so library the root directory is the working directory of cyber (the same directory of `setup.bash`) - **components & timer_component**: Select the base component class type that needs to be loaded. - **class_name**: the name of the component class to load - **name**: the loaded class_name as the identifier of the loading example - **readers**: Data received by the current component, supporting 1-3 channels of data. ### Demo - examples #### Common_component_example(cyber/examples/common_component_example/*) Header definition(common_component_example.h) ```cpp #include <memory> #include "cyber/class_loader/class_loader.h" #include "cyber/component/component.h" #include "cyber/examples/proto/examples.pb.h" using apollo::cyber::examples::proto::Driver; using apollo::cyber::Component; using apollo::cyber::ComponentBase; class Commontestcomponent : public Component<Driver, Driver> { public: bool Init() override; bool Proc(const std::shared_ptr<Driver>& msg0, const std::shared_ptr<Driver>& msg1) override; }; CYBER_REGISTER_COMPONENT(Commontestcomponent) ``` Cpp file implementation(common_component_example.cc) ```cpp #include "cyber/examples/common_component_smaple/common_component_example.h" #include "cyber/class_loader/class_loader.h" #include "cyber/component/component.h" bool Commontestcomponent::Init() { AINFO << "Commontest component init"; return true; } bool Commontestcomponent::Proc(const std::shared_ptr<Driver>& msg0, const std::shared_ptr<Driver>& msg1) { AINFO << "Start commontest component Proc [" << msg0->msg_id() << "] [" << msg1->msg_id() << "]"; return true; } ``` #### Timer_component_example(cyber/examples/timer_component_example/*) Header definition(timer_component_example.h) ```cpp #include <memory> #include "cyber/class_loader/class_loader.h" #include "cyber/component/component.h" #include "cyber/component/timer_component.h" #include "cyber/examples/proto/examples.pb.h" using apollo::cyber::examples::proto::Driver; using apollo::cyber::Component; using apollo::cyber::ComponentBase; using apollo::cyber::TimerComponent; using apollo::cyber::Writer; class TimertestComponent : public TimerComponent { public: bool Init() override; bool Proc() override; private: std::shared_ptr<Writer<Driver>> driver_writer_ = nullptr; }; CYBER_REGISTER_COMPONENT(TimertestComponent) ``` Cpp file implementation(timer_component_example.cc) ```cpp #include "cyber/examples/timer_component_example/timer_component_example.h" #include "cyber/class_loader/class_loader.h" #include "cyber/component/component.h" #include "cyber/examples/proto/examples.pb.h" bool TimertestComponent::Init() { driver_writer_ = node_->CreateWriter<Driver>("/carstatus/channel"); return true; } bool TimertestComponent::Proc() { static int i = 0; auto out_msg = std::make_shared<Driver>(); out_msg->set_msg_id(i++); driver_writer_->Write(out_msg); AINFO << "timertestcomponent: Write drivermsg->" << out_msg->ShortDebugString(); return true; } ``` #### Build and run Use timertestcomponent as example: - Build: bazel build cyber/examples/timer_component_smaple/… - Run: mainboard -d cyber/examples/timer_component_smaple/timer.dag ### Precautions - Component needs to be registered to load the class through SharedLibrary. The registration interface looks like: ```cpp CYBER_REGISTER_COMPONENT(DriverComponent) ``` If you use a namespace when registering, you also need to add a namespace when you define it in the dag file. - The configuration files of the Component and TimerComponent are different, please be careful not to mix the two up. ## Launch **cyber_launch** is the launcher of the Cyber RT framework. It starts multiple mainboards according to the launch file, and loads different components into different mainboards according to the dag file. cyber_launch supports two scenarios for dynamically loading components or starting Binary programs in a child process. ### Launch File Format ```xml <cyber> <module> <name>driver</name> <dag_conf>driver.dag</dag_conf> <process_name></process_name> <exception_handler>exit</exception_handler> </module> <module> <name>perception</name> <dag_conf>perception.dag</dag_conf> <process_name></process_name> <exception_handler>respawn</exception_handler> </module> <module> <name>planning</name> <dag_conf>planning.dag</dag_conf> <process_name></process_name> </module> </cyber> ``` **Module**: Each loaded component or binary is a module - **name** is the loaded module name - **dag_conf** is the name of the corresponding dag file of the component - **process_name** is the name of the mainboard process once started, and the same component of process_name will be loaded and run in the same process. - **exception_handler** is the handler method when the exception occurs in the process. The value can be exit or respawn listed below. - exit, which means that the entire process needs to stop running when the current process exits abnormally. - respawn, the current process needs to be restarted after abnormal exit. Start this process. If there is no such thing as it is empty, it means no treatment. Can be controlled by the user according to the specific conditions of the process ## Timer Timer can be used to create a timed task to run on a periodic basis, or to run only once ### Timer Interface ```cpp /** * @brief Construct a new Timer object * * @param period The period of the timer, unit is ms * @param callback The tasks that the timer needs to perform * @param oneshot True: perform the callback only after the first timing cycle * False: perform the callback every timed period */ Timer(uint32_t period, std::function<void()> callback, bool oneshot); ``` Or you could encapsulate the parameters into a timer option as follows: ```cpp struct TimerOption { uint32_t period; // The period of the timer, unit is ms std::function<void()> callback; // The tasks that the timer needs to perform bool oneshot; // True: perform the callback only after the first timing cycle // False: perform the callback every timed period }; /** * @brief Construct a new Timer object * * @param opt Timer option */ explicit Timer(TimerOption opt); ``` ### Start Timer After creating a Timer instance, you must call `Timer::Start()` to start the timer. ### Stop Timer When you need to manually stop a timer that has already started, you can call the `Timer::Stop()` interface. ### Demo - example ```cpp #include <iostream> #include "cyber/cyber.h" int main(int argc, char** argv) { cyber::Init(argv[0]); // Print current time every 100ms cyber::Timer timer(100, [](){ std::cout << cyber::Time::Now() << std::endl; }, false); timer.Start() sleep(1); timer.Stop(); } ``` ## Time API Time is a class used to manage time; it can be used for current time acquisition, time-consuming calculation, time conversion, and so on. The time interfaces are as follows: ```cpp // constructor, passing in a different value to construct Time Time(uint64_t nanoseconds); //uint64_t, in nanoseconds Time(int nanoseconds); // int type, unit: nanoseconds Time(double seconds); // double, in seconds Time(uint32_t seconds, uint32_t nanoseconds); // seconds seconds + nanoseconds nanoseconds Static Time Now(); // Get the current time Double ToSecond() const; // convert to seconds Uint64_t ToNanosecond() const; // Convert to nanoseconds Std::string ToString() const; // Convert to a string in the format "2018-07-10 20:21:51.123456789" Bool IsZero() const; // Determine if the time is 0 ``` A code example can be seen below: ```cpp #include <iostream> #include "cyber/cyber.h" #include "cyber/duration.h" int main(int argc, char** argv) { cyber::Init(argv[0]); Time t1(1531225311123456789UL); std::cout << t1.ToString() << std::endl; // 2018-07-10 20:21:51.123456789 // Duration time interval Time t1(100); Duration d(200); Time t2(300); assert(d == (t1-t2)); // true } ``` ## Record file: Read and Write ### Reading the Reader file **RecordReader** is the component used to read messages in the cyber framework. Each RecordReader can open an existing record file through the `Open` method, and the thread will asynchronously read the information in the record file. The user only needs to execute ReadMessage to extract the latest message in RecordReader, and then get the message information through GetCurrentMessageChannelName, GetCurrentRawMessage, GetCurrentMessageTime. **RecordWriter** is the component used to record messages in the cyber framework. Each RecordWriter can create a new record file through the Open method. The user only needs to execute WriteMessage and WriteChannel to write message and channel information, and the writing process is asynchronous. ### Demo - example(cyber/examples/record.cc) Write 100 RawMessage to`TEST_FILE` through `test_write` method, then read them out through `test_read` method. ```cpp #include <string> #include "cyber/cyber.h" #include "cyber/message/raw_message.h" #include "cyber/proto/record.pb.h" #include "cyber/record/record_message.h" #include "cyber/record/record_reader.h" #include "cyber/record/record_writer.h" using ::apollo::cyber::record::RecordReader; using ::apollo::cyber::record::RecordWriter; using ::apollo::cyber::record::RecordMessage; using apollo::cyber::message::RawMessage; const char CHANNEL_NAME_1[] = "/test/channel1"; const char CHANNEL_NAME_2[] = "/test/channel2"; const char MESSAGE_TYPE_1[] = "apollo.cyber.proto.Test"; const char MESSAGE_TYPE_2[] = "apollo.cyber.proto.Channel"; const char PROTO_DESC[] = "1234567890"; const char STR_10B[] = "1234567890"; const char TEST_FILE[] = "test.record"; void test_write(const std::string &writefile) { RecordWriter writer; writer.SetSizeOfFileSegmentation(0); writer.SetIntervalOfFileSegmentation(0); writer.Open(writefile); writer.WriteChannel(CHANNEL_NAME_1, MESSAGE_TYPE_1, PROTO_DESC); for (uint32_t i = 0; i < 100; ++i) { auto msg = std::make_shared<RawMessage>("abc" + std::to_string(i)); writer.WriteMessage(CHANNEL_NAME_1, msg, 888 + i); } writer.Close(); } void test_read(const std::string &readfile) { RecordReader reader(readfile); RecordMessage message; uint64_t msg_count = reader.GetMessageNumber(CHANNEL_NAME_1); AINFO << "MSGTYPE: " << reader.GetMessageType(CHANNEL_NAME_1); AINFO << "MSGDESC: " << reader.GetProtoDesc(CHANNEL_NAME_1); // read all message uint64_t i = 0; uint64_t valid = 0; for (i = 0; i < msg_count; ++i) { if (reader.ReadMessage(&message)) { AINFO << "msg[" << i << "]-> " << "channel name: " << message.channel_name << "; content: " << message.content << "; msg time: " << message.time; valid++; } else { AERROR << "read msg[" << i << "] failed"; } } AINFO << "static msg================="; AINFO << "MSG validmsg:totalcount: " << valid << ":" << msg_count; } int main(int argc, char *argv[]) { apollo::cyber::Init(argv[0]); test_write(TEST_FILE); sleep(1); test_read(TEST_FILE); return 0; } ``` #### Build and run - Build: bazel build cyber/examples/… - Run: ./bazel-bin/cyber/examples/record - Examining result: ``` I1124 16:56:27.248200 15118 record.cc:64] [record] msg[0]-> channel name: /test/channel1; content: abc0; msg time: 888 I1124 16:56:27.248227 15118 record.cc:64] [record] msg[1]-> channel name: /test/channel1; content: abc1; msg time: 889 I1124 16:56:27.248239 15118 record.cc:64] [record] msg[2]-> channel name: /test/channel1; content: abc2; msg time: 890 I1124 16:56:27.248252 15118 record.cc:64] [record] msg[3]-> channel name: /test/channel1; content: abc3; msg time: 891 I1124 16:56:27.248297 15118 record.cc:64] [record] msg[4]-> channel name: /test/channel1; content: abc4; msg time: 892 I1124 16:56:27.248378 15118 record.cc:64] [record] msg[5]-> channel name: /test/channel1; content: abc5; msg time: 893 ... I1124 16:56:27.250422 15118 record.cc:73] [record] static msg================= I1124 16:56:27.250434 15118 record.cc:74] [record] MSG validmsg:totalcount: 100:100 ``` ## API Directory ### Node API For additional information and examples, refer to [Node](#node) ### API List ```cpp //create writer with user-define attr and message type auto CreateWriter(const proto::RoleAttributes& role_attr) -> std::shared_ptr<transport::Writer<MessageT>>; //create reader with user-define attr, callback and message type auto CreateReader(const proto::RoleAttributes& role_attr, const croutine::CRoutineFunc<MessageT>& reader_func) -> std::shared_ptr<transport::Reader<MessageT>>; //create writer with specific channel name and message type auto CreateWriter(const std::string& channel_name) -> std::shared_ptr<transport::Writer<MessageT>>; //create reader with specific channel name, callback and message type auto CreateReader(const std::string& channel_name, const croutine::CRoutineFunc<MessageT>& reader_func) -> std::shared_ptr<transport::Reader<MessageT>>; //create reader with user-define config, callback and message type auto CreateReader(const ReaderConfig& config, const CallbackFunc<MessageT>& reader_func) -> std::shared_ptr<cybertron::Reader<MessageT>>; //create service with name and specific callback auto CreateService(const std::string& service_name, const typename service::Service<Request, Response>::ServiceCallback& service_calllback) -> std::shared_ptr<service::Service<Request, Response>>; //create client with name to send request to server auto CreateClient(const std::string& service_name) -> std::shared_ptr<service::Client<Request, Response>>; ``` ## Writer API For additional information and examples, refer to [Writer](#writer) ### API List ```cpp bool Write(const std::shared_ptr<MessageT>& message); ``` ## Client API For additional information and examples, refer to [Client](#service-creation-and-use) ### API List ```cpp SharedResponse SendRequest(SharedRequest request, const std::chrono::seconds& timeout_s = std::chrono::seconds(5)); SharedResponse SendRequest(const Request& request, const std::chrono::seconds& timeout_s = std::chrono::seconds(5)); ``` ## Parameter API The interface that the user uses to perform parameter related operations: - Set the parameter related API. - Read the parameter related API. - Create a ParameterService to provide parameter service related APIs for other nodes. - Create a ParameterClient that uses the parameters provided by other nodes to service related APIs. For additional information and examples, refer to [Parameter](##param-parameter-service) ### API List - Setting parameters ```cpp Parameter(); // Name is empty, type is NOT_SET explicit Parameter(const Parameter& parameter); explicit Parameter(const std::string& name); // Type is NOT_SET Parameter(const std::string& name, const bool bool_value); Parameter(const std::string& name, const int int_value); Parameter(const std::string& name, const int64_t int_value); Parameter(const std::string& name, const float double_value); Parameter(const std::string& name, const double double_value); Parameter(const std::string& name, const std::string& string_value); Parameter(const std::string& name, const char* string_value); Parameter(const std::string& name, const std::string& msg_str, const std::string& full_name, const std::string& proto_desc); Parameter(const std::string& name, const google::protobuf::Message& msg); ``` ### API List - Reading parameters ```cpp inline ParamType type() const; inline std::string TypeName() const; inline std::string Descriptor() const; inline const std::string Name() const; inline bool AsBool() const; inline int64_t AsInt64() const; inline double AsDouble() const; inline const std::string AsString() const; std::string DebugString() const; template <typename Type> typename std::enable_if<std::is_base_of<google::protobuf::Message, Type>::value, Type>::type value() const; template <typename Type> typename std::enable_if<std::is_integral<Type>::value && !std::is_same<Type, bool>::value, Type>::type value() const; template <typename Type> typename std::enable_if<std::is_floating_point<Type>::value, Type>::type value() const; template <typename Type> typename std::enable_if<std::is_convertible<Type, std::string>::value, const std::string&>::type value() const; template <typename Type> typename std::enable_if<std::is_same<Type, bool>::value, bool>::type value() const; ``` ### API List - Creating parameter service ```cpp explicit ParameterService(const std::shared_ptr<Node>& node); void SetParameter(const Parameter& parameter); bool GetParameter(const std::string& param_name, Parameter* parameter); bool ListParameters(std::vector<Parameter>* parameters); ``` ### API List - Creating parameter client ```cpp ParameterClient(const std::shared_ptr<Node>& node, const std::string& service_node_name); bool SetParameter(const Parameter& parameter); bool GetParameter(const std::string& param_name, Parameter* parameter); bool ListParameters(std::vector<Parameter>* parameters); ``` ## Timer API You can set the parameters of the Timer and call the start and stop interfaces to start the timer and stop the timer. For additional information and examples, refer to [Timer](#timer) ### API List ```cpp Timer(uint32_t period, std::function<void()> callback, bool oneshot); Timer(TimerOption opt); void SetTimerOption(TimerOption opt); void Start(); void Stop(); ``` ## Time API For additional information and examples, refer to [Time](#use-of-time) ### API List ```cpp static const Time MAX; static const Time MIN; Time() {} explicit Time(uint64_t nanoseconds); explicit Time(int nanoseconds); explicit Time(double seconds); Time(uint32_t seconds, uint32_t nanoseconds); Time(const Time& other); static Time Now(); static Time MonoTime(); static void SleepUntil(const Time& time); double ToSecond() const; uint64_t ToNanosecond() const; std::string ToString() const; bool IsZero() const; ``` ## Duration API Interval-related interface, used to indicate the time interval, can be initialized according to the specified nanosecond or second. ### API List ```cpp Duration() {} Duration(int64_t nanoseconds); Duration(int nanoseconds); Duration(double seconds); Duration(uint32_t seconds, uint32_t nanoseconds); Duration(const Rate& rate); Duration(const Duration& other); double ToSecond() const; int64_t ToNanosecond() const; bool IsZero() const; void Sleep() const; ``` ## Rate API The frequency interface is generally used to initialize the time of the sleep frequency after the object is initialized according to the specified frequency. ### API List ```cpp Rate(double frequency); Rate(uint64_t nanoseconds); Rate(const Duration&); void Sleep(); void Reset(); Duration CycleTime() const; Duration ExpectedCycleTime() const { return expected_cycle_time_; } ``` ## RecordReader API The interface for reading the record file is used to read the message and channel information in the record file. ### API List ```cpp RecordReader(); bool Open(const std::string& filename, uint64_t begin_time = 0, uint64_t end_time = UINT64_MAX); void Close(); bool ReadMessage(); bool EndOfFile(); const std::string& CurrentMessageChannelName(); std::shared_ptr<RawMessage> CurrentRawMessage(); uint64_t CurrentMessageTime(); ``` ## RecordWriter API The interface for writing the record file, used to record the message and channel information into the record file. ### API List ```cpp RecordWriter(); bool Open(const std::string& file); void Close(); bool WriteChannel(const std::string& name, const std::string& type, const std::string& proto_desc); template <typename MessageT> bool WriteMessage(const std::string& channel_name, const MessageT& message, const uint64_t time_nanosec, const std::string& proto_desc = ""); bool SetSizeOfFileSegmentation(uint64_t size_kilobytes); bool SetIntervalOfFileSegmentation(uint64_t time_sec); ```
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/04_CyberRT/CyberRT_Migration_Guide.md
# Migration guide from Apollo ROS This article describes the essential changes for projects to migrate from Apollo ROS (Apollo 3.0 and before) to Apollo Cyber RT (Apollo 3.5 and after). We will be using the very first ROS project talker/listener as example to demonstrate step by step migration instruction. ## Build system ROS use `CMake` as its build system but Cyber RT use `bazel`. In a ROS project, CmakeLists.txt and package.xml are required for defining build configs like build target, dependency, message files and so on. As for a Cyber RT component, a single bazel BUILD file covers. Some key build config mappings are listed below. Cmake ``` cmake project(pb_msgs_example) add_proto_files( DIRECTORY proto FILES chatter.proto ) ## Declare a C++ executable add_executable(pb_talker src/talker.cpp) target_link_libraries(pb_talker ${catkin_LIBRARIES}pb_msgs_example_proto) add_executable(pb_listener src/listener.cpp) target_link_libraries(pb_listener ${catkin_LIBRARIES} pb_msgs_example_proto) ``` Bazel ```python cc_binary( name = "talker", srcs = ["talker.cc"], deps = [ "//cyber", "//cyber/examples/proto:examples_cc_proto", ], ) cc_binary( name = "listener", srcs = ["listener.cc"], deps = [ "//cyber", "//cyber/examples/proto:examples_cc_proto", ], ) ``` We can find the mapping easily from the 2 file snippets. For example, `pb_talker` and `src/talker.cpp` in cmake `add_executable` setting map to `name = "talker"` and `srcs = ["talker.cc"]` in BUILD file `cc_binary`. ### Proto Apollo ROS has customized to support proto message formate that a separate section `add_proto_files` and projectName_proto(`pb_msgs_example_proto`) in `target_link_libraries` are required to send message in proto formate. For config proto message in Cyber RT, it's as simple as adding the target proto file path concantenated with name of `cc_proto_library` in `deps` setting. The `cc_proto_library` is set up in BUILD file under proto folder. ```python cc_proto_library( name = "examples_cc_proto", deps = [ ":examples_proto", ], ) proto_library( name = "examples_proto", srcs = [ "examples.proto", ], ) ``` The package definition has also changed in Cyber RT. In Apollo ROS a fixed package `package pb_msgs;` is used for proto files, but in Cyber RT, the proto file path `package apollo.cyber.examples.proto;` is used instead. ## Folder structure As shown below, Cyber RT remove the src folder and pull all source code in the same folder as BUILD file. BUILD file plays the same role as CMakeLists.txt plus package.xml. Both Cyber RT and Apollo ROS talker/listener example have a proto folder for message proto files but Cyber RT requires a separate BUILD file for proto folder to set up the proto library. ### Apollo ROS - CMakeLists.txt - package.xml - proto - chatter.proto - src - listener.cpp - talker.cpp ### Cyber RT - BUILD - listener.cc - talker.cc - proto - BUILD - examples.proto (with chatter message) ## Update source code ### Listener Cyber RT ```cpp #include "cyber/cyber.h" #include "cyber/examples/proto/examples.pb.h" void MessageCallback( const std::shared_ptr<apollo::cyber::examples::proto::Chatter>& msg) { AINFO << "Received message seq-> " << msg->seq(); AINFO << "msgcontent->" << msg->content(); } int main(int argc, char* argv[]) { // init cyber framework apollo::cyber::Init(argv[0]); // create listener node auto listener_node = apollo::cyber::CreateNode("listener"); // create listener auto listener = listener_node->CreateReader<apollo::cyber::examples::proto::Chatter>( "channel/chatter", MessageCallback); apollo::cyber::WaitForShutdown(); return 0; } ``` ROS ```cpp #include "ros/ros.h" #include "chatter.pb.h" void MessageCallback(const boost::shared_ptr<pb_msgs::Chatter>& msg) { ROS_INFO_STREAM("Time: " << msg->stamp().sec() << "." << msg->stamp().nsec()); ROS_INFO("I heard pb Chatter message: [%s]", msg->content().c_str()); } int main(int argc, char** argv) { ros::init(argc, argv, "listener"); ros::NodeHandle n; ros::Subscriber pb_sub = n.subscribe("chatter", 1000, MessageCallback); ros::spin(); return 0; } ``` You can see easily from the two listener code above that Cyber RT provides very similar API to for developers to migrate from ROS. - `ros::init(argc, argv, "listener");` --> `apollo::cyber::Init(argv[0]);` - `ros::NodeHandle n;` --> `auto listener_node = apollo::cyber::CreateNode("listener");` - `ros::Subscriber pb_sub = n.subscribe("chatter", 1000, MessageCallback);` --> `auto listener = listener_node->CreateReader("channel/chatter", MessageCallback);` - `ros::spin();` --> `apollo::cyber::WaitForShutdown();` Note: for Cyber RT, a listener node has to use `node->CreateReader<messageType>(channelName, callback)` to read data from channel. ### Talker Cyber RT ```cpp #include "cyber/cyber.h" #include "cyber/examples/proto/examples.pb.h" using apollo::cyber::examples::proto::Chatter; int main(int argc, char *argv[]) { // init cyber framework apollo::cyber::Init(argv[0]); // create talker node auto talker_node = apollo::cyber::CreateNode("talker"); // create talker auto talker = talker_node->CreateWriter<Chatter>("channel/chatter"); Rate rate(1.0); while (apollo::cyber::OK()) { static uint64_t seq = 0; auto msg = std::make_shared<Chatter>(); msg->set_timestamp(Time::Now().ToNanosecond()); msg->set_lidar_timestamp(Time::Now().ToNanosecond()); msg->set_seq(seq++); msg->set_content("Hello, apollo!"); talker->Write(msg); AINFO << "talker sent a message!"; rate.Sleep(); } return 0; } ``` ROS ```cpp #include "ros/ros.h" #include "chatter.pb.h" #include <sstream> int main(int argc, char** argv) { ros::init(argc, argv, "talker"); ros::NodeHandle n; ros::Publisher chatter_pub = n.advertise<pb_msgs::Chatter>("chatter", 1000); ros::Rate loop_rate(10); int count = 0; while (ros::ok()) { pb_msgs::Chatter msg; ros::Time now = ros::Time::now(); msg.mutable_stamp()->set_sec(now.sec); msg.mutable_stamp()->set_nsec(now.nsec); std::stringstream ss; ss << "Hello world " << count; msg.set_content(ss.str()); chatter_pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); } return 0; } ``` Most of the mappings are illustrated in listener code above, the rest are listed here. - `ros::Publisher chatter_pub = n.advertise<pb_msgs::Chatter>("chatter", 1000);` --> `auto talker = talker_node->CreateWriter<Chatter>("channel/chatter");` - `chatter_pub.publish(msg);` --> ` talker->Write(msg);` ## Tools mapping ROS | Cyber RT | Note :------------- | :------------- | :-------------- rosbag | cyber_recorder | data file scripts/diagnostics.sh | cyber_monitor | channel debug offline_lidar_visualizer_tool | cyber_visualizer |point cloud visualizer ## ROS bag data migration The data file changed from ROS bag to Cyber record in Cyber RT. Cyber RT has a data migration tool `rosbag_to_record` for users to easily migrate data files before Apollo 3.0 (ROS) to Cyber RT like the sample usage below. ```bash rosbag_to_record demo_3.0.bag demo_3.5.record ```
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/04_CyberRT/CyberRT_Python_API_cn.md
## 1. 背景 Cyber 核心代码是由 C++ 开发,同时为了方便开发者,提供了 Python 接口。 ## 2. CyberRT Python 接口实现思路 Cyber Python 接口的实现思路是在 Cyber C++ 实现的基础上,做了一层 Python 的封装,由 Python 来调用 C++ 的实现函数。Cyber Python Wrapper 的实现没有使用 swig 等第三方工具,完全自主实现,以此保证代码的高可维护性和可读性。 ## 3. 主要接口 目前提供的主要接口包括: * channel 读、写 * server/client 通信 * record 信息查询 * record 文件读、写 * Time/Duration/Rate 时间操作 * Timer ### 3.1 Channel 读写接口 使用步骤是: 1. 首先创建 Node; 2. 创建对应的 reader 或 writer; 3. 如果是向 channel 写数据,调用 writer 的 write 接口; 4. 如果是从 channel 读数据,调用 node 的 spin,对收到的消息进行消费; 接口定义如下: ```python class Node: """ Class for cyber Node wrapper. """ def create_writer(self, name, data_type, qos_depth=1): """ create a topic writer for send message to topic. @param self @param name str: topic name @param data_type proto: message class for serialization """ def create_reader(self, name, data_type, callback, args=None): """ create a topic reader for receive message from topic. @param self @param name str: topic name @param data_type proto: message class for serialization @callback fn: function to call (fn(data)) when data is received. If args is set, the function must accept the args as a second argument, i.e. fn(data, args) @args any: additional arguments to pass to the callback """ def create_client(self, name, request_data_type, response_data_type): """ """ def create_service(self, name, req_data_type, res_data_type, callback, args=None): def spin(self): """ spin in wait and process message. @param self """ class Writer(object): """ Class for cyber writer wrapper. """ def write(self, data): """ writer msg string """ ``` ### 3.2 Record 接口 Record 读的操作是: 1. 创建一个 RecordReader; 2. 对 Record 进行迭代读; Record 写的操作是: 1. 创建一个 RecordWriter 2. 对 Record 进行写消息; 接口定义如下: ```python class RecordReader(object): """ Class for cyber RecordReader wrapper. """ def read_messages(self, start_time=0, end_time=18446744073709551615): """ read message from bag file. @param self @param start_time: @param end_time: @return: generator of (message, data_type, timestamp) """ def get_messagenumber(self, channel_name): """ return message count. """ def get_messagetype(self, channel_name): """ return message type. """ def get_protodesc(self, channel_name): """ return message protodesc. """ def get_headerstring(self): """ return message header string. """ def reset(self): """ return reset. """ return _CYBER_RECORD.PyRecordReader_Reset(self.record_reader) def get_channellist(self): """ return channel list. """ return _CYBER_RECORD.PyRecordReader_GetChannelList(self.record_reader) class RecordWriter(object): """ Class for cyber RecordWriter wrapper. """ def open(self, path): """ open record file for write. """ def write_channel(self, channel_name, type_name, proto_desc): """ writer channel by channelname,typename,protodesc """ def write_message(self, channel_name, data, time, raw = True): """ writer msg:channelname,data,time,is data raw """ def set_size_fileseg(self, size_kilobytes): """ return filesegment size. """ def set_intervaltime_fileseg(self, time_sec): """ return file interval time. """ def get_messagenumber(self, channel_name): """ return message count. """ def get_messagetype(self, channel_name): """ return message type. """ def get_protodesc(self, channel_name): """ return message protodesc. """ ``` ### 3.3 Time 接口 ```python class Time(object): @staticmethod def now(): time_now = Time(_CYBER_TIME.PyTime_now()) return time_now @staticmethod def mono_time(): mono_time = Time(_CYBER_TIME.PyTime_mono_time()) return mono_time def to_sec(self): return _CYBER_TIME.PyTime_to_sec(self.time) def to_nsec(self): return _CYBER_TIME.PyTime_to_nsec(self.time) def sleep_until(self, nanoseconds): return _CYBER_TIME.PyTime_sleep_until(self.time, nanoseconds) ``` ### 3.4 Timer 接口 ``` class Timer(object): def set_option(self, period, callback, oneshot=0): ''' period The period of the timer, unit is ms callback The tasks that the timer needs to perform oneshot 1: perform the callback only after the first timing cycle 0:perform the callback every timed period ''' def start(self): def stop(self): ``` ## 4. 例子 ### 4.1 读 channel (参见 cyber/python/cyber_py3/examples/listener.py) ```python """Module for example of listener.""" from cyber_py3 import cyber from cyber.proto.unit_test_pb2 import ChatterBenchmark def callback(data): """ Reader message callback. """ print("=" * 80) print("py:reader callback msg->:") print(data) print("=" * 80) def test_listener_class(): """ Reader message. """ print("=" * 120) test_node = cyber.Node("listener") test_node.create_reader("channel/chatter", ChatterBenchmark, callback) test_node.spin() if __name__ == '__main__': cyber.init() test_listener_class() cyber.shutdown() ``` ### 4.2 写 channel(参见 cyber/python/cyber_py3/examples/talker.py) ```python """Module for example of talker.""" import time from cyber_py3 import cyber from cyber.proto.unit_test_pb2 import ChatterBenchmark def test_talker_class(): """ Test talker. """ msg = ChatterBenchmark() msg.content = "py:talker:send Alex!" msg.stamp = 9999 msg.seq = 0 print(msg) test_node = cyber.Node("node_name1") g_count = 1 writer = test_node.create_writer("channel/chatter", ChatterBenchmark, 6) while not cyber.is_shutdown(): time.sleep(1) g_count = g_count + 1 msg.seq = g_count msg.content = "I am python talker." print("=" * 80) print("write msg -> %s" % msg) writer.write(msg) if __name__ == '__main__': cyber.init("talker_sample") test_talker_class() cyber.shutdown() ``` ### 4.3 读写消息到 Record 文件(参见 cyber/python/cyber_py3/examples/record.py) ```python cyber/python/cyber_py3/examples/record.py) ```python """ Module for example of record. Run with: bazel run //cyber/python/cyber_py3/examples:record """ import time from google.protobuf.descriptor_pb2 import FileDescriptorProto from cyber.proto.unit_test_pb2 import Chatter from cyber.python.cyber_py3 import record from modules.common.util.testdata.simple_pb2 import SimpleMessage MSG_TYPE = "apollo.common.util.test.SimpleMessage" MSG_TYPE_CHATTER = "apollo.cyber.proto.Chatter" def test_record_writer(writer_path): """ Record writer. """ fwriter = record.RecordWriter() fwriter.set_size_fileseg(0) fwriter.set_intervaltime_fileseg(0) if not fwriter.open(writer_path): print('Failed to open record writer!') return print('+++ Begin to writer +++') # Writer 2 SimpleMessage msg = SimpleMessage() msg.text = "AAAAAA" file_desc = msg.DESCRIPTOR.file proto = FileDescriptorProto() file_desc.CopyToProto(proto) proto.name = file_desc.name desc_str = proto.SerializeToString() print(msg.DESCRIPTOR.full_name) fwriter.write_channel( 'simplemsg_channel', msg.DESCRIPTOR.full_name, desc_str) fwriter.write_message('simplemsg_channel', msg, 990, False) fwriter.write_message('simplemsg_channel', msg.SerializeToString(), 991) # Writer 2 Chatter msg = Chatter() msg.timestamp = 99999 msg.lidar_timestamp = 100 msg.seq = 1 file_desc = msg.DESCRIPTOR.file proto = FileDescriptorProto() file_desc.CopyToProto(proto) proto.name = file_desc.name desc_str = proto.SerializeToString() print(msg.DESCRIPTOR.full_name) fwriter.write_channel('chatter_a', msg.DESCRIPTOR.full_name, desc_str) fwriter.write_message('chatter_a', msg, 992, False) msg.seq = 2 fwriter.write_message("chatter_a", msg.SerializeToString(), 993) fwriter.close() def test_record_reader(reader_path): """ Record reader. """ freader = record.RecordReader(reader_path) time.sleep(1) print('+' * 80) print('+++ Begin to read +++') count = 0 for channel_name, msg, datatype, timestamp in freader.read_messages(): count += 1 print('=' * 80) print('read [%d] messages' % count) print('channel_name -> %s' % channel_name) print('msgtime -> %d' % timestamp) print('msgnum -> %d' % freader.get_messagenumber(channel_name)) print('msgtype -> %s' % datatype) print('message is -> %s' % msg) print('***After parse(if needed),the message is ->') if datatype == MSG_TYPE: msg_new = SimpleMessage() msg_new.ParseFromString(msg) print(msg_new) elif datatype == MSG_TYPE_CHATTER: msg_new = Chatter() msg_new.ParseFromString(msg) print(msg_new) if __name__ == '__main__': test_record_file = "/tmp/test_writer.record" print('Begin to write record file: {}'.format(test_record_file)) test_record_writer(test_record_file) print('Begin to read record file: {}'.format(test_record_file)) test_record_reader(test_record_file) ```
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/04_CyberRT/CyberRT_Quick_Start.md
# How to Create and Run a new Component in Cyber RT Apollo Cyber RT framework is built upon the concept of components. As the building block of Cyber RT, each component is a specific algorithm module which processes a set of inputs and generates its set of outputs. To successfully create and launch a new component, there are basically 4 steps: - Set up directory layout - Implement the component class - Configuration setup - Launch the component The example below demonstrates how to create, build and run a simple component named `CommonComponentExample`. To explore more about Cyber RT, you can find a couple of examples showing different functionalities of Cyber RT under the `cyber/examples` directory. > **Note**: The examples need to run after successfully built within Apollo > Docker container. ## Set up directry layout Take the sample component under `cyber/examples/common_component_example` for example: - Header file: common_component_example.h - Source file: common_component_example.cc - BUILD file: BUILD - DAG file: common.dag - Launch file: common.launch ## Implement the sample component class ### Header file In the header file (`common_component_example.h`) for the sample component: - Inherit the `Component` base class - Define your own `Init` and `Proc` functions. Please note that for `proc`, input data types need to be specified also. - Register the sample component class to be globally visible using the `CYBER_REGISTER_COMPONENT` macro. ```cpp #include <memory> #include "cyber/component/component.h" #include "cyber/examples/proto/examples.pb.h" using apollo::cyber::Component; using apollo::cyber::ComponentBase; using apollo::cyber::examples::proto::Driver; class CommonComponentSample : public Component<Driver, Driver> { public: bool Init() override; bool Proc(const std::shared_ptr<Driver>& msg0, const std::shared_ptr<Driver>& msg1) override; }; CYBER_REGISTER_COMPONENT(CommonComponentSample) ``` ### Source File Implement both the `Init` and `Proc` functions in `common_component_example.cc`: ```cpp #include "cyber/examples/common_component_example/common_component_example.h" bool CommonComponentSample::Init() { AINFO << "Commontest component init"; return true; } bool CommonComponentSample::Proc(const std::shared_ptr<Driver>& msg0, const std::shared_ptr<Driver>& msg1) { AINFO << "Start common component Proc [" << msg0->msg_id() << "] [" << msg1->msg_id() << "]"; return true; } ``` ### BUILD file ```python load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_binary( name = "libcommon_component_example.so", linkshared = True, linkstatic = False, deps = [":common_component_example_lib"], ) cc_library( name = "common_component_example_lib", srcs = ["common_component_example.cc"], hdrs = ["common_component_example.h"], visibility = ["//visibility:private"], deps = [ "//cyber", "//cyber/examples/proto:examples_cc_proto", ], ) cpplint() ``` ## Configuration setup ### DAG file To configure the DAG file (`common.dag` here), specify the following items: - Channel names: for data input and output - Library path: library built from component class - Class name: the class name of the component ```protobuf # Define all components in DAG streaming. module_config { module_library : "/apollo/bazel-bin/cyber/examples/common_component_example/libcommon_component_example.so" components { class_name : "CommonComponentSample" config { name : "common" readers { channel: "/apollo/prediction" } readers { channel: "/apollo/test" } } } } ``` ### Launch file To configure the launch (`common.launch`) file, specify the following items: - The name of the component - The DAG file created in the previous step - The name of the process to run the component ```xml <cyber> <component> <name>common</name> <dag_conf>/apollo/cyber/examples/common_component_example/common.dag</dag_conf> <process_name>common</process_name> </component> </cyber> ``` ## Launch the component ### Build Build the sample component by running the command below: ```bash cd /apollo bash apollo.sh build ``` ### Environment setup Then configure the environment: ```bash source cyber/setup.bash # To see output from terminal export GLOG_alsologtostderr=1 ``` ### Launch the component You can choose either of the two ways to launch the newly built component: - Launch with the launch file (recommended) ```bash cyber_launch start cyber/examples/common_component_example/common.launch ``` - Launch with the DAG file ```bash mainboard -d cyber/examples/common_component_example/common.dag ``` ### _Feed_ channel data for the component to process Open another terminal: ```bash source cyber/setup.bash export GLOG_alsologtostderr=1 /apollo/bazel-bin/cyber/examples/common_component_example/channel_test_writer ``` Open the 3rd terminal and run: ```bash source cyber/setup.bash export GLOG_alsologtostderr=1 /apollo/bazel-bin/cyber/examples/common_component_example/channel_prediction_writer ``` And you should see output from terminal #1 like the following: ``` I0331 16:49:34.736016 1774773 common_component_example.cc:25] [mainboard]Start common component Proc [1094] [766] I0331 16:49:35.069005 1774775 common_component_example.cc:25] [mainboard]Start common component Proc [1095] [767] I0331 16:49:35.402289 1774783 common_component_example.cc:25] [mainboard]Start common component Proc [1096] [768] ```
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/05_Localization/how_to_run_RTK_localization_module_on_your_local_computer_cn.md
# 如何在本地运行RTK定位模块 本文档提供了如何在本地运行RTK定位模块的方法。 ## 1. 事先准备 - 从[GitHub网站](https://github.com/ApolloAuto/apollo)下载Apollo源代码 - 按照[教程](../01_Installation%20Instructions/apollo_software_installation_guide.md)设置Docker环境 - 从[Apollo数据平台](http://data.apollo.auto/?name=sensor%20data&data_key=multisensor&data_type=1&locale=en-us&lang=en)下载多传感器融合定位demo数据包(仅限美国地区),使用其中*apollo3.5*文件夹下的数据。 ## 2. 编译apollo工程 ### 2.1 启动并进入Apollo开发版Docker容器 ``` bash docker/scripts/dev_start.sh bash docker/scripts/dev_into.sh ``` ### 2.2 编译工程 ``` # (Optional) To make sure you start clean bash apollo.sh clean -a bash apollo.sh build_opt ``` ## 3. 运行RTK模式定位 ``` cyber_launch start /apollo/modules/localization/launch/rtk_localization.launch ``` 在/apollo/data/log目录下,可以看到定位模块输出的相关log文件。 - localization.INFO : INFO级别的log信息 - localization.WARNING : WARNING级别的log信息 - localization.ERROR : ERROR级别的log信息 - localization.out : 标准输出重定向文件 - localizaiton.flags : 启动localization模块使用的配置 ## 4. 播放record文件 在下载好的定位demo数据中,找到一个名为"apollo3.5"的文件夹,假设该文件夹所在路径为DATA_PATH。 ``` cd DATA_PATH/records cyber_recorder play -f record.* ``` ## 6. 可视化定位结果(可选) ### 可视化定位结果 运行可视化工具 ``` cyber_launch start /apollo/modules/localization/launch/msf_visualizer.launch ``` 该可视化工具首先根据定位地图生成用于可视化的缓存文件,存放在/apollo/cyber/data/map_visual目录下。 然后接收以下topic并进行可视化绘制。 - /apollo/sensor/lidar128/compensator/PointCloud2 - /apollo/localization/pose 可视化效果如下 ![1](images/rtk_localization/online_visualizer.png)
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/05_Localization/how_to_run_MSF_localization_module_on_your_local_computer.md
# How to Run MSF Localization Module On Your Local Computer ## 1. Preparation - Download source code of Apollo from [GitHub](https://github.com/ApolloAuto/apollo) - Follow the tutorial to set up [docker environment](../01_Installation%20Instructions/apollo_software_installation_guide.md). - Download localization data from [Apollo Data Open Platform](http://data.apollo.auto/?name=sensor%20data&data_key=multisensor&data_type=1&locale=en-us&lang=en)(US only). the localization data is a experimental dataset to verify the availability of localization. It contains localization map(local_map/), vehicle params(params/), sensor recording data(records/). The specific attributes are as follows: duration: 5 mins mileage: 3km areas: city roads in Sunnyvale weather: sunny day ## 2. Build Apollo First check and make sure you are in development docker container before you proceed. Now you will need to build from the source. ``` # To make sure you start clean bash apollo.sh clean # Build the full system bash apollo.sh build_opt ``` ## 3. Configuring Parameters In the downloaded data, you can find a folder named *apollo3.5*. Let's assume the path of this folder as DATA_PATH. ### 3.1 Configure Sensor Extrinsics ``` cp -r DATA_PATH/params/* /apollo/modules/localization/msf/params/ ``` The meaning of each file in the folder - **ant_imu_leverarm.yaml**: Lever arm value - **velodyne128_novatel_extrinsics.yaml**: Transform from IMU coord to LiDAR coord - **velodyne128_height.yaml**: Height of the LiDAR relative to the ground ### 3.2 Configure Map Path Add config of map path in /apollo/modules/localization/conf/localization.conf ``` # Redefine the map_dir in global_flagfile.txt --map_dir=DATA_PATH ``` This will overwrite the default config defined in global_flagfile.txt ## 4. Run the multi-sensor fusion localization module run the script in apollo directory ``` cyber_launch start /apollo/modules/localization/launch/msf_localization.launch ``` In /apollo/data/log directory, you can see the localization log files. - localization.INFO : INFO log - localization.WARNING : WARNING log - localization.ERROR : ERROR log - localization.out : Redirect standard output - localizaiton.flags : A backup of configuration file ## 5. Play cyber records ``` cd DATA_PATH/records cyber_recorder play -f record.* ``` The localization module will finish initialization and start publishing localization results after around 50 seconds. ## 6. Record and Visualize localization result (optional) ### Record localization result ``` python /apollo/scripts/record_bag.py --start ``` ### Visualize Localization result ``` cyber_launch start /apollo/modules/localization/launch/msf_visualizer.launch ``` First, the visualization tool will generate a series of cache files from the localization map, which will be stored in the /apollo/cyber/data/map_visual directory. Then it will receive the topics blew and draw them on screen. - /apollo/sensor/lidar128/compensator/PointCloud2 - /apollo/localization/msf_lidar - /apollo/localization/msf_gnss - /apollo/localization/pose If everything is fine, you should see this on screen. ![1](images/msf_localization/online_visualizer.png) `Note:` The visualization tool will show up the windows after the localization module started to published localization msgs to topic /apollo/localization/pose. You can use command *cyber_monitor* to monitor the status of topics. ## 7. Stop localization module If you record localization result in step 6, you will also need to end the recording process: ``` python /apollo/scripts/record_bag.py --stop ``` ## 8. Verify the localization result (optional) ``` ./scripts/msf_local_evaluation.sh OUTPUT_PATH ``` OUTPUT_PATH is the folder stored recording bag in step 6. This script compares the localization results of MSF mode to RTK mode. `Note:` Aware that this comparison makes sense only when the RTK mode runs well. And we can get the statistical results like this ![2](images/msf_localization/localization_result.png) The first table is the statistical data of Fusion localization. The second table is the statistical result of Lidar localization. The meaning of each row in the table - **error**: the plane error, unit is meter - **error lon**: the error in the car's heading direction, unit is meter - **error lat**: the error in the car's lateral direction, unit is meter - **error roll**: the roll angle error, unit is degree - **error pit**: the pitch angle error, unit is degree - **error yaw**: the yaw angle error, unit is degree The meaning of each col in the table - **mean**: evaluation value of the error - **std**: the standard deviation of the error - **max**: the maximum value of the error - **< xx**: percentage of frames whose error is smaller than the indicated range - **con_frame()**: the maximum number of consecutive frames that satisfy the conditions in parentheses
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/05_Localization/how_to_generate_local_map_for_MSF_localization_module_cn.md
# 如何生产多传感器融合定位模块所需的地图 本文档介绍了如何利用apollo开源的工具生产多传感器融合定位模块所需要的地图。 ## 1. 事先准备 - 从[GitHub网站](https://github.com/ApolloAuto/apollo)下载Apollo源代码 - 按照[教程](../01_Installation%20Instructions/apollo_software_installation_guide.md)设置Docker环境 - ~~从[Apollo数据平台](http://data.apollo.auto/?name=sensor%20data&data_key=multisensor&data_type=1&locale=en-us&lang=en)的“多传感器融合定位数据”栏目下载多传感器融合定位demo数据包(仅限美国地区)。~~ - 下载数据集: 请发邮件至*zhouyao@baidu.com*来申请数据。邮件中需要包含以下内容:(1) 你所在的机构名称和邮件地址; (2)数据集使用目的。 ## 2. 编译apollo工程 ### 2.1 构建docker容器 我们提供了一个叫做*dev-latest*的docker镜像,docker容器会将你本地的apollo工程挂载到 */apollo* 。 ``` bash docker/scripts/dev_start.sh ``` ### 2.2 进入docker容器 ``` bash docker/scripts/dev_into.sh ``` ### 2.3 编译工程 ``` # To make sure you start clean bash apollo.sh clean # Build the full system bash apollo.sh build_opt ``` ## 3. 生产定位地图 在下载好的定位demo数据中,找到一个名为"apollo3.5"的文件夹,将其中的数据包解压,假设该文件夹所在路径为DATA_PATH。 执行以下脚本 ``` /apollo/scripts/msf_simple_map_creator.sh DATA_PATH/records/ DATA_PATH/params/velodyne_params/velodyne128_novatel_extrinsics.yaml 10 OUT_FOLDER_PATH ``` 该脚本会在OUT_FOLDER_PATH的路径下生成定位需要的地图。 下图为地图中某个node使用LiDAR放射值进行渲染的效果。 ![1](images/msf_localization/map_node_image.png)
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/05_Localization/how_to_run_MSF_localization_module_on_your_local_computer_cn.md
# 如何在本地运行多传感器融合定位模块 本文档提供了如何在本地运行多传感器融合定位模块的方法。 ## 1. 事先准备 - 从[GitHub网站](https://github.com/ApolloAuto/apollo)下载Apollo源代码 - 按照[教程](../01_Installation%20Instructions/apollo_software_installation_guide.md)设置Docker环境 - 从[Apollo数据平台](http://data.apollo.auto/?name=sensor%20data&data_key=multisensor&data_type=1&locale=en-us&lang=en)下载多传感器融合定位demo数据包(仅限美国地区),使用其中*apollo3.5*文件夹下的数据。 此定位数据为实验性质的demo数据,用于验证定位模块的可用性。数据主要包含定位地图(local_map/), 车辆参数(params/), 传感器数据(records/)。具体属性如下: 时长:5分钟 里程:3km 场景:Sunnyvale 城市道路 天气:晴天 ## 2. 编译apollo工程 ### 2.1 构建docker容器 我们提供了一个叫做*dev-latest*的docker镜像,docker容器会将你本地的apollo工程挂载到 */apollo* 。 ``` bash docker/scripts/dev_start.sh ``` ### 2.2 进入docker容器 ``` bash docker/scripts/dev_into.sh ``` ### 2.3 编译工程 ``` # To make sure you start clean bash apollo.sh clean # Build the full system bash apollo.sh build_opt ``` ## 3. 配置定位模块 为了使定位模块正确运行,需要对地图路径和传感器外参进行配置。假设下载的定位数据的所在路径为DATA_PATH。 在进行以下步骤前,首先确定你在docker容器中。 ### 3.1 配置传感器外参 将定位数据中的传感器外参拷贝至指定文件夹下。 ``` cp -r DATA_PATH/params/* /apollo/modules/localization/msf/params/ ``` 文件夹中各个外参的意义 - ant_imu_leverarm.yaml: 杆臂值参数,GNSS天线相对Imu的距离 - velodyne128_novatel_extrinsics.yaml: Lidar相对Imu的外参 - velodyne128_height.yaml: Lidar相对地面的高度 ### 3.2 配置地图和参数路径 在/apollo/modules/localization/conf/localization.conf中配置地图和参数的路径 ``` # Redefine the map_dir in global_flagfile.txt --map_dir=DATA_PATH # The pointcloud topic name. --lidar_topic=/apollo/sensor/lidar128/compensator/PointCloud2 # The lidar extrinsics file --lidar_extrinsics_file=/apollo/modules/localization/msf/params/velodyne_params/velodyne128_novatel_extrinsics.yaml ``` 这将会覆盖global_flagfile.txt中的默认值。 ## 4. 运行多传感器融合定位模块 ``` cyber_launch start /apollo/modules/localization/launch/msf_localization.launch ``` 在/apollo/data/log目录下,可以看到定位模块输出的相关log文件。 - localization.INFO : INFO级别的log信息 - localization.WARNING : WARNING级别的log信息 - localization.ERROR : ERROR级别的log信息 - localization.out : 标准输出重定向文件 - localizaiton.flags : 启动localization模块使用的配置 ## 5. 播放演示record文件 ``` cd DATA_PATH/records cyber_recorder play -f record.* ``` 从播放数据到定位模块开始输出定位消息,大约需要50s左右时间。 ## 6. 记录并可视化定位结果(可选) ### 记录定位结果 ``` python /apollo/scripts/record_bag.py --start ``` 该脚本会在后台运行录包程序,并将存放路径输出到终端上。 ### 可视化定位结果 运行可视化工具 ``` cyber_launch start /apollo/modules/localization/launch/msf_visualizer.launch ``` 该可视化工具首先根据定位地图生成用于可视化的缓存文件,存放在/apollo/cyber/data/map_visual目录下。 然后接收以下topic并进行可视化绘制。 - /apollo/sensor/lidar128/compensator/PointCloud2 - /apollo/localization/msf_lidar - /apollo/localization/msf_gnss - /apollo/localization/pose 可视化效果如下 ![1](images/msf_localization/online_visualizer.png) `注意:` 在定位模块正常工作之后(/apollo/localization/pose开始输出消息),可视化模块才会弹出显示窗口。可以用*/cyber_monitor*命令查看topic情况。 ## 7. 结束运行定位模块 退出定位程序和播包程序,如果有运行步骤6的录包脚本,需执行以下命令关闭后台录包程序。 ``` python /apollo/scripts/record_bag.py --stop ``` ## 8. 验证定位结果(可选) 假设步骤6中录取的数据存放路径为OUTPUT_PATH,杆臂值外参的路径为ANT_IMU_PATH 运行脚本 ``` /apollo/scripts/msf_local_evaluation.sh OUTPUT_PATH ``` 该脚本会以RTK模式的定位结果为基准,与多传感器融合模式的定位结果进行对比。 `注意:` (注意只有在GNSS信号良好,RTK定位模式运行良好的区域,这样的对比才是有意义的。) 获得如下统计结果: ![2](images/msf_localization/localization_result.png) 可以看到两组统计结果,第一组是组合导航(输出频率200hz)的统计结果,第二组是点云定位(输出频率5hz)的统计结果。 表格中各项的意义, - error: 平面误差,单位为米 - error lon: 车前进方向的误差,单位为米 - error lat: 车横向方向的误差,单位为米 - error roll: 翻滚角误差,单位为度 - error pit: 俯仰角误差,单位为度 - error yaw: 偏航角误差,单位为度 - mean: 误差的平均值 - std: 误差的标准差 - max: 误差的最大值 - <30cm: 距离误差少于30cm的帧所占的百分比 - <1.0d: 角度误差小于1.0d的帧所占的百分比 - con_frame(): 满足括号内条件的最大连续帧数
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/05_Localization/how_to_run_RTK_localization_module_on_your_local_computer.md
# How to Run RTK Localization Module On Your Local Computer ## 1. Preparation - Download source code of Apollo from [GitHub](https://github.com/ApolloAuto/apollo) - Follow the tutorial to set up [docker environment](../01_Installation%20Instructions/apollo_software_installation_guide.md). - Download localization data from [Apollo Data Open Platform](http://data.apollo.auto/?name=sensor%20data&data_key=multisensor&data_type=1&locale=en-us&lang=en)(US only). ## 2. Build Apollo First check and make sure you are in Apollo Development Docker container before you proceed. Now you will need to build from the source. ``` # (Optional) To make sure you start clean bash apollo.sh clean bash apollo.sh build_opt ``` ## 3. Run the RTK localization module ``` cyber_launch start /apollo/modules/localization/launch/rtk_localization.launch ``` In /apollo/data/log directory, you can see the localization log files. - localization.INFO : INFO log - localization.WARNING : WARNING log - localization.ERROR : ERROR log - localization.out : Redirect standard output - localizaiton.flags : A backup of configuration file ## 5. Play cyber records In the downloaded data, you can find a folder named *apollo3.5*. Let's assume the path of this folder as DATA_PATH. ``` cd DATA_PATH/records cyber_recorder play -f record.* ``` ## 6. Record and Visualize localization result (optional) ### Visualize Localization result ``` cyber_launch start /apollo/modules/localization/launch/msf_visualizer.launch ``` First, the visualization tool will generate a series of cache files from the localization map, which will be stored in the /apollo/cyber/data/map_visual directory. Then it will receive the topics listed below and draw them on screen. - /apollo/sensor/lidar128/compensator/PointCloud2 - /apollo/localization/pose If everything is fine, you should see this on screen. ![1](images/rtk_localization/online_visualizer.png)
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/05_Localization/how_to_generate_local_map_for_MSF_localization_module.md
# How to Generate Local Map For MSF Localization Module ## Prerequisites - Download source code of Apollo from [GitHub](https://github.com/ApolloAuto/apollo) - Follow the tutorial to set up [docker environment](../01_Installation%20Instructions/apollo_software_installation_guide.md). - ~~Download localization data from the [Multi-Sensor Fusion Localization Data](http://data.apollo.auto/help?name=sensor%20data&data_key=multisensor&data_type=1&locale=en-us&lang=en)(US only).~~ - Download localization dataset: please contact Yao Zhou, zhouyao@baidu.com, to request the dataset. Requests need contain the following: (1) Email address and affiliation (business or school); (2) Application purpose. ## Build Apollo First check to make sure you are in development docker container before you proceed. Now you will need to build from source: ``` # To make sure you start clean bash apollo.sh clean # Build the full system bash apollo.sh build_opt ``` ## Generate Localization Map In the downloaded data, look for a folder named *apollo3.5*. Let's assume the path of this folder to be DATA_PATH. ``` /apollo/scripts/msf_simple_map_creator.sh DATA_PATH/records/ DATA_PATH/params/velodyne_params/velodyne128_novatel_extrinsics.yaml 10 OUT_FOLDER_PATH ``` After the script is finished, you can find the produced localization map named *local_map* in the output folder. The scripts also stores the visualization of each generated map node in the map's subfolder named `image`. The visualization of a map node filled with LiDAR data looks like this: ![1](images/msf_localization/map_node_image.png)
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/05_Localization/coordination_cn.md
# Apollo坐标系统 我们欢迎每一位开发者加入Apollo开发平台。Apollo系统涉及到了多种坐标系。在本文档中,我们将讨论在Apollo系统中使用的各个坐标系的定义。 ## 1. 全球地理坐标系统 在Apollo系统中,我们采用全球地理坐标系统来表示高精地图(HD Map)中各个元素的地理位置。全球地理坐标系统的通常用途是用来表示纬度、经度和海拔。Apollo采用的是WGS84(World Geodetic System 1984)作为标准坐标系来表示物体的纬度和经度。通过使用该标准坐标系统,我们可以使用2个数字:x坐标和y坐标来唯一的确定地球表面上除北极点之外的所有点,其中x坐标表示经度,y坐标表示纬度。WGS-84常用于GIS服务,例如地图绘制、定位和导航等。全球地理坐标系统的定义在下图中展示。 ![Image](images/coordination_01.png) ## 2. 局部坐标系 – 东-北-上(East-North-Up ENU) 在Apollo系统中,局部坐标系的定义为: z轴 – 指向上方(和重力线成一条直线) y轴 – 指向北面 x轴 – 指向东面 ![Image](images/coordination_02.png) ENU局部坐标系依赖于在地球表面上建立的3D笛卡尔坐标系。 通用横轴墨卡托正形投影(Universal Transverse Mercator UTM)使用2D的笛卡尔坐标系来给出地球表面点的位置。这不仅只是一次地图的映射。该坐标系统将地球划分为60个区域,每个区域表示为6度的经度带,并且在每个区域上使用割线横轴墨卡托投影。在Apollo系统中,UTM坐标系统在定位、Planning等模块中作为局部坐标系使用。 ![Image](images/coordination_03.png) 关于UTM坐标系统的使用,我们遵从国际标准规范。开发者可以参考下述网站获取更多细节: [http://geokov.com/education/utm.aspx](http://geokov.com/education/utm.aspx) [https://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system](https://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system) ## 3. 车辆坐标系 – 右-前-上(Right-Forward-Up RFU) 车辆坐标系的定义为: z轴 – 通过车顶垂直于地面指向上方 y轴 – 在行驶的方向上指向车辆前方 x轴 – 面向前方时,指向车辆右侧 车辆坐标系的原点在车辆后轮轴的中心。 ![Image](images/coordination_04.png)
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/05_Localization/how_to_run_NDT_localization_module_on_your_local_computer.md
# How to Run NDT Localization Module On Your Local Computer ## 1. Preparation - Follow the instructions in [Apollo Software Installation Guide](../01_Installation%20Instructions/apollo_software_installation_guide.md) - Download localization data from [Apollo Data Open Platform](http://data.apollo.auto/?name=sensor%20data&data_key=multisensor&data_type=1&locale=en-us&lang=en)(US only) the localization data is a experimental dataset to verify the availability of localization. It contains localization map(ndt_map/), vehicle params(params/), sensor recording data(records/). The specific attributes are as follows: duration: 5 mins mileage: 3km areas: city roads in Sunnyvale weather: sunny day ## 2. Configuring Parameters Assume that the path to download localization data from is DATA_PATH. ### 2.1. Configure Sensor Extrinsics NDT localization module use the same params path as msf localization module. ``` cp DATA_PATH/params/ant_imu_leverarm.yaml /apollo/modules/localization/msf/params/gnss_params/ cp DATA_PATH/params/velodyne64_novatel_extrinsics_example.yaml /apollo/modules/localization/msf/params/velodyne_params/ cp DATA_PATH/params/velodyne64_height.yaml /apollo/modules/localization/msf/params/velodyne_params/ ``` Add config of sensor extrinsics in `/apollo/modules/localization/conf/localization.conf` to overwrite the default value. ``` # The lidar extrinsics file --lidar_extrinsics_file=/apollo/modules/localization/msf/params/velodyne_params/velodyne64_novatel_extrinsics_example.yaml ``` The meaning of each file - **ant_imu_leverarm.yaml**: Lever arm value - **velodyne64_novatel_extrinsics_example.yaml**: Transform from IMU coord to LiDAR coord - **velodyne64_height.yaml**: Height of the LiDAR relative to the ground ### 2.2. Configure Map Path Add config of map path in /apollo/modules/localization/conf/localization.conf ``` # Redefine the map_dir in global_flagfile.txt --map_dir=DATA_PATH ``` This will overwrite the default config defined in global_flagfile.txt ### 2.3 Configure Topic Name For different LIDAR sensor, Apollo may has different LIDAR topic name. So set the right lidar topic name in `/apollo/modules/localization/conf/localization.conf` to overwrite the default value. ``` # The pointcloud topic name. --lidar_topic=/apollo/sensor/velodyne64/compensator/PointCloud2 ``` [optional] if you want to visualize localization result, you should also modify the LIDAR topic name in `/apollo/modules/localization/dag/dag_streaming_msf_visualizer.dag` ``` channel: /apollo/sensor/velodyne64/compensator/PointCloud2 ``` ## 3. Run the multi-sensor fusion localization module run the script in apollo directory ``` ./scripts/ndt_localization.sh ``` This script will run localization program in the background. You can check if the program is running by using the command. ``` ps -e | grep "ndt_localization" ``` In /apollo/data/log directory, you can see the localization log files. - localization.INFO : INFO log - localization.WARNING : WARNING log - localization.ERROR : ERROR log - localization.out : Redirect standard output - localizaiton.flags : A backup of configuration file ## 4. Play record bag ``` cd DATA_PATH/bag cyber_recorder play -f *.record ``` Open another ternimal and log in the docker environment, then execute: ``` cyber_monitor ``` It will display a topic list in which you can see topic `/apollo/localization/pose` ## 5. Record and Visualize localization result (optional) ### Record localization result ``` python ./scripts/record_bag.py ``` ### Visualize Localization result NDT localization module use the same visualization tools as MSF localization module. ``` ./scripts/localization_online_visualizer.sh ``` First, the visualization tool will generate a series of cache files from the localization map, which will be stored in the apollo/data/map_visual directory. Then it will receive the topics blew and draw them on screen. - /apollo/sensor/velodyne64/compensator/PointCloud2 - /apollo/localization/pose If everything is fine, you should see this on screen. ![1](images/ndt_localization/online_visualizer.png) ## 6. Stop localization module You can stop localizaiton module by ``` ./scripts/ndt_localization.sh stop ``` If you record localization result in step 5, you will also need to end the recording process: ``` python ./scripts/record_bag.py stop ``` ## 7. Verify the localization result (optional) NDT localization module also use the same evaluation scripts as MSF localization module. First, rename the recording file with suffix `.record`. ``` ./scripts/msf_local_evaluation.sh OUTPUT_PATH ANT_IMU_PATH ``` OUTPUT_PATH is the folder stored recording bag in step 5, and ANT_IMU_PATH is the file stored lever arm value. This script compares the localization results of NDT mode to RTK mode. (Aware that this comparison makes sense only when the RTK mode runs well.) And we can get the statistical results like this ![2](images/ndt_localization/ndt_eval.png) It only has one statistical data which is the localization result. Other result as in MSF mode will not show. The meaning of each row in the table - **error**: the plane error, unit is meter - **error lon**: the error in the car's heading direction, unit is meter - **error lat**: the error in the car's lateral direction, unit is meter - **error roll**: the roll angle error, unit is degree - **error pit**: the pitch angle error, unit is degree - **error yaw**: the yaw angle error, unit is degree The meaning of each col in the table - **mean**: evaluation value of the error - **std**: the standard deviation of the error - **max**: the maximum value of the error - **< xx**: percentage of frames whose error is smaller than the indicated range - **con_frame()**: the maximum number of consecutive frames that satisfy the conditions in parentheses
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/05_Localization/how_to_leverage_rtk_mode.md
# How to Leverage Apollo's RTK mode RTK mode helps developers and partners to better test your perception and control modules without needing to check the planning decisions. ## Process to use RTK Mode ### Step 1: Mode Selection 1. Build Apollo and Launch DreamView on http://localhost:8888 2. Set the mode as `RTK`, and select the vehicle type and map for your specific case ![](images/rtk_1.png) ### Step 2: Module Initialization 1. Select `Module Controller` from the left-side of Dreamview 2. Enable all modules under the RTK mode except `RTK Player` and `RTK Recorder` from the bottom right-hand side of the window 3. Under the Components section, pause until the `Data Recorder` and `Localization` both display `OK` status. ``` Note: to activate the localization module with accurate position signal shown on the Dreamview, the driver may need to manually drive the car around your parking lot several times. ``` ![](images/rtk_2.png) ### Step 3: Enable RTK Recorder 1. Drive the car to the beginning of the desired testing path. The car should currently be in `Manual` mode. 2. Enable the `RTK recorder`. From this moment on, Dreamview enters the `Path Recording` mode ![](images/rtk_3.png) ### Step 4: Manual Path Generation 1. Manually drive the car along the desired test path. This path will be recorded automatically 2. After reaching the end of the desired path, it is important to remember that you must disable the `RTK Recorder` module before anything else 3. Manually drive back to the initial position with both `RTK Player` and `RTK Recorder` off. ### Step 5: Enabling RTK Player 1. Enable the `RTK player`. The driver should be able to see the recorded path trajectory 2. The driver can then decide if he needs to adjust the car's position to record the path better 3. Once ready, the driver may click on `Start Auto`, and the car will be expected to track the recorded path automatically ```Note: Start Auto refers to putting the car into autonomous mode. This can be done by putting the car in neutral and clicking on the Start Auto button present in the Tasks window. ``` 4. When path tracking is complete, the driver may disable the `RTK player` or directly return back to the start point for the second/third/… run if applied ![](images/rtk_4.png) ``` Note: The blue line in the above image is the recorded path ``` ### 1. The recorded path will be never be cleared unless you re-record the path, so feel free to repeat the auto-mode path-tracking tests as many times as you may need 2. If a new path is needed, simply repeat steps 3 - 5 to record the new path. The newly recorded path will overwrite the old path automatically.
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/05_Localization/how_to_run_NDT_localization_module_on_your_local_computer_cn.md
# 如何在本地运行基于NDT点云匹配的定位模块 本文档提供了如何在本地基于NDT点云匹配的定位模块的方法。 ## 1. 事先准备 - 从[GitHub网站](https://github.com/ApolloAuto/apollo)下载Apollo master分支源代码 - 按照[教程](../01_Installation%20Instructions/apollo_software_installation_guide.md)设置Docker环境并搭建Apollo工程 - 从[Apollo数据平台](http://data.apollo.auto/?name=sensor%20data&data_key=multisensor&data_type=1&locale=en-us&lang=en)下载定位数据(仅限美国地区) 此定位数据为实验性质的demo数据,用于验证定位模块的可用性。数据主要包含定位地图(ndt_map/), 车辆参数(params/), 传感器数据(records/)。具体属性如下: 时长:5分钟 里程:3km 场景:Sunnyvale 城市道路 天气:晴天 ## 2. 配置定位模块 为了使定位模块正确运行,需要对地图路径和传感器外参进行配置。假设下载的定位数据的所在路径为DATA_PATH。 在进行以下步骤前,首先确定你在docker容器中。 ### 2.1 配置传感器外参 将定位数据中的传感器外参拷贝至指定文件夹下, 目前NDT定位模块与MSF定位模块使用相同外参路径。 ``` cp DATA_PATH/params/ant_imu_leverarm.yaml /apollo/modules/localization/msf/params/gnss_params/ cp DATA_PATH/params/velodyne64_novatel_extrinsics_example.yaml /apollo/modules/localization/msf/params/velodyne_params/ cp DATA_PATH/params/velodyne64_height.yaml /apollo/modules/localization/msf/params/velodyne_params/ ``` 在`/apollo/modules/localization/conf/localization.conf`中添加传感器外参文件配置,以覆盖默认值。 ``` # The lidar extrinsics file --lidar_extrinsics_file=/apollo/modules/localization/msf/params/velodyne_params/velodyne64_novatel_extrinsics_example.yaml ``` 各个外参的意义 - ant_imu_leverarm.yaml: 杆臂值参数,GNSS天线相对Imu的距离 - velodyne64_novatel_extrinsics_example.yaml: Lidar相对Imu的外参 - velodyne64_height.yaml: Lidar相对地面的高度 ### 2.2 配置地图路径 在`/apollo/modules/localization/conf/localization.conf`中添加关于地图路径的配置 ``` # Redefine the map_dir in global_flagfile.txt --map_dir=DATA_PATH ``` 这将会覆盖global_flagfile.txt中的默认值。 ### 2.3 修改Topic名称 由于目前Apollo支持velodyne 64线,128线lidar, 因此为区分不同设备数据,采用不同的topic名称。因此,在启动之前需要设置正确的lidar topic名称。在`/apollo/modules/localization/conf/localization.conf`中添加lidar topic名称,以覆盖默认值。 ``` # The pointcloud topic name. --lidar_topic=/apollo/sensor/velodyne64/compensator/PointCloud2 ``` (可选)另外,对于定位可视化工具的使用,同样需要配置相应的topic名称。修改文件`/apollo/modules/localization/dag/dag_streaming_msf_visualizer.dag` 中的channel值为: ``` channel: /apollo/sensor/velodyne64/compensator/PointCloud2 ``` ## 3. 运行NDT定位模块 ``` ./scripts/ndt_localization.sh ``` 定位程序将在后台运行,可以通过以下命令进行查看。 ``` ps -e | grep ndt_localization ``` 在/apollo/data/log目录下,可以看到定位模块输出的相关文件。 - localization.INFO : INFO级别的log信息 - localization.WARNING : WARNING级别的log信息 - localization.ERROR : ERROR级别的log信息 - localization.out : 标准输出重定向文件 - localizaiton.flags : 启动localization模块使用的配置 ## 4. 播放演示record ``` cd DATA_PATH/record cyber_record play -f *.record ``` 另外打开一个终端,进入docker环境,执行 ``` cyber_monitor ``` 终端会显示出topic列表,可以看到定位topic `/apollo/localization/pose` 有输出。 ## 5. 记录与可视化定位结果(可选) ### 记录定位结果 ``` python ./scripts/record_bag.py ``` 该脚本会在后台运行录包程序,并将存放路径输出到终端上。 ### 可视化定位结果 NDT定位模块使用与MSF定位模块相同的可视化工具。 运行可视化工具 ``` ./scripts/localization_online_visualizer.sh ``` 该可视化工具首先根据MSF定位地图生成用于可视化的缓存文件,存放在/apollo/data/map_visual目录下。 然后接收以下topic并进行可视化绘制。 - /apollo/sensor/velodyne64/compensator/PointCloud2 - /apollo/localization/pose 可视化效果如下 ![1](images/ndt_localization/online_visualizer.png) 如果发现可视化工具运行时卡顿,可使用如下命令重新编译可视化工具 ``` cd /apollo bazel build -c opt //modules/localization/msf/local_tool/local_visualization/online_visual:online_local_visualizer ``` 编译选项-c opt优化程序性能,从而使可视化工具可以实时运行。 ## 6. 结束运行定位模块 ``` ./scripts/ndt_localization.sh stop ``` 如果之前有运行步骤5的录包脚本,还需执行 ``` python ./scripts/record_bag.py --stop ``` ## 7. 验证定位结果(可选) NDT模块定位结果的验证使用MSF模块的验证工具。 假设步骤5中录取的数据存放路径为OUTPUT_PATH,杆臂值外参的路径为ANT_IMU_PATH。 首先将录制的数据包重命名为以`.record`为后缀的文件。 运行脚本 ``` ./scripts/msf_local_evaluation.sh OUTPUT_PATH ANT_IMU_PATH ``` 该脚本会以RTK定位模式为基准,将多传感器融合模式的定位结果进行对比。 (注意只有在GNSS信号良好,RTK定位模式运行良好的区域,这样的对比才是有意义的。) 获得如下统计结果: ![2](images/ndt_localization/ndt_eval.png) NDT模块的统计结果只有一组,即定位输出`/apollo/localization/pose`的统计结果。 表格中各项的意义, - error: 平面误差,单位为米 - error lon: 车前进方向的误差,单位为米 - error lat: 车横向方向的误差,单位为米 - error roll: 翻滚角误差,单位为度 - error pit: 俯仰角误差,单位为度 - error yaw: 偏航角误差,单位为度 - mean: 误差的平均值 - std: 误差的标准差 - max: 误差的最大值 - <30cm: 距离误差少于30cm的帧所占的百分比 - <1.0d: 角度误差小于1.0d的帧所占的百分比 - con_frame(): 满足括号内条件的最大连续帧数
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/05_Localization/apollo1.5_localization_module_study_notes_cn.md
# Localization module 分析 ## 作用: 实时确定车辆的位置。 ## Localization节点流图: ### 节点数据流图: ![localization data flow](images/localization_node_arch.bmp) ### 输入: * Imu数据:/apollo/sensor/gnss/corrected_imu。 * Gps数据:/apollo/sensor/gnss/odometry。 ### 输出: * 定位信息:/apollo/localization/pose。 * 监视信息:/apollo/localization/。 ## 代码分析: 主要文件:localization.cc,localization.h,localization_base.h。 ### Localization类: * 继承于ApolloApp类,有三个数据,localization_具体的定位算法实例指针,localization_factory_存储定位算法类,config_存储配置文件信息。 * Init()函数注册RTKLocalization类到localization_factory_,此类基于RTK算法实现定位算法;读取配置文件到config_。 * Name()函数返回模块名字。 * Start()函数,用localization_factory_类实例化一个定位算法对象,用localization_直向。若创建成功,调用定位算法的start()函数。 ### LocalizationBase类: * 定位算法的基类。 * Start()函数启动定位算法。 * Stop()函数终止定位算法。 ### RTKLocalization类: * 继承LocalizationBase类。 * Start()函数:创建timer,检测gps和imu是否有数据。超时执行OnTimer()函数。OnTimer()函数检查gps和imu是否有数据,然后调用PublishLocalization()发布定位信息,并更新数据接收时间。在PublishLocalization()函数中先调用PrepareLocalizationMsg()函数计算定位信息,并填充发布数据结构localization;然后调用AdapterManager::PublishLocalization发布定位topic。PrepareLocalizationMsg(&localization)函数首先获取gps数据,然后根据gps数据时间戳获取imu数据,然后调用ComposeLocalizationMsg()函数,进行数据融合以定位,其实所谓的数据融合也就是在最终的定位信息中分别使用gps和imu测得数据设置定位信息,唯一由两个器件融合的量只有线速度。所谓RTK算法应该单指由gps数据获取gps定位信息,在localization阶段其实是使用这个定位信息,真正RTK算法应该是作用在gps数据的处理上。 * Stop()函数停止timer,即退出定位模式。 ## 疑惑: * 定位信息给出的应该是车辆在世界中的的绝对位置,因为采用gps数据,那么这个位置如何与地图建立关系的? 答:地图中的点也可能是世界中的绝对位置。 * map_offset这个量的作用://TODO
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/09_Decider/path_bounds_decider_cn.md
# 路径边界决策 ### *目录* - [概览](#概览) - [路径边界决策代码及对应版本](#路径边界决策代码及对应版本) + [类关系](#类关系) + [路径边界决策数据](#路径边界决策数据) - [路径边界决策代码流程及框架](#路径边界决策代码流程及框架) - [路径边界决策算法解析](#路径边界决策算法解析) + [1.fallback](#1.fallback) + [2.pull over](#2.pull-over) + [3.lane change](#3.lane-change) + [4.Regular](#4.Regular) # 概览 `路径边界决策`是规划模块的任务,属于task中的decider类别。 规划模块的运动总体流程图如下: ![总体流程图](../images/task/lane_follow.png) 总体流程图以[lane follow](https://github.com/ApolloAuto/apollo/blob/r6.0.0/modules/planning/conf/scenario/lane_follow_config.pb.txt)场景为例子进行说明。这里只说明主体的流程,不涉及到所有细节。task的主要功能位于`Process`函数中。 第一,规划模块的入口函数是PlanningComponent的[Proc](https://github.com/ApolloAuto/apollo/blob/r6.0.0/modules/planning/planning_component.cc#L118)。 第二,以规划模式OnLanePlanning,执行[RunOnce](https://github.com/ApolloAuto/apollo/blob/r6.0.0/modules/planning/on_lane_planning.cc#L205)。在RunOnce中先执行交通规则,再规划轨迹。规划轨迹的函数是[Plan](https://github.com/ApolloAuto/apollo/blob/r6.0.0/modules/planning/on_lane_planning.cc#L487)。 第三,进入到PublicRoadPlanner中的[Plan](https://github.com/ApolloAuto/apollo/blob/r6.0.0/modules/planning/planner/public_road/public_road_planner.cc#L33)函数,进行轨迹规划。ScenarioManager的[Update](https://github.com/ApolloAuto/apollo/blob/r6.0.0/modules/planning/scenarios/scenario_manager.cc#L798)函数根据当前的scenario_type选择合适的场景。这里的流程图是以lane follow为例。 第四,选择lane follow的场景后,执行[Process](https://github.com/ApolloAuto/apollo/blob/r6.0.0/modules/planning/scenarios/scenario.cc#L66)函数。然后,执行LaneFollowStage中的[Process](https://github.com/ApolloAuto/apollo/blob/r6.0.0/modules/planning/scenarios/lane_follow/lane_follow_stage.cc#L93)函数,在[PlanOnReferenceLine](https://github.com/ApolloAuto/apollo/blob/r6.0.0/modules/planning/scenarios/lane_follow/lane_follow_stage.cc#L153)中执行LaneFollowStage中的所有的task。通过调用[Excute](https://github.com/ApolloAuto/apollo/blob/r6.0.0/modules/planning/scenarios/lane_follow/lane_follow_stage.cc#L167)函数执行task,Excute调用了task的[Process](https://github.com/ApolloAuto/apollo/blob/r6.0.0/modules/planning/tasks/deciders/decider.cc#L37)(以decider为例子)函数。最后一个图中,TaskType指的不是具体的类名称,代表所有的task类型。虚线的箭头,表示在LaneFollowStage中按照vector中的顺序执行所有的任务。 最后,Task的流程都在Process函数中。之后对task的讲解都从Process函数开始。 # 路径边界决策代码及对应版本 本节说明path_bounds_decider任务。 请参考 [Apollo r6.0.0 path_bounds_decider](https://github.com/ApolloAuto/apollo/tree/r6.0.0/modules/planning/tasks/deciders/path_bounds_decider) ## 类关系 ![path_bounds_decider_task](../images/task/path_bounds_decider/task.png) ### (1)继承关系 ① `PathBoundsDecider`类继承`Decider`类,实现了`Process`方法,路径边界决策主要的执行过程就在`process`方法中。 ```C++ // modules/planning/tasks/deciders/path_bounds_decider/path_bounds_decider.h class PathBoundsDecider : public Decider { ... }; ``` ② `Decider`类继承`Task`类,实现类Excute方法,主要是给两个变量赋值:`frame`和`reference_line_info`,并且执行**Process**方法。对应了上述的**Process**方法 ```C++ // modules/planning/tasks/deciders/decider.h class Decider : public Task { ... }; // modules/planning/tasks/deciders/decider.cc apollo::common::Status Decider::Execute( Frame* frame, ReferenceLineInfo* reference_line_info) { Task::Execute(frame, reference_line_info); return Process(frame, reference_line_info); } apollo::common::Status Decider::Execute(Frame* frame) { Task::Execute(frame); return Process(frame); } ``` ③ `Task`类,定义类保护类型的变量,是路径边界决策的输入 ```C++ // modules/planning/tasks/task.h class Task { public: // 虚方法,主要是给frame和reference_line_info赋值 virtual common::Status Execute(Frame* frame, ReferenceLineInfo* reference_line_info); virtual common::Status Execute(Frame* frame); protected: // frame和reference_line_info变量 Frame* frame_ = nullptr; ReferenceLineInfo* reference_line_info_ = nullptr; // 配置与名字 TaskConfig config_; std::string name_; ... }; ``` ### (2)调用 主要描述task在stage中是如何创建和调用的 ① `TaskFactory`类,注册所有的task,包括decider、optimizer和other(E2E的task)。工厂模式 ```C++ // modules/planning/tasks/task_factory.h class TaskFactory { public: // 两个函数都是static属性 static void Init(...); // 在初始化函数中,注册所有的task static std::unique_ptr<Task> CreateTask(...); // 创建具体task的实例,返回指向该实例的指针 ... }; ``` ② stage中task的创建与执行 - 创建:在stage的构造函数中根据stage配置创建task。并将指针放入到task_和task_list_中 - 使用:在具体的stage中,重写Process方法。调用Process方法,进而调用ExecuteTask*方法(ExecuteTaskOnReferenceLine),最后调用相应的task的Process方法 ```C++ // modules/planning/scenarios/stage.h class Stage { // 在构造函数中根据stage的配置创建task Stage(const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector); public: // 纯虚函数,留给具体的stage实现,不同的stage有不同的实现逻辑 virtual StageStatus Process( const common::TrajectoryPoint& planning_init_point, Frame* frame) = 0; protected: // 三个执行task的函数,在每个函数中都调用类task的Excute方法,进一步调用具体task的Process方法 bool ExecuteTaskOnReferenceLine( const common::TrajectoryPoint& planning_start_point, Frame* frame); bool ExecuteTaskOnReferenceLineForOnlineLearning( const common::TrajectoryPoint& planning_start_point, Frame* frame); bool ExecuteTaskOnOpenSpace(Frame* frame); protected: // task的map,key是TaskType,value是指向Task的指针 std::map<TaskConfig::TaskType, std::unique_ptr<Task>> tasks_; // 保存Task列表 std::vector<Task*> task_list_; // stage 配置 ScenarioConfig::StageConfig config_; ...}; ``` ## 路径边界决策数据 `PathBoundsDecider`类主要的输入、输出,数据结构,变量设置。 ### (1)输入和输出 ① 输入有两个:`frame`与`reference_line_info` - **frame** frame中包含的一次规划所需要的所有的数据 ```C++ // modules/planning/common/frame.h class Frame { private: static DrivingAction pad_msg_driving_action_; uint32_t sequence_num_ = 0; /* Local_view是一个结构体,包含了如下信息 // modules/planning/common/local_view.h struct LocalView { std::shared_ptr<prediction::PredictionObstacles> prediction_obstacles; std::shared_ptr<canbus::Chassis> chassis; std::shared_ptr<localization::LocalizationEstimate> localization_estimate; std::shared_ptr<perception::TrafficLightDetection> traffic_light; std::shared_ptr<routing::RoutingResponse> routing; std::shared_ptr<relative_map::MapMsg> relative_map; std::shared_ptr<PadMessage> pad_msg; std::shared_ptr<storytelling::Stories> stories; }; */ LocalView local_view_; // 高清地图 const hdmap::HDMap *hdmap_ = nullptr; common::TrajectoryPoint planning_start_point_; // 车辆状态 // modules/common/vehicle_state/proto/vehicle_state.proto common::VehicleState vehicle_state_; // 参考线信息 std::list<ReferenceLineInfo> reference_line_info_; bool is_near_destination_ = false; /** * the reference line info that the vehicle finally choose to drive on **/ const ReferenceLineInfo *drive_reference_line_info_ = nullptr; ThreadSafeIndexedObstacles obstacles_; std::unordered_map<std::string, const perception::TrafficLight *> traffic_lights_; // current frame published trajectory ADCTrajectory current_frame_planned_trajectory_; // current frame path for future possible speed fallback DiscretizedPath current_frame_planned_path_; const ReferenceLineProvider *reference_line_provider_ = nullptr; OpenSpaceInfo open_space_info_; std::vector<routing::LaneWaypoint> future_route_waypoints_; common::monitor::MonitorLogBuffer monitor_logger_buffer_; }; ``` - **reference_line_info** reference_line_info包含了有关reference_line的所有的数据 ```C++ // modules/planning/common/reference_line_info.h class ReferenceLineInfo { ... private: static std::unordered_map<std::string, bool> junction_right_of_way_map_; const common::VehicleState vehicle_state_; // 车辆状态 const common::TrajectoryPoint adc_planning_point_; // TrajectoryPoint定义在modules/common/proto/pnc_point.proto中 /* 参考线,以道路中心线,做过顺滑的一条轨迹,往后80米,往前130米。 class ReferenceLine { ... private: struct SpeedLimit { double start_s = 0.0; double end_s = 0.0; double speed_limit = 0.0; // unit m/s ...}; // This speed limit overrides the lane speed limit std::vector<SpeedLimit> speed_limit_; std::vector<ReferencePoint> reference_points_; // ReferencePoint包含有信息(k, dk, x, y, heading, s, l) hdmap::Path map_path_; uint32_t priority_ = 0; }; */ ReferenceLine reference_line_; /** * @brief this is the number that measures the goodness of this reference * line. The lower the better. */ // 评价函数,值越低越好 double cost_ = 0.0; bool is_drivable_ = true; // PathDecision包含了一条路径上的所有obstacle的决策,有两种:lateral(Nudge, Ignore)和longitudinal(Stop, Yield, Follow, Overtake, Ignore) PathDecision path_decision_; // 指针 Obstacle* blocking_obstacle_; /* path的边界,结果保存在这个变量里。通过**SetCandidatePathBoundaries**方法保存到此变量 // modules/planning/common/path_boundary.h class PathBoundary { ... private: double start_s_ = 0.0; double delta_s_ = 0.0; std::vector<std::pair<double, double>> boundary_; std::string label_ = "regular"; std::string blocking_obstacle_id_ = ""; }; */ std::vector<PathBoundary> candidate_path_boundaries_; // PathData类,包含XY坐标系和SL坐标系的相互转化 std::vector<PathData> candidate_path_data_; PathData path_data_; PathData fallback_path_data_; SpeedData speed_data_; DiscretizedTrajectory discretized_trajectory_; RSSInfo rss_info_; /** * @brief SL boundary of stitching point (starting point of plan trajectory) * relative to the reference line */ SLBoundary adc_sl_boundary_; ... }; ``` ② 输出: ```C++ Status PathBoundsDecider::Process( Frame* const frame, ReferenceLineInfo* const reference_line_info) ``` Process 函数定义,最终结果保存到了`reference_line_info`中 ### (2)参数设置 ```C++ // modules/planning/tasks/deciders/path_bounds_decider/path_bounds_decider.cc // s方向的距离 constexpr double kPathBoundsDeciderHorizon = 100.0; // s方向的间隔 constexpr double kPathBoundsDeciderResolution = 0.5; // Lane宽度 constexpr double kDefaultLaneWidth = 5.0; // Road的道路 constexpr double kDefaultRoadWidth = 20.0; // TODO(all): Update extra tail point base on vehicle speed. constexpr int kNumExtraTailBoundPoint = 20; constexpr double kPulloverLonSearchCoeff = 1.5; constexpr double kPulloverLatSearchCoeff = 1.25; ``` ### (3)数据结构 ```C++ // modules/planning/tasks/deciders/path_bounds_decider/path_bounds_decider.cc namespace { // PathBoundPoint contains: (s, l_min, l_max). 路径边界点 using PathBoundPoint = std::tuple<double, double, double>; // PathBound contains a vector of PathBoundPoints. 路径边界 using PathBound = std::vector<PathBoundPoint>; // ObstacleEdge contains: (is_start_s, s, l_min, l_max, obstacle_id). 障碍物的边 using ObstacleEdge = std::tuple<int, double, double, double, std::string>; } // namespace ``` # 路径边界决策代码流程及框架 Fig.2是路径边界决策的流程图。 ![path_bounds_decider](../images/task/path_bounds_decider/path_bounds_decider.png) 在**Process**方法中,分四种场景对路径边界进行计算,按照处理的顺序分别是:fallback,pull-over,lane-change,regular。 其中regular场景根据是否借道又分为LEFT_BORROW, NO_BORROW, RIGHT_BORROW。 fallback场景的path bounds一定会生成,另外三种看情况,都是需要if判断。 # 路径边界决策算法解析 ## 1.fallback ![fallback](../images/task/path_bounds_decider/fallback.png) fallback场景生成过程如上图所示。 fallback只考虑adc信息和静态道路信息,主要调用两个函数 - InitPathBoundary ```C++ bool PathBoundsDecider::InitPathBoundary( ... // Starting from ADC's current position, increment until the horizon, and // set lateral bounds to be infinite at every spot. // 从adc当前位置开始,以0.5m为间隔取点,直到终点,将 [左, 右] 边界设置为double的 [lowerst, max] for (double curr_s = adc_frenet_s_; curr_s < std::fmin(adc_frenet_s_ + std::fmax(kPathBoundsDeciderHorizon, reference_line_info.GetCruiseSpeed() * FLAGS_trajectory_time_length), reference_line.Length()); curr_s += kPathBoundsDeciderResolution) { path_bound->emplace_back(curr_s, std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max()); } ...} ``` - GetBoundaryFromLanesAndADC ```C++ // TODO(jiacheng): this function is to be retired soon. bool PathBoundsDecider::GetBoundaryFromLanesAndADC( ... for (size_t i = 0; i < path_bound->size(); ++i) { double curr_s = std::get<0>((*path_bound)[i]); // 1. Get the current lane width at current point.获取当前点车道的宽度 if (!reference_line.GetLaneWidth(curr_s, &curr_lane_left_width, &curr_lane_right_width)) { AWARN << "Failed to get lane width at s = " << curr_s; curr_lane_left_width = past_lane_left_width; curr_lane_right_width = past_lane_right_width; } else {...} // 2. Get the neighbor lane widths at the current point.获取当前点相邻车道的宽度 double curr_neighbor_lane_width = 0.0; if (CheckLaneBoundaryType(reference_line_info, curr_s, lane_borrow_info)) { hdmap::Id neighbor_lane_id; if (lane_borrow_info == LaneBorrowInfo::LEFT_BORROW) { // 借左车道 ... } else if (lane_borrow_info == LaneBorrowInfo::RIGHT_BORROW) { // 借右车道 ... } } // 3. 根据道路宽度,adc的位置和速度计算合适的边界。 static constexpr double kMaxLateralAccelerations = 1.5; double offset_to_map = 0.0; reference_line.GetOffsetToMap(curr_s, &offset_to_map); double ADC_speed_buffer = (adc_frenet_ld_ > 0 ? 1.0 : -1.0) * adc_frenet_ld_ * adc_frenet_ld_ / kMaxLateralAccelerations / 2.0; // 向左车道借到,左边界会变成左侧车道左边界 double curr_left_bound_lane = curr_lane_left_width + (lane_borrow_info == LaneBorrowInfo::LEFT_BORROW ? curr_neighbor_lane_width : 0.0); // 和上面类似 double curr_right_bound_lane = -curr_lane_right_width - (lane_borrow_info == LaneBorrowInfo::RIGHT_BORROW ? curr_neighbor_lane_width : 0.0); double curr_left_bound = 0.0; // 左边界 double curr_right_bound = 0.0; // 右边界 // 计算左边界和右边界 if (config_.path_bounds_decider_config() .is_extend_lane_bounds_to_include_adc() || is_fallback_lanechange) { // extend path bounds to include ADC in fallback or change lane path // bounds. double curr_left_bound_adc = std::fmax(adc_l_to_lane_center_, adc_l_to_lane_center_ + ADC_speed_buffer) + GetBufferBetweenADCCenterAndEdge() + ADC_buffer; curr_left_bound = std::fmax(curr_left_bound_lane, curr_left_bound_adc) - offset_to_map; double curr_right_bound_adc = std::fmin(adc_l_to_lane_center_, adc_l_to_lane_center_ + ADC_speed_buffer) - GetBufferBetweenADCCenterAndEdge() - ADC_buffer; curr_right_bound = std::fmin(curr_right_bound_lane, curr_right_bound_adc) - offset_to_map; } else { curr_left_bound = curr_left_bound_lane - offset_to_map; curr_right_bound = curr_right_bound_lane - offset_to_map; } // 4. 更新边界. if (!UpdatePathBoundaryWithBuffer(i, curr_left_bound, curr_right_bound, path_bound, is_left_lane_boundary, is_right_lane_boundary)) { path_blocked_idx = static_cast<int>(i); } ... } ``` ## 2.pull over ![pull_over](../images/task/path_bounds_decider/pull_over.png) ### (1)GetBoundaryFromRoads 与`GetBoundaryFromLanesAndADC`不同,`GetBoundaryFromRoads`函数根据道路信息计算出边界: - 获取参考线信息 - 对路径上的点,逐点计算 + 边界 + 更新 ### (2)GetBoundaryFromStaticObstacles 根据障碍车调整边界: - 计算障碍车在frenet坐标系下的坐标 - 扫描线排序,S方向扫描 + 只关注在路径边界内的障碍物 + 只关注在adc前方的障碍物 + 将障碍物分解为两个边界,开始和结束 - 映射障碍物ID + Adc能从左边通过为True,否则为False - 逐个点的检查path路径上的障碍物 + 根据新来的障碍物 + 根据已有的障碍物 ### (3)SearchPullOverPosition 搜索pull over位置的过程: - 根据pull_over_status.pull_over_type()判断是前向搜索(pull over开头第一个点),还是后向搜索(pull over末尾后一个点) - 两层循环,外层控制搜索的索引idx,内层控制进一步的索引(前向idx+1,后向idx-1)。 - 根据内外两层循环的索引,判断搜索到的空间是否满足宽度和长度要求,判断是否可以pull over 代码如下: ```C++ bool PathBoundsDecider::SearchPullOverPosition( const Frame& frame, const ReferenceLineInfo& reference_line_info, const std::vector<std::tuple<double, double, double>>& path_bound, std::tuple<double, double, double, int>* const pull_over_configuration) { const auto& pull_over_status = injector_->planning_context()->planning_status().pull_over(); // 搜索方向,默认前向搜索 bool search_backward = false; // search FORWARD by default double pull_over_s = 0.0; if (pull_over_status.pull_over_type() == PullOverStatus::EMERGENCY_PULL_OVER) {...} int idx = 0; if (search_backward) { // 后向搜索,定位pull over末尾的一个点. idx = static_cast<int>(path_bound.size()) - 1; while (idx >= 0 && std::get<0>(path_bound[idx]) > pull_over_s) { --idx; } } else { // 前向搜索,定位emergency pull over开头后的第一个点. while (idx < static_cast<int>(path_bound.size()) && std::get<0>(path_bound[idx]) < pull_over_s) { ++idx; } } // 为pull over搜索到一个可行的位置,主要是确定该区域的宽度和长度 const double pull_over_space_length = kPulloverLonSearchCoeff * VehicleConfigHelper::GetConfig().vehicle_param().length() - FLAGS_obstacle_lon_start_buffer - FLAGS_obstacle_lon_end_buffer; const double pull_over_space_width = (kPulloverLatSearchCoeff - 1.0) * VehicleConfigHelper::GetConfig().vehicle_param().width(); const double adc_half_width = VehicleConfigHelper::GetConfig().vehicle_param().width() / 2.0; // 2. Find a window that is close to road-edge. /* 这里用了内外两层循环进行搜索,外层循环控制搜索的开始的端点idx。 内层控制另一个端点。根据找到的两个端点,判断区域是否可以pull over */ bool has_a_feasible_window = false; while ((search_backward && idx >= 0 && std::get<0>(path_bound[idx]) - std::get<0>(path_bound.front()) > pull_over_space_length) || (!search_backward && idx < static_cast<int>(path_bound.size()) && std::get<0>(path_bound.back()) - std::get<0>(path_bound[idx]) > pull_over_space_length)) { while ((search_backward && j >= 0 && std::get<0>(path_bound[idx]) - std::get<0>(path_bound[j]) < pull_over_space_length) || (!search_backward && j < static_cast<int>(path_bound.size()) && std::get<0>(path_bound[j]) - std::get<0>(path_bound[idx]) < pull_over_space_length)) {...} // 找到可行区域,获取停车区域的位置和姿态 if (is_feasible_window) { ... break;} ...} // 外层while ... } ``` ## 3.lane change ![lane_change](../images/task/path_bounds_decider/lane_change.png) 代码流程如下: ```C++ Status PathBoundsDecider::GenerateLaneChangePathBound( const ReferenceLineInfo& reference_line_info, std::vector<std::tuple<double, double, double>>* const path_bound) { // 1.初始化,和前面的步骤类似 if (!InitPathBoundary(reference_line_info, path_bound)) {...} // 2. 根据道路和adc的信息获取一个大致的路径边界 std::string dummy_borrow_lane_type; if (!GetBoundaryFromLanesAndADC(reference_line_info, LaneBorrowInfo::NO_BORROW, 0.1, path_bound, &dummy_borrow_lane_type, true)) {...} // 3. Remove the S-length of target lane out of the path-bound. GetBoundaryFromLaneChangeForbiddenZone(reference_line_info, path_bound); // 根据静态障碍物调整边界. if (!GetBoundaryFromStaticObstacles(reference_line_info.path_decision(), path_bound, &blocking_obstacle_id)) {...} ... } ``` GetBoundaryFromLaneChangeForbiddenZone函数是lane change重要的函数。运行过程如下: - 如果当前位置可以变道,则直接变道 - 如果有一个lane-change的起点,则直接使用它 - 逐个检查变道前的点的边界,改变边界的值(如果已经过了变道点,则返回) ```C++ void PathBoundsDecider::GetBoundaryFromLaneChangeForbiddenZone( const ReferenceLineInfo& reference_line_info, PathBound* const path_bound) { // 1.当前位置直接变道。 auto* lane_change_status = injector_->planning_context() ->mutable_planning_status() ->mutable_change_lane(); if (lane_change_status->is_clear_to_change_lane()) { ADEBUG << "Current position is clear to change lane. No need prep s."; lane_change_status->set_exist_lane_change_start_position(false); return; } // 2.如果已经有一个lane-change的起点,就直接使用它,否则再找一个 double lane_change_start_s = 0.0; if (lane_change_status->exist_lane_change_start_position()) { common::SLPoint point_sl; reference_line.XYToSL(lane_change_status->lane_change_start_position(), &point_sl); lane_change_start_s = point_sl.s(); } else { // TODO(jiacheng): train ML model to learn this. // 设置为adc前方一段距离为变道起始点 lane_change_start_s = FLAGS_lane_change_prepare_length + adc_frenet_s_; // Update the decided lane_change_start_s into planning-context. // 更新变道起始点的信息 common::SLPoint lane_change_start_sl; lane_change_start_sl.set_s(lane_change_start_s); lane_change_start_sl.set_l(0.0); common::math::Vec2d lane_change_start_xy; reference_line.SLToXY(lane_change_start_sl, &lane_change_start_xy); lane_change_status->set_exist_lane_change_start_position(true); lane_change_status->mutable_lane_change_start_position()->set_x( lane_change_start_xy.x()); lane_change_status->mutable_lane_change_start_position()->set_y( lane_change_start_xy.y()); } // Remove the target lane out of the path-boundary, up to the decided S. // 逐个检查变道前的点的边界,改变边界的值 for (size_t i = 0; i < path_bound->size(); ++i) { double curr_s = std::get<0>((*path_bound)[i]); if (curr_s > lane_change_start_s) { break; } double curr_lane_left_width = 0.0; double curr_lane_right_width = 0.0; double offset_to_map = 0.0; reference_line.GetOffsetToMap(curr_s, &offset_to_map); if (reference_line.GetLaneWidth(curr_s, &curr_lane_left_width, &curr_lane_right_width)) { double offset_to_lane_center = 0.0; reference_line.GetOffsetToMap(curr_s, &offset_to_lane_center); curr_lane_left_width += offset_to_lane_center; curr_lane_right_width -= offset_to_lane_center; } curr_lane_left_width -= offset_to_map; curr_lane_right_width += offset_to_map; std::get<1>((*path_bound)[i]) = adc_frenet_l_ > curr_lane_left_width ? curr_lane_left_width + GetBufferBetweenADCCenterAndEdge() : std::get<1>((*path_bound)[i]); std::get<1>((*path_bound)[i]) = std::fmin(std::get<1>((*path_bound)[i]), adc_frenet_l_ - 0.1); std::get<2>((*path_bound)[i]) = adc_frenet_l_ < -curr_lane_right_width ? -curr_lane_right_width - GetBufferBetweenADCCenterAndEdge() : std::get<2>((*path_bound)[i]); std::get<2>((*path_bound)[i]) = std::fmax(std::get<2>((*path_bound)[i]), adc_frenet_l_ + 0.1); } } ``` ## 4.Regular ![lane_change](../images/task/path_bounds_decider/regular.png) 代码流程如下: ```C++ Status PathBoundsDecider::GenerateRegularPathBound( const ReferenceLineInfo& reference_line_info, const LaneBorrowInfo& lane_borrow_info, PathBound* const path_bound, std::string* const blocking_obstacle_id, std::string* const borrow_lane_type) { // 1.初始化边界. if (!InitPathBoundary(reference_line_info, path_bound)) {...} // 2.根据adc位置和lane信息确定大致的边界 if (!GetBoundaryFromLanesAndADC(reference_line_info, lane_borrow_info, 0.1, path_bound, borrow_lane_type)) {...} // PathBoundsDebugString(*path_bound); // 3.根据障碍物调整道路边界 if (!GetBoundaryFromStaticObstacles(reference_line_info.path_decision(), path_bound, blocking_obstacle_id)) {...} ... } ``` 流程和上面的几个基本类似,借道有三种类型 ```C++ enum class LaneBorrowInfo { LEFT_BORROW, NO_BORROW, RIGHT_BORROW, }; ```
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/09_Decider/piece_wise_jerk_path_cn.md
# 分段加加速度路径优化 _**Tip**: 为了更好的展示本文档中的等式,我们建议使用者使用带有[插件](https://chrome.google.com/webstore/detail/tex-all-the-things/cbimabofgmfdkicghcadidpemeenbffn)的Chrome浏览器,或者将Latex等式拷贝到[在线编辑公式网站](http://www.hostmath.com/)进行浏览。_ ### *目录* - [概览](#概览) - [相关代码及对应版本](#相关代码及对应版本) - [代码流程及框架](#代码流程及框架) - [相关算法解析](#相关算法解析) # 概览 `分段加加速度路径优化`是规划模块的任务,属于task中的optimizer类别。 规划模块的运动总体流程图如下: ![总体流程图](../images/task/lane_follow.png) 总体流程图以[lane follow](https://github.com/ApolloAuto/apollo/blob/r6.0.0/modules/planning/conf/scenario/lane_follow_config.pb.txt)场景为例子进行说明。task的主要功能位于`Process`函数中。 Fig.1的具体运行过程可以参考[path_bounds_decider]()。 `分段加加速度路径优化`的流程如下图: ![总体流程图](../images/task/piecewise_jerk_path/piecewise_jerk_path.png) # 相关代码及对应版本 本节说明`分段加加速度路径优化`代码和算法。 请参考代码[Apollo r6.0.0 piecewise_jerk_path_optimization](https://github.com/ApolloAuto/apollo/tree/r6.0.0/modules/planning/tasks/optimizers/piecewise_jerk_path) - 输入 `PiecewiseJerkPathOptimizer::Process( const SpeedData& speed_data, const ReferenceLine& reference_line, const common::TrajectoryPoint& init_point, const bool path_reusable, PathData* const final_path_data)` 其中包括参考线,起始点等。 - 输出 `OptimizePath`函数得到最优的路径,信息包括$opt\_l, opt\_dl, opt\_ddl$。在`Process`函数中最终结果保存到了task基类的变量reference_line_info_中。 # 代码流程及框架 `分段加加速度路径优化`代码的流程图如下。 ![代码流程图](../images/task/piecewise_jerk_path/code.png) - 如果重复使用path则return ```C++ common::Status PiecewiseJerkPathOptimizer::Process( const SpeedData& speed_data, const ReferenceLine& reference_line, const common::TrajectoryPoint& init_point, const bool path_reusable, PathData* const final_path_data) { // 跳过piecewise_jerk_path_optimizer 如果路径重复使用 if (FLAGS_enable_skip_path_tasks && path_reusable) { return Status::OK(); } ... ... ``` - adc起始点转化到frenet坐标 ```C++ ... ... const auto init_frenet_state = reference_line.ToFrenetFrame(planning_start_point); // 为lane-change选择lane_change_path_config // 否则, 选择default_path_config const auto& config = reference_line_info_->IsChangeLanePath() ? config_.piecewise_jerk_path_optimizer_config() .lane_change_path_config() : config_.piecewise_jerk_path_optimizer_config() .default_path_config(); ... ... ``` - 遍历每个路径边界 ```C++ ... ... const auto& path_boundaries = reference_line_info_->GetCandidatePathBoundaries(); ADEBUG << "There are " << path_boundaries.size() << " path boundaries."; const auto& reference_path_data = reference_line_info_->path_data(); std::vector<PathData> candidate_path_data; // 遍历每个路径 for (const auto& path_boundary : path_boundaries) { size_t path_boundary_size = path_boundary.boundary().size(); ... ... ``` - 判断是否pull-over或regular ① 判断是否是pull-over ```C++ ... ... if (!FLAGS_enable_force_pull_over_open_space_parking_test) { // pull over场景 const auto& pull_over_status = injector_->planning_context()->planning_status().pull_over(); if (pull_over_status.has_position() && pull_over_status.position().has_x() && pull_over_status.position().has_y() && path_boundary.label().find("pullover") != std::string::npos) { common::SLPoint pull_over_sl; reference_line.XYToSL(pull_over_status.position(), &pull_over_sl); end_state[0] = pull_over_sl.l(); } } ... ... ``` ② 判断是否是regular ```C++ ... ... if (path_boundary.label().find("regular") != std::string::npos && reference_path_data.is_valid_path_reference()) { ADEBUG << "path label is: " << path_boundary.label(); // 当参考路径就位 for (size_t i = 0; i < path_reference_size; ++i) { common::SLPoint path_reference_sl; reference_line.XYToSL( common::util::PointFactory::ToPointENU( reference_path_data.path_reference().at(i).x(), reference_path_data.path_reference().at(i).y()), &path_reference_sl); path_reference_l[i] = path_reference_sl.l(); } end_state[0] = path_reference_l.back(); path_data.set_is_optimized_towards_trajectory_reference(true); is_valid_path_reference = true; } ... ... ``` - 优化路径 ```C++ ... ... // 设置参数 const auto& veh_param = common::VehicleConfigHelper::GetConfig().vehicle_param(); const double lat_acc_bound = std::tan(veh_param.max_steer_angle() / veh_param.steer_ratio()) / veh_param.wheel_base(); std::vector<std::pair<double, double>> ddl_bounds; for (size_t i = 0; i < path_boundary_size; ++i) { double s = static_cast<double>(i) * path_boundary.delta_s() + path_boundary.start_s(); double kappa = reference_line.GetNearestReferencePoint(s).kappa(); ddl_bounds.emplace_back(-lat_acc_bound - kappa, lat_acc_bound - kappa); } // 优化算法 bool res_opt = OptimizePath( init_frenet_state.second, end_state, std::move(path_reference_l), path_reference_size, path_boundary.delta_s(), is_valid_path_reference, path_boundary.boundary(), ddl_bounds, w, max_iter, &opt_l, &opt_dl, &opt_ddl); ... ... ``` 优化过程: 1).定义piecewise_jerk_problem变量,优化算法 2).设置变量 &emsp; a.权重 &emsp; b.D方向距离、速度加速度边界 &emsp; c.最大转角速度 &emsp; d.jerk bound 3).优化算法 4).获取结果 - 如果成功将值保存到candidate_path_data ```C++ ... ... if (res_opt) { for (size_t i = 0; i < path_boundary_size; i += 4) { ADEBUG << "for s[" << static_cast<double>(i) * path_boundary.delta_s() << "], l = " << opt_l[i] << ", dl = " << opt_dl[i]; } auto frenet_frame_path = ToPiecewiseJerkPath(opt_l, opt_dl, opt_ddl, path_boundary.delta_s(), path_boundary.start_s()); path_data.SetReferenceLine(&reference_line); path_data.SetFrenetPath(std::move(frenet_frame_path)); if (FLAGS_use_front_axe_center_in_path_planning) { auto discretized_path = DiscretizedPath( ConvertPathPointRefFromFrontAxeToRearAxe(path_data)); path_data.SetDiscretizedPath(discretized_path); } path_data.set_path_label(path_boundary.label()); path_data.set_blocking_obstacle_id(path_boundary.blocking_obstacle_id()); candidate_path_data.push_back(std::move(path_data)); } ... ... ``` - 失败则返回错误码,成功则保存路径点 ```C++ ... ... if (candidate_path_data.empty()) { return Status(ErrorCode::PLANNING_ERROR, "Path Optimizer failed to generate path"); } reference_line_info_->SetCandidatePathData(std::move(candidate_path_data)); return Status::OK(); ... ... ``` # 相关算法解析 `分段加加速度路径优化`算法详细介绍在论文[Optimal Vehicle Path Planning Using Quadratic Optimization for Baidu Apollo Open Platform ](https://ieeexplore.ieee.org/document/9304787)中。 ![算法](../images/task/piecewise_jerk_path/path.png) 路径优化算法: - 根据导引线和障碍物生成路径边界 - 将导引线在s方向等间隔采样 - 对每个s方向的离散点迭代的优化 $𝑙, 𝑙^{'}, 𝑙^{''}$ 。 ## 建立数学模型 ### (1)轨迹平滑 ![平滑](../images/task/piecewise_jerk_path/smooth.png) $$ min \sum_{k=1}^{n-2} ||2P_k - P_{k-1} + P_{k+1}||_2^2 +\\ \sum_{k=0}^{n-1} ||2P_k - P_{k-ref}||_2^2 +\\ \sum_{k=0}^{n-2} ||P_{k+1} - P_k||_2^2 $$ subject to: $$ P_k \in B, for: k = 0,...,n-1 \\ ||2P_k - P_{k-1} - P_{k+1}||_2 < \frac{d_{ref}^2}{R_{min}} \\ for: k=1,...,n-2 $$ 其中 - $P_k$是$(x_k, y_k)$ - $P_{k\_ref}$是路由线的原始点 - $B$是$P_k$在$P_{k\_ref}$的边界 - $\frac{d_{ref}^2}{R_{min}}$是最大曲率约束 ### (2)优化目标 $$ \tilde{f}(l(s)) = w_l * \sum_{i=0}^{n-1} l_i^2 + w_{l^{'}} * \sum_{i=0}^{n-1} l_i^{'2} + w_{l^{''}} * \sum_{i=0}^{n-1} l_i^{''2} +\\ w_{l^{'''}} * \sum_{i=0}^{n-2}(\frac{l_{i+1}^{''} - l_i^{''}}{\Delta s})^2 +\\ w_{obs} * \sum_{i=0}^{n-1}(l_i - 0.5*(l_{min}^i + l_{max}^i))^2 $$ ### (3)约束条件 - 连续性约束 $$ l_{i+1}^{'''} = l_i^{''} + \int_0^{\Delta{s}} l_{i\rightarrow{i+1}}^{'''} ds = l_i^{''} + l_{i\rightarrow{i+1}}^{'''} * \Delta{s} \\ l_{i+1}^{'} = l_i^{'} + \int_0^{\Delta{s}}l^{''}(s)ds = l_i^{'} + l_i^{''}*\Delta{s} + \frac{1}{2} * l_{i\rightarrow{i+1}}^{'''} * \Delta{s^2} \\ l_{i+1} = l_i + \int_0^{\Delta{s}}l^{'}(s)ds \\ = l_i + l_i^{'}*\Delta(s^2) + \frac{1}{6}*l_{i\rightarrow{i+1}}*\Delta{s^3} $$ - 安全性约束 $l$方向的点需要在边界内。 $$ l(s) \in l_B(s), \forall{s} \in [0, s_{max}] $$ - 曲率约束 自车的转角不能超过最大转角。 $$ tan(\alpha_{max})*k_r*l - tan(\alpha_{max}) + |k_r|*L \leqslant 0 $$ 优化方法采用[OSQP](https://osqp.org/)方法。
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/09_Decider/path_assessment_decider_cn.md
# 路径评估决策 ### *目录* - [概览](#概览) - [路径评估决策相关代码及对应版本](#路径评估决策相关代码及对应版本) - [路径评估决策代码流程及框架](#路径评估决策代码流程及框架) - [路径重复使用](#路径重复使用) - [去掉无效路径](#去掉无效路径) - [分析并加入重要信息](#分析并加入重要信息) - [排序并选出最有路径](#排序并选出最有路径) - [更新必要信息](#更新必要信息) - [路径排序算法解析](#路径排序算法解析) # 概览 `路径评估决策`是规划模块的任务,属于task中的decider类别。 规划模块的运动总体流程图如下: ![总体流程图](../images/task/lane_follow.png) 总体流程图以[lane follow](https://github.com/ApolloAuto/apollo/blob/r6.0.0/modules/planning/conf/scenario/lane_follow_config.pb.txt)场景为例子进行说明。task的主要功能位于`Process`函数中。 Fig.1的具体运行过程可以参考[path_bounds_decider]()。 # 路径评估决策相关代码及对应版本 本节说明path assessment decider的代码流程。 请参考代码[Apollo r6.0.0 path_assessment_decider](https://github.com/ApolloAuto/apollo/tree/r6.0.0/modules/planning/tasks/deciders/path_assessment_decider) - 输入 `Status PathAssessmentDecider::Process(Frame* const frame, ReferenceLineInfo* const reference_line_info)` 输入Frame,reference_line_info。具体解释可以参考[path_bounds_decider]()。 - 输出 路径排序之后,选择第一个路径。结果保存在reference_line_info中。 # 路径评估决策代码流程及框架 代码主体流程如下图: ![流程图](../images/task/path_assessment/path_assessment.png) ## 路径重复使用 ```C++ ... ... // 如果路径重复使用则跳过 if (FLAGS_enable_skip_path_tasks && reference_line_info->path_reusable()) { return Status::OK(); ... ... ``` ## 去掉无效路径 ```C++ ... ... // 1. 删掉无效路径. std::vector<PathData> valid_path_data; for (const auto& curr_path_data : candidate_path_data) { // RecordDebugInfo(curr_path_data, curr_path_data.path_label(), // reference_line_info); if (curr_path_data.path_label().find("fallback") != std::string::npos) { if (IsValidFallbackPath(*reference_line_info, curr_path_data)) { valid_path_data.push_back(curr_path_data); } } else { if (IsValidRegularPath(*reference_line_info, curr_path_data)) { valid_path_data.push_back(curr_path_data); } } } const auto& end_time1 = std::chrono::system_clock::now(); std::chrono::duration<double> diff = end_time1 - end_time0; ADEBUG << "Time for path validity checking: " << diff.count() * 1000 << " msec."; ... ... ``` 其中fallback的无效路径是偏离参考线以及道路的路径。regular的无效路径是偏离参考线、道路,碰撞,停在相邻的逆向车道的路径。 ## 分析并加入重要信息 ```C++ ... ... // 2. 分析并加入重要信息给speed决策 size_t cnt = 0; const Obstacle* blocking_obstacle_on_selflane = nullptr; for (size_t i = 0; i != valid_path_data.size(); ++i) { auto& curr_path_data = valid_path_data[i]; if (curr_path_data.path_label().find("fallback") != std::string::npos) { // remove empty path_data. if (!curr_path_data.Empty()) { if (cnt != i) { valid_path_data[cnt] = curr_path_data; } ++cnt; } continue; } SetPathInfo(*reference_line_info, &curr_path_data); // 修剪所有的借道路径,使其能够以in-lane结尾 if (curr_path_data.path_label().find("pullover") == std::string::npos) { TrimTailingOutLanePoints(&curr_path_data); } // 找到 blocking_obstacle_on_selflane, 为下一步选择车道做准备 if (curr_path_data.path_label().find("self") != std::string::npos) { const auto blocking_obstacle_id = curr_path_data.blocking_obstacle_id(); blocking_obstacle_on_selflane = reference_line_info->path_decision()->Find(blocking_obstacle_id); } // 删掉空路径 if (!curr_path_data.Empty()) { if (cnt != i) { valid_path_data[cnt] = curr_path_data; } ++cnt; } // RecordDebugInfo(curr_path_data, curr_path_data.path_label(), // reference_line_info); ADEBUG << "For " << curr_path_data.path_label() << ", " << "path length = " << curr_path_data.frenet_frame_path().size(); } valid_path_data.resize(cnt); // 如果没有有效路径,退出 if (valid_path_data.empty()) { const std::string msg = "Neither regular nor fallback path is valid."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } ADEBUG << "There are " << valid_path_data.size() << " valid path data."; const auto& end_time2 = std::chrono::system_clock::now(); diff = end_time2 - end_time1; ADEBUG << "Time for path info labeling: " << diff.count() * 1000 << " msec."; ... ... ``` 这一步骤的代码执行流程如下: 1). 去掉空的路径 2). 从尾部开始剪掉lane-borrow路径,从尾部开始向前搜索,剪掉如下类型path_point: &emsp; (1) OUT_ON_FORWARD_LANE &emsp; (2) OUT_ON_REVERSE_LANE &emsp; (3) 未知类型 3). 找到自车道的障碍物id,用于车道选择 4). 如果没有有效路径,返回错误码 ## 排序并选出最有路径 这一步请看最后一章`相关算法解析` ## 更新必要信息 ```C++ // 4. Update necessary info for lane-borrow decider's future uses. // Update front static obstacle's info. auto* mutable_path_decider_status = injector_->planning_context() ->mutable_planning_status() ->mutable_path_decider(); if (reference_line_info->GetBlockingObstacle() != nullptr) { int front_static_obstacle_cycle_counter = mutable_path_decider_status->front_static_obstacle_cycle_counter(); mutable_path_decider_status->set_front_static_obstacle_cycle_counter( std::max(front_static_obstacle_cycle_counter, 0)); mutable_path_decider_status->set_front_static_obstacle_cycle_counter( std::min(front_static_obstacle_cycle_counter + 1, 10)); mutable_path_decider_status->set_front_static_obstacle_id( reference_line_info->GetBlockingObstacle()->Id()); } else { int front_static_obstacle_cycle_counter = mutable_path_decider_status->front_static_obstacle_cycle_counter(); mutable_path_decider_status->set_front_static_obstacle_cycle_counter( std::min(front_static_obstacle_cycle_counter, 0)); mutable_path_decider_status->set_front_static_obstacle_cycle_counter( std::max(front_static_obstacle_cycle_counter - 1, -10)); } // Update self-lane usage info. if (reference_line_info->path_data().path_label().find("self") != std::string::npos) { // && std::get<1>(reference_line_info->path_data() // .path_point_decision_guide() // .front()) == PathData::PathPointType::IN_LANE) int able_to_use_self_lane_counter = mutable_path_decider_status->able_to_use_self_lane_counter(); if (able_to_use_self_lane_counter < 0) { able_to_use_self_lane_counter = 0; } mutable_path_decider_status->set_able_to_use_self_lane_counter( std::min(able_to_use_self_lane_counter + 1, 10)); } else { mutable_path_decider_status->set_able_to_use_self_lane_counter(0); } // Update side-pass direction. if (mutable_path_decider_status->is_in_path_lane_borrow_scenario()) { bool left_borrow = false; bool right_borrow = false; const auto& path_decider_status = injector_->planning_context()->planning_status().path_decider(); for (const auto& lane_borrow_direction : path_decider_status.decided_side_pass_direction()) { if (lane_borrow_direction == PathDeciderStatus::LEFT_BORROW && reference_line_info->path_data().path_label().find("left") != std::string::npos) { left_borrow = true; } if (lane_borrow_direction == PathDeciderStatus::RIGHT_BORROW && reference_line_info->path_data().path_label().find("right") != std::string::npos) { right_borrow = true; } } mutable_path_decider_status->clear_decided_side_pass_direction(); if (right_borrow) { mutable_path_decider_status->add_decided_side_pass_direction( PathDeciderStatus::RIGHT_BORROW); } if (left_borrow) { mutable_path_decider_status->add_decided_side_pass_direction( PathDeciderStatus::LEFT_BORROW); } } const auto& end_time4 = std::chrono::system_clock::now(); diff = end_time4 - end_time3; ADEBUG << "Time for FSM state updating: " << diff.count() * 1000 << " msec."; // Plot the path in simulator for debug purpose. RecordDebugInfo(reference_line_info->path_data(), "Planning PathData", reference_line_info); return Status::OK(); ``` 更新必要信息: 1.更新adc前方静态障碍物的信息 2.更新自车道使用信息 3.更新旁车道的方向 (1) 根据PathDeciderStatus是RIGHT_BORROW或LEFT_BORROW判断是从左侧借道,还是从右侧借道 # 路径排序算法解析 最后这里说明排序算法。 ```C++ ... ... // 3. Pick the optimal path. std::sort(valid_path_data.begin(), valid_path_data.end(), std::bind(ComparePathData, std::placeholders::_1, std::placeholders::_2, blocking_obstacle_on_selflane)); ADEBUG << "Using '" << valid_path_data.front().path_label() << "' path out of " << valid_path_data.size() << " path(s)"; if (valid_path_data.front().path_label().find("fallback") != std::string::npos) { FLAGS_static_obstacle_nudge_l_buffer = 0.8; } *(reference_line_info->mutable_path_data()) = valid_path_data.front(); reference_line_info->SetBlockingObstacle( valid_path_data.front().blocking_obstacle_id()); const auto& end_time3 = std::chrono::system_clock::now(); diff = end_time3 - end_time2; ADEBUG << "Time for optimal path selection: " << diff.count() * 1000 << " msec."; reference_line_info->SetCandidatePathData(std::move(valid_path_data)); ... ... ``` 排序算法的流程具体如下: `ComparePathData(lhs, rhs, …)` 路径排序:(道路评估的优劣通过排序获得) - 1.空的路径永远排在后面 - 2.regular > fallback - 3.如果self-lane有一个存在,选择那个。如果都存在,选择较长的.如果长度接近,选择self-lane 如果self-lane都不存在,选择较长的路径 - 4.如果路径长度接近,且都要借道: - (1) 都要借逆向车道,选择距离短的 - (2) 针对具有两个借道方向的情况: + 有障碍物,选择合适的方向,左或右借道 + 无障碍物,根据adc的位置选择借道方向 - (3) 路径长度相同,相邻车道都是前向的,选择较早返回自车道的路径 - (4) 如果路径长度相同,前向借道,返回自车道时间相同,选择从左侧借道的路径 - 5.最后如果两条路径相同,则 lhs is not < rhl 排序之后:选择最优路径,即第一个路径
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/09_Decider/path_decider_cn.md
# 路径决策 ### *目录* - [概览](#概览) - [路径决策相关代码及对应版本](#路径决策相关代码及对应版本) - [路径决策代码流程及框架](#路径决策代码流程及框架) - [路径决策相关算法解析](#路径决策相关算法解析) # 概览 `路径决策`是规划模块的任务,属于task中的decider类别。 规划模块的运动总体流程图如下: ![总体流程图](../images/task/lane_follow.png) 总体流程图以[lane follow](https://github.com/ApolloAuto/apollo/blob/r6.0.0/modules/planning/conf/scenario/lane_follow_config.pb.txt)场景为例子进行说明。task的主要功能位于`Process`函数中。 Fig.1的具体运行过程可以参考[path_bounds_decider]()。 # 路径决策相关代码及对应版本 在上一个任务中获得了最优的路径,`路径决策`的功能是根据静态障碍物做出自车的决策。 `路径决策`的代码是[Apollo r6.0.0 path_decider](https://github.com/ApolloAuto/apollo/tree/r6.0.0/modules/planning/tasks/deciders/path_decider) - 输入 `Status PathDecider::Process(const ReferenceLineInfo *reference_line_info, const PathData &path_data, PathDecision *const path_decision)` - 输出 路径决策的信息都保存到了`path_decision`中。 # 路径决策代码流程及框架 `路径决策`的整体流程如下图: ![流程图](../images/task/path_decider/path_decider.png) 在`Process`函数主要功能是调用了`MakeObjectDecision`函数。而在`MakeObjectDecision`函数中调用了`MakeStaticObstacleDecision`函数。 路径决策的主要功能都在`MakeStaticObstacleDecision`中。 ```C++ Status PathDecider::Process(const ReferenceLineInfo *reference_line_info, const PathData &path_data, PathDecision *const path_decision) { // skip path_decider if reused path if (FLAGS_enable_skip_path_tasks && reference_line_info->path_reusable()) { return Status::OK(); } std::string blocking_obstacle_id; if (reference_line_info->GetBlockingObstacle() != nullptr) { blocking_obstacle_id = reference_line_info->GetBlockingObstacle()->Id(); } // 调用MakeObjectDecision函数 if (!MakeObjectDecision(path_data, blocking_obstacle_id, path_decision)) { const std::string msg = "Failed to make decision based on tunnel"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } return Status::OK(); } bool PathDecider::MakeObjectDecision(const PathData &path_data, const std::string &blocking_obstacle_id, PathDecision *const path_decision) { // path decider的主要功能在MakeStaticObstacleDecision中 if (!MakeStaticObstacleDecision(path_data, blocking_obstacle_id, path_decision)) { AERROR << "Failed to make decisions for static obstacles"; return false; } return true; } ``` # 路径决策相关算法解析 针对上述的path-decider的流程图,进行代码分析。 - 获取frenet坐标系下的坐标 ```C++ ... ... // 1.获取frenet坐标下的path路径 const auto &frenet_path = path_data.frenet_frame_path(); if (frenet_path.empty()) { AERROR << "Path is empty."; return false; } ... ... ``` - 根据障碍物做决策 ```C++ ... ... // 2.遍历每个障碍物,做决策 for (const auto *obstacle : path_decision->obstacles().Items()) { const std::string &obstacle_id = obstacle->Id(); const std::string obstacle_type_name = PerceptionObstacle_Type_Name(obstacle->Perception().type()); ADEBUG << "obstacle_id[<< " << obstacle_id << "] type[" << obstacle_type_name << "]"; ... ... ``` 上图的红框中是循环体的主要内容,主要功能是遍历每个障碍物做决策。 - 如果障碍物不是静态或virtual,则跳过 ```C++ // 2.1 如果障碍物不是静态的或者是virtual的,就跳过 if (!obstacle->IsStatic() || obstacle->IsVirtual()) { // (stop fence,各种fence) continue; } ``` - 如果障碍物有了ignore/stop决策,则跳过 ```C++ // 2.2 如果障碍物已经有 ignore/stop 决策,就跳过 if (obstacle->HasLongitudinalDecision() && obstacle->LongitudinalDecision().has_ignore() && obstacle->HasLateralDecision() && obstacle->LateralDecision().has_ignore()) { continue; } if (obstacle->HasLongitudinalDecision() && obstacle->LongitudinalDecision().has_stop()) { // STOP decision continue; } ``` - 如果障碍物挡住了路径,加stop决策 ```C++ // 2.3 如果障碍物挡住了路径,加stop决策 if (obstacle->Id() == blocking_obstacle_id && !injector_->planning_context() ->planning_status() .path_decider() .is_in_path_lane_borrow_scenario()) { // Add stop decision ADEBUG << "Blocking obstacle = " << blocking_obstacle_id; ObjectDecisionType object_decision; *object_decision.mutable_stop() = GenerateObjectStopDecision(*obstacle); path_decision->AddLongitudinalDecision("PathDecider/blocking_obstacle", obstacle->Id(), object_decision); continue; } ``` - 如果是clear-zone,跳过 ```C++ // 2.4 如果是clear-zone,跳过 if (obstacle->reference_line_st_boundary().boundary_type() == STBoundary::BoundaryType::KEEP_CLEAR) { continue; } ``` - 如果障碍物不在路径上,跳过 ```C++ // 2.5 如果障碍物不在路径上,跳过 ObjectDecisionType object_decision; object_decision.mutable_ignore(); const auto &sl_boundary = obstacle->PerceptionSLBoundary(); if (sl_boundary.end_s() < frenet_path.front().s() || sl_boundary.start_s() > frenet_path.back().s()) { path_decision->AddLongitudinalDecision("PathDecider/not-in-s", obstacle->Id(), object_decision); path_decision->AddLateralDecision("PathDecider/not-in-s", obstacle->Id(), object_decision); continue; } ``` - nudge判断 ```C++ // 2.6 nudge判断,如果距离静态障碍物距离太远,则忽略。 // 如果静态障碍物距离车道中心太近,则停止。 // 如果横向方向很近,则避开。 if (curr_l - lateral_radius > sl_boundary.end_l() || curr_l + lateral_radius < sl_boundary.start_l()) { // 1. IGNORE if laterally too far away. path_decision->AddLateralDecision("PathDecider/not-in-l", obstacle->Id(), object_decision); } else if (sl_boundary.end_l() >= curr_l - min_nudge_l && sl_boundary.start_l() <= curr_l + min_nudge_l) { // 2. STOP if laterally too overlapping. *object_decision.mutable_stop() = GenerateObjectStopDecision(*obstacle); if (path_decision->MergeWithMainStop( object_decision.stop(), obstacle->Id(), reference_line_info_->reference_line(), reference_line_info_->AdcSlBoundary())) { path_decision->AddLongitudinalDecision("PathDecider/nearest-stop", obstacle->Id(), object_decision); } else { ObjectDecisionType object_decision; object_decision.mutable_ignore(); path_decision->AddLongitudinalDecision("PathDecider/not-nearest-stop", obstacle->Id(), object_decision); } } else { // 3. NUDGE if laterally very close. if (sl_boundary.end_l() < curr_l - min_nudge_l) { // && // sl_boundary.end_l() > curr_l - min_nudge_l - 0.3) { // LEFT_NUDGE ObjectNudge *object_nudge_ptr = object_decision.mutable_nudge(); object_nudge_ptr->set_type(ObjectNudge::LEFT_NUDGE); object_nudge_ptr->set_distance_l( config_.path_decider_config().static_obstacle_buffer()); path_decision->AddLateralDecision("PathDecider/left-nudge", obstacle->Id(), object_decision); } else if (sl_boundary.start_l() > curr_l + min_nudge_l) { // && // sl_boundary.start_l() < curr_l + min_nudge_l + 0.3) { // RIGHT_NUDGE ObjectNudge *object_nudge_ptr = object_decision.mutable_nudge(); object_nudge_ptr->set_type(ObjectNudge::RIGHT_NUDGE); object_nudge_ptr->set_distance_l( -config_.path_decider_config().static_obstacle_buffer()); path_decision->AddLateralDecision("PathDecider/right-nudge", obstacle->Id(), object_decision); } } ```
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/09_Decider/open_space_decider.md
# OPEN SPACE DECIDER # Introduction Apollo planning is scenario based, where each driving case is treated as a different driving scenario. Open space decider is used to process related infomation and provide information for subsequent optimizers. # Where is the code Please refer [open space decider](https://github.com/ApolloAuto/apollo/modules/planning/tasks/deciders/open_space_decider/open_space_roi_decider.cc). # Code Reading ## Open space roi decider 1. Input : obstacles info \ vehicle info \ road info \ parking space info. - IN PARKING STAGE (roi_type == OpenSpaceRoiDeciderConfig::PARKING) 1. Check parking space id and parking space boundary, then get parking spot. ```cpp bool GetParkingSpot(Frame *const frame, std::array<common::math::Vec2d, 4> *vertices, hdmap::Path *nearby_path); ``` 2. Search target parking spot on path and check whether the distance between ADC and target parking spot is appropriate. ```cpp void SearchTargetParkingSpotOnPath( const hdmap::Path &nearby_path, hdmap::ParkingSpaceInfoConstPtr *target_parking_spot); ``` 3. Set ADC origin state, include ADC position and heading. ```cpp void SetOrigin(Frame *const frame, const std::array<common::math::Vec2d, 4> &vertices); ``` 4. Get parking spot(left top \ left down \ right down \ right top) points info, convert parking spot points coordinates to vehicle coorinates, according to the relative position and parking direction(inward or outward) to set parking end pose. ```cpp void SetParkingSpotEndPose( Frame *const frame, const std::array<common::math::Vec2d, 4> &vertices); ``` 5. Get parking boundary: convert parking spot points coordinates to vehicle coorinates and get points' projections on reference line. ```cpp bool GetParkingBoundary(Frame *const frame, const std::array<common::math::Vec2d, 4> &vertices, const hdmap::Path &nearby_path, std::vector<std::vector<common::math::Vec2d>> *const roi_parking_boundary); ``` 6. Get road boundary: it starts from parking space center line(center_line_s) and extends a distance(roi longitudinal range) to both sides along the s direction to get start_s and end_s. Search key points(the point on the left/right lane boundary is close to a curb corner) and anchor points(a start/end point or the point on path with large curvatures) in this roi range. Those key points and anchor points are called boundary points. The line segements between those points are called roi parking boundarys. ```cpp void GetRoadBoundary( const hdmap::Path &nearby_path, const double center_line_s, const common::math::Vec2d &origin_point, const double origin_heading, std::vector<common::math::Vec2d> *left_lane_boundary, std::vector<common::math::Vec2d> *right_lane_boundary, std::vector<common::math::Vec2d> *center_lane_boundary_left, std::vector<common::math::Vec2d> *center_lane_boundary_right, std::vector<double> *center_lane_s_left, std::vector<double> *center_lane_s_right, std::vector<double> *left_lane_road_width, std::vector<double> *right_lane_road_width); ``` 7. Fuse line segements: remove repeat points of roi parking boundary to meet the requirements of open space algorithm. ```cpp bool FuseLineSegments( std::vector<std::vector<common::math::Vec2d>> *line_segments_vec); ``` - IN PULL OVER STAGE (roi_type == OpenSpaceRoiDeciderConfig::PULL_OVER) 1. The main process is same as parking stage, get pull over spot -> set origin -> set pull over spot end pose -> get pull over boundary. ```cpp void SetPullOverSpotEndPose(Frame *const frame); ``` ```cpp bool GetPullOverBoundary(Frame *const frame, const std::array<common::math::Vec2d, 4> &vertices, const hdmap::Path &nearby_path, std::vector<std::vector<common::math::Vec2d>> *const roi_parking_boundary); ``` - IN PARK AND GO STAGE (roi_type == OpenSpaceRoiDeciderConfig::PARK_AND_GO) 1. The main process is same as parking stage, set orgin from adc -> set park and go end pose -> get park and go boundary. ```cpp void SetOriginFromADC(Frame *const frame, const hdmap::Path &nearby_path); ``` ```cpp void SetParkAndGoEndPose(Frame *const frame); ``` ```cpp bool GetParkAndGoBoundary(Frame *const frame, const hdmap::Path &nearby_path, std::vector<std::vector<common::math::Vec2d>> *const roi_parking_boundary); ``` 2. By calling ```formulateboundaryconstraints()``` to gather vertice needed by warm start and distance approach, then transform vertices into the form of Ax > b. ```cpp bool FormulateBoundaryConstraints( const std::vector<std::vector<common::math::Vec2d>> &roi_parking_boundary, Frame *const frame); ``` 3. Return process status. 4. Output: open space roi boundary and boundary constraints ## Open space pre stop decider 1. Input: obstacles info \ vehicle info \ road info \ parking space info - IN PARKING STAGE (OpenSpacePreStopDeciderConfig::PARKING) 1. Check parking space info(parking spot id and parking spot points), fill those info into target_parking_spot_ptr. Take the s info of parking space center line as target_s. ```cpp bool CheckParkingSpotPreStop(Frame* const frame, ReferenceLineInfo* const reference_line_info, double* target_s); ``` 2. Base on ADC position, stop distance to target parking space and obstacle positon to set stop fence. ```cpp void SetParkingSpotStopFence(const double target_s, Frame* const frame, ReferenceLineInfo* const reference_line_info); ``` - IN PULL OVER STAGE (OpenSpacePreStopDeciderConfig::PULL_OVER) 1. Same with parking stage, check pull over pre stop -> set pull over stop fence. ```cpp bool CheckPullOverPreStop(Frame* const frame, ReferenceLineInfo* const reference_line_info, double* target_s); ``` ```cpp void SetPullOverStopFence(const double target_s, Frame* const frame, ReferenceLineInfo* const reference_line_info); ``` 2. Return process status. 3. Output: pre stop fence for open space planner. ## Open space fallback decider 1. Input: obstacles info \ vehicle info \ road info \ parking space info. 2. Base on the prdicted trajectory of obstacles, the bounding box info of obstacles in each time interval is obtained, then we add it into predicted_bounding_rectangles. ```cpp void BuildPredictedEnvironment(const std::vector<const Obstacle*>& obstacles, std::vector<std::vector<common::math::Box2d>>& predicted_bounding_rectangles); ``` 3. By calling ```IsCollisonFreeTrajectory()``` to determine whether it will intersect with obstacles. ```cpp bool IsCollisionFreeTrajectory( const TrajGearPair& trajectory_pb, const std::vector<std::vector<common::math::Box2d>>& predicted_bounding_rectangles, size_t* current_idx, size_t* first_collision_idx); ``` 4. If ADC trajectroy is collision free, the chosen partitioned trajectory can be used directly, otherwise a fallback trajectroy base on current partition trajectroy will be gererated, which leads ADC stop inside safety distance. 5. Return process status. 6. Output: fallback trajectory.
0
apollo_public_repos/apollo/docs
apollo_public_repos/apollo/docs/09_Decider/rule_based_stop_decider_cn.md
# 基于规则的停止决策 ### *目录* - [概览](#概览) - [相关代码及对应版本](#相关代码及对应版本) - [代码流程及框架](#代码流程及框架) - [相关算法解析](#相关算法解析) # 概览 `基于规则的停止决策`是规划模块的任务,属于task中的decider类别。 规划模块的运动总体流程图如下: ![总体流程图](../images/task/lane_follow.png) 总体流程图以[lane follow](https://github.com/ApolloAuto/apollo/blob/r6.0.0/modules/planning/conf/scenario/lane_follow_config.pb.txt)场景为例子进行说明。task的主要功能位于`Process`函数中。 Fig.1的具体运行过程可以参考[path_bounds_decider]()。 # 相关代码及对应版本 基于规则的停止决策根据一些规则来设置停止标志。 代码位于[Apollo r6.0.0 rule_based_stop_decider](https://github.com/ApolloAuto/apollo/tree/r6.0.0/modules/planning/tasks/deciders/rule_based_stop_decider)。 - 输入 `apollo::common::Status RuleBasedStopDecider::Process(Frame *const frame, ReferenceLineInfo *const reference_line_info)` 输入是frame和reference_line_info。具体解释可以参考[path_bounds_decider]()。 - 输出 输出保存到reference_line_info中。 # 代码流程及框架 代码的运行流程如下图。 ![流程图](../images/task/rule_based_stop_decider/rule_based_stop_decider.png) 代码结构比较清楚: ```C++ apollo::common::Status RuleBasedStopDecider::Process( Frame *const frame, ReferenceLineInfo *const reference_line_info) { // 1. 逆向车道通过,停止 StopOnSidePass(frame, reference_line_info); // 2. 紧急换道,停止 if (FLAGS_enable_lane_change_urgency_checking) { CheckLaneChangeUrgency(frame); } // 3. 路径尽头,停止 AddPathEndStop(frame, reference_line_info); return Status::OK(); } ``` # 相关算法解析 对上图总流程的的每个部分拆分开分析。 - Stop on side pass ![StopOnSidePass](../images/task/rule_based_stop_decider/stop_on_side_pass.png) 代码如下: ```C++ void RuleBasedStopDecider::StopOnSidePass( Frame *const frame, ReferenceLineInfo *const reference_line_info) { static bool check_clear; // 默认false static common::PathPoint change_lane_stop_path_point; // 获取path_data const PathData &path_data = reference_line_info->path_data(); double stop_s_on_pathdata = 0.0; // 1. 找到"self",直接return if (path_data.path_label().find("self") != std::string::npos) { check_clear = false; change_lane_stop_path_point.Clear(); return; } // 2. 如果check_clear为true,且CheckClearDone成功。设置check_clear为false if (check_clear && CheckClearDone(*reference_line_info, change_lane_stop_path_point)) { check_clear = false; } // 3.如果check_clear为false,且检查stop fence if (!check_clear && CheckSidePassStop(path_data, *reference_line_info, &stop_s_on_pathdata)) { // 3.1 如果障碍物没有阻塞且可以换道,直接return if (!LaneChangeDecider::IsPerceptionBlocked( *reference_line_info, rule_based_stop_decider_config_.search_beam_length(), rule_based_stop_decider_config_.search_beam_radius_intensity(), rule_based_stop_decider_config_.search_range(), rule_based_stop_decider_config_.is_block_angle_threshold()) && LaneChangeDecider::IsClearToChangeLane(reference_line_info)) { return; } // 3.2 检查adc是否停在了stop fence前,否返回true if (!CheckADCStop(path_data, *reference_line_info, stop_s_on_pathdata)) { // 设置stop fence,成功就执行 check_clear = true; if (!BuildSidePassStopFence(path_data, stop_s_on_pathdata, &change_lane_stop_path_point, frame, reference_line_info)) { AERROR << "Set side pass stop fail"; } } else { if (LaneChangeDecider::IsClearToChangeLane(reference_line_info)) { check_clear = true; } } } } ``` - Check lane change Urgency ![StopOnSidePass](../images/task/rule_based_stop_decider/check_lane_change_urgency.png) 检查紧急换道,代码如下: ```C++ void RuleBasedStopDecider::CheckLaneChangeUrgency(Frame *const frame) { // 直接进入循环,检查每个reference_line_info for (auto &reference_line_info : *frame->mutable_reference_line_info()) { // 1. 检查目标道路是否阻塞,如果在change lane path上,就跳过 if (reference_line_info.IsChangeLanePath()) { is_clear_to_change_lane_ = LaneChangeDecider::IsClearToChangeLane(&reference_line_info); is_change_lane_planning_succeed_ = reference_line_info.Cost() < kStraightForwardLineCost; continue; } // 2.如果不是换道的场景,或者(目标lane没有阻塞)并且换道规划成功,跳过 if (frame->reference_line_info().size() <= 1 || (is_clear_to_change_lane_ && is_change_lane_planning_succeed_)) { continue; } // When the target lane is blocked in change-lane case, check the urgency // Get the end point of current routing const auto &route_end_waypoint = reference_line_info.Lanes().RouteEndWaypoint(); // 3.在route的末端无法获得lane,跳过 if (!route_end_waypoint.lane) { continue; } auto point = route_end_waypoint.lane->GetSmoothPoint(route_end_waypoint.s); auto *reference_line = reference_line_info.mutable_reference_line(); common::SLPoint sl_point; // 将当前参考线的点映射到frenet坐标系下 if (reference_line->XYToSL(point, &sl_point) && reference_line->IsOnLane(sl_point)) { // Check the distance from ADC to the end point of current routing double distance_to_passage_end = sl_point.s() - reference_line_info.AdcSlBoundary().end_s(); // 4. 如果adc距离routing终点较远,不需要停止,跳过 if (distance_to_passage_end > rule_based_stop_decider_config_.approach_distance_for_lane_change()) { continue; } // 5.如果遇到紧急情况,设置临时的stop fence,等待换道 const std::string stop_wall_id = "lane_change_stop"; std::vector<std::string> wait_for_obstacles; util::BuildStopDecision( stop_wall_id, sl_point.s(), rule_based_stop_decider_config_.urgent_distance_for_lane_change(), StopReasonCode::STOP_REASON_LANE_CHANGE_URGENCY, wait_for_obstacles, "RuleBasedStopDecider", frame, &reference_line_info); } } } ``` - Add path end stop ![StopOnSidePass](../images/task/rule_based_stop_decider/add_path_end_stop.png) 在道路的尽头添加stop fence。代码如下: ```C++ void RuleBasedStopDecider::AddPathEndStop( Frame *const frame, ReferenceLineInfo *const reference_line_info) { if (!reference_line_info->path_data().path_label().empty() && reference_line_info->path_data().frenet_frame_path().back().s() - reference_line_info->path_data().frenet_frame_path().front().s() < FLAGS_short_path_length_threshold) { const std::string stop_wall_id = PATH_END_VO_ID_PREFIX + reference_line_info->path_data().path_label(); std::vector<std::string> wait_for_obstacles; // 创建stop fence util::BuildStopDecision( stop_wall_id, reference_line_info->path_data().frenet_frame_path().back().s() - 5.0, 0.0, StopReasonCode::STOP_REASON_REFERENCE_END, wait_for_obstacles, "RuleBasedStopDecider", frame, reference_line_info); } } ```
0
apollo_public_repos/apollo
apollo_public_repos/apollo/third_party/ACKNOWLEDGEMENT.txt
* Redistributions of source code must retain all third party copyright notice. * Redistributions in binary form must reproduce all third party copyright notice in the documentation and/or other materials provided with the distribution. * Abseil Apache License 2.0 https://github.com/abseil/abseil-cpp/blob/master/LICENSE * ADOL-C Eclipse Public License 1.0 https://github.com/coin-or/ADOL-C/blob/master/LICENSE * ad-rss-lib GNU General Public License 2.1 https://github.com/intel/ad-rss-lib/blob/master/LICENSE * Benchmark Apache License 2.0 https://github.com/google/benchmark/blob/master/LICENSE * Bazel: Apache License 2.0 https://github.com/bazelbuild/bazel/blob/master/LICENSE * Boost: Boost Software License 1.0 http://www.boost.org/users/license.html http://www.boost.org/LICENSE_1_0.txt * Bootstrap MIT License https://github.com/twbs/bootstrap/blob/master/LICENSE * Buildifier Apache License 2.0 https://github.com/bazelbuild/buildtools/blob/master/LICENSE * ColPack GNU Lesser General Public License 3.0 https://github.com/CSCsw/ColPack/blob/master/COPYING * CivetWeb MIT License https://github.com/civetweb/civetweb/blob/master/LICENSE.md * Cpplint BSD 3-clause "New" or "Revised" License https://github.com/cpplint/cpplint/blob/master/LICENSE * cuteci MIT License https://github.com/hasboeuf/cuteci/blob/master/LICENSE * Docker Apache License 2.0 https://www.docker.com/components-licenses * Eigen Mozilla Public License version 2.0 http://eigen.tuxfamily.org/index.php?title=Licensing_FAQ * FastCDR Apache License 2.0 https://github.com/eProsima/Fast-CDR/blob/master/LICENSE * Fast RTPS Apache License 2.0 https://github.com/eProsima/Fast-RTPS/blob/release/1.4.0/LICENSE * FFmpeg GNU Lesser General Public License 2.1+ https://github.com/FFmpeg/FFmpeg/blob/master/LICENSE.md * FFTW GNU General Public License 2+ http://www.fftw.org/fftw3_doc/License-and-Copyright.html * Ipopt Eclipse Public License 2.0 https://github.com/coin-or/Ipopt/blob/master/LICENSE * GFlags BSD 3-clause "New" or "Revised" License https://github.com/gflags/gflags/blob/master/COPYING.txt * GLog BSD 3-Clause License https://github.com/google/glog/blob/master/COPYING * gRPC Apache License 2.0 https://github.com/grpc/grpc/blob/master/LICENSE * GoogleTest https://github.com/google/googletest/blob/master/googletest/LICENSE * jQuery MIT License https://jquery.org/license/ * JSON for Modern C++ MIT License https://github.com/nlohmann/json/blob/develop/LICENSE.MIT * OpenCV BSD 3-Clause License https://opencv.org/license * OSQP Apache License 2.0 https://github.com/oxfordcontrol/osqp/blob/master/LICENSE * PCL BSD License https://github.com/PointCloudLibrary/pcl/blob/master/LICENSE.txt * PyTorch https://github.com/pytorch/pytorch/blob/master/LICENSE * PROJ MIT License https://github.com/OSGeo/PROJ/blob/master/COPYING * Prettier MIT License https://github.com/prettier/prettier/blob/master/LICENSE * Protocol Buffer https://github.com/protocolbuffers/protobuf/blob/master/LICENSE * python-requests Apache2 License http://docs.python-requests.org/en/master/user/intro/#apache2-license * Qt5 GNU Lesser General Public License 3 https://doc.qt.io/qt-5/licensing.html * shfmt BSD 3-Clause "New" or "Revised" License https://github.com/mvdan/sh/blob/master/LICENSE * socketio MIT License https://github.com/socketio/socket.io-client/blob/master/LICENSE * VTK https://github.com/Kitware/VTK/blob/master/Copyright.txt * YAML-cpp MIT License https://github.com/jbeder/yaml-cpp/blob/master/LICENSE
0
apollo_public_repos/apollo
apollo_public_repos/apollo/third_party/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) cc_library( name = "libtorch", deps = select({ "//tools/platform:use_nvidia_gpu": [ "@libtorch_gpu_cuda", ], "//tools/platform:use_amd_gpu": [ "@libtorch_gpu_rocm", ], "//conditions:default": [ "@libtorch_cpu", ], }), )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/benchmark/cyberfile.xml
<package format="2"> <name>3rd-benchmark</name> <version>local</version> <description> Apollo packaged benchmark Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-binary</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/benchmark</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/benchmark/benchmark.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) licenses(["notice"]) cc_library( name = "benchmark", includes = [ ".", ], linkopts = [ "-L/opt/apollo/sysroot/lib", "-lbenchmark", "-pthread", ], visibility = ["//visibility:public"], ) cc_library( name = "benchmark_main", linkopts = [ "-L/opt/apollo/sysroot/lib", "-lbenchmark_main", ], visibility = ["//visibility:public"], deps = [":benchmark"], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/benchmark/3rd-benchmark.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) licenses(["notice"]) cc_library( name = "benchmark", includes = [ "include", ], linkopts = [ "-lbenchmark", "-pthread", ], visibility = ["//visibility:public"], strip_include_prefix = "include", ) cc_library( name = "benchmark_main", linkopts = [ "-lbenchmark_main", ], visibility = ["//visibility:public"], deps = [":benchmark"], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/benchmark/workspace.bzl
"""Loads the benchmark library""" #@unused load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") # Sanitize a dependency so that it works correctly from code that includes # Apollo as a submodule. def clean_dep(dep): return str(Label(dep)) def repo(): # benchmark # native.new_local_repository( # name = "com_google_benchmark", # build_file = clean_dep("//third_party/benchmark:benchmark.BUILD"), # path = "/opt/apollo/sysroot/include", # ) http_archive( name = "com_google_benchmark", sha256 = "23082937d1663a53b90cb5b61df4bcc312f6dee7018da78ba00dd6bd669dfef2", strip_prefix = "benchmark-1.5.1", urls = [ "https://apollo-system.cdn.bcebos.com/archive/6.0/v1.5.1.tar.gz", "https://github.com/google/benchmark/archive/v1.5.1.tar.gz", ], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/benchmark/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", data_dest = "3rd-benchmark", data = [ ":cyberfile.xml", ":3rd-benchmark.BUILD", ], ) install_src_files( name = "install_src", src_dir = ["."], dest = "3rd-benchmark/src", filter = "*", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/proj/cyberfile.xml
<package format="2"> <name>3rd-proj</name> <version>local</version> <description> Apollo packaged proj Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-binary</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/proj</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/proj/workspace.bzl
"""Loads the proj library""" # Sanitize a dependency so that it works correctly from code that includes # Apollo as a submodule. def clean_dep(dep): return str(Label(dep)) def repo(): native.new_local_repository( name = "proj", build_file = clean_dep("//third_party/proj:proj.BUILD"), path = "/opt/apollo/sysroot/include", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/proj/3rd-proj.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) licenses(["notice"]) cc_library( name = "proj", includes = [ "include", ], hdrs = glob(["include/**/*"]), linkopts = [ "-lproj", ], linkstatic = False, strip_include_prefix = "include", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/proj/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", data_dest = "3rd-proj", data = [ ":cyberfile.xml", ":3rd-proj.BUILD", ], ) install_src_files( name = "install_src", src_dir = ["."], dest = "3rd-proj/src", filter = "*", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/proj/proj.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) licenses(["notice"]) cc_library( name = "proj", includes = [ ".", ], linkopts = [ "-L/opt/apollo/sysroot/lib", "-lproj", ], linkstatic = False, )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/ffmpeg/cyberfile.xml
<package format="2"> <name>3rd-ffmpeg</name> <version>local</version> <description> Apollo packaged 3rd-ffmpeg Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-binary</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/ffmpeg</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/ffmpeg/ffmpeg.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) licenses(["notice"]) cc_library( name = "avcodec", includes = ["."], hdrs = glob(["libavcodec/*.h"]), linkopts = [ "-L/opt/apollo/sysroot/lib", "-lavcodec", ], ) cc_library( name = "avformat", includes = ["."], hdrs = glob(["libavformat/*.h"]), linkopts = [ "-L/opt/apollo/sysroot/lib", "-lavformat", ], ) cc_library( name = "swscale", includes = ["."], hdrs = glob(["libswscale/*.h"]), linkopts = [ "-L/opt/apollo/sysroot/lib", "-lswscale", ], ) cc_library( name = "avutil", includes = ["."], hdrs = glob(["libavutil/*.h"]), linkopts = [ "-L/opt/apollo/sysroot/lib", "-lavutil", ], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/ffmpeg/workspace.bzl
"""Loads the ffmpeg library""" # Sanitize a dependency so that it works correctly from code that includes # Apollo as a submodule. def clean_dep(dep): return str(Label(dep)) def repo(): native.new_local_repository( name = "ffmpeg", build_file = clean_dep("//third_party/ffmpeg:ffmpeg.BUILD"), path = "/opt/apollo/sysroot/include", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/ffmpeg/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", data_dest = "3rd-ffmpeg", data = [ ":cyberfile.xml", ":3rd-ffmpeg.BUILD", ], ) install_src_files( name = "install_src", src_dir = ["."], dest = "3rd-ffmpeg/src", filter = "*", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/ffmpeg/3rd-ffmpeg.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) licenses(["notice"]) cc_library( name = "avcodec", hdrs = glob(["include/libavcodec/*.h"]), strip_include_prefix = "include", linkopts = [ "-L/opt/apollo/sysroot/lib", "-lavcodec", ], ) cc_library( name = "avformat", hdrs = glob(["include/libavformat/*.h"]), strip_include_prefix = "include", linkopts = [ "-L/opt/apollo/sysroot/lib", "-lavformat", ], ) cc_library( name = "swscale", hdrs = glob(["include/libswscale/*.h"]), strip_include_prefix = "include", linkopts = [ "-L/opt/apollo/sysroot/lib", "-lswscale", ], ) cc_library( name = "avutil", hdrs = glob(["include/libavutil/*.h"]), strip_include_prefix = "include", linkopts = [ "-L/opt/apollo/sysroot/lib", "-lavutil", ], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tf2/geometry2_0.5.16_tf2.patch
diff -uprN 0.5.16/CHANGELOG.rst tf2/CHANGELOG.rst --- 0.5.16/CHANGELOG.rst 2018-09-18 15:00:42.778601493 -0700 +++ tf2/CHANGELOG.rst 2018-09-17 20:13:41.139660229 -0700 @@ -168,7 +168,7 @@ Changelog for package tf2 ------------------ * splitting rospy dependency into tf2_py so tf2 is pure c++ library. * switching to console_bridge from rosconsole -* moving convert methods back into tf2 because it does not have any ros dependencies beyond ros::Time which is already a dependency of tf2 +* moving convert methods back into tf2 because it does not have any ros dependencies beyond Time which is already a dependency of tf2 * Cleaning up unnecessary dependency on roscpp * Cleaning up packaging of tf2 including: removing unused nodehandle diff -uprN 0.5.16/CMakeLists.txt tf2/CMakeLists.txt --- 0.5.16/CMakeLists.txt 2018-09-18 15:00:42.778601493 -0700 +++ tf2/CMakeLists.txt 2018-09-17 22:27:05.414285664 -0700 @@ -1,54 +1,41 @@ cmake_minimum_required(VERSION 2.8.3) project(tf2) -find_package(console_bridge REQUIRED) -find_package(catkin REQUIRED COMPONENTS geometry_msgs rostime tf2_msgs) find_package(Boost REQUIRED COMPONENTS signals system thread) -catkin_package( - INCLUDE_DIRS include - LIBRARIES tf2 - DEPENDS console_bridge - CATKIN_DEPENDS geometry_msgs tf2_msgs rostime) - -include_directories (src/bt) -include_directories(include ${catkin_INCLUDE_DIRS} ${console_bridge_INCLUDE_DIRS}) - +include_directories(include ) +link_directories(/apollo/framework/third_party/gtest/lib) # export user definitions #CPP Libraries -add_library(tf2 src/cache.cpp src/buffer_core.cpp src/static_cache.cpp) -target_link_libraries(tf2 ${Boost_LIBRARIES} ${catkin_LIBRARIES} ${console_bridge_LIBRARIES}) -add_dependencies(tf2 ${catkin_EXPORTED_TARGETS}) +add_library(tf2 SHARED src/cache.cpp src/buffer_core.cpp src/static_cache.cpp) +target_link_libraries(tf2 ${Boost_LIBRARIES} ${catkin_LIBRARIES}) + +set(CMAKE_INSTALL_PREFIX ${CMAKE_SOURCE_DIR}/install) install(TARGETS tf2 - ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} - LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} - RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} + ARCHIVE DESTINATION ${CMAKE_INSTALL_PREFIX}/lib + LIBRARY DESTINATION ${CMAKE_INSTALL_PREFIX}/lib + RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin ) -install(DIRECTORY include/${PROJECT_NAME}/ - DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} +install(DIRECTORY include + DESTINATION ${CMAKE_INSTALL_PREFIX} ) # Tests -if(CATKIN_ENABLE_TESTING) +# if(CATKIN_ENABLE_TESTING) + +add_executable(test_cache_unittest test/cache_unittest.cpp) +target_link_libraries(test_cache_unittest tf2 gtest) + +add_executable(test_static_cache_unittest test/static_cache_test.cpp) +target_link_libraries(test_static_cache_unittest tf2 gtest) -catkin_add_gtest(test_cache_unittest test/cache_unittest.cpp) -target_link_libraries(test_cache_unittest tf2 ${console_bridge_LIBRARIES}) -add_dependencies(test_cache_unittest ${catkin_EXPORTED_TARGETS}) - -catkin_add_gtest(test_static_cache_unittest test/static_cache_test.cpp) -target_link_libraries(test_static_cache_unittest tf2 ${console_bridge_LIBRARIES}) -add_dependencies(test_static_cache_unittest ${catkin_EXPORTED_TARGETS}) - -catkin_add_gtest(test_simple test/simple_tf2_core.cpp) -target_link_libraries(test_simple tf2 ${console_bridge_LIBRARIES}) -add_dependencies(test_simple ${catkin_EXPORTED_TARGETS}) +add_executable(test_simple test/simple_tf2_core.cpp) +target_link_libraries(test_simple tf2 gtest) add_executable(speed_test EXCLUDE_FROM_ALL test/speed_test.cpp) -target_link_libraries(speed_test tf2 ${console_bridge_LIBRARIES}) -add_dependencies(tests speed_test) -add_dependencies(tests ${catkin_EXPORTED_TARGETS}) +target_link_libraries(speed_test tf2 gtest) -endif() +# endif() diff -uprN 0.5.16/include/tf2/buffer_core.h tf2/include/tf2/buffer_core.h --- 0.5.16/include/tf2/buffer_core.h 2018-09-18 15:00:42.778601493 -0700 +++ tf2/include/tf2/buffer_core.h 2018-09-17 22:40:06.359925557 -0700 @@ -33,15 +33,14 @@ #define TF2_BUFFER_CORE_H #include "transform_storage.h" +#include "tf2/time.h" #include <boost/signals2.hpp> #include <string> -#include "ros/duration.h" -#include "ros/time.h" //#include "geometry_msgs/TwistStamped.h" -#include "geometry_msgs/TransformStamped.h" +#include "tf2/transform_stamped.h" //////////////////////////backwards startup for porting //#include "tf/tf.h" @@ -54,7 +53,7 @@ namespace tf2 { -typedef std::pair<ros::Time, CompactFrameID> P_TimeAndFrameID; +typedef std::pair<Time, CompactFrameID> P_TimeAndFrameID; typedef uint32_t TransformableCallbackHandle; typedef uint64_t TransformableRequestHandle; @@ -89,7 +88,7 @@ class BufferCore { public: /************* Constants ***********************/ - static const int DEFAULT_CACHE_TIME = 10; //!< The default amount of time to cache data in seconds + static const uint64_t DEFAULT_CACHE_TIME = 10 * 1e9; //!< The default amount of time to cache data in seconds (nanoseconds) static const uint32_t MAX_GRAPH_DEPTH = 1000UL; //!< Maximum graph search depth (deeper graphs will be assumed to have loops) /** Constructor @@ -97,7 +96,7 @@ public: * \param cache_time How long to keep a history of transforms in nanoseconds * */ - BufferCore(ros::Duration cache_time_ = ros::Duration(DEFAULT_CACHE_TIME)); + BufferCore(Duration cache_time_ = Duration(DEFAULT_CACHE_TIME)); virtual ~BufferCore(void); /** \brief Clear all data */ @@ -124,7 +123,7 @@ public: */ geometry_msgs::TransformStamped lookupTransform(const std::string& target_frame, const std::string& source_frame, - const ros::Time& time) const; + const Time& time) const; /** \brief Get the transform between two frames by frame ID assuming fixed frame. * \param target_frame The frame to which data should be transformed @@ -139,8 +138,8 @@ public: */ geometry_msgs::TransformStamped - lookupTransform(const std::string& target_frame, const ros::Time& target_time, - const std::string& source_frame, const ros::Time& source_time, + lookupTransform(const std::string& target_frame, const Time& target_time, + const std::string& source_frame, const Time& source_time, const std::string& fixed_frame) const; /** \brief Lookup the twist of the tracking_frame with respect to the observation frame in the reference_frame using the reference point @@ -167,7 +166,7 @@ public: geometry_msgs::Twist lookupTwist(const std::string& tracking_frame, const std::string& observation_frame, const std::string& reference_frame, const tf::Point & reference_point, const std::string& reference_point_frame, - const ros::Time& time, const ros::Duration& averaging_interval) const; + const Time& time, const Duration& averaging_interval) const; */ /** \brief lookup the twist of the tracking frame with respect to the observational frame * @@ -184,7 +183,7 @@ public: /* geometry_msgs::Twist lookupTwist(const std::string& tracking_frame, const std::string& observation_frame, - const ros::Time& time, const ros::Duration& averaging_interval) const; + const Time& time, const Duration& averaging_interval) const; */ /** \brief Test if a transform is possible * \param target_frame The frame into which to transform @@ -194,7 +193,7 @@ public: * \return True if the transform is possible, false otherwise */ bool canTransform(const std::string& target_frame, const std::string& source_frame, - const ros::Time& time, std::string* error_msg = NULL) const; + const Time& time, std::string* error_msg = NULL) const; /** \brief Test if a transform is possible * \param target_frame The frame into which to transform @@ -205,8 +204,8 @@ public: * \param error_msg A pointer to a string which will be filled with why the transform failed, if not NULL * \return True if the transform is possible, false otherwise */ - bool canTransform(const std::string& target_frame, const ros::Time& target_time, - const std::string& source_frame, const ros::Time& source_time, + bool canTransform(const std::string& target_frame, const Time& target_time, + const std::string& source_frame, const Time& source_time, const std::string& fixed_frame, std::string* error_msg = NULL) const; /** \brief A way to see what frames have been cached in yaml format @@ -224,14 +223,14 @@ public: std::string allFramesAsString() const; typedef boost::function<void(TransformableRequestHandle request_handle, const std::string& target_frame, const std::string& source_frame, - ros::Time time, TransformableResult result)> TransformableCallback; + Time time, TransformableResult result)> TransformableCallback; /// \brief Internal use only TransformableCallbackHandle addTransformableCallback(const TransformableCallback& cb); /// \brief Internal use only void removeTransformableCallback(TransformableCallbackHandle handle); /// \brief Internal use only - TransformableRequestHandle addTransformableRequest(TransformableCallbackHandle handle, const std::string& target_frame, const std::string& source_frame, ros::Time time); + TransformableRequestHandle addTransformableRequest(TransformableCallbackHandle handle, const std::string& target_frame, const std::string& source_frame, Time time); /// \brief Internal use only void cancelTransformableRequest(TransformableRequestHandle handle); @@ -269,7 +268,7 @@ public: * @param frame_id The frame id of the frame in question * @param parent The reference to the string to fill the parent * Returns true unless "NO_PARENT" */ - bool _getParent(const std::string& frame_id, ros::Time time, std::string& parent) const; + bool _getParent(const std::string& frame_id, Time time, std::string& parent) const; /** \brief A way to get a std::vector of available frame ids */ void _getFrameStrings(std::vector<std::string>& ids) const; @@ -282,7 +281,7 @@ public: return lookupOrInsertFrameNumber(frameid_str); } - int _getLatestCommonTime(CompactFrameID target_frame, CompactFrameID source_frame, ros::Time& time, std::string* error_string) const { + int _getLatestCommonTime(CompactFrameID target_frame, CompactFrameID source_frame, Time& time, std::string* error_string) const { boost::mutex::scoped_lock lock(frame_mutex_); return getLatestCommonTime(target_frame, source_frame, time, error_string); } @@ -292,7 +291,7 @@ public: } /**@brief Get the duration over which this transformer will cache */ - ros::Duration getCacheLength() { return cache_time_;} + Duration getCacheLength() { return cache_time_;} /** \brief Backwards compatabilityA way to see what frames have been cached * Useful for debugging @@ -303,7 +302,7 @@ public: /** \brief Backwards compatabilityA way to see what frames are in a chain * Useful for debugging */ - void _chainAsVector(const std::string & target_frame, ros::Time target_time, const std::string & source_frame, ros::Time source_time, const std::string & fixed_frame, std::vector<std::string>& output) const; + void _chainAsVector(const std::string & target_frame, Time target_time, const std::string & source_frame, Time source_time, const std::string & fixed_frame, std::vector<std::string>& output) const; private: @@ -333,7 +332,7 @@ private: /// How long to cache transform history - ros::Duration cache_time_; + Duration cache_time_; typedef boost::unordered_map<TransformableCallbackHandle, TransformableCallback> M_TransformableCallback; M_TransformableCallback transformable_callbacks_; @@ -342,7 +341,7 @@ private: struct TransformableRequest { - ros::Time time; + Time time; TransformableRequestHandle request_handle; TransformableCallbackHandle cb_handle; CompactFrameID target_id; @@ -393,21 +392,21 @@ private: /**@brief Return the latest rostime which is common across the spanning set * zero if fails to cross */ - int getLatestCommonTime(CompactFrameID target_frame, CompactFrameID source_frame, ros::Time& time, std::string* error_string) const; + int getLatestCommonTime(CompactFrameID target_frame, CompactFrameID source_frame, Time& time, std::string* error_string) const; template<typename F> - int walkToTopParent(F& f, ros::Time time, CompactFrameID target_id, CompactFrameID source_id, std::string* error_string) const; + int walkToTopParent(F& f, Time time, CompactFrameID target_id, CompactFrameID source_id, std::string* error_string) const; /**@brief Traverse the transform tree. If frame_chain is not NULL, store the traversed frame tree in vector frame_chain. * */ template<typename F> - int walkToTopParent(F& f, ros::Time time, CompactFrameID target_id, CompactFrameID source_id, std::string* error_string, std::vector<CompactFrameID> *frame_chain) const; + int walkToTopParent(F& f, Time time, CompactFrameID target_id, CompactFrameID source_id, std::string* error_string, std::vector<CompactFrameID> *frame_chain) const; void testTransformableRequests(); bool canTransformInternal(CompactFrameID target_id, CompactFrameID source_id, - const ros::Time& time, std::string* error_msg) const; + const Time& time, std::string* error_msg) const; bool canTransformNoLock(CompactFrameID target_id, CompactFrameID source_id, - const ros::Time& time, std::string* error_msg) const; + const Time& time, std::string* error_msg) const; //Whether it is safe to use canTransform with a timeout. (If another thread is not provided it will always timeout.) diff -uprN 0.5.16/include/tf2/convert.h tf2/include/tf2/convert.h --- 0.5.16/include/tf2/convert.h 2018-09-18 15:00:42.778601493 -0700 +++ tf2/include/tf2/convert.h 2018-09-17 20:15:05.000000000 -0700 @@ -35,8 +35,9 @@ #include <tf2/transform_datatypes.h> #include <tf2/exceptions.h> -#include <geometry_msgs/TransformStamped.h> +#include <tf2/transform_stamped.h> #include <tf2/impl/convert.h> +#include <tf2/time.h> namespace tf2 { @@ -58,7 +59,7 @@ template <class T> * reference is bound to the lifetime of the argument. */ template <class T> - const ros::Time& getTimestamp(const T& t); + const Time& getTimestamp(const T& t); /**\brief Get the frame_id from data * \param t The data input. @@ -72,7 +73,7 @@ template <class T> /* An implementation for Stamped<P> datatypes */ template <class P> - const ros::Time& getTimestamp(const tf2::Stamped<P>& t) + const Time& getTimestamp(const tf2::Stamped<P>& t) { return t.stamp_; } @@ -113,7 +114,7 @@ template <class A, class B> void convert(const A& a, B& b) { //printf("In double type convert\n"); - impl::Converter<ros::message_traits::IsMessage<A>::value, ros::message_traits::IsMessage<B>::value>::convert(a, b); + // impl::Converter<ros::message_traits::IsMessage<A>::value, ros::message_traits::IsMessage<B>::value>::convert(a, b); } template <class A> diff -uprN 0.5.16/include/tf2/exceptions.h tf2/include/tf2/exceptions.h --- 0.5.16/include/tf2/exceptions.h 2018-09-18 15:00:42.778601493 -0700 +++ tf2/include/tf2/exceptions.h 2018-09-17 20:13:41.143660229 -0700 @@ -37,7 +37,7 @@ namespace tf2{ /** \brief A base class for all tf2 exceptions - * This inherits from ros::exception + * This inherits from exception * which inherits from std::runtime_exception */ class TransformException: public std::runtime_error diff -uprN 0.5.16/include/tf2/tf2_error.h tf2/include/tf2/tf2_error.h --- 0.5.16/include/tf2/tf2_error.h 1969-12-31 16:00:00.000000000 -0800 +++ tf2/include/tf2/tf2_error.h 2018-09-17 22:28:14.435000000 -0700 @@ -0,0 +1,15 @@ +#ifndef TF2_MSGS_TF2_ERROR_H +#define TF2_MSGS_TF2_ERROR_H + +namespace tf2_msgs { +namespace TF2Error { + const uint8_t NO_ERROR = 0; + const uint8_t LOOKUP_ERROR = 1; + const uint8_t CONNECTIVITY_ERROR = 2; + const uint8_t EXTRAPOLATION_ERROR = 3; + const uint8_t INVALID_ARGUMENT_ERROR = 4; + const uint8_t TIMEOUT_ERROR = 5; + const uint8_t TRANSFORM_ERROR = 6; +} +} +#endif diff -uprN 0.5.16/include/tf2/time_cache.h tf2/include/tf2/time_cache.h --- 0.5.16/include/tf2/time_cache.h 2018-09-18 15:00:42.778601493 -0700 +++ tf2/include/tf2/time_cache.h 2018-09-17 20:15:27.000000000 -0700 @@ -33,31 +33,27 @@ #define TF2_TIME_CACHE_H #include "transform_storage.h" +#include "tf2/time.h" #include <list> #include <sstream> -#include <ros/message_forward.h> -#include <ros/time.h> #include <boost/shared_ptr.hpp> -namespace geometry_msgs -{ -ROS_DECLARE_MESSAGE(TransformStamped); -} + namespace tf2 { -typedef std::pair<ros::Time, CompactFrameID> P_TimeAndFrameID; +typedef std::pair<Time, CompactFrameID> P_TimeAndFrameID; class TimeCacheInterface { public: /** \brief Access data from the cache */ - virtual bool getData(ros::Time time, TransformStorage & data_out, std::string* error_str = 0)=0; //returns false if data unavailable (should be thrown as lookup exception + virtual bool getData(Time time, TransformStorage & data_out, std::string* error_str = 0)=0; //returns false if data unavailable (should be thrown as lookup exception /** \brief Insert data into the cache */ virtual bool insertData(const TransformStorage& new_data)=0; @@ -66,7 +62,7 @@ public: virtual void clearList()=0; /** \brief Retrieve the parent at a specific time */ - virtual CompactFrameID getParent(ros::Time time, std::string* error_str) = 0; + virtual CompactFrameID getParent(Time time, std::string* error_str) = 0; /** * \brief Get the latest time stored in this cache, and the parent associated with it. Returns parent = 0 if no data. @@ -79,10 +75,10 @@ public: virtual unsigned int getListLength()=0; /** @brief Get the latest timestamp cached */ - virtual ros::Time getLatestTimestamp()=0; + virtual Time getLatestTimestamp()=0; /** @brief Get the oldest timestamp cached */ - virtual ros::Time getOldestTimestamp()=0; + virtual Time getOldestTimestamp()=0; }; typedef boost::shared_ptr<TimeCacheInterface> TimeCacheInterfacePtr; @@ -98,35 +94,35 @@ class TimeCache : public TimeCacheInterf static const unsigned int MAX_LENGTH_LINKED_LIST = 1000000; //!< Maximum length of linked list, to make sure not to be able to use unlimited memory. static const int64_t DEFAULT_MAX_STORAGE_TIME = 1ULL * 1000000000LL; //!< default value of 10 seconds storage - TimeCache(ros::Duration max_storage_time = ros::Duration().fromNSec(DEFAULT_MAX_STORAGE_TIME)); + TimeCache(Duration max_storage_time = DEFAULT_MAX_STORAGE_TIME); /// Virtual methods - virtual bool getData(ros::Time time, TransformStorage & data_out, std::string* error_str = 0); + virtual bool getData(Time time, TransformStorage & data_out, std::string* error_str = 0); virtual bool insertData(const TransformStorage& new_data); virtual void clearList(); - virtual CompactFrameID getParent(ros::Time time, std::string* error_str); + virtual CompactFrameID getParent(Time time, std::string* error_str); virtual P_TimeAndFrameID getLatestTimeAndParent(); /// Debugging information methods virtual unsigned int getListLength(); - virtual ros::Time getLatestTimestamp(); - virtual ros::Time getOldestTimestamp(); + virtual Time getLatestTimestamp(); + virtual Time getOldestTimestamp(); private: typedef std::list<TransformStorage> L_TransformStorage; L_TransformStorage storage_; - ros::Duration max_storage_time_; + Duration max_storage_time_; /// A helper function for getData //Assumes storage is already locked for it - inline uint8_t findClosest(TransformStorage*& one, TransformStorage*& two, ros::Time target_time, std::string* error_str); + inline uint8_t findClosest(TransformStorage*& one, TransformStorage*& two, Time target_time, std::string* error_str); - inline void interpolate(const TransformStorage& one, const TransformStorage& two, ros::Time time, TransformStorage& output); + inline void interpolate(const TransformStorage& one, const TransformStorage& two, Time time, TransformStorage& output); void pruneList(); @@ -140,17 +136,17 @@ class StaticCache : public TimeCacheInte public: /// Virtual methods - virtual bool getData(ros::Time time, TransformStorage & data_out, std::string* error_str = 0); //returns false if data unavailable (should be thrown as lookup exception + virtual bool getData(Time time, TransformStorage & data_out, std::string* error_str = 0); //returns false if data unavailable (should be thrown as lookup exception virtual bool insertData(const TransformStorage& new_data); virtual void clearList(); - virtual CompactFrameID getParent(ros::Time time, std::string* error_str); + virtual CompactFrameID getParent(Time time, std::string* error_str); virtual P_TimeAndFrameID getLatestTimeAndParent(); /// Debugging information methods virtual unsigned int getListLength(); - virtual ros::Time getLatestTimestamp(); - virtual ros::Time getOldestTimestamp(); + virtual Time getLatestTimestamp(); + virtual Time getOldestTimestamp(); private: diff -uprN 0.5.16/include/tf2/time.h tf2/include/tf2/time.h --- 0.5.16/include/tf2/time.h 1969-12-31 16:00:00.000000000 -0800 +++ tf2/include/tf2/time.h 2018-09-17 20:17:32.191167256 -0700 @@ -0,0 +1,13 @@ +#ifndef TF2_TIME_H +#define TF2_TIME_H + +#include <stdint.h> +#include <limits> + +namespace tf2 { +typedef uint64_t Time; +typedef uint64_t Duration; +const uint64_t TIME_MAX = std::numeric_limits<uint64_t>::max(); +inline double time_to_sec(Time t) { return static_cast<double>(t) / 1e9; } +} +#endif diff -uprN 0.5.16/include/tf2/transform_datatypes.h tf2/include/tf2/transform_datatypes.h --- 0.5.16/include/tf2/transform_datatypes.h 2018-09-18 15:00:42.778601493 -0700 +++ tf2/include/tf2/transform_datatypes.h 2018-09-17 20:15:43.000000000 -0700 @@ -33,7 +33,7 @@ #define TF2_TRANSFORM_DATATYPES_H #include <string> -#include "ros/time.h" +#include "tf2/time.h" namespace tf2 { @@ -43,14 +43,14 @@ namespace tf2 template <typename T> class Stamped : public T{ public: - ros::Time stamp_; ///< The timestamp associated with this data + Time stamp_; ///< The timestamp associated with this data std::string frame_id_; ///< The frame_id associated this data /** Default constructor */ Stamped() :frame_id_ ("NO_ID_STAMPED_DEFAULT_CONSTRUCTION"){}; //Default constructor used only for preallocation /** Full constructor */ - Stamped(const T& input, const ros::Time& timestamp, const std::string & frame_id) : + Stamped(const T& input, const Time& timestamp, const std::string & frame_id) : T (input), stamp_ ( timestamp ), frame_id_ (frame_id){ } ; /** Copy Constructor */ diff -uprN 0.5.16/include/tf2/transform_stamped.h tf2/include/tf2/transform_stamped.h --- 0.5.16/include/tf2/transform_stamped.h 1969-12-31 16:00:00.000000000 -0800 +++ tf2/include/tf2/transform_stamped.h 2018-09-17 22:28:25.086000000 -0700 @@ -0,0 +1,44 @@ +#ifndef GEOMETRY_MSGS_TRANSFORM_STAMPED_H +#define GEOMETRY_MSGS_TRANSFORM_STAMPED_H + +#include <iostream> +#include <stdint.h> + +namespace geometry_msgs { + +struct Header { + uint32_t seq; + uint64_t stamp; + std::string frame_id; + Header() : seq(0), stamp(0), frame_id("") {} +}; + +struct Vector3 { + double x; + double y; + double z; + Vector3() : x(0.0), y(0.0), z(0.0) {} +}; + +struct Quaternion { + double x; + double y; + double z; + double w; + Quaternion(): x(0.0), y(0.0), z(0.0), w(0.0) {} +}; + +struct Transform { + Vector3 translation; + Quaternion rotation; +}; + +struct TransformStamped { + Header header; + std::string child_frame_id; + Transform transform; +}; + +} + +#endif diff -uprN 0.5.16/include/tf2/transform_storage.h tf2/include/tf2/transform_storage.h --- 0.5.16/include/tf2/transform_storage.h 2018-09-18 15:00:42.778601493 -0700 +++ tf2/include/tf2/transform_storage.h 2018-09-18 13:22:49.074170176 -0700 @@ -35,14 +35,9 @@ #include <tf2/LinearMath/Vector3.h> #include <tf2/LinearMath/Quaternion.h> -#include <ros/message_forward.h> -#include <ros/time.h> -#include <ros/types.h> +#include <tf2/transform_stamped.h> +#include "tf2/time.h" -namespace geometry_msgs -{ -ROS_DECLARE_MESSAGE(TransformStamped); -} namespace tf2 { @@ -75,7 +70,7 @@ public: tf2::Quaternion rotation_; tf2::Vector3 translation_; - ros::Time stamp_; + Time stamp_; CompactFrameID frame_id_; CompactFrameID child_frame_id_; }; diff -uprN 0.5.16/src/buffer_core.cpp tf2/src/buffer_core.cpp --- 0.5.16/src/buffer_core.cpp 2018-09-18 15:00:42.778601493 -0700 +++ tf2/src/buffer_core.cpp 2018-09-18 13:23:28.104931970 -0700 @@ -30,14 +30,16 @@ /** \author Tully Foote */ #include "tf2/buffer_core.h" -#include "tf2/time_cache.h" #include "tf2/exceptions.h" -#include "tf2_msgs/TF2Error.h" +#include "tf2/time_cache.h" +#include "tf2/time.h" +#include <stdio.h> #include <assert.h> -#include <console_bridge/console.h> -#include "tf2/LinearMath/Transform.h" +#include <iostream> #include <boost/foreach.hpp> +#include "tf2/LinearMath/Transform.h" +#include "tf2/tf2_error.h" namespace tf2 { @@ -62,7 +64,7 @@ void transformTF2ToMsg(const tf2::Transf } /** \brief convert Transform to Transform msg*/ -void transformTF2ToMsg(const tf2::Transform& tf2, geometry_msgs::TransformStamped& msg, ros::Time stamp, const std::string& frame_id, const std::string& child_frame_id) +void transformTF2ToMsg(const tf2::Transform& tf2, geometry_msgs::TransformStamped& msg, Time stamp, const std::string& frame_id, const std::string& child_frame_id) { transformTF2ToMsg(tf2, msg.transform); msg.header.stamp = stamp; @@ -81,7 +83,7 @@ void transformTF2ToMsg(const tf2::Quater msg.rotation.w = orient.w(); } -void transformTF2ToMsg(const tf2::Quaternion& orient, const tf2::Vector3& pos, geometry_msgs::TransformStamped& msg, ros::Time stamp, const std::string& frame_id, const std::string& child_frame_id) +void transformTF2ToMsg(const tf2::Quaternion& orient, const tf2::Vector3& pos, geometry_msgs::TransformStamped& msg, Time stamp, const std::string& frame_id, const std::string& child_frame_id) { transformTF2ToMsg(orient, pos, msg.transform); msg.header.stamp = stamp; @@ -123,7 +125,7 @@ bool BufferCore::warnFrameId(const char* { std::stringstream ss; ss << "Invalid argument passed to "<< function_name_arg <<" in tf2 frame_ids cannot be empty"; - logWarn("%s",ss.str().c_str()); + // logWarn("%s",ss.str().c_str()); return true; } @@ -131,7 +133,7 @@ bool BufferCore::warnFrameId(const char* { std::stringstream ss; ss << "Invalid argument \"" << frame_id << "\" passed to "<< function_name_arg <<" in tf2 frame_ids cannot start with a '/' like: "; - logWarn("%s",ss.str().c_str()); + // logWarn("%s",ss.str().c_str()); return true; } @@ -165,7 +167,7 @@ CompactFrameID BufferCore::validateFrame return id; } -BufferCore::BufferCore(ros::Duration cache_time) +BufferCore::BufferCore(Duration cache_time) : cache_time_(cache_time) , transformable_callbacks_counter_(0) , transformable_requests_counter_(0) @@ -218,30 +220,37 @@ bool BufferCore::setTransform(const geom bool error_exists = false; if (stripped.child_frame_id == stripped.header.frame_id) { - logError("TF_SELF_TRANSFORM: Ignoring transform from authority \"%s\" with frame_id and child_frame_id \"%s\" because they are the same", authority.c_str(), stripped.child_frame_id.c_str()); + std::stringstream ss; + ss << "TF_SELF_TRANSFORM: Ignoring transform from authority \"" << authority << "\" with frame_id and child_frame_id \"" << stripped.child_frame_id << "\" because they are the same"; + perror(ss.str().c_str()); error_exists = true; } if (stripped.child_frame_id == "") { - logError("TF_NO_CHILD_FRAME_ID: Ignoring transform from authority \"%s\" because child_frame_id not set ", authority.c_str()); + std::stringstream ss; + ss << "TF_NO_CHILD_FRAME_ID: Ignoring transform from authority \"" << authority << "\" because child_frame_id not set"; + perror(ss.str().c_str()); error_exists = true; } if (stripped.header.frame_id == "") { - logError("TF_NO_FRAME_ID: Ignoring transform with child_frame_id \"%s\" from authority \"%s\" because frame_id not set", stripped.child_frame_id.c_str(), authority.c_str()); + std::stringstream ss; + ss << "TF_NO_FRAME_ID: Ignoring transform with child_frame_id \"" << stripped.child_frame_id << "\" from authority \"" << authority << "\" because frame_id not set"; + perror(ss.str().c_str()); error_exists = true; } if (std::isnan(stripped.transform.translation.x) || std::isnan(stripped.transform.translation.y) || std::isnan(stripped.transform.translation.z)|| std::isnan(stripped.transform.rotation.x) || std::isnan(stripped.transform.rotation.y) || std::isnan(stripped.transform.rotation.z) || std::isnan(stripped.transform.rotation.w)) { - logError("TF_NAN_INPUT: Ignoring transform for child_frame_id \"%s\" from authority \"%s\" because of a nan value in the transform (%f %f %f) (%f %f %f %f)", - stripped.child_frame_id.c_str(), authority.c_str(), - stripped.transform.translation.x, stripped.transform.translation.y, stripped.transform.translation.z, - stripped.transform.rotation.x, stripped.transform.rotation.y, stripped.transform.rotation.z, stripped.transform.rotation.w - ); + std::stringstream ss; + ss << "TF_NAN_INPUT: Ignoring transform for child_frame_id \"" << stripped.child_frame_id + << "\" from authority \"" << authority << "\" because of a nan value in the transform (" + << stripped.transform.translation.x << " " << stripped.transform.translation.y << " " << stripped.transform.translation.z << ") (" + << stripped.transform.rotation.x << " " << stripped.transform.rotation.y << " " << stripped.transform.rotation.z << " " << stripped.transform.rotation.w << ")"; + perror(ss.str().c_str()); error_exists = true; } @@ -252,9 +261,10 @@ bool BufferCore::setTransform(const geom if (!valid) { - logError("TF_DENORMALIZED_QUATERNION: Ignoring transform for child_frame_id \"%s\" from authority \"%s\" because of an invalid quaternion in the transform (%f %f %f %f)", - stripped.child_frame_id.c_str(), authority.c_str(), - stripped.transform.rotation.x, stripped.transform.rotation.y, stripped.transform.rotation.z, stripped.transform.rotation.w); + std::stringstream ss; + ss << "TF_DENORMALIZED_QUATERNION: Ignoring transform for child_frame_id \"" << stripped.child_frame_id << "\" from authority \"" << authority << "\" because of an invalid quaternion in the transform (" + << stripped.transform.rotation.x << " " << stripped.transform.rotation.y << " " << stripped.transform.rotation.z << " " << stripped.transform.rotation.w << ")"; + perror(ss.str().c_str()); error_exists = true; } @@ -274,7 +284,7 @@ bool BufferCore::setTransform(const geom } else { - logWarn("TF_OLD_DATA ignoring data from the past for frame %s at time %g according to authority %s\nPossible reasons are listed at http://wiki.ros.org/tf/Errors%%20explained", stripped.child_frame_id.c_str(), stripped.header.stamp.toSec(), authority.c_str()); + // logWarn("TF_OLD_DATA ignoring data from the past for frame %s at time %g according to authority %s\nPossible reasons are listed at http://wiki.ros.org/tf/Errors%%20explained", stripped.child_frame_id.c_str(), time_to_sec(stripped.header.stamp), authority.c_str()); return false; } } @@ -306,13 +316,13 @@ enum WalkEnding // TODO for Jade: Merge walkToTopParent functions; this is now a stub to preserve ABI template<typename F> -int BufferCore::walkToTopParent(F& f, ros::Time time, CompactFrameID target_id, CompactFrameID source_id, std::string* error_string) const +int BufferCore::walkToTopParent(F& f, Time time, CompactFrameID target_id, CompactFrameID source_id, std::string* error_string) const { return walkToTopParent(f, time, target_id, source_id, error_string, NULL); } template<typename F> -int BufferCore::walkToTopParent(F& f, ros::Time time, CompactFrameID target_id, +int BufferCore::walkToTopParent(F& f, Time time, CompactFrameID target_id, CompactFrameID source_id, std::string* error_string, std::vector<CompactFrameID> *frame_chain) const { @@ -327,7 +337,7 @@ int BufferCore::walkToTopParent(F& f, ro } //If getting the latest get the latest common time - if (time == ros::Time()) + if (time == 0) { int retval = getLatestCommonTime(target_id, source_id, time, error_string); if (retval != tf2_msgs::TF2Error::NO_ERROR) @@ -510,7 +520,7 @@ struct TransformAccum { } - CompactFrameID gather(TimeCacheInterfacePtr cache, ros::Time time, std::string* error_string) + CompactFrameID gather(TimeCacheInterfacePtr cache, Time time, std::string* error_string) { if (!cache->getData(time, st, error_string)) { @@ -534,7 +544,7 @@ struct TransformAccum } } - void finalize(WalkEnding end, ros::Time _time) + void finalize(WalkEnding end, Time _time) { switch (end) { @@ -567,7 +577,7 @@ struct TransformAccum } TransformStorage st; - ros::Time time; + Time time; tf2::Quaternion source_to_top_quat; tf2::Vector3 source_to_top_vec; tf2::Quaternion target_to_top_quat; @@ -579,7 +589,7 @@ struct TransformAccum geometry_msgs::TransformStamped BufferCore::lookupTransform(const std::string& target_frame, const std::string& source_frame, - const ros::Time& time) const + const Time& time) const { boost::mutex::scoped_lock lock(frame_mutex_); @@ -589,7 +599,7 @@ geometry_msgs::TransformStamped BufferCo identity.child_frame_id = source_frame; identity.transform.rotation.w = 1; - if (time == ros::Time()) + if (time == 0) { CompactFrameID target_id = lookupFrameNumber(target_frame); TimeCacheInterfacePtr cache = getFrame(target_id); @@ -617,12 +627,15 @@ geometry_msgs::TransformStamped BufferCo { case tf2_msgs::TF2Error::CONNECTIVITY_ERROR: throw ConnectivityException(error_string); + break; case tf2_msgs::TF2Error::EXTRAPOLATION_ERROR: throw ExtrapolationException(error_string); + break; case tf2_msgs::TF2Error::LOOKUP_ERROR: throw LookupException(error_string); + break; default: - logError("Unknown error code: %d", retval); + // logError("Unknown error code: %d", retval); assert(0); } } @@ -634,9 +647,9 @@ geometry_msgs::TransformStamped BufferCo geometry_msgs::TransformStamped BufferCore::lookupTransform(const std::string& target_frame, - const ros::Time& target_time, + const Time& target_time, const std::string& source_frame, - const ros::Time& source_time, + const Time& source_time, const std::string& fixed_frame) const { validateFrameId("lookupTransform argument target_frame", target_frame); @@ -662,8 +675,8 @@ geometry_msgs::TransformStamped BufferCo /* geometry_msgs::Twist BufferCore::lookupTwist(const std::string& tracking_frame, const std::string& observation_frame, - const ros::Time& time, - const ros::Duration& averaging_interval) const + const Time& time, + const Duration& averaging_interval) const { try { @@ -695,8 +708,8 @@ geometry_msgs::Twist BufferCore::lookupT const std::string& reference_frame, const tf2::Point & reference_point, const std::string& reference_point_frame, - const ros::Time& time, - const ros::Duration& averaging_interval) const + const Time& time, + const Duration& averaging_interval) const { try{ geometry_msgs::Twist t; @@ -725,7 +738,7 @@ geometry_msgs::Twist BufferCore::lookupT struct CanTransformAccum { - CompactFrameID gather(TimeCacheInterfacePtr cache, ros::Time time, std::string* error_string) + CompactFrameID gather(TimeCacheInterfacePtr cache, Time time, std::string* error_string) { return cache->getParent(time, error_string); } @@ -734,7 +747,7 @@ struct CanTransformAccum { } - void finalize(WalkEnding end, ros::Time _time) + void finalize(WalkEnding end, Time _time) { } @@ -742,7 +755,7 @@ struct CanTransformAccum }; bool BufferCore::canTransformNoLock(CompactFrameID target_id, CompactFrameID source_id, - const ros::Time& time, std::string* error_msg) const + const Time& time, std::string* error_msg) const { if (target_id == 0 || source_id == 0) { @@ -779,14 +792,14 @@ bool BufferCore::canTransformNoLock(Comp } bool BufferCore::canTransformInternal(CompactFrameID target_id, CompactFrameID source_id, - const ros::Time& time, std::string* error_msg) const + const Time& time, std::string* error_msg) const { boost::mutex::scoped_lock lock(frame_mutex_); return canTransformNoLock(target_id, source_id, time, error_msg); } bool BufferCore::canTransform(const std::string& target_frame, const std::string& source_frame, - const ros::Time& time, std::string* error_msg) const + const Time& time, std::string* error_msg) const { // Short circuit if target_frame == source_frame if (target_frame == source_frame) @@ -824,8 +837,8 @@ bool BufferCore::canTransform(const std: return canTransformNoLock(target_id, source_id, time, error_msg); } -bool BufferCore::canTransform(const std::string& target_frame, const ros::Time& target_time, - const std::string& source_frame, const ros::Time& source_time, +bool BufferCore::canTransform(const std::string& target_frame, const Time& target_time, + const std::string& source_frame, const Time& source_time, const std::string& fixed_frame, std::string* error_msg) const { if (warnFrameId("canTransform argument target_frame", target_frame)) @@ -955,7 +968,7 @@ std::string BufferCore::allFramesAsStrin if (frame_ptr == NULL) continue; CompactFrameID frame_id_num; - if( frame_ptr->getData(ros::Time(), temp)) + if( frame_ptr->getData(0, temp)) frame_id_num = temp.frame_id_; else { @@ -981,7 +994,7 @@ struct TimeAndFrameIDFrameComparator CompactFrameID id; }; -int BufferCore::getLatestCommonTime(CompactFrameID target_id, CompactFrameID source_id, ros::Time & time, std::string * error_string) const +int BufferCore::getLatestCommonTime(CompactFrameID target_id, CompactFrameID source_id, Time & time, std::string * error_string) const { // Error if one of the frames don't exist. if (source_id == 0 || target_id == 0) return tf2_msgs::TF2Error::LOOKUP_ERROR; @@ -993,7 +1006,7 @@ int BufferCore::getLatestCommonTime(Comp if (cache) time = cache->getLatestTimestamp(); else - time = ros::Time(); + time = 0; return tf2_msgs::TF2Error::NO_ERROR; } @@ -1004,7 +1017,7 @@ int BufferCore::getLatestCommonTime(Comp CompactFrameID frame = source_id; P_TimeAndFrameID temp; uint32_t depth = 0; - ros::Time common_time = ros::TIME_MAX; + Time common_time = TIME_MAX; while (frame != 0) { TimeCacheInterfacePtr cache = getFrame(frame); @@ -1023,7 +1036,7 @@ int BufferCore::getLatestCommonTime(Comp break; } - if (!latest.first.isZero()) + if (latest.first != 0) { common_time = std::min(latest.first, common_time); } @@ -1036,9 +1049,9 @@ int BufferCore::getLatestCommonTime(Comp if (frame == target_id) { time = common_time; - if (time == ros::TIME_MAX) + if (time == TIME_MAX) { - time = ros::Time(); + time = 0; } return tf2_msgs::TF2Error::NO_ERROR; } @@ -1060,7 +1073,7 @@ int BufferCore::getLatestCommonTime(Comp // Now walk to the top parent from the target frame, accumulating the latest time and looking for a common parent frame = target_id; depth = 0; - common_time = ros::TIME_MAX; + common_time = TIME_MAX; CompactFrameID common_parent = 0; while (true) { @@ -1078,7 +1091,7 @@ int BufferCore::getLatestCommonTime(Comp break; } - if (!latest.first.isZero()) + if (latest.first != 0) { common_time = std::min(latest.first, common_time); } @@ -1096,9 +1109,9 @@ int BufferCore::getLatestCommonTime(Comp if (frame == source_id) { time = common_time; - if (time == ros::TIME_MAX) + if (time == TIME_MAX) { - time = ros::Time(); + time = 0; } return tf2_msgs::TF2Error::NO_ERROR; } @@ -1129,7 +1142,7 @@ int BufferCore::getLatestCommonTime(Comp std::vector<P_TimeAndFrameID>::iterator end = lct_cache.end(); for (; it != end; ++it) { - if (!it->first.isZero()) + if (it->first != 0) { common_time = std::min(common_time, it->first); } @@ -1141,9 +1154,9 @@ int BufferCore::getLatestCommonTime(Comp } } - if (common_time == ros::TIME_MAX) + if (common_time == TIME_MAX) { - common_time = ros::Time(); + common_time = 0; } time = common_time; @@ -1174,7 +1187,7 @@ std::string BufferCore::allFramesAsYAML( continue; } - if(!cache->getData(ros::Time(), temp)) + if(!cache->getData(0, temp)) { continue; } @@ -1187,8 +1200,8 @@ std::string BufferCore::allFramesAsYAML( authority = it->second; } - double rate = cache->getListLength() / std::max((cache->getLatestTimestamp().toSec() - - cache->getOldestTimestamp().toSec() ), 0.0001); + double rate = cache->getListLength() / std::max(time_to_sec(cache->getLatestTimestamp() - + cache->getOldestTimestamp() ), 0.0001); mstream << std::fixed; //fixed point notation mstream.precision(3); //3 decimal places @@ -1196,12 +1209,12 @@ std::string BufferCore::allFramesAsYAML( mstream << " parent: '" << frameIDs_reverse[frame_id_num] << "'" << std::endl; mstream << " broadcaster: '" << authority << "'" << std::endl; mstream << " rate: " << rate << std::endl; - mstream << " most_recent_transform: " << (cache->getLatestTimestamp()).toSec() << std::endl; - mstream << " oldest_transform: " << (cache->getOldestTimestamp()).toSec() << std::endl; + mstream << " most_recent_transform: " << time_to_sec(cache->getLatestTimestamp()) << std::endl; + mstream << " oldest_transform: " << time_to_sec(cache->getOldestTimestamp()) << std::endl; if ( current_time > 0 ) { - mstream << " transform_delay: " << current_time - cache->getLatestTimestamp().toSec() << std::endl; + mstream << " transform_delay: " << current_time - time_to_sec(cache->getLatestTimestamp()) << std::endl; } - mstream << " buffer_length: " << (cache->getLatestTimestamp() - cache->getOldestTimestamp()).toSec() << std::endl; + mstream << " buffer_length: " << time_to_sec(cache->getLatestTimestamp() - cache->getOldestTimestamp()) << std::endl; } return mstream.str(); @@ -1252,7 +1265,7 @@ void BufferCore::removeTransformableCall } } -TransformableRequestHandle BufferCore::addTransformableRequest(TransformableCallbackHandle handle, const std::string& target_frame, const std::string& source_frame, ros::Time time) +TransformableRequestHandle BufferCore::addTransformableRequest(TransformableCallbackHandle handle, const std::string& target_frame, const std::string& source_frame, Time time) { // shortcut if target == source if (target_frame == source_frame) @@ -1273,11 +1286,11 @@ TransformableRequestHandle BufferCore::a // Might not be transformable at all, ever (if it's too far in the past) if (req.target_id && req.source_id) { - ros::Time latest_time; + Time latest_time; // TODO: This is incorrect, but better than nothing. Really we want the latest time for // any of the frames getLatestCommonTime(req.target_id, req.source_id, latest_time, 0); - if (!latest_time.isZero() && time + cache_time_ < latest_time) + if (latest_time != 0 && time + cache_time_ < latest_time) { return 0xffffffffffffffffULL; } @@ -1354,7 +1367,7 @@ bool BufferCore::_frameExists(const std: return frameIDs_.count(frame_id_str); } -bool BufferCore::_getParent(const std::string& frame_id, ros::Time time, std::string& parent) const +bool BufferCore::_getParent(const std::string& frame_id, Time time, std::string& parent) const { boost::mutex::scoped_lock lock(frame_mutex_); @@ -1397,7 +1410,7 @@ void BufferCore::testTransformableReques V_TransformableRequest::iterator it = transformable_requests_.begin(); typedef boost::tuple<TransformableCallback&, TransformableRequestHandle, std::string, - std::string, ros::Time&, TransformableResult&> TransformableTuple; + std::string, Time&, TransformableResult&> TransformableTuple; std::vector<TransformableTuple> transformables; for (; it != transformable_requests_.end();) @@ -1415,13 +1428,13 @@ void BufferCore::testTransformableReques req.source_id = lookupFrameNumber(req.source_string); } - ros::Time latest_time; + Time latest_time; bool do_cb = false; TransformableResult result = TransformAvailable; // TODO: This is incorrect, but better than nothing. Really we want the latest time for // any of the frames getLatestCommonTime(req.target_id, req.source_id, latest_time, 0); - if (!latest_time.isZero() && req.time + cache_time_ < latest_time) + if (latest_time != 0 && req.time + cache_time_ < latest_time) { do_cb = true; result = TransformFailure; @@ -1495,7 +1508,7 @@ std::string BufferCore::_allFramesAsDot( if (!counter_frame) { continue; } - if(!counter_frame->getData(ros::Time(), temp)) { + if(!counter_frame->getData(0, temp)) { continue; } else { frame_id_num = temp.frame_id_; @@ -1505,8 +1518,8 @@ std::string BufferCore::_allFramesAsDot( if (it != frame_authority_.end()) authority = it->second; - double rate = counter_frame->getListLength() / std::max((counter_frame->getLatestTimestamp().toSec() - - counter_frame->getOldestTimestamp().toSec()), 0.0001); + double rate = counter_frame->getListLength() / std::max(time_to_sec(counter_frame->getLatestTimestamp() - + counter_frame->getOldestTimestamp()), 0.0001); mstream << std::fixed; //fixed point notation mstream.precision(3); //3 decimal places @@ -1515,14 +1528,14 @@ std::string BufferCore::_allFramesAsDot( //<< "Time: " << current_time.toSec() << "\\n" << "Broadcaster: " << authority << "\\n" << "Average rate: " << rate << " Hz\\n" - << "Most recent transform: " << (counter_frame->getLatestTimestamp()).toSec() <<" "; + << "Most recent transform: " << time_to_sec(counter_frame->getLatestTimestamp()) <<" "; if (current_time > 0) - mstream << "( "<< current_time - counter_frame->getLatestTimestamp().toSec() << " sec old)"; + mstream << "( "<< current_time - time_to_sec(counter_frame->getLatestTimestamp()) << " sec old)"; mstream << "\\n" // << "(time: " << getFrame(counter)->getLatestTimestamp().toSec() << ")\\n" // << "Oldest transform: " << (current_time - getFrame(counter)->getOldestTimestamp()).toSec() << " sec old \\n" // << "(time: " << (getFrame(counter)->getOldestTimestamp()).toSec() << ")\\n" - << "Buffer length: " << (counter_frame->getLatestTimestamp()-counter_frame->getOldestTimestamp()).toSec() << " sec\\n" + << "Buffer length: " << time_to_sec(counter_frame->getLatestTimestamp()-counter_frame->getOldestTimestamp()) << " sec\\n" <<"\"];" <<std::endl; } @@ -1539,7 +1552,7 @@ std::string BufferCore::_allFramesAsDot( } continue; } - if (counter_frame->getData(ros::Time(), temp)) { + if (counter_frame->getData(0, temp)) { frame_id_num = temp.frame_id_; } else { frame_id_num = 0; @@ -1563,7 +1576,7 @@ std::string BufferCore::_allFramesAsDot( return _allFramesAsDot(0.0); } -void BufferCore::_chainAsVector(const std::string & target_frame, ros::Time target_time, const std::string & source_frame, ros::Time source_time, const std::string& fixed_frame, std::vector<std::string>& output) const +void BufferCore::_chainAsVector(const std::string & target_frame, Time target_time, const std::string & source_frame, Time source_time, const std::string& fixed_frame, std::vector<std::string>& output) const { std::string error_string; @@ -1593,7 +1606,7 @@ void BufferCore::_chainAsVector(const st case tf2_msgs::TF2Error::LOOKUP_ERROR: throw LookupException(error_string); default: - logError("Unknown error code: %d", retval); + // logError("Unknown error code: %d", retval); assert(0); } } @@ -1613,7 +1626,7 @@ void BufferCore::_chainAsVector(const st case tf2_msgs::TF2Error::LOOKUP_ERROR: throw LookupException(error_string); default: - logError("Unknown error code: %d", retval); + // logError("Unknown error code: %d", retval); assert(0); } } diff -uprN 0.5.16/src/cache.cpp tf2/src/cache.cpp --- 0.5.16/src/cache.cpp 2018-09-18 15:00:42.778601493 -0700 +++ tf2/src/cache.cpp 2018-09-17 22:40:20.792429438 -0700 @@ -35,9 +35,10 @@ #include <tf2/LinearMath/Vector3.h> #include <tf2/LinearMath/Quaternion.h> #include <tf2/LinearMath/Transform.h> -#include <geometry_msgs/TransformStamped.h> #include <assert.h> +#include "tf2/transform_stamped.h" + namespace tf2 { TransformStorage::TransformStorage() @@ -56,13 +57,13 @@ TransformStorage::TransformStorage(const translation_ = tf2::Vector3(v.x, v.y, v.z); } -TimeCache::TimeCache(ros::Duration max_storage_time) +TimeCache::TimeCache(Duration max_storage_time) : max_storage_time_(max_storage_time) {} namespace cache { // Avoid ODR collisions https://github.com/ros/geometry2/issues/175 // hoisting these into separate functions causes an ~8% speedup. Removing calling them altogether adds another ~10% -void createExtrapolationException1(ros::Time t0, ros::Time t1, std::string* error_str) +void createExtrapolationException1(Time t0, Time t1, std::string* error_str) { if (error_str) { @@ -72,7 +73,7 @@ void createExtrapolationException1(ros:: } } -void createExtrapolationException2(ros::Time t0, ros::Time t1, std::string* error_str) +void createExtrapolationException2(Time t0, Time t1, std::string* error_str) { if (error_str) { @@ -82,7 +83,7 @@ void createExtrapolationException2(ros:: } } -void createExtrapolationException3(ros::Time t0, ros::Time t1, std::string* error_str) +void createExtrapolationException3(Time t0, Time t1, std::string* error_str) { if (error_str) { @@ -93,7 +94,7 @@ void createExtrapolationException3(ros:: } } // namespace cache -uint8_t TimeCache::findClosest(TransformStorage*& one, TransformStorage*& two, ros::Time target_time, std::string* error_str) +uint8_t TimeCache::findClosest(TransformStorage*& one, TransformStorage*& two, Time target_time, std::string* error_str) { //No values stored if (storage_.empty()) @@ -102,7 +103,7 @@ uint8_t TimeCache::findClosest(Transform } //If time == 0 return the latest - if (target_time.isZero()) + if (target_time == 0) { one = &storage_.front(); return 1; @@ -124,8 +125,8 @@ uint8_t TimeCache::findClosest(Transform } } - ros::Time latest_time = (*storage_.begin()).stamp_; - ros::Time earliest_time = (*(storage_.rbegin())).stamp_; + Time latest_time = (*storage_.begin()).stamp_; + Time earliest_time = (*(storage_.rbegin())).stamp_; if (target_time == latest_time) { @@ -159,6 +160,15 @@ uint8_t TimeCache::findClosest(Transform storage_it++; } + if (storage_it == storage_.end()) { + return 0; + } + + if (storage_it == storage_.begin()) { + one = &*(storage_it); //Older + return 1; + } + //Finally the case were somewhere in the middle Guarenteed no extrapolation :-) one = &*(storage_it); //Older two = &*(--storage_it); //Newer @@ -167,7 +177,7 @@ uint8_t TimeCache::findClosest(Transform } -void TimeCache::interpolate(const TransformStorage& one, const TransformStorage& two, ros::Time time, TransformStorage& output) +void TimeCache::interpolate(const TransformStorage& one, const TransformStorage& two, Time time, TransformStorage& output) { // Check for zero distance case if( two.stamp_ == one.stamp_ ) @@ -176,7 +186,7 @@ void TimeCache::interpolate(const Transf return; } //Calculate the ratio - tf2Scalar ratio = (time.toSec() - one.stamp_.toSec()) / (two.stamp_.toSec() - one.stamp_.toSec()); + tf2Scalar ratio = time_to_sec(time - one.stamp_) / time_to_sec(two.stamp_ - one.stamp_); //Interpolate translation output.translation_.setInterpolate3(one.translation_, two.translation_, ratio); @@ -189,7 +199,7 @@ void TimeCache::interpolate(const Transf output.child_frame_id_ = one.child_frame_id_; } -bool TimeCache::getData(ros::Time time, TransformStorage & data_out, std::string* error_str) //returns false if data not available +bool TimeCache::getData(Time time, TransformStorage & data_out, std::string* error_str) //returns false if data not available { TransformStorage* p_temp_1; TransformStorage* p_temp_2; @@ -222,7 +232,7 @@ bool TimeCache::getData(ros::Time time, return true; } -CompactFrameID TimeCache::getParent(ros::Time time, std::string* error_str) +CompactFrameID TimeCache::getParent(Time time, std::string* error_str) { TransformStorage* p_temp_1; TransformStorage* p_temp_2; @@ -275,28 +285,28 @@ P_TimeAndFrameID TimeCache::getLatestTim { if (storage_.empty()) { - return std::make_pair(ros::Time(), 0); + return std::make_pair(0, 0); } const TransformStorage& ts = storage_.front(); return std::make_pair(ts.stamp_, ts.frame_id_); } -ros::Time TimeCache::getLatestTimestamp() +Time TimeCache::getLatestTimestamp() { - if (storage_.empty()) return ros::Time(); //empty list case + if (storage_.empty()) return 0; //empty list case return storage_.front().stamp_; } -ros::Time TimeCache::getOldestTimestamp() +Time TimeCache::getOldestTimestamp() { - if (storage_.empty()) return ros::Time(); //empty list case + if (storage_.empty()) return 0; //empty list case return storage_.back().stamp_; } void TimeCache::pruneList() { - ros::Time latest_time = storage_.begin()->stamp_; + Time latest_time = storage_.begin()->stamp_; while(!storage_.empty() && storage_.back().stamp_ + max_storage_time_ < latest_time) { diff -uprN 0.5.16/src/static_cache.cpp tf2/src/static_cache.cpp --- 0.5.16/src/static_cache.cpp 2018-09-18 15:00:42.778601493 -0700 +++ tf2/src/static_cache.cpp 2018-09-17 20:25:41.773942935 -0700 @@ -38,7 +38,7 @@ using namespace tf2; -bool StaticCache::getData(ros::Time time, TransformStorage & data_out, std::string* error_str) //returns false if data not available +bool StaticCache::getData(Time time, TransformStorage & data_out, std::string* error_str) //returns false if data not available { data_out = storage_; data_out.stamp_ = time; @@ -58,23 +58,23 @@ void StaticCache::clearList() { return; unsigned int StaticCache::getListLength() { return 1; }; -CompactFrameID StaticCache::getParent(ros::Time time, std::string* error_str) +CompactFrameID StaticCache::getParent(Time time, std::string* error_str) { return storage_.frame_id_; } P_TimeAndFrameID StaticCache::getLatestTimeAndParent() { - return std::make_pair(ros::Time(), storage_.frame_id_); + return std::make_pair(0, storage_.frame_id_); } -ros::Time StaticCache::getLatestTimestamp() +Time StaticCache::getLatestTimestamp() { - return ros::Time(); + return 0; }; -ros::Time StaticCache::getOldestTimestamp() +Time StaticCache::getOldestTimestamp() { - return ros::Time(); + return 0; }; diff -uprN 0.5.16/test/cache_unittest.cpp tf2/test/cache_unittest.cpp --- 0.5.16/test/cache_unittest.cpp 2018-09-18 15:00:42.778601493 -0700 +++ tf2/test/cache_unittest.cpp 2018-09-17 22:40:19.212429441 -0700 @@ -33,7 +33,8 @@ #include "tf2/LinearMath/Quaternion.h" #include <stdexcept> -#include <geometry_msgs/TransformStamped.h> +// #include <geometry_msgs/TransformStamped.h> +#include "tf2/transform_stamped.h" #include <cmath> @@ -83,7 +84,7 @@ TEST(TimeCache, Repeatability) for ( uint64_t i = 1; i < runs ; i++ ) { stor.frame_id_ = i; - stor.stamp_ = ros::Time().fromNSec(i); + stor.stamp_ = tf2::Time(i); cache.insertData(stor); } @@ -91,9 +92,9 @@ TEST(TimeCache, Repeatability) for ( uint64_t i = 1; i < runs ; i++ ) { - cache.getData(ros::Time().fromNSec(i), stor); + cache.getData(tf2::Time(i), stor); EXPECT_EQ(stor.frame_id_, i); - EXPECT_EQ(stor.stamp_, ros::Time().fromNSec(i)); + EXPECT_EQ(stor.stamp_, tf2::Time(i)); } } @@ -110,16 +111,16 @@ TEST(TimeCache, RepeatabilityReverseInse for ( int i = runs -1; i >= 0 ; i-- ) { stor.frame_id_ = i; - stor.stamp_ = ros::Time().fromNSec(i); + stor.stamp_ = tf2::Time(i); cache.insertData(stor); } for ( uint64_t i = 1; i < runs ; i++ ) { - cache.getData(ros::Time().fromNSec(i), stor); + cache.getData(tf2::Time(i), stor); EXPECT_EQ(stor.frame_id_, i); - EXPECT_EQ(stor.stamp_, ros::Time().fromNSec(i)); + EXPECT_EQ(stor.stamp_, tf2::Time(i)); } } @@ -174,36 +175,36 @@ TEST(TimeCache, ZeroAtFront) for ( uint64_t i = 1; i < runs ; i++ ) { stor.frame_id_ = i; - stor.stamp_ = ros::Time().fromNSec(i); + stor.stamp_ = tf2::Time(i); cache.insertData(stor); } stor.frame_id_ = runs; - stor.stamp_ = ros::Time().fromNSec(runs); + stor.stamp_ = tf2::Time(runs); cache.insertData(stor); for ( uint64_t i = 1; i < runs ; i++ ) { - cache.getData(ros::Time().fromNSec(i), stor); + cache.getData(tf2::Time(i), stor); EXPECT_EQ(stor.frame_id_, i); - EXPECT_EQ(stor.stamp_, ros::Time().fromNSec(i)); + EXPECT_EQ(stor.stamp_, tf2::Time(i)); } - cache.getData(ros::Time(), stor); + cache.getData(0, stor); EXPECT_EQ(stor.frame_id_, runs); - EXPECT_EQ(stor.stamp_, ros::Time().fromNSec(runs)); + EXPECT_EQ(stor.stamp_, tf2::Time(runs)); stor.frame_id_ = runs; - stor.stamp_ = ros::Time().fromNSec(runs+1); + stor.stamp_ = tf2::Time(runs + 1); cache.insertData(stor); //Make sure we get a different value now that a new values is added at the front - cache.getData(ros::Time(), stor); + cache.getData(0, stor); EXPECT_EQ(stor.frame_id_, runs); - EXPECT_EQ(stor.stamp_, ros::Time().fromNSec(runs+1)); + EXPECT_EQ(stor.stamp_, tf2::Time(runs + 1)); } @@ -234,13 +235,13 @@ TEST(TimeCache, CartesianInterpolation) stor.translation_.setValue(xvalues[step], yvalues[step], zvalues[step]); stor.frame_id_ = 2; - stor.stamp_ = ros::Time().fromNSec(step * 100 + offset); + stor.stamp_ = tf2::Time(step * 100 + offset); cache.insertData(stor); } for (int pos = 0; pos < 100 ; pos ++) { - cache.getData(ros::Time().fromNSec(offset + pos), stor); + cache.getData(tf2::Time(offset + pos), stor); double x_out = stor.translation_.x(); double y_out = stor.translation_.y(); double z_out = stor.translation_.z(); @@ -284,13 +285,13 @@ TEST(TimeCache, ReparentingInterpolation stor.translation_.setValue(xvalues[step], yvalues[step], zvalues[step]); stor.frame_id_ = step + 4; - stor.stamp_ = ros::Time().fromNSec(step * 100 + offset); + stor.stamp_ = tf2::Time(step * 100 + offset); cache.insertData(stor); } for (int pos = 0; pos < 100 ; pos ++) { - EXPECT_TRUE(cache.getData(ros::Time().fromNSec(offset + pos), stor)); + EXPECT_TRUE(cache.getData(tf2::Time(offset + pos), stor)); double x_out = stor.translation_.x(); double y_out = stor.translation_.y(); double z_out = stor.translation_.z(); @@ -352,13 +353,13 @@ TEST(TimeCache, AngularInterpolation) quats[step].setRPY(yawvalues[step], pitchvalues[step], rollvalues[step]); stor.rotation_ = quats[step]; stor.frame_id_ = 3; - stor.stamp_ = ros::Time().fromNSec(offset + (step * 100)); //step = 0 or 1 + stor.stamp_ = tf2::Time(offset + (step * 100)); //step = 0 or 1 cache.insertData(stor); } for (int pos = 0; pos < 100 ; pos ++) { - EXPECT_TRUE(cache.getData(ros::Time().fromNSec(offset + pos), stor)); //get the transform for the position + EXPECT_TRUE(cache.getData(tf2::Time(offset + pos), stor)); //get the transform for the position tf2::Quaternion quat (stor.rotation_); //Generate a ground truth quaternion directly calling slerp @@ -383,14 +384,14 @@ TEST(TimeCache, DuplicateEntries) TransformStorage stor; setIdentity(stor); stor.frame_id_ = 3; - stor.stamp_ = ros::Time().fromNSec(1); + stor.stamp_ = tf2::Time(1); cache.insertData(stor); cache.insertData(stor); - cache.getData(ros::Time().fromNSec(1), stor); + cache.getData(tf2::Time(1), stor); //printf(" stor is %f\n", stor.translation_.x()); EXPECT_TRUE(!std::isnan(stor.translation_.x())); diff -uprN 0.5.16/test/simple_tf2_core.cpp tf2/test/simple_tf2_core.cpp --- 0.5.16/test/simple_tf2_core.cpp 2018-09-18 15:00:42.778601493 -0700 +++ tf2/test/simple_tf2_core.cpp 2018-09-17 20:47:37.000000000 -0700 @@ -30,7 +30,7 @@ #include <gtest/gtest.h> #include <tf2/buffer_core.h> #include <sys/time.h> -#include <ros/ros.h> +// #include <ros/ros.h> #include "tf2/LinearMath/Vector3.h" #include "tf2/exceptions.h" @@ -47,7 +47,7 @@ TEST(tf2, setTransformValid) tf2::BufferCore tfc; geometry_msgs::TransformStamped st; st.header.frame_id = "foo"; - st.header.stamp = ros::Time(1.0); + st.header.stamp = tf2::Time(1e9); st.child_frame_id = "child"; st.transform.rotation.w = 1; EXPECT_TRUE(tfc.setTransform(st, "authority1")); @@ -59,7 +59,7 @@ TEST(tf2, setTransformInvalidQuaternion) tf2::BufferCore tfc; geometry_msgs::TransformStamped st; st.header.frame_id = "foo"; - st.header.stamp = ros::Time(1.0); + st.header.stamp = tf2::Time(1e9); st.child_frame_id = "child"; st.transform.rotation.w = 0; EXPECT_FALSE(tfc.setTransform(st, "authority1")); @@ -69,17 +69,17 @@ TEST(tf2, setTransformInvalidQuaternion) TEST(tf2_lookupTransform, LookupException_Nothing_Exists) { tf2::BufferCore tfc; - EXPECT_THROW(tfc.lookupTransform("a", "b", ros::Time().fromSec(1.0)), tf2::LookupException); + EXPECT_THROW(tfc.lookupTransform("a", "b", tf2::Time(1e9)), tf2::LookupException); } TEST(tf2_canTransform, Nothing_Exists) { tf2::BufferCore tfc; - EXPECT_FALSE(tfc.canTransform("a", "b", ros::Time().fromSec(1.0))); + EXPECT_FALSE(tfc.canTransform("a", "b", tf2::Time(1e9))); std::string error_msg = std::string(); - EXPECT_FALSE(tfc.canTransform("a", "b", ros::Time().fromSec(1.0), &error_msg)); + EXPECT_FALSE(tfc.canTransform("a", "b", tf2::Time(1e9), &error_msg)); ASSERT_STREQ(error_msg.c_str(), "canTransform: target_frame a does not exist. canTransform: source_frame b does not exist."); } @@ -89,11 +89,11 @@ TEST(tf2_lookupTransform, LookupExceptio tf2::BufferCore tfc; geometry_msgs::TransformStamped st; st.header.frame_id = "foo"; - st.header.stamp = ros::Time(1.0); + st.header.stamp = tf2::Time(1e9); st.child_frame_id = "child"; st.transform.rotation.w = 1; EXPECT_TRUE(tfc.setTransform(st, "authority1")); - EXPECT_THROW(tfc.lookupTransform("foo", "bar", ros::Time().fromSec(1.0)), tf2::LookupException); + EXPECT_THROW(tfc.lookupTransform("foo", "bar", tf2::Time(1e9)), tf2::LookupException); } @@ -102,16 +102,16 @@ TEST(tf2_canTransform, One_Exists) tf2::BufferCore tfc; geometry_msgs::TransformStamped st; st.header.frame_id = "foo"; - st.header.stamp = ros::Time(1.0); + st.header.stamp = tf2::Time(1e9); st.child_frame_id = "child"; st.transform.rotation.w = 1; EXPECT_TRUE(tfc.setTransform(st, "authority1")); - EXPECT_FALSE(tfc.canTransform("foo", "bar", ros::Time().fromSec(1.0))); + EXPECT_FALSE(tfc.canTransform("foo", "bar", tf2::Time(1e9))); } int main(int argc, char **argv){ testing::InitGoogleTest(&argc, argv); - ros::Time::init(); //needed for ros::TIme::now() + // ros::Time::init(); //needed for ros::TIme::now() return RUN_ALL_TESTS(); } diff -uprN 0.5.16/test/speed_2_test.cpp tf2/test/speed_2_test.cpp --- 0.5.16/test/speed_2_test.cpp 1969-12-31 16:00:00.000000000 -0800 +++ tf2/test/speed_2_test.cpp 2018-09-10 11:54:40.000000000 -0700 @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2010, Willow Garage, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Willow Garage, Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include <stdio.h> + +#include <tf2/buffer_core.h> +#include "tf2/time.h" +#include <boost/lexical_cast.hpp> +#include <chrono> +#include <thread> +#include <mutex> +#include <atomic> + +using std::chrono::system_clock; +using std::chrono::steady_clock; +using std::chrono::high_resolution_clock; + +uint64_t now_time() { + high_resolution_clock::time_point now = high_resolution_clock::now(); + auto nano_now = std::chrono::time_point_cast<std::chrono::nanoseconds>(now); + auto epoch = nano_now.time_since_epoch(); + uint64_t nano_time = + std::chrono::duration_cast<std::chrono::nanoseconds>(epoch).count(); + return nano_time; +} + +tf2::BufferCore bc; +std::atomic<bool> is_stop(false); + +void set_trans_form_1000() { + for (uint64_t i = 0; i < 1000; ++i) { + geometry_msgs::TransformStamped t; + t.header.stamp = i; + t.header.frame_id = "world"; + t.child_frame_id = "novatel"; + t.transform.translation.x = 1; + t.transform.rotation.w = 1.0; + bc.setTransform(t, "test"); + } +} + +std::mutex cout_mutex; + +std::atomic<uint64_t> total_cost_time(0); +std::atomic<uint64_t> total_exec_cnt(0); + +void look_transform(int count, int look_idx = 0) { + std::string frame_target = "world"; + std::string frame_source = "velodyne64"; + if (look_idx >= 1000) { + look_idx = 999; + } + geometry_msgs::TransformStamped out_t; + for (int i = 0; i < count; ++i) { + uint64_t start = now_time(); + out_t = bc.lookupTransform(frame_target, frame_source, look_idx); + uint64_t end = now_time(); + double dur = (double)end - (double)start; + total_cost_time.fetch_add(dur); + total_exec_cnt.fetch_add(1); + } +} + +std::atomic<uint64_t> can_total_cost(0); +std::atomic<uint64_t> can_exec_cnt(0); + +void can_transform(int count, int look_idx = 0) { + std::string frame_target = "world"; + std::string frame_source = "velodyne64"; + if (look_idx >= 1000) { + look_idx = 999; + } + for (int i = 0; i < count; ++i) { + uint64_t start = now_time(); + bc.canTransform(frame_target, frame_source, look_idx); + uint64_t end = now_time(); + double dur = (double)end - (double)start; + can_total_cost.fetch_add(dur); + can_exec_cnt.fetch_add(1); + } +} + +int main(int argc, char **argv) { + set_trans_form_1000(); + geometry_msgs::TransformStamped t; + t.header.stamp = 0; + t.header.frame_id = "novatel"; + t.child_frame_id = "velodyne64"; + t.transform.translation.x = 1; + t.transform.rotation.w = 1.0; + bc.setTransform(t, "test", true); + int th_nums = 1; + int lookup_index = 0; + // if (argc >= 2) { + // th_nums = boost::lexical_cast<int>(argv[1]); + // } + // if (argc >= 3) { + // lookup_index = boost::lexical_cast<int>(argv[2]); + // } + std::cout << "lookup max thread nums: " << th_nums << ", lookup index: " << lookup_index << std::endl; + std::vector<std::thread> td_vec; + std::vector<std::thread> can_tds; + for (int i = 1; i <= th_nums; ++i) { + total_cost_time = 0; + total_exec_cnt = 0; + + can_total_cost = 0; + can_exec_cnt = 0; + for (int j = 1; j <= i; ++j) { + td_vec.push_back(std::thread(look_transform, 100, lookup_index)); + can_tds.push_back(std::thread(can_transform, 100, lookup_index)); + } + for (auto &td : td_vec) { + td.join(); + } + + for (auto &td : can_tds) { + td.join(); + } + td_vec.clear(); + can_tds.clear(); + std::cout << "Thread Nums: " << i + << ", lookup cnt: " << total_exec_cnt.load() + << ", Total Time(ms): " + << static_cast<double>(total_cost_time.load()) / 1e6 + << ", Avg Time(ms): " + << static_cast<double>(total_cost_time.load()) / 1e6 / + total_exec_cnt.load() + << std::endl; + + std::cout << "Thread Nums: " << i + << ", can cnt: " << can_exec_cnt.load() + << ", Total Time(ms): " + << static_cast<double>(can_total_cost.load()) / 1e6 + << ", Avg Time(ms): " + << static_cast<double>(can_total_cost.load()) / 1e6 / + can_exec_cnt.load() + << std::endl; + } +} diff -uprN 0.5.16/test/speed_test.cpp tf2/test/speed_test.cpp --- 0.5.16/test/speed_test.cpp 2018-09-18 15:00:42.778601493 -0700 +++ tf2/test/speed_test.cpp 2018-09-10 11:54:40.000000000 -0700 @@ -27,30 +27,34 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include <tf2/buffer_core.h> - -#include <ros/time.h> -#include <console_bridge/console.h> +#include <stdio.h> +#include <tf2/buffer_core.h> +#include "tf2/time.h" #include <boost/lexical_cast.hpp> +#include <chrono> + +using std::chrono::system_clock; +using std::chrono::steady_clock; +using std::chrono::high_resolution_clock; int main(int argc, char** argv) { uint32_t num_levels = 10; - if (argc > 1) - { - num_levels = boost::lexical_cast<uint32_t>(argv[1]); - } + // if (argc > 1) + // { + // num_levels = boost::lexical_cast<uint32_t>(argv[1]); + // } tf2::BufferCore bc; geometry_msgs::TransformStamped t; - t.header.stamp = ros::Time(1); + t.header.stamp = 1; t.header.frame_id = "root"; t.child_frame_id = "0"; t.transform.translation.x = 1; t.transform.rotation.w = 1.0; bc.setTransform(t, "me"); - t.header.stamp = ros::Time(2); + t.header.stamp = 2; bc.setTransform(t, "me"); for (uint32_t i = 1; i < num_levels/2; ++i) @@ -62,7 +66,7 @@ int main(int argc, char** argv) std::stringstream child_ss; child_ss << i; - t.header.stamp = ros::Time(j); + t.header.stamp = tf2::Time(j); t.header.frame_id = parent_ss.str(); t.child_frame_id = child_ss.str(); bc.setTransform(t, "me"); @@ -72,10 +76,10 @@ int main(int argc, char** argv) t.header.frame_id = "root"; std::stringstream ss; ss << num_levels/2; - t.header.stamp = ros::Time(1); + t.header.stamp = 1; t.child_frame_id = ss.str(); bc.setTransform(t, "me"); - t.header.stamp = ros::Time(2); + t.header.stamp = 2; bc.setTransform(t, "me"); for (uint32_t i = num_levels/2 + 1; i < num_levels; ++i) @@ -87,7 +91,7 @@ int main(int argc, char** argv) std::stringstream child_ss; child_ss << i; - t.header.stamp = ros::Time(j); + t.header.stamp = tf2::Time(j); t.header.frame_id = parent_ss.str(); t.child_frame_id = child_ss.str(); bc.setTransform(t, "me"); @@ -98,121 +102,113 @@ int main(int argc, char** argv) std::string v_frame0 = boost::lexical_cast<std::string>(num_levels - 1); std::string v_frame1 = boost::lexical_cast<std::string>(num_levels/2 - 1); - logInform("%s to %s", v_frame0.c_str(), v_frame1.c_str()); + printf("%s to %s\n", v_frame0.c_str(), v_frame1.c_str()); geometry_msgs::TransformStamped out_t; const uint32_t count = 1000000; - logInform("Doing %d %d-level tests", count, num_levels); + printf("Doing %d %d-level tests\n", count, num_levels); #if 01 { - ros::WallTime start = ros::WallTime::now(); + steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { - out_t = bc.lookupTransform(v_frame1, v_frame0, ros::Time(0)); + out_t = bc.lookupTransform(v_frame1, v_frame0, 0); } - ros::WallTime end = ros::WallTime::now(); - ros::WallDuration dur = end - start; - //ROS_INFO_STREAM(out_t); - logInform("lookupTransform at Time(0) took %f for an average of %.9f", dur.toSec(), dur.toSec() / (double)count); + steady_clock::time_point end = steady_clock::now(); + double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); + printf("lookupTransform at Time(0) took: %f (secs) for an average of: %.9f (secs)\n", dur, dur / (double)count); } #endif #if 01 { - ros::WallTime start = ros::WallTime::now(); + steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { - out_t = bc.lookupTransform(v_frame1, v_frame0, ros::Time(1)); + out_t = bc.lookupTransform(v_frame1, v_frame0, tf2::Time(1)); } - ros::WallTime end = ros::WallTime::now(); - ros::WallDuration dur = end - start; - //ROS_INFO_STREAM(out_t); - logInform("lookupTransform at Time(1) took %f for an average of %.9f", dur.toSec(), dur.toSec() / (double)count); + steady_clock::time_point end = steady_clock::now(); + double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); + printf("lookupTransform at Time(1) took: %f for an average of: %.9f\n", dur, dur / (double)count); } #endif #if 01 { - ros::WallTime start = ros::WallTime::now(); + steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { - out_t = bc.lookupTransform(v_frame1, v_frame0, ros::Time(1.5)); + out_t = bc.lookupTransform(v_frame1, v_frame0, tf2::Time(1.5)); } - ros::WallTime end = ros::WallTime::now(); - ros::WallDuration dur = end - start; - //ROS_INFO_STREAM(out_t); - logInform("lookupTransform at Time(1.5) took %f for an average of %.9f", dur.toSec(), dur.toSec() / (double)count); + steady_clock::time_point end = steady_clock::now(); + double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); + printf("lookupTransform at Time(1.5) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif #if 01 { - ros::WallTime start = ros::WallTime::now(); + steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { - out_t = bc.lookupTransform(v_frame1, v_frame0, ros::Time(2)); + out_t = bc.lookupTransform(v_frame1, v_frame0, tf2::Time(2)); } - ros::WallTime end = ros::WallTime::now(); - ros::WallDuration dur = end - start; - //ROS_INFO_STREAM(out_t); - logInform("lookupTransform at Time(2) took %f for an average of %.9f", dur.toSec(), dur.toSec() / (double)count); + steady_clock::time_point end = steady_clock::now(); + double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); + printf("lookupTransform at Time(2) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif #if 01 { - ros::WallTime start = ros::WallTime::now(); + steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { - bc.canTransform(v_frame1, v_frame0, ros::Time(0)); + bc.canTransform(v_frame1, v_frame0, tf2::Time(0)); } - ros::WallTime end = ros::WallTime::now(); - ros::WallDuration dur = end - start; - //ROS_INFO_STREAM(out_t); - logInform("canTransform at Time(0) took %f for an average of %.9f", dur.toSec(), dur.toSec() / (double)count); + steady_clock::time_point end = steady_clock::now(); + double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); + printf("canTransform at Time(0) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif #if 01 { - ros::WallTime start = ros::WallTime::now(); + steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { - bc.canTransform(v_frame1, v_frame0, ros::Time(1)); + bc.canTransform(v_frame1, v_frame0, tf2::Time(1)); } - ros::WallTime end = ros::WallTime::now(); - ros::WallDuration dur = end - start; - //ROS_INFO_STREAM(out_t); - logInform("canTransform at Time(1) took %f for an average of %.9f", dur.toSec(), dur.toSec() / (double)count); + steady_clock::time_point end = steady_clock::now(); + double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); + printf("canTransform at Time(1) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif #if 01 { - ros::WallTime start = ros::WallTime::now(); + steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { - bc.canTransform(v_frame1, v_frame0, ros::Time(1.5)); + bc.canTransform(v_frame1, v_frame0, tf2::Time(1.5 * 1e9)); } - ros::WallTime end = ros::WallTime::now(); - ros::WallDuration dur = end - start; - //ROS_INFO_STREAM(out_t); - logInform("canTransform at Time(1.5) took %f for an average of %.9f", dur.toSec(), dur.toSec() / (double)count); + steady_clock::time_point end = steady_clock::now(); + double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); + printf("canTransform at Time(1.5) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif #if 01 { - ros::WallTime start = ros::WallTime::now(); + steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { - bc.canTransform(v_frame1, v_frame0, ros::Time(2)); + bc.canTransform(v_frame1, v_frame0, tf2::Time(2)); } - ros::WallTime end = ros::WallTime::now(); - ros::WallDuration dur = end - start; - //ROS_INFO_STREAM(out_t); - logInform("canTransform at Time(2) took %f for an average of %.9f", dur.toSec(), dur.toSec() / (double)count); + steady_clock::time_point end = steady_clock::now(); + double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); + printf("canTransform at Time(2) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif } diff -uprN 0.5.16/test/static_cache_test.cpp tf2/test/static_cache_test.cpp --- 0.5.16/test/static_cache_test.cpp 2018-09-18 15:00:42.778601493 -0700 +++ tf2/test/static_cache_test.cpp 2018-09-18 13:23:55.024931923 -0700 @@ -32,7 +32,7 @@ #include <sys/time.h> #include <stdexcept> -#include <geometry_msgs/TransformStamped.h> +#include <tf2/transform_stamped.h> #include <cmath> @@ -57,14 +57,14 @@ TEST(StaticCache, Repeatability) for ( uint64_t i = 1; i < runs ; i++ ) { stor.frame_id_ = CompactFrameID(i); - stor.stamp_ = ros::Time().fromNSec(i); + stor.stamp_ = tf2::Time(i); cache.insertData(stor); - cache.getData(ros::Time().fromNSec(i), stor); + cache.getData(tf2::Time(i), stor); EXPECT_EQ(stor.frame_id_, i); - EXPECT_EQ(stor.stamp_, ros::Time().fromNSec(i)); + EXPECT_EQ(stor.stamp_, tf2::Time(i)); } } @@ -77,14 +77,14 @@ TEST(StaticCache, DuplicateEntries) TransformStorage stor; setIdentity(stor); stor.frame_id_ = CompactFrameID(3); - stor.stamp_ = ros::Time().fromNSec(1); + stor.stamp_ = tf2::Time(1); cache.insertData(stor); cache.insertData(stor); - cache.getData(ros::Time().fromNSec(1), stor); + cache.getData(tf2::Time(1), stor); //printf(" stor is %f\n", stor.transform.translation.x); EXPECT_TRUE(!std::isnan(stor.translation_.x()));
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tf2/index.rst
tf2 ===== This is the Python API reference of the tf2 package. .. toctree:: :maxdepth: 2 tf2 Indices and tables ================== * :ref:`genindex` * :ref:`search`
0