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-contrib/velodyne_vls/velodyne_msgs
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_msgs/msg/VelodyneScan.msg
# Velodyne LIDAR scan packets. Header header # standard ROS message header VelodynePacket[] packets # vector of raw packets
0
apollo_public_repos/apollo-contrib/velodyne_vls
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3) project(velodyne_laserscan) find_package(catkin REQUIRED COMPONENTS roscpp nodelet sensor_msgs dynamic_reconfigure ) generate_dynamic_reconfigure_options( cfg/VelodyneLaserScan.cfg ) catkin_package() include_directories( ${catkin_INCLUDE_DIRS} ) add_library(${PROJECT_NAME} src/VelodyneLaserScan.cpp src/nodelet.cpp ) add_dependencies(${PROJECT_NAME} ${PROJECT_NAME}_gencfg ) target_link_libraries(${PROJECT_NAME} ${catkin_LIBRARIES} ) add_executable(${PROJECT_NAME}_node src/node.cpp ) target_link_libraries(${PROJECT_NAME}_node ${catkin_LIBRARIES} ${PROJECT_NAME} ) install(TARGETS ${PROJECT_NAME} ${PROJECT_NAME}_node RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} ) install(FILES nodelets.xml DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} ) if (CATKIN_ENABLE_TESTING) add_subdirectory(tests) endif()
0
apollo_public_repos/apollo-contrib/velodyne_vls
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan/package.xml
<package format="2"> <name>velodyne_laserscan</name> <version>1.3.0</version> <description> Extract a single ring of a Velodyne PointCloud2 and publish it as a LaserScan message </description> <maintainer email="jwhitley@autonomoustuff.com">Josh Whitley</maintainer> <author>Micho Radovnikovich</author> <author>Kevin Hallenbeck</author> <license>BSD</license> <url type="website">http://ros.org/wiki/velodyne_laserscan</url> <url type="repository">https://github.com/ros-drivers/velodyne</url> <url type="bugtracker">https://github.com/ros-drivers/velodyne/issues</url> <buildtool_depend>catkin</buildtool_depend> <depend>roscpp</depend> <depend>nodelet</depend> <depend>sensor_msgs</depend> <depend>dynamic_reconfigure</depend> <test_depend>roslaunch</test_depend> <test_depend>rostest</test_depend> <export> <nodelet plugin="${prefix}/nodelets.xml" /> </export> </package>
0
apollo_public_repos/apollo-contrib/velodyne_vls
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan/nodelets.xml
<library path="libvelodyne_laserscan"> <class name="velodyne_laserscan/LaserScanNodelet" type="velodyne_laserscan::LaserScanNodelet" base_class_type="nodelet::Nodelet"> <description> Extract a single ring from a Velodyne PointCloud2 and publish as a LaserScan. </description> </class> </library>
0
apollo_public_repos/apollo-contrib/velodyne_vls
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan/CHANGELOG.rst
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Changelog for package velodyne_laserscan ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1.3.0 (2017-11-10) ------------------ * Merge pull request `#110 <https://github.com/ros-drivers/velodyne/issues/110>`_ from kmhallen/master Added velodyne_laserscan package * Added tests for velodyne_laserscan * Fixed validating PointCloud2 field types * Package.xml format version 2 * Merge pull request `#1 <https://github.com/ros-drivers/velodyne/issues/1>`_ from volkandre/master Fixed bug. Laserscans now cover full 360 degrees. * Fixed bug. Laserscans now cover full 360 degrees. * Added velodyne_laserscan package and inserted into existing launch files * Contributors: Joshua Whitley, Kevin Hallenbeck, kmhallen, volkandre
0
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan/tests/lazy_subscriber_node.test
<!-- -*- mode: XML -*- --> <!-- rostest of the lazy subscriber --> <launch> <!-- Select log or screen output --> <arg name="output" default="log"/> <!-- screen/log --> <!-- Start the laserscan node --> <node pkg="velodyne_laserscan" type="velodyne_laserscan_node" name="laserscan" output="$(arg output)" /> <!-- Start the rostest --> <test test-name="test_lazy_subscriber_node" pkg="velodyne_laserscan" type="test_lazy_subscriber_node" name="test_lazy_subscriber"> </test> </launch>
0
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan/tests/CMakeLists.txt
### Unit tests # # Only configured when CATKIN_ENABLE_TESTING is true. # These dependencies are only needed for unit testing find_package(roslaunch REQUIRED) find_package(rostest REQUIRED) # C++ gtests #catkin_add_gtest(test_calibration test_calibration.cpp) #add_dependencies(test_calibration ${catkin_EXPORTED_TARGETS}) #target_link_libraries(test_calibration velodyne_rawdata ${catkin_LIBRARIES}) # ROS rostests add_rostest_gtest(test_lazy_subscriber_node lazy_subscriber_node.test lazy_subscriber.cpp) add_dependencies(test_lazy_subscriber_node ${catkin_EXPORTED_TARGETS}) target_link_libraries(test_lazy_subscriber_node ${catkin_LIBRARIES}) add_rostest_gtest(test_lazy_subscriber_nodelet lazy_subscriber_nodelet.test lazy_subscriber.cpp) add_dependencies(test_lazy_subscriber_nodelet ${catkin_EXPORTED_TARGETS}) target_link_libraries(test_lazy_subscriber_nodelet ${catkin_LIBRARIES}) add_rostest_gtest(test_system_node system_node.test system.cpp) add_dependencies(test_system_node ${catkin_EXPORTED_TARGETS}) target_link_libraries(test_system_node ${catkin_LIBRARIES}) add_rostest_gtest(test_system_nodelet system_nodelet.test system.cpp) add_dependencies(test_system_nodelet ${catkin_EXPORTED_TARGETS}) target_link_libraries(test_system_nodelet ${catkin_LIBRARIES})
0
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan/tests/system_nodelet.test
<!-- -*- mode: XML -*- --> <!-- rostest of the velodyne_laserscan system --> <launch> <!-- Select log or screen output --> <arg name="output" default="log"/> <!-- screen/log --> <!-- Start the laserscan nodelet --> <arg name="manager" default="nodelet_manager" /> <node pkg="nodelet" type="nodelet" name="$(arg manager)" args="manager" output="$(arg output)" /> <node pkg="nodelet" type="nodelet" name="velodyne_laserscan" output="$(arg output)" args="load velodyne_laserscan/LaserScanNodelet $(arg manager)"> </node> <!-- Start the rostest --> <test test-name="test_system_nodelet" pkg="velodyne_laserscan" type="test_system_nodelet" name="test_system"> </test> </launch>
0
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan/tests/lazy_subscriber.cpp
/********************************************************************* * C++ unit test for velodyne_laserscan * Verify correct handling of subscribe and unsubscribe events *********************************************************************/ #include <gtest/gtest.h> #include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include <sensor_msgs/LaserScan.h> // Subscriber receive callback void recv(const sensor_msgs::LaserScanConstPtr& msg) {} // Build and publish a minimal PointCloud2 message void publish(const ros::Publisher &pub) { const uint32_t POINT_STEP = 32; sensor_msgs::PointCloud2 msg; msg.header.frame_id = ""; msg.header.stamp = ros::Time::now(); msg.fields.resize(5); msg.fields[0].name = "x"; msg.fields[0].offset = 0; msg.fields[0].datatype = sensor_msgs::PointField::FLOAT32; msg.fields[0].count = 1; msg.fields[1].name = "y"; msg.fields[1].offset = 4; msg.fields[1].datatype = sensor_msgs::PointField::FLOAT32; msg.fields[1].count = 1; msg.fields[2].name = "z"; msg.fields[2].offset = 8; msg.fields[2].datatype = sensor_msgs::PointField::FLOAT32; msg.fields[2].count = 1; msg.fields[3].name = "intensity"; msg.fields[3].offset = 16; msg.fields[3].datatype = sensor_msgs::PointField::FLOAT32; msg.fields[3].count = 1; msg.fields[4].name = "ring"; msg.fields[4].offset = 20; msg.fields[4].datatype = sensor_msgs::PointField::UINT16; msg.fields[4].count = 1; msg.data.resize(1 * POINT_STEP, 0x00); msg.point_step = POINT_STEP; msg.row_step = msg.data.size(); msg.height = 1; msg.width = msg.row_step / POINT_STEP; msg.is_bigendian = false; msg.is_dense = true; pub.publish(msg); } // Verify correct handling of subscribe and unsubscribe events TEST(Main, subscribe_unsubscribe) { ros::NodeHandle nh; ros::Publisher pub = nh.advertise<sensor_msgs::PointCloud2>("velodyne_points", 2); // Wait for node to startup ros::WallDuration(2.0).sleep(); ros::spinOnce(); EXPECT_EQ(0, pub.getNumSubscribers()); // Subscribe to 'scan' and expect the node to subscribe to 'velodyne_points' ros::Subscriber sub = nh.subscribe("scan", 2, recv); for (size_t i = 10; i > 0; i--) { publish(pub); ros::WallDuration(0.1).sleep(); ros::spinOnce(); } EXPECT_EQ(1, sub.getNumPublishers()); EXPECT_EQ(1, pub.getNumSubscribers()); // Unsubscribe from 'scan' and expect the node to unsubscribe from 'velodyne_points' sub.shutdown(); for (size_t i = 10; i > 0; i--) { publish(pub); ros::WallDuration(0.1).sleep(); ros::spinOnce(); } EXPECT_EQ(0, sub.getNumPublishers()); EXPECT_EQ(0, pub.getNumSubscribers()); } // Run all the tests that were declared with TEST() int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "test_lazy_subscriber"); return RUN_ALL_TESTS(); }
0
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan/tests/system.cpp
/********************************************************************* * C++ unit test for velodyne_laserscan * Verify all aspects of the system *********************************************************************/ #include <gtest/gtest.h> #include <ros/ros.h> #include <sensor_msgs/LaserScan.h> #include <sensor_msgs/PointCloud2.h> // Define our own PointCloud type for easy use typedef struct { float x; // x float y; // y float z; // z float i; // intensity uint16_t r; // ring } Point; typedef struct { std_msgs::Header header; std::vector<Point> points; } PointCloud; // Global variables ros::Publisher g_pub; ros::Subscriber g_sub; sensor_msgs::LaserScan g_scan; volatile bool g_scan_new = false; // Convert WallTime to Time static inline ros::Time rosTime(const ros::WallTime &stamp) { return ros::Time(stamp.sec, stamp.nsec); } // Subscriber receive callback void recv(const sensor_msgs::LaserScanConstPtr &msg) { g_scan = *msg; g_scan_new = true; } // Wait for incoming LaserScan message bool waitForScan(ros::WallDuration dur) { const ros::WallTime start = ros::WallTime::now(); while (!g_scan_new) { if ((ros::WallTime::now() - start) > dur) { return false; } ros::WallDuration(0.001).sleep(); ros::spinOnce(); } return true; } // Build and publish PointCloud2 messages of various structures void publishXYZIR1(const PointCloud &cloud) { g_scan_new = false; const uint32_t POINT_STEP = 32; sensor_msgs::PointCloud2 msg; msg.header.frame_id = cloud.header.frame_id; msg.header.stamp = cloud.header.stamp; msg.fields.resize(5); msg.fields[0].name = "x"; msg.fields[0].offset = 0; msg.fields[0].datatype = sensor_msgs::PointField::FLOAT32; msg.fields[0].count = 1; msg.fields[1].name = "y"; msg.fields[1].offset = 4; msg.fields[1].datatype = sensor_msgs::PointField::FLOAT32; msg.fields[1].count = 1; msg.fields[2].name = "z"; msg.fields[2].offset = 8; msg.fields[2].datatype = sensor_msgs::PointField::FLOAT32; msg.fields[2].count = 1; msg.fields[3].name = "intensity"; msg.fields[3].offset = 16; msg.fields[3].datatype = sensor_msgs::PointField::FLOAT32; msg.fields[3].count = 1; msg.fields[4].name = "ring"; msg.fields[4].offset = 20; msg.fields[4].datatype = sensor_msgs::PointField::UINT16; msg.fields[4].count = 1; msg.data.resize(std::max((size_t)1, cloud.points.size()) * POINT_STEP, 0x00); msg.point_step = POINT_STEP; msg.row_step = msg.data.size(); msg.height = 1; msg.width = msg.row_step / POINT_STEP; msg.is_bigendian = false; msg.is_dense = true; uint8_t *ptr = msg.data.data(); for (size_t i = 0; i < cloud.points.size(); i++) { *(reinterpret_cast<float *>(ptr + 0)) = cloud.points[i].x; *(reinterpret_cast<float *>(ptr + 4)) = cloud.points[i].y; *(reinterpret_cast<float *>(ptr + 8)) = cloud.points[i].z; *(reinterpret_cast<float *>(ptr + 16)) = cloud.points[i].i; *(reinterpret_cast<uint16_t *>(ptr + 20)) = cloud.points[i].r; ptr += POINT_STEP; } g_pub.publish(msg); } void publishXYZIR2(const PointCloud &cloud) { g_scan_new = false; const uint32_t POINT_STEP = 19; sensor_msgs::PointCloud2 msg; msg.header.frame_id = cloud.header.frame_id; msg.header.stamp = cloud.header.stamp; msg.fields.resize(5); msg.fields[0].name = "z"; msg.fields[0].offset = 4; msg.fields[0].datatype = sensor_msgs::PointField::FLOAT32; msg.fields[0].count = 1; msg.fields[1].name = "y"; msg.fields[1].offset = 8; msg.fields[1].datatype = sensor_msgs::PointField::FLOAT32; msg.fields[1].count = 1; msg.fields[2].name = "x"; msg.fields[2].offset = 12; msg.fields[2].datatype = sensor_msgs::PointField::FLOAT32; msg.fields[2].count = 1; msg.fields[3].name = "intensity"; msg.fields[3].offset = 0; msg.fields[3].datatype = sensor_msgs::PointField::FLOAT32; msg.fields[3].count = 1; msg.fields[4].name = "ring"; msg.fields[4].offset = 16; msg.fields[4].datatype = sensor_msgs::PointField::UINT16; msg.fields[4].count = 1; msg.data.resize(std::max((size_t)1, cloud.points.size()) * POINT_STEP, 0x00); msg.point_step = POINT_STEP; msg.row_step = msg.data.size(); msg.height = 1; msg.width = msg.row_step / POINT_STEP; msg.is_bigendian = false; msg.is_dense = true; uint8_t *ptr = msg.data.data(); for (size_t i = 0; i < cloud.points.size(); i++) { *(reinterpret_cast<float *>(ptr + 0)) = cloud.points[i].i; *(reinterpret_cast<float *>(ptr + 4)) = cloud.points[i].z; *(reinterpret_cast<float *>(ptr + 8)) = cloud.points[i].y; *(reinterpret_cast<float *>(ptr + 12)) = cloud.points[i].x; *(reinterpret_cast<uint16_t *>(ptr + 16)) = cloud.points[i].r; ptr += POINT_STEP; } g_pub.publish(msg); } void publishXYZR(const PointCloud &cloud) { g_scan_new = false; const uint32_t POINT_STEP = 15; sensor_msgs::PointCloud2 msg; msg.header.frame_id = cloud.header.frame_id; msg.header.stamp = cloud.header.stamp; msg.fields.resize(4); msg.fields[0].name = "x"; msg.fields[0].offset = 0; msg.fields[0].datatype = sensor_msgs::PointField::FLOAT32; msg.fields[0].count = 1; msg.fields[1].name = "y"; msg.fields[1].offset = 4; msg.fields[1].datatype = sensor_msgs::PointField::FLOAT32; msg.fields[1].count = 1; msg.fields[2].name = "z"; msg.fields[2].offset = 8; msg.fields[2].datatype = sensor_msgs::PointField::FLOAT32; msg.fields[2].count = 1; msg.fields[3].name = "ring"; msg.fields[3].offset = 12; msg.fields[3].datatype = sensor_msgs::PointField::UINT16; msg.fields[3].count = 1; msg.data.resize(std::max((size_t)1, cloud.points.size()) * POINT_STEP, 0x00); msg.point_step = POINT_STEP; msg.row_step = msg.data.size(); msg.height = 1; msg.width = msg.row_step / POINT_STEP; msg.is_bigendian = false; msg.is_dense = true; uint8_t *ptr = msg.data.data(); for (size_t i = 0; i < cloud.points.size(); i++) { *(reinterpret_cast<float *>(ptr + 0)) = cloud.points[i].x; *(reinterpret_cast<float *>(ptr + 4)) = cloud.points[i].y; *(reinterpret_cast<float *>(ptr + 8)) = cloud.points[i].z; *(reinterpret_cast<uint16_t *>(ptr + 12)) = cloud.points[i].r; ptr += POINT_STEP; } g_pub.publish(msg); } void publishR(const PointCloud &cloud) { g_scan_new = false; const uint32_t POINT_STEP = 2; sensor_msgs::PointCloud2 msg; msg.header.stamp = rosTime(ros::WallTime::now()); msg.fields.resize(1); msg.fields[0].name = "ring"; msg.fields[0].offset = 0; msg.fields[0].datatype = sensor_msgs::PointField::UINT16; msg.fields[0].count = 1; msg.data.resize(std::max((size_t)1, cloud.points.size()) * POINT_STEP, 0x00); msg.point_step = POINT_STEP; msg.row_step = msg.data.size(); msg.height = 1; msg.width = msg.row_step / POINT_STEP; uint8_t *ptr = msg.data.data(); for (size_t i = 0; i < cloud.points.size(); i++) { *((uint16_t *)(ptr + 0)) = cloud.points[i].r; ptr += POINT_STEP; } g_pub.publish(msg); } void publishXYZR32(const PointCloud &cloud) { g_scan_new = false; const uint32_t POINT_STEP = 16; sensor_msgs::PointCloud2 msg; msg.header.frame_id = cloud.header.frame_id; msg.header.stamp = cloud.header.stamp; msg.fields.resize(4); msg.fields[0].name = "x"; msg.fields[0].offset = 0; msg.fields[0].datatype = sensor_msgs::PointField::FLOAT32; msg.fields[0].count = 1; msg.fields[1].name = "y"; msg.fields[1].offset = 4; msg.fields[1].datatype = sensor_msgs::PointField::FLOAT32; msg.fields[1].count = 1; msg.fields[2].name = "z"; msg.fields[2].offset = 8; msg.fields[2].datatype = sensor_msgs::PointField::FLOAT32; msg.fields[2].count = 1; msg.fields[3].name = "ring"; msg.fields[3].offset = 12; msg.fields[3].datatype = sensor_msgs::PointField::UINT32; msg.fields[3].count = 1; msg.data.resize(std::max((size_t)1, cloud.points.size()) * POINT_STEP, 0x00); msg.point_step = POINT_STEP; msg.row_step = msg.data.size(); msg.height = 1; msg.width = msg.row_step / POINT_STEP; msg.is_bigendian = false; msg.is_dense = true; uint8_t *ptr = msg.data.data(); for (size_t i = 0; i < cloud.points.size(); i++) { *(reinterpret_cast<float *>(ptr + 0)) = cloud.points[i].x; *(reinterpret_cast<float *>(ptr + 4)) = cloud.points[i].y; *(reinterpret_cast<float *>(ptr + 8)) = cloud.points[i].z; *(reinterpret_cast<uint32_t *>(ptr + 12)) = cloud.points[i].r; ptr += POINT_STEP; } g_pub.publish(msg); } void publishXYZ(const PointCloud &cloud) { g_scan_new = false; const uint32_t POINT_STEP = 12; sensor_msgs::PointCloud2 msg; msg.header.stamp = rosTime(ros::WallTime::now()); msg.fields.resize(3); msg.fields[0].name = "x"; msg.fields[0].offset = 0; msg.fields[0].datatype = sensor_msgs::PointField::FLOAT32; msg.fields[0].count = 1; msg.fields[1].name = "y"; msg.fields[1].offset = 4; msg.fields[1].datatype = sensor_msgs::PointField::FLOAT32; msg.fields[1].count = 1; msg.fields[2].name = "z"; msg.fields[2].offset = 8; msg.fields[2].datatype = sensor_msgs::PointField::FLOAT32; msg.fields[2].count = 1; msg.data.resize(std::max((size_t)1, cloud.points.size()) * POINT_STEP, 0x00); msg.point_step = POINT_STEP; msg.row_step = msg.data.size(); msg.height = 1; msg.width = msg.row_step / POINT_STEP; uint8_t *ptr = msg.data.data(); for (size_t i = 0; i < cloud.points.size(); i++) { *(reinterpret_cast<float *>(ptr + 0)) = cloud.points[i].x; *(reinterpret_cast<float *>(ptr + 4)) = cloud.points[i].y; *(reinterpret_cast<float *>(ptr + 8)) = cloud.points[i].z; ptr += POINT_STEP; } g_pub.publish(msg); } void publishNone() { g_scan_new = false; const uint32_t POINT_STEP = 16; sensor_msgs::PointCloud2 msg; msg.header.stamp = rosTime(ros::WallTime::now()); msg.data.resize(1 * POINT_STEP, 0x00); msg.point_step = POINT_STEP; msg.row_step = msg.data.size(); msg.height = 1; msg.width = msg.row_step / POINT_STEP; g_pub.publish(msg); } // Find the index of the point in the PointCloud with the shortest 2d distance // to the point (x,y) static inline float SQUARE(float x) { return x * x; } size_t findClosestIndex(const PointCloud &cloud, uint16_t ring, float x, float y) { size_t index = SIZE_MAX; float delta = INFINITY; for (size_t i = 0; i < cloud.points.size(); i++) { if (cloud.points[i].r == ring) { float dist = SQUARE(x - cloud.points[i].x) + SQUARE(y - cloud.points[i].y); if (dist < delta) { delta = dist; index = i; } } } return index; } // Verify that all LaserScan header values are values are passed through, and // other values are default void verifyScanEmpty(const PointCloud &cloud, bool intensity = true) { ASSERT_EQ(cloud.header.stamp, g_scan.header.stamp); EXPECT_EQ(cloud.header.frame_id, g_scan.header.frame_id); for (size_t i = 0; i < g_scan.ranges.size(); i++) { EXPECT_EQ(INFINITY, g_scan.ranges[i]); } if (!intensity) { EXPECT_EQ(0, g_scan.intensities.size()); } else { EXPECT_EQ(g_scan.ranges.size(), g_scan.intensities.size()); for (size_t i = 0; i < g_scan.intensities.size(); i++) { EXPECT_EQ(0.0, g_scan.intensities[i]); } } } // Verify that every PointCloud point made it to the LaserScan and other values // are default void verifyScanSparse(const PointCloud &cloud, uint16_t ring, uint16_t ring_count, bool intensity = true) { ASSERT_EQ(cloud.header.stamp, g_scan.header.stamp); EXPECT_EQ(cloud.header.frame_id, g_scan.header.frame_id); EXPECT_EQ(intensity ? g_scan.ranges.size() : 0, g_scan.intensities.size()); size_t count = 0; for (size_t i = 0; i < g_scan.ranges.size(); i++) { double r = g_scan.ranges[i]; if (std::isfinite(r)) { float a = g_scan.angle_min + i * g_scan.angle_increment; float x = g_scan.ranges[i] * cosf(a); float y = g_scan.ranges[i] * sinf(a); float e = g_scan.ranges[i] * g_scan.angle_increment + (float)1e-3; // allowable error size_t index = findClosestIndex(cloud, ring, x, y); if (index < cloud.points.size()) { count++; EXPECT_NEAR(cloud.points[index].x, x, e); EXPECT_NEAR(cloud.points[index].y, y, e); if (i < g_scan.intensities.size()) { EXPECT_EQ(cloud.points[index].i, g_scan.intensities[i]); } } else { EXPECT_TRUE(false); // LaserScan point not found in PointCloud } } else { EXPECT_EQ(INFINITY, r); } } if (ring_count > 0) { EXPECT_EQ(cloud.points.size() / ring_count, count); // Make sure that all points were converted to ranges } } // Verify that every LaserScan point is not default, and every point came from // the PointCloud void verifyScanDense(const PointCloud &cloud, uint16_t ring, bool intensity = true) { ASSERT_EQ(cloud.header.stamp, g_scan.header.stamp); EXPECT_EQ(cloud.header.frame_id, g_scan.header.frame_id); EXPECT_EQ(intensity ? g_scan.ranges.size() : 0, g_scan.intensities.size()); for (size_t i = 0; i < g_scan.ranges.size(); i++) { double r = g_scan.ranges[i]; if (std::isfinite(r)) { float a = g_scan.angle_min + i * g_scan.angle_increment; float x = g_scan.ranges[i] * cosf(a); float y = g_scan.ranges[i] * sinf(a); float e = g_scan.ranges[i] * g_scan.angle_increment + (float)1e-3; // allowable error size_t index = findClosestIndex(cloud, ring, x, y); if (index < cloud.points.size()) { EXPECT_NEAR(cloud.points[index].x, x, e); EXPECT_NEAR(cloud.points[index].y, y, e); ///@TODO: Test for matching intensity } else { EXPECT_TRUE(false); // LaserScan point not found in PointCloud } } else { EXPECT_TRUE( false); // Dense PointCloud should populate every range in LaserScan } } } // Verify that no LaserScan is generated when the PointCloud2 message is missing // required fields TEST(System, missing_fields) { // Make sure system is connected ASSERT_EQ(1, g_sub.getNumPublishers()); ASSERT_EQ(1, g_pub.getNumSubscribers()); // Create PointCloud with 16 rings PointCloud cloud; cloud.points.resize(1); cloud.points[0].x = 0.0; cloud.points[0].y = 0.0; cloud.points[0].z = 0.0; cloud.points[0].i = 0.0; cloud.points[0].r = 15; // Verify no LaserScan when PointCloud2 fields are empty publishNone(); EXPECT_FALSE(waitForScan(ros::WallDuration(0.5))); // Verify no LaserScan when PointCloud2 fields are missing 'ring' publishXYZ(cloud); EXPECT_FALSE(waitForScan(ros::WallDuration(0.5))); // Verify no LaserScan when PointCloud2 field 'ring' is the incorrect type publishXYZR32(cloud); EXPECT_FALSE(waitForScan(ros::WallDuration(0.5))); // Verify no LaserScan when PointCloud2 fields are missing 'x' and 'y' publishR(cloud); EXPECT_FALSE(waitForScan(ros::WallDuration(0.5))); // Verify that the node hasn't crashed by sending normal PointCloud2 fields cloud.header.stamp = rosTime(ros::WallTime::now()); publishXYZIR1(cloud); ASSERT_TRUE(waitForScan(ros::WallDuration(1.0))); ASSERT_EQ(cloud.header.stamp, g_scan.header.stamp); } // Verify that non-point fields are passed through unmodified TEST(System, empty_data) { // Make sure system is connected ASSERT_EQ(1, g_sub.getNumPublishers()); ASSERT_EQ(1, g_pub.getNumSubscribers()); // Create PointCloud with 16 rings PointCloud cloud; cloud.header.frame_id = "abcdefghijklmnopqrstuvwxyz"; cloud.points.resize(1); cloud.points[0].x = 0.0; cloud.points[0].y = 0.0; cloud.points[0].z = 0.0; cloud.points[0].i = 0.0; cloud.points[0].r = 15; // Verify that all three PointCloud2 types create proper default values // PointXYZIR (expected format) cloud.header.stamp = rosTime(ros::WallTime::now()); publishXYZIR1(cloud); ASSERT_TRUE(waitForScan(ros::WallDuration(1.0))); verifyScanEmpty(cloud, true); // PointXYZIR (unexpected format with intensity) cloud.header.stamp = rosTime(ros::WallTime::now()); publishXYZIR2(cloud); ASSERT_TRUE(waitForScan(ros::WallDuration(1.0))); verifyScanEmpty(cloud, true); // PointXYZR (unexpected format without intensity) cloud.header.stamp = rosTime(ros::WallTime::now()); publishXYZR(cloud); ASSERT_TRUE(waitForScan(ros::WallDuration(1.0))); verifyScanEmpty(cloud, false); } // Verify that every piece of a small amount of random data is passed through TEST(System, random_data_sparse) { // Make sure system is connected ASSERT_EQ(1, g_sub.getNumPublishers()); ASSERT_EQ(1, g_pub.getNumSubscribers()); // Create PointCloud with sparse random data PointCloud cloud; cloud.header.frame_id = "velodyne"; const size_t RANGE_COUNT = 100; const size_t RING_COUNT = 16; const double RANGE_MAX = 20.0; const double INTENSITY_MAX = 1.0; for (size_t i = 0; i < RANGE_COUNT; i++) { double angle_y = i * 1.99 * M_PI / RANGE_COUNT; // yaw for (size_t j = 0; j < RING_COUNT; j++) { double angle_p = j * 0.2 * M_PI / RING_COUNT - 0.1 * M_PI; // pitch double range = rand() * (RANGE_MAX / RAND_MAX); Point point; point.x = range * cos(angle_p) * cos(angle_y); point.y = range * cos(angle_p) * sin(angle_y); point.z = range * sin(angle_p); point.i = rand() * (INTENSITY_MAX / RAND_MAX); point.r = j; cloud.points.push_back(point); } } // Verify that all three PointCloud2 types are handled correctly // PointXYZIR (expected format) cloud.header.stamp = rosTime(ros::WallTime::now()); publishXYZIR1(cloud); ASSERT_TRUE(waitForScan(ros::WallDuration(1.0))); verifyScanSparse(cloud, 8, RING_COUNT, true); // PointXYZIR (unexpected format with intensity) cloud.header.stamp = rosTime(ros::WallTime::now()); publishXYZIR2(cloud); ASSERT_TRUE(waitForScan(ros::WallDuration(1.0))); verifyScanSparse(cloud, 8, RING_COUNT, true); // PointXYZR (unexpected format without intensity) cloud.header.stamp = rosTime(ros::WallTime::now()); publishXYZR(cloud); ASSERT_TRUE(waitForScan(ros::WallDuration(1.0))); verifyScanSparse(cloud, 8, RING_COUNT, false); } // Verify that every LaserScan range is valid when given an extra large amount // of random data TEST(System, random_data_dense) { // Make sure system is connected ASSERT_EQ(1, g_sub.getNumPublishers()); ASSERT_EQ(1, g_pub.getNumSubscribers()); // Create PointCloud with dense random data PointCloud cloud; cloud.header.frame_id = "velodyne"; const size_t RANGE_COUNT = 2500; const size_t RING_COUNT = 16; const double RANGE_MAX = 20.0; const double INTENSITY_MAX = 1.0; for (size_t i = 0; i < RANGE_COUNT; i++) { double angle_y = i * 2.0 * M_PI / RANGE_COUNT; // yaw for (size_t j = 0; j < RING_COUNT; j++) { double angle_p = j * 0.2 * M_PI / RING_COUNT - 0.1 * M_PI; // pitch double range = rand() * (RANGE_MAX / RAND_MAX); Point point; point.x = range * cos(angle_p) * cos(angle_y); point.y = range * cos(angle_p) * sin(angle_y); point.z = range * sin(angle_p); point.i = rand() * (INTENSITY_MAX / RAND_MAX); point.r = j; cloud.points.push_back(point); } } // Verify that all three PointCloud2 types are handled correctly // PointXYZIR (expected format) cloud.header.stamp = rosTime(ros::WallTime::now()); publishXYZIR1(cloud); ASSERT_TRUE(waitForScan(ros::WallDuration(1.0))); verifyScanDense(cloud, 8, true); // PointXYZIR (unexpected format with intensity) cloud.header.stamp = rosTime(ros::WallTime::now()); publishXYZIR2(cloud); ASSERT_TRUE(waitForScan(ros::WallDuration(1.0))); verifyScanDense(cloud, 8, true); // PointXYZR (unexpected format without intensity) cloud.header.stamp = rosTime(ros::WallTime::now()); publishXYZR(cloud); ASSERT_TRUE(waitForScan(ros::WallDuration(1.0))); verifyScanDense(cloud, 8, false); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); // Initialize ROS ros::init(argc, argv, "test_lazy_subscriber"); ros::NodeHandle nh; // Setup publisher and subscriber g_pub = nh.advertise<sensor_msgs::PointCloud2>("velodyne_points", 2); g_sub = nh.subscribe("scan", 2, recv); // Wait for other nodes to startup ros::WallDuration(1.0).sleep(); ros::spinOnce(); // Run all the tests that were declared with TEST() return RUN_ALL_TESTS(); }
0
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan/tests/system_node.test
<!-- -*- mode: XML -*- --> <!-- rostest of the velodyne_laserscan system --> <launch> <!-- Select log or screen output --> <arg name="output" default="log"/> <!-- screen/log --> <!-- Start the laserscan node --> <node pkg="velodyne_laserscan" type="velodyne_laserscan_node" name="laserscan" output="$(arg output)" /> <!-- Start the rostest --> <test test-name="test_system_node" pkg="velodyne_laserscan" type="test_system_node" name="test_system"> </test> </launch>
0
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan/tests/lazy_subscriber_nodelet.test
<!-- -*- mode: XML -*- --> <!-- rostest of the lazy subscriber --> <launch> <!-- Select log or screen output --> <arg name="output" default="log"/> <!-- screen/log --> <!-- Start the laserscan nodelet --> <arg name="manager" default="nodelet_manager" /> <node pkg="nodelet" type="nodelet" name="$(arg manager)" args="manager" output="$(arg output)" /> <node pkg="nodelet" type="nodelet" name="velodyne_laserscan" output="$(arg output)" args="load velodyne_laserscan/LaserScanNodelet $(arg manager)"> </node> <!-- Start the rostest --> <test test-name="test_lazy_subscriber_nodelet" pkg="velodyne_laserscan" type="test_lazy_subscriber_nodelet" name="test_lazy_subscriber"> </test> </launch>
0
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan/cfg/VelodyneLaserScan.cfg
#! /usr/bin/env python PACKAGE='velodyne_laserscan' from dynamic_reconfigure.parameter_generator_catkin import * gen = ParameterGenerator() # Name Type Lvl Description Default Min Max gen.add("ring", int_t, 0, "Ring to extract as laser scan (-1 default)", -1, -1, 31) gen.add("resolution", double_t, 0, "Laser scan angular resolution (rad)", 0.007, 0.001, 0.05) exit(gen.generate(PACKAGE, PACKAGE, "VelodyneLaserScan"))
0
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan/src/VelodyneLaserScan.cpp
#include "VelodyneLaserScan.h" #include <sensor_msgs/point_cloud2_iterator.h> namespace velodyne_laserscan { VelodyneLaserScan::VelodyneLaserScan(ros::NodeHandle &nh, ros::NodeHandle &nh_priv) : ring_count_(0), nh_(nh), srv_(nh_priv) { ros::SubscriberStatusCallback connect_cb = boost::bind(&VelodyneLaserScan::connectCb, this); pub_ = nh.advertise<sensor_msgs::LaserScan>("scan", 10, connect_cb, connect_cb); srv_.setCallback(boost::bind(&VelodyneLaserScan::reconfig, this, _1, _2)); } void VelodyneLaserScan::connectCb() { boost::lock_guard<boost::mutex> lock(connect_mutex_); if (!pub_.getNumSubscribers()) { sub_.shutdown(); } else if (!sub_) { sub_ = nh_.subscribe("velodyne_points", 10, &VelodyneLaserScan::recvCallback, this); } } void VelodyneLaserScan::recvCallback(const sensor_msgs::PointCloud2ConstPtr& msg) { // Latch ring count if (!ring_count_) { // Check for PointCloud2 field 'ring' bool found = false; for (size_t i = 0; i < msg->fields.size(); i++) { if (msg->fields[i].datatype == sensor_msgs::PointField::UINT16) { if (msg->fields[i].name == "ring") { found = true; break; } } } if (!found) { ROS_ERROR("VelodyneLaserScan: Field 'ring' of type 'UINT16' not present in PointCloud2"); return; } for (sensor_msgs::PointCloud2ConstIterator<uint16_t> it(*msg, "ring"); it != it.end(); ++it) { const uint16_t ring = *it; if (ring + 1 > ring_count_) { ring_count_ = ring + 1; } } if (ring_count_) { ROS_INFO("VelodyneLaserScan: Latched ring count of %u", ring_count_); } else { ROS_ERROR("VelodyneLaserScan: Field 'ring' of type 'UINT16' not present in PointCloud2"); return; } } // Select ring to use uint16_t ring; if ((cfg_.ring < 0) || (cfg_.ring >= ring_count_)) { // Default to ring closest to being level for each known sensor if (ring_count_ > 32) { ring = 57; // HDL-64E } else if (ring_count_ > 16) { ring = 23; // HDL-32E } else { ring = 8; // VLP-16 } } else { ring = cfg_.ring; } ROS_INFO_ONCE("VelodyneLaserScan: Extracting ring %u", ring); // Load structure of PointCloud2 int offset_x = -1; int offset_y = -1; int offset_z = -1; int offset_i = -1; int offset_r = -1; for (size_t i = 0; i < msg->fields.size(); i++) { if (msg->fields[i].datatype == sensor_msgs::PointField::FLOAT32) { if (msg->fields[i].name == "x") { offset_x = msg->fields[i].offset; } else if (msg->fields[i].name == "y") { offset_y = msg->fields[i].offset; } else if (msg->fields[i].name == "z") { offset_z = msg->fields[i].offset; } else if (msg->fields[i].name == "intensity") { offset_i = msg->fields[i].offset; } } else if (msg->fields[i].datatype == sensor_msgs::PointField::UINT16) { if (msg->fields[i].name == "ring") { offset_r = msg->fields[i].offset; } } } // Construct LaserScan message if ((offset_x >= 0) && (offset_y >= 0) && (offset_r >= 0)) { const float RESOLUTION = fabsf(cfg_.resolution); const size_t SIZE = 2.0 * M_PI / RESOLUTION; sensor_msgs::LaserScanPtr scan(new sensor_msgs::LaserScan()); scan->header = msg->header; scan->angle_increment = RESOLUTION; scan->angle_min = -M_PI; scan->angle_max = M_PI; scan->range_min = 0.0; scan->range_max = 200.0; scan->time_increment = 0.0; scan->ranges.resize(SIZE, INFINITY); if ((offset_x == 0) && (offset_y == 4) && (offset_z == 8) && (offset_i == 16) && (offset_r == 20)) { scan->intensities.resize(SIZE); for (sensor_msgs::PointCloud2ConstIterator<float> it(*msg, "x"); it != it.end(); ++it) { const uint16_t r = *((const uint16_t*)(&it[5])); // ring if (r == ring) { const float x = it[0]; // x const float y = it[1]; // y const float i = it[4]; // intensity const int bin = (atan2f(y, x) + (float)M_PI) / RESOLUTION; if ((bin >= 0) && (bin < (int)SIZE)) { scan->ranges[bin] = sqrtf(x * x + y * y); scan->intensities[bin] = i; } } } } else { ROS_WARN_ONCE("VelodyneLaserScan: PointCloud2 fields in unexpected order. Using slower generic method."); if (offset_i >= 0) { scan->intensities.resize(SIZE); sensor_msgs::PointCloud2ConstIterator<uint16_t> iter_r(*msg, "ring"); sensor_msgs::PointCloud2ConstIterator<float> iter_x(*msg, "x"); sensor_msgs::PointCloud2ConstIterator<float> iter_y(*msg, "y"); sensor_msgs::PointCloud2ConstIterator<float> iter_i(*msg, "intensity"); for ( ; iter_r != iter_r.end(); ++iter_x, ++iter_y, ++iter_r, ++iter_i) { const uint16_t r = *iter_r; // ring if (r == ring) { const float x = *iter_x; // x const float y = *iter_y; // y const float i = *iter_i; // intensity const int bin = (atan2f(y, x) + (float)M_PI) / RESOLUTION; if ((bin >= 0) && (bin < (int)SIZE)) { scan->ranges[bin] = sqrtf(x * x + y * y); scan->intensities[bin] = i; } } } } else { sensor_msgs::PointCloud2ConstIterator<uint16_t> iter_r(*msg, "ring"); sensor_msgs::PointCloud2ConstIterator<float> iter_x(*msg, "x"); sensor_msgs::PointCloud2ConstIterator<float> iter_y(*msg, "y"); for ( ; iter_r != iter_r.end(); ++iter_x, ++iter_y, ++iter_r) { const uint16_t r = *iter_r; // ring if (r == ring) { const float x = *iter_x; // x const float y = *iter_y; // y const int bin = (atan2f(y, x) + (float)M_PI) / RESOLUTION; if ((bin >= 0) && (bin < (int)SIZE)) { scan->ranges[bin] = sqrtf(x * x + y * y); } } } } } pub_.publish(scan); } else { ROS_ERROR("VelodyneLaserScan: PointCloud2 missing one or more required fields! (x,y,ring)"); } } void VelodyneLaserScan::reconfig(VelodyneLaserScanConfig& config, uint32_t level) { cfg_ = config; } }
0
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan/src/node.cpp
#include <ros/ros.h> #include "VelodyneLaserScan.h" int main(int argc, char** argv) { ros::init(argc, argv, "velodyne_laserscan_node"); ros::NodeHandle nh; ros::NodeHandle nh_priv("~"); // create VelodyneLaserScan class velodyne_laserscan::VelodyneLaserScan n(nh, nh_priv); // handle callbacks until shut down ros::spin(); return 0; }
0
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan/src/VelodyneLaserScan.h
#ifndef VELODYNELASERSCAN_H #define VELODYNELASERSCAN_H #include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include <sensor_msgs/LaserScan.h> #include <boost/thread/mutex.hpp> #include <boost/thread/lock_guard.hpp> #include <dynamic_reconfigure/server.h> #include <velodyne_laserscan/VelodyneLaserScanConfig.h> namespace velodyne_laserscan { class VelodyneLaserScan { public: VelodyneLaserScan(ros::NodeHandle &nh, ros::NodeHandle &nh_priv); private: boost::mutex connect_mutex_; void connectCb(); void recvCallback(const sensor_msgs::PointCloud2ConstPtr& msg); ros::NodeHandle nh_; ros::Subscriber sub_; ros::Publisher pub_; VelodyneLaserScanConfig cfg_; dynamic_reconfigure::Server<VelodyneLaserScanConfig> srv_; void reconfig(VelodyneLaserScanConfig& config, uint32_t level); unsigned int ring_count_; }; } #endif // VELODYNELASERSCAN_H
0
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne_laserscan/src/nodelet.cpp
#include <ros/ros.h> #include <pluginlib/class_list_macros.h> #include <nodelet/nodelet.h> #include "VelodyneLaserScan.h" namespace velodyne_laserscan { class LaserScanNodelet: public nodelet::Nodelet { public: LaserScanNodelet() {} ~LaserScanNodelet() {} private: virtual void onInit() { node_.reset(new VelodyneLaserScan(getNodeHandle(), getPrivateNodeHandle())); } boost::shared_ptr<VelodyneLaserScan> node_; }; } PLUGINLIB_DECLARE_CLASS(velodyne_laserscan, LaserScanNodelet, velodyne_laserscan::LaserScanNodelet, nodelet::Nodelet);
0
apollo_public_repos/apollo-contrib/velodyne_vls
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3) project(velodyne) find_package(catkin REQUIRED) catkin_metapackage()
0
apollo_public_repos/apollo-contrib/velodyne_vls
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne/package.xml
<package> <name>velodyne</name> <version>1.3.0</version> <description> Basic ROS support for the Velodyne VLS3D LIDARs. </description> <maintainer email="nbarot@velodyne.com">Nitinkumar Barot</maintainer> <author> Jack O'Quin</author> <license>BSD</license> <!-- <review status="API reviewed" notes="2012-02-02"/> --> <buildtool_depend>catkin</buildtool_depend> <run_depend>velodyne_driver</run_depend> <run_depend>velodyne_laserscan</run_depend> <run_depend>velodyne_msgs</run_depend> <run_depend>velodyne_pointcloud</run_depend> <export> <metapackage/> </export> </package>
0
apollo_public_repos/apollo-contrib/velodyne_vls
apollo_public_repos/apollo-contrib/velodyne_vls/velodyne/CHANGELOG.rst
Change history ============== 1.3.0 (2017-11-10) ------------------ * Merge pull request `#110 <https://github.com/ros-drivers/velodyne/issues/110>`_ from kmhallen/master Added velodyne_laserscan package * Added velodyne_laserscan package and inserted into existing launch files * Contributors: Jack O'Quin, Joshua Whitley, Kevin Hallenbeck 1.2.0 (2014-08-06) ------------------ 1.1.2 (2013-11-05) ------------------- 1.1.1 (2013-07-30) ------------------ 1.1.0 (2013-07-16) ------------------ 1.0.1 (2013-06-15) ------------------ 1.0.0 (2013-06-14) ------------------ * Convert to catkin (`#1`_). * Release to Hydro. 0.9.2 (2013-07-08) ------------------ 0.9.1 (2012-06-05) ------------------ 0.9.0 (2012-04-03) ------------------ * Completely revised API, anticipating a 1.0.0 release. * New velodyne_driver and velodyne_pointcloud packages. * Old velodyne_common and velodyne_pcl packages no longer included. * Released to Electric, Fuerte and Groovy. 0.2.6 (2011-02-23) ------------------ 0.2.5 (2010-11-19) ------------------ * Initial implementation of new 0.3 interfaces. 0.2.0 (2010-08-17) ------------------ * Initial release to ROS C-turtle. .. _`#1`: https://github.com/ros-drivers/velodyne/issues/1 .. _`#4`: https://github.com/ros-drivers/velodyne/issues/4 .. _`#7`: https://github.com/ros-drivers/velodyne/issues/7 .. _`#8`: https://github.com/ros-drivers/velodyne/pull/8 .. _`#9`: https://github.com/ros-drivers/velodyne/issues/9 .. _`#10`: https://github.com/ros-drivers/velodyne/issues/10 .. _`#11`: https://github.com/ros-drivers/velodyne/issues/11 .. _`#12`: https://github.com/ros-drivers/velodyne/pull/12 .. _`#13`: https://github.com/ros-drivers/velodyne/issues/13 .. _`#14`: https://github.com/ros-drivers/velodyne/pull/14 .. _`#17`: https://github.com/ros-drivers/velodyne/issues/17 .. _`#18`: https://github.com/ros-drivers/velodyne/issues/18 .. _`#20`: https://github.com/ros-drivers/velodyne/issues/20
0
apollo_public_repos/apollo-contrib
apollo_public_repos/apollo-contrib/obu/main.cc
/****************************************************************************** * 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. *****************************************************************************/ /** * @file main.cc * @brief main function for OBU */ #include <linux/limits.h> #include <stdio.h> #include <unistd.h> #include <string> #include "database/v2x_db.h" #include "gflags/gflags.h" #include "glog/logging.h" #include "network_adapter/pc5/adapter_pc5.h" #include "network_adapter/uu/adapter_uu.h" #include "network_adapter/uu/uu_send.h" #include "platform_auth/auth_manager.h" #include "platform_auth/auth_para.h" #include "platform_auth/device_info.h" #include "proxy/proxy.h" #include "scenario/traffic_light/traffic_light_thread.h" #include "scenario/shared_sensor/shared_sensor_thread.h" #include "v2x_gflags.h" void log_init() { std::string path(PATH_MAX, '\0'); // get the current path int cnt = readlink("/proc/self/exe", (char*)path.c_str(), path.size()); int i = 0; // delete the exe name for (i = cnt; i >= 0; --i) { if (path[i] == '/') { path[i + 1] = '\0'; break; } } std::string path2(path, 0, i); // append log folder to path path = path2 + "/log"; if (access(path.c_str(), F_OK) != 0) { std::string cmd("mkdir "); cmd += path; system(cmd.c_str()); } // init glog google::InitGoogleLogging("v2x"); // output log immediately FLAGS_logbufsecs = 0; // set the log file to 100MB FLAGS_max_log_size = 1; FLAGS_stop_logging_if_full_disk = true; // log with level >=ERROR is output to stderr google::SetStderrLogging(google::GLOG_FATAL); // set the path for the log file std::string dest_dir = path + "/info"; google::SetLogDestination(google::GLOG_INFO, dest_dir.c_str()); dest_dir = path + "/warning"; google::SetLogDestination(google::GLOG_WARNING, dest_dir.c_str()); dest_dir = path + "/error"; google::SetLogDestination(google::GLOG_ERROR, dest_dir.c_str()); dest_dir = path + "/fatal"; google::SetLogDestination(google::GLOG_FATAL, dest_dir.c_str()); } int main(int argc, char** argv) { google::ParseCommandLineFlags(&argc, &argv, true); log_init(); std::string auth_url = v2x::fLS::FLAGS_auth_url; v2x::AuthPara* auth_parameter = new v2x::AuthPara(auth_url); const std::string device_id = v2x::fLS::FLAGS_uu_device_id; const std::string mac = v2x::fLS::FLAGS_uu_device_mac; const std::string phone_num = ""; v2x::DeviceInfo* device_info = new v2x::DeviceInfo(device_id, mac, phone_num); v2x::BaseAuthManager* auth_manager = v2x::BaseAuthManager::Create( (int)v2x::PLATFORM_VENDOR::CMCC_V2X, *auth_parameter, *device_info); if (auth_manager == nullptr) { LOG(FATAL) << "Create the auth manager failed"; return 1; } v2x::BaseAuthManagerSingleton::InstallInstance(auth_manager); auth_manager->Start(); v2x::V2xDbSingleton::InstallInstance(new v2x::V2xDb()); v2x::V2xDb* db = v2x::V2xDbSingleton::Instance(); db->V2xDbInit(); std::string data_url = v2x::fLS::FLAGS_uu_server_ip_addr; uint32_t data_port = v2x::fLU::FLAGS_uu_socket_port; v2x::UuSend* uu_send = new v2x::UuSend( data_url, data_port, v2x::fLU::FLAGS_uu_message_interval_in_ms); v2x::AdapterUu* adpt_uu = new v2x::AdapterUu(uu_send->GetSocketFd()); uu_send->Start(); adpt_uu->Start(); std::string obu_address = v2x::fLS::FLAGS_obu_ip_addr + ":50100"; std::string svb_address = v2x::fLS::FLAGS_svb_ip_addr + ":50101"; v2x::V2xProxySingleton::InstallInstance( new v2x::V2xProxy(obu_address, svb_address)); v2x::V2xProxy* grpc = v2x::V2xProxySingleton::Instance(); grpc->StartAll(); v2x::TrafficLightThread* traffic_light_thread = new v2x::TrafficLightThread(); traffic_light_thread->Start(); v2x::SharedSensorThread* shared_sensor_thread = new v2x::SharedSensorThread(); shared_sensor_thread->Start(); bool security_flag = v2x::fLB::FLAGS_security_flag; std::string root_ca = v2x::fLS::FLAGS_root_ca; std::string self_ca = v2x::fLS::FLAGS_self_ca; v2x::Adapter* recv_thread = new v2x::Adapter(security_flag, root_ca, self_ca); recv_thread->Start(); recv_thread->Join(); return 0; }
0
apollo_public_repos/apollo-contrib
apollo_public_repos/apollo-contrib/obu/v2x_gflags.cc
/****************************************************************************** * 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. *****************************************************************************/ /** * File: v2x_gflags.cc * Brief: Global flags definition. */ #include "v2x_gflags.h" namespace v2x { DEFINE_string(obu_ip_addr, "192.168.10.123", "OBU IP address"); DEFINE_string(svb_ip_addr, "192.168.10.6", "SVB IP address"); DEFINE_bool(security_flag, false, "security enable flag"); DEFINE_string(root_ca, "", "Root CA File"); DEFINE_string(self_ca, "", "Self CA File"); DEFINE_string(auth_url, "http://112.25.66.162:8003/v2x-auth/v1/auth", "Authentication url for UU mode"); DEFINE_string(uu_device_id, "0066680081700001", "Device id which is registered in UU server"); DEFINE_string(uu_device_mac, "D89EF3821FB6", "Device MAC address"); DEFINE_string(uu_server_ip_addr, "112.25.66.161", "UU server IP address"); DEFINE_uint32(uu_socket_port, 28120, "UDP socket port"); DEFINE_uint32(uu_message_interval_in_ms, 1000, "BSM message interval"); DEFINE_bool(uu_debug, false, "uu interface debug flag"); DEFINE_int32(zone, 50, "designating the UTM zone"); DEFINE_bool(southernhemi_flag, false, "the southern hemisphere flag"); DEFINE_bool(debug_flag, true, "the debug print flag"); } // namespace v2x
0
apollo_public_repos/apollo-contrib
apollo_public_repos/apollo-contrib/obu/CMakeLists.txt
############################################################################### # Copyright 2020 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. ############################################################################### cmake_minimum_required(VERSION 2.8) project(v2x) # set the cross compiling set(CMAKE_SYSTEM_NAME Linux) set(CMAKE_C_COMPILER "arm-poky-linux-gnueabi-gcc") set(CMAKE_CXX_COMPILER "arm-poky-linux-gnueabi-g++") set(CMAKE_CXX_FLAGS "-std=c++11") add_compile_options(-DDEBUG) # where to find header files include_directories(.) include_directories(${v2x_SOURCE_DIR}/third_party/gflags/include) include_directories(${v2x_SOURCE_DIR}/third_party/glog/include) include_directories(${v2x_SOURCE_DIR}/third_party/grpc/include) include_directories(${v2x_SOURCE_DIR}/third_party/protobuf/include) #include_directories(/usr/local/include) include_directories(${v2x_SOURCE_DIR}/third_party/obu/include) include_directories(${v2x_SOURCE_DIR}/third_party/openssl/include) include_directories(${v2x_SOURCE_DIR}/third_party/obu/include/asn1_source) include_directories(${v2x_SOURCE_DIR}/third_party/security/include) include_directories(${v2x_SOURCE_DIR}/third_party/curl/include) include_directories(${v2x_SOURCE_DIR}/third_party/cJSON/include) include_directories(${v2x_SOURCE_DIR}/third_party) include_directories(${v2x_SOURCE_DIR}) include_directories(${v2x_SOURCE_DIR}/app) include_directories(${v2x_SOURCE_DIR}/utils) include_directories(${v2x_SOURCE_DIR}/network/pc5) include_directories(${v2x_SOURCE_DIR}/security) include_directories(${v2x_SOURCE_DIR}/vendor) include_directories(./app/proto-apollo) # where to find library link_directories(${v2x_SOURCE_DIR}/third_party/glog/lib) link_directories(${v2x_SOURCE_DIR}/third_party/gflags/lib) link_directories(${v2x_SOURCE_DIR}/third_party/grpc/lib) link_directories(${v2x_SOURCE_DIR}/third_party/protobuf/lib) link_directories(${v2x_SOURCE_DIR}/third_party/obu/lib) link_directories(${v2x_SOURCE_DIR}/third_party/openssl/lib) link_directories(${v2x_SOURCE_DIR}/third_party/security/lib) link_directories(${v2x_SOURCE_DIR}/third_party/curl/lib) link_directories(${v2x_SOURCE_DIR}/third_party/cJSON/lib) link_directories(${v2x_SOURCE_DIR}/vendor/ctfo) link_directories(${v2x_SOURCE_DIR}/vendor/cmcc/lib) include_directories(./lib) # which subdirectory to compile add_subdirectory(app) add_subdirectory(utils) add_subdirectory(security) add_library(obu_conf v2x_gflags.cc) add_executable(v2x main.cc) target_link_libraries(v2x ntw_adapter v2x_db tl ssm policy proxy msg_set uu_auth obu_conf cmcc curl JSON glog gpr grpc++ protobuf utils proto security cncrypto cert ssl crypto cV2xAppLyr cV2xNtwkLyr selfcomm event pthread config apollo_ssm_decoder )
0
apollo_public_repos/apollo-contrib
apollo_public_repos/apollo-contrib/obu/README.md
## Introduction These pieces of code under this folder is for OBU box. ## How to compile and run Follow the step below to generate a binary for OBU. 0. Install cross compilation chain, we may get it from the OBU vendor. 0. Install gRPC, glog, gflags and protobuf on the host PC and copy their include folder into third_party/ directory. + Get gRPC from <https://github.com/grpc/grpc/releases/tag/v1.14.0> + Get Protobuf from <https://github.com/protocolbuffers/protobuf/releases/tag/v2.6.1> + Get glog from <https://github.com/google/glog/releases/tag/v0.3.3> + Get gflags from <https://github.com/gflags/gflags/releases/tag/v2.2.1> 0. Download the so libraries from https://apollo-v2x.bj.bcebos.com/obu-library.tar.gz and decompress it into obu folder. 0. Run the command "bash build.sh build", it will generate the v2x.tar.gz in the output folder. 0. Download and decompress the v2x.tar.gz to the OBU box. Run "./v2x --flagfile=v2x.flag". ## How to integrate to a new OBU For PC5 mode, we define the interfaces between the network layer and application layer. The interfaces are in network/pc5/cv2x_app.h. Also need to provide the decode/encode interfaces for messages to application layer. For uu mode, need to define the following variables in the conf/v2x.flag. auth_url, # server authentication address uu_server_addr, # server address to get the SPAT and the MAP messages uu_socket_port, # server port for uu UDP socket uu_device_id, # device id which is assigned by the uu platform uu_device_mac, # device MAC address for OBU Also need to implement the interfaces which are defined in network/uu/gb_bsm.h ## Security for communications The apollo V2X security is for data security. Asymmetric encryption algorithm SM2 and cryptographic hash algorithm SM3 are used. The CA format is followed the standard "Intelligent transport - Certificate application interface". More detail is at <http://www.mot.gov.cn/yijianzhengji/lishizhengji/201711/P020171101362371804539.pdf>. In asymmetric encryption algorithm, every user has a CA file including private key and public key, it also has another file of root CA public key. User use his private key to sign the payload, send a package including the raw payload, signature and the security info(public key and signature by root CA). The receiver should also has the root CA public key. He would use the root CA public key to verify the validation of received public key then use the received public key to verify the signature. ## Usage example For privacy reason, the generating CA function is not published. You could use the sample file "ca_cert.pem" for root CA file and "child_cert.pem" for child CA. Or you could write your own generating function by the format defined in "third_party/security/include/Certificate.h".
0
apollo_public_repos/apollo-contrib
apollo_public_repos/apollo-contrib/obu/build.sh
#!/bin/bash set -e #set -u set -o pipefail CORENUM=$(grep -c ^processor /proc/cpuinfo) export MAKEFLAGS="-j${CORENUM} -l${CORENUM}" function clean() { if [[ -d "./build" ]]; then rm -rf ./build fi if [[ -d "./output" ]]; then rm -rf ./output fi } function build() { mkdir -p ./build ./output cd build cmake .. make cd ../output if [ -d install ]; then rm -rf install fi mkdir install cd install cp ../../build/v2x . cp ../../conf/v2x.flag . cp ../../vendor/cmcc/lib/libcmcc.so . files=`find ../../build/ -name "*.so*" |wc -l` if [ $files -ne 0 ]; then find ../../build/ -name "*.so*" |xargs cp -d -t . fi find ../../third_party/ -name "*.so*" |xargs cp -d -t . cd .. tar -zcvf v2x.tar.gz ./install rm -rf install cd .. } case $1 in clean) clean ;; build) build ;; *) clean && build ;; esac
0
apollo_public_repos/apollo-contrib
apollo_public_repos/apollo-contrib/obu/v2x_gflags.h
/****************************************************************************** * 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. *****************************************************************************/ /** * File: v2x_gflags.h * Brief: Global flags definition. */ #ifndef V2X_COMMON_V2X_GFLAGS_H #define V2X_COMMON_V2X_GFLAGS_H #include "gflags/gflags.h" namespace v2x { DECLARE_string(obu_ip_addr); DECLARE_string(svb_ip_addr); DECLARE_bool(security_flag); DECLARE_string(root_ca); DECLARE_string(self_ca); DECLARE_string(auth_url); DECLARE_string(uu_device_id); DECLARE_string(uu_device_mac); DECLARE_string(uu_server_ip_addr); DECLARE_uint32(uu_socket_port); DECLARE_uint32(uu_message_interval_in_ms); DECLARE_bool(uu_debug); DECLARE_int32(zone); DECLARE_bool(southernhemi_flag); DECLARE_bool(debug_flag); } // namespace v2x #endif // V2X_COMMON_V2X_GFLAGS_H
0
apollo_public_repos/apollo-contrib/obu
apollo_public_repos/apollo-contrib/obu/app/CMakeLists.txt
cmake_minimum_required(VERSION 2.8) find_program(PROTOBUF_PROTOC_EXECUTABLE protoc) find_program(GRPC_CPP_PLUGIN grpc_cpp_plugin) set(ENV{PROTOC_FILEPATH} ${PROTOBUF_PROTOC_EXECUTABLE}) set(ENV{GRPC_CPP_PLUGIN_FILEPATH} ${GRPC_CPP_PLUGIN}) message(STATUS "Compiling protos...") execute_process( COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/proto-apollo/compile-apollo-proto.bash RESULT_VARIABLE script_res ) if (NOT ${script_res} EQUAL 0) message(FATAL "Failed to compiling protos") endif () include_directories(proto-apollo) file(GLOB_RECURSE pb_cc_apollo ./proto-apollo *.pb.cc) add_library(proto ${pb_cc_apollo} ) add_subdirectory(database) #add_subdirectory(proto) add_subdirectory(network_adapter) add_subdirectory(scenario) add_subdirectory(proxy) add_subdirectory(msg_sets) add_subdirectory(policies) add_subdirectory(platform_auth)
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/database/CMakeLists.txt
cmake_minimum_required(VERSION 2.8) aux_source_directory(. DIRSRCS) add_library(v2x_db ${DIRSRCS}) add_dependencies(v2x_db proto)
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/database/v2x_table.cc
/****************************************************************************** * 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. *****************************************************************************/ /** * @file v2x_table.cc * @brief define V2X Table class */ #include "v2x_table.h" #include <string.h> #include <iostream> #include "glog/logging.h" namespace v2x { V2xTable::V2xTable(bool notify_flag, uint32_t entry_num) : notify_flag_(notify_flag), max_entry_num_(entry_num) {} V2xTable::~V2xTable() {} bool V2xTable::IsEmpty() { std::lock_guard<std::mutex> guard(table_mutex_); return table_.empty(); } int V2xTable::TableSize() { return table_.size(); } void V2xTable::AddEntry(V2xData& data) { std::lock_guard<std::mutex> guard(table_mutex_); if (TableSize() + 1 > max_entry_num_) { V2xData* entry = table_.front(); table_.pop_front(); delete entry; } table_.push_front(&data); if (notify_flag_) { refresh_ = true; table_condition_.notify_one(); } } V2xData* V2xTable::GetLatestEntry() { V2xData* entry = nullptr; if (notify_flag_) { std::unique_lock<std::mutex> guard(table_mutex_); table_condition_.wait(guard, [this] { return refresh_; }); entry = table_.front(); refresh_ = false; } else { std::lock_guard<std::mutex> guard(table_mutex_); if (table_.empty()) return nullptr; entry = table_.front(); } return entry; } bool V2xTable::AddEntryWithCompare(V2xData& data) { std::lock_guard<std::mutex> guard(table_mutex_); for (auto& v2x_data : table_) { if (v2x_data->get_len() == data.get_len()) { if (memcmp(v2x_data->get_buf(), data.get_buf(), data.get_len()) == 0) { LOG(INFO) << "buf content is same, ignore this message with len " << data.get_len(); return false; } } } // check the table size, if > max_entry_num, delete one if (TableSize() + 1 > max_entry_num_) { V2xData* entry = table_.front(); if (entry != nullptr) { table_.pop_front(); delete entry; } } table_.push_front(&data); if (notify_flag_) { refresh_ = true; table_condition_.notify_one(); } return true; } } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/database/v2x_data.cc
/****************************************************************************** * 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. *****************************************************************************/ /** * @file v2x_data.cc * @brief implement the v2x data class */ #include "v2x_data.h" namespace v2x { V2xData::V2xData(char* buf, uint32_t len) : buf_(buf), len_(len) {} V2xData::~V2xData() { if (nullptr != buf_) { delete[] buf_; } } char* V2xData::get_buf() const { // std::cout << "v2x get buf " << (void*)buf_ << std::endl; return buf_; } uint32_t V2xData::get_len() const { return len_; } } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/database/v2x_data.h
/****************************************************************************** * 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. *****************************************************************************/ /** * @file v2x_data.h * @brief define V2X data class */ #pragma once #include <stdint.h> namespace v2x { class V2xData { public: V2xData(char* buf, uint32_t len); ~V2xData(); char* get_buf() const; uint32_t get_len() const; private: char* buf_; uint32_t len_ = 0; }; } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/database/v2x_db.h
/****************************************************************************** * 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. *****************************************************************************/ /** * @file v2x_db.h * @brief define V2X database class */ #pragma once #include "cv2x_app.h" #include "singleton.h" #include "v2x_table.h" namespace v2x { class V2xDb { public: // const static uint32_t map_appid = 29; // const static uint32_t spat_appid = 30; // const static uint32_t g_max_buf_max = 1000; V2xDb() = default; ~V2xDb() { delete spat_; delete map_; delete ssm_; }; void V2xDbInit(); void SubmitData(char* buf, uint32_t len, uint32_t appid); bool GetData(char* buf, uint32_t* len, eMsgType type); private: V2xTable* spat_ = nullptr; V2xTable* map_ = nullptr; V2xTable* ssm_ = nullptr; }; typedef SingletonService<V2xDb> V2xDbSingleton; } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/database/v2x_db.cc
/****************************************************************************** * 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. *****************************************************************************/ /** * @file v2x_db.cc * @brief implement V2X database class */ #include "v2x_db.h" #include <cstring> #include <iostream> #include "glog/logging.h" #include "network_adapter/pc5/adapter_pc5.h" #include "v2x_data.h" #include "v2x_table.h" namespace v2x { void V2xDb::V2xDbInit() { spat_ = new V2xTable(true, 5); map_ = new V2xTable(false, 5); ssm_ = new V2xTable(true, 5); } void V2xDb::SubmitData(char* buf, uint32_t len, uint32_t appid) { V2xData* data = nullptr; if (buf == nullptr) { return; } // map message if (MSG_TYPE_MAP == GetMsgType(appid)) { #if 0 { // the code will show the content of buf int i = 0; printf("recieved the map msg with len %d\n", len); for (i = 0; i < len / 16; i++) { for (int j = 0; j < 16; j++) { printf("%02x", *(uint8_t*)((uint8_t*)buf + i * 16 + j)); } printf("\n"); } for (int j = 0; j < len % 16; j++) { printf("%02x", *(uint8_t*)((uint8_t*)buf + i * 16 + j)); } printf("\n"); } #endif data = new V2xData(buf, len); if (!map_->AddEntryWithCompare(*data)) { delete data; } LOG(INFO) << "submit the MAP message to table"; } else if (MSG_TYPE_SPAT == GetMsgType(appid)) { // spat message data = new V2xData(buf, len); if (!spat_->AddEntryWithCompare(*data)) { delete data; } LOG(INFO) << "submit the SPAT message to table"; } else if (MSG_TYPE_SSM == GetMsgType(appid)) { // ssm message data = new V2xData(buf, len); if (!ssm_->AddEntryWithCompare(*data)) { delete data; } LOG(INFO) << "submit the SSM message to table"; } else { delete[] buf; LOG(INFO) << "appid is wrong, appid " << appid; } } bool V2xDb::GetData(char* buf, uint32_t* len, eMsgType type) { V2xData* data = nullptr; if (MSG_TYPE_MAP == type) { data = map_->GetLatestEntry(); } else if (MSG_TYPE_SPAT == type) { data = spat_->GetLatestEntry(); } else if (MSG_TYPE_SSM == type) { data = ssm_->GetLatestEntry(); } else { // delete [] buf; LOG(INFO) << "type is wrong, appid " << type; return false; } if (data != nullptr) { memcpy(buf, data->get_buf(), data->get_len()); *len = data->get_len(); return true; } return false; } } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/database/v2x_table.h
/****************************************************************************** * 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. *****************************************************************************/ /** * @file v2x_table.h * @brief define V2X table class */ #pragma once #include <condition_variable> #include <list> #include <mutex> #include "v2x_data.h" namespace v2x { class V2xTable { public: V2xTable(bool notify_flag, uint32_t entry_num); ~V2xTable(); bool IsEmpty(); int TableSize(); void AddEntry(V2xData& data); V2xData* GetLatestEntry(); bool AddEntryWithCompare(V2xData& data); private: bool notify_flag_ = false; uint32_t max_entry_num_ = 0; std::mutex table_mutex_; std::list<V2xData*> table_; bool refresh_ = false; std::condition_variable table_condition_; }; } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proxy/CMakeLists.txt
add_library(proxy STATIC proxy.cc) target_link_libraries(proxy proto protobuf grpc grpc++ pthread)
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proxy/proxy.h
/****************************************************************************** * 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. *****************************************************************************/ /** * @file proxy.h * @brief define Proxy class */ #ifndef APP_PROXY_PROXY_H_ #define APP_PROXY_PROXY_H_ #include <iostream> #include <mutex> #include <queue> #include <string> #include <thread> #include <grpc/grpc.h> #include <grpc/support/log.h> #include <grpcpp/channel.h> #include <grpcpp/client_context.h> #include <grpcpp/create_channel.h> #include <grpcpp/grpcpp.h> #include <grpcpp/security/credentials.h> #include <grpcpp/security/server_credentials.h> #include <grpcpp/server.h> #include <grpcpp/server_builder.h> #include <grpcpp/server_context.h> #include "cmn_queue.h" #include "macro.h" #include "singleton.h" #include "modules/v2x/proto/v2x_service_car_to_obu.grpc.pb.h" #include "modules/v2x/proto/v2x_service_obu_to_car.grpc.pb.h" namespace v2x { class V2xProxy { public: V2xProxy(const std::string& rsu_or_obu_address, const std::string& svb_address) : service_(rsu_or_obu_address), client_(svb_address) {} ~V2xProxy() { StopAll(); } void StartAll() { ServerStart(); ClientStart(); } void StopAll() { service_.Stop(); client_.Stop(); } void ServerStart() { service_.Start(); } void ClientStart() { client_.Start(); } std::shared_ptr<apollo::perception::PerceptionObstacles> GetObstacles(); std::shared_ptr<apollo::v2x::CarStatus> GetCarStatus(); void SendObstacles(const apollo::v2x::V2XObstacles& request); void SendTrafficLights(const apollo::v2x::obu::ObuTrafficLight& request); private: class CarToObuService final : public apollo::v2x::CarToObu::Service { public: explicit CarToObuService(const std::string& address) : address_(address), server_thread_(nullptr), stop_flag_(false) {} grpc::Status PushCarStatus(grpc::ServerContext* context, const apollo::v2x::CarStatus* request, apollo::v2x::UpdateStatus* response) override; void Start(); void Stop(); std::shared_ptr<apollo::perception::PerceptionObstacles> pop_obstacles(); std::shared_ptr<apollo::v2x::CarStatus> pop_carstatus(); private: void ServerThread(); std::string address_; std::unique_ptr<std::thread> server_thread_ = nullptr; std::mutex mutex_; std::condition_variable condition_; bool stop_flag_ = false; CmnQueue<apollo::v2x::CarStatus> car_status_; CmnQueue<apollo::perception::PerceptionObstacles> perception_obstacles_; DISALLOW_COPY_AND_ASSIGN(CarToObuService); }; class ObuToCarClient { public: explicit ObuToCarClient(const std::string& address) : address_(address), client_thread_(nullptr), cq_(nullptr) { channel_ = grpc::CreateChannel(address_, grpc::InsecureChannelCredentials()); stub_ = apollo::v2x::ObuToCar::NewStub(channel_); } void SendPerceptionObstacles(const apollo::v2x::V2XObstacles& request); void SendV2xTrafficLight(const apollo::v2x::obu::ObuTrafficLight& request); void Start(); void Stop(); private: struct AsyncClientCall { apollo::v2x::StatusResponse reply; grpc::ClientContext context; grpc::Status status; std::unique_ptr< grpc::ClientAsyncResponseReader<apollo::v2x::StatusResponse>> response_reader; }; void ClientThread(); std::string address_; std::unique_ptr<std::thread> client_thread_ = nullptr; std::shared_ptr<grpc::Channel> channel_ = nullptr; std::unique_ptr<apollo::v2x::ObuToCar::Stub> stub_ = nullptr; std::unique_ptr<grpc::CompletionQueue> cq_ = nullptr; }; CarToObuService service_; ObuToCarClient client_; DISALLOW_COPY_AND_ASSIGN(V2xProxy); }; typedef SingletonService<V2xProxy> V2xProxySingleton; } // namespace v2x #endif // APP_PROXY_PROXY_H_
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proxy/proxy.cc
/****************************************************************************** * 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. *****************************************************************************/ /** * @file proxy.cc * @brief define Proxy class */ #include "app/proxy/proxy.h" #include "glog/logging.h" namespace v2x { using grpc::Channel; using grpc::ClientAsyncResponseReader; using grpc::ClientContext; using grpc::ClientReader; using grpc::ClientReaderWriter; using grpc::ClientWriter; using grpc::CompletionQueue; using grpc::Server; using grpc::ServerBuilder; using grpc::ServerContext; using grpc::ServerReader; using grpc::ServerReaderWriter; using grpc::ServerWriter; using apollo::perception::PerceptionObstacles; using apollo::v2x::CarStatus; using apollo::v2x::IntersectionTrafficLightData; using apollo::v2x::StatusResponse; using apollo::v2x::UpdateStatus; void V2xProxy::CarToObuService::Start() { if (server_thread_ == nullptr) { server_thread_.reset(new std::thread( std::bind(&V2xProxy::CarToObuService::ServerThread, this))); stop_flag_ = false; } } void V2xProxy::CarToObuService::ServerThread() { grpc::ServerBuilder builder; builder.AddListeningPort(address_, grpc::InsecureServerCredentials()); builder.RegisterService(this); std::unique_ptr<grpc::Server> server(builder.BuildAndStart()); LOG(INFO) << "Grpc server listening on " << address_; std::unique_lock<std::mutex> lk(mutex_); condition_.wait(lk, [&]() { return stop_flag_; }); server->Shutdown(); } void V2xProxy::ObuToCarClient::Start() { if (client_thread_ == nullptr) { cq_.reset(new grpc::CompletionQueue); client_thread_.reset(new std::thread( std::bind(&V2xProxy::ObuToCarClient::ClientThread, this))); } } void V2xProxy::ObuToCarClient::ClientThread() { void* got_tag; bool ok = false; while (cq_->Next(&got_tag, &ok)) { AsyncClientCall* call = static_cast<AsyncClientCall*>(got_tag); GPR_ASSERT(ok); if (!call->status.ok()) { LOG_EVERY_N(ERROR, 10) << "Client send failed"; } delete call; } cq_.reset(nullptr); } void V2xProxy::CarToObuService::Stop() { if (server_thread_ != nullptr) { { std::lock_guard<std::mutex> lk(mutex_); stop_flag_ = true; } condition_.notify_one(); server_thread_->join(); server_thread_.reset(nullptr); } } void V2xProxy::ObuToCarClient::Stop() { if (client_thread_ != nullptr) { if (cq_ != nullptr) { cq_->Shutdown(); } client_thread_->join(); client_thread_.reset(nullptr); } } grpc::Status V2xProxy::CarToObuService::PushCarStatus(ServerContext* context, const CarStatus* request, UpdateStatus* response) { car_status_.push(*request); response->set_updated(true); return grpc::Status::OK; } std::shared_ptr<CarStatus> V2xProxy::CarToObuService::pop_carstatus() { return car_status_.try_pop(); } std::shared_ptr<PerceptionObstacles> V2xProxy::CarToObuService::pop_obstacles() { return perception_obstacles_.try_pop(); } std::shared_ptr<CarStatus> V2xProxy::GetCarStatus() { return service_.pop_carstatus(); } std::shared_ptr<PerceptionObstacles> V2xProxy::GetObstacles() { return service_.pop_obstacles(); } void V2xProxy::ObuToCarClient::SendPerceptionObstacles( const apollo::v2x::V2XObstacles& request) { AsyncClientCall* call = new AsyncClientCall; call->response_reader = stub_->PrepareAsyncSendPerceptionObstacles( &call->context, request, cq_.get()); call->response_reader->StartCall(); call->response_reader->Finish(&call->reply, &call->status, static_cast<void*>(call)); } void V2xProxy::SendObstacles(const apollo::v2x::V2XObstacles& request) { client_.SendPerceptionObstacles(request); } void V2xProxy::ObuToCarClient::SendV2xTrafficLight( const apollo::v2x::obu::ObuTrafficLight& request) { AsyncClientCall* call = new AsyncClientCall; call->response_reader = stub_->PrepareAsyncSendV2xTrafficLight( &call->context, request, cq_.get()); call->response_reader->StartCall(); call->response_reader->Finish(&call->reply, &call->status, static_cast<void*>(call)); } void V2xProxy::SendTrafficLights( const apollo::v2x::obu::ObuTrafficLight& request) { client_.SendV2xTrafficLight(request); } } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto/header.proto
syntax = "proto2"; package apollo.common; import "error_code.proto"; message Header { // Message publishing time in seconds. It is recommended to obtain // timestamp_sec from ros::Time::now(), right before calling // SerializeToString() and publish(). optional double timestamp_sec = 1; // Module name. optional string module_name = 2; // Sequence number for each message. Each module maintains its own counter for // sequence_num, always starting from 1 on boot. optional uint32 sequence_num = 3; // Lidar Sensor timestamp for nano-second. optional uint64 lidar_timestamp = 4; // Camera Sensor timestamp for nano-second. optional uint64 camera_timestamp = 5; // Radar Sensor timestamp for nano-second. optional uint64 radar_timestamp = 6; // data version optional uint32 version = 7 [default = 1]; optional StatusPb status = 8; optional string frame_id = 9; }
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto/traffic_light_detection.proto
package apollo.perception; import "header.proto"; message TrafficLightBox{ optional int32 x = 1; optional int32 y = 2; optional int32 width = 3; optional int32 height = 4; optional TrafficLight.Color color = 5; optional bool selected = 6; } message TrafficLightDebug{ optional TrafficLightBox cropbox = 1; repeated TrafficLightBox box = 2; optional int32 signal_num = 3; optional int32 valid_pos = 4; optional double ts_diff_pos = 5; optional double ts_diff_sys = 6; optional int32 project_error = 7; optional double distance_to_stop_line = 8; repeated TrafficLightBox crop_roi = 9; repeated TrafficLightBox projected_roi = 10; repeated TrafficLightBox rectified_roi = 11; repeated TrafficLightBox debug_roi = 12; } message TrafficLight { enum Color { UNKNOWN = 0; RED = 1; YELLOW = 2; GREEN = 3; BLACK = 4; }; optional Color color = 1; // Traffic light string-ID in the map data. optional string id = 2; // How confidence about the detected results, between 0 and 1. optional double confidence = 3 [default = 1.0]; // Duration of the traffic light since detected. optional double tracking_time = 4; // Is traffic blinking optional bool blink = 5; } message TrafficLightDetection { enum CameraID { CAMERA_FRONT_LONG = 0; CAMERA_FRONT_NARROW = 1; CAMERA_FRONT_SHORT = 2; CAMERA_FRONT_WIDE = 3; }; optional apollo.common.Header header = 2; repeated TrafficLight traffic_light = 1; optional TrafficLightDebug traffic_light_debug = 3; optional bool contain_lights = 4; optional CameraID camera_id = 5; }
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto/v2x_trafficlight_policy.proto
syntax = "proto2"; package apollo.v2x; message Position2D { optional double x = 1; optional double y = 2; } message Connection { enum Type { STRAIGHT = 0; LEFT = 1; RIGHT = 2; U_TURN = 3; }; optional Type allow_driving_behavior = 1; optional int32 phase_id = 2; } message Lane { optional int32 lane_id = 1; repeated Position2D position_offset = 2; repeated Connection connections = 3; } message Road { optional int32 upstream_node_id = 1; optional Position2D points = 2; repeated Lane lanes = 3; } message Intersection { optional int32 id = 1; optional Position2D position = 2; repeated Road roads = 3; } message Map { optional double time_stamp = 1; optional int32 msg_cnt = 2; repeated Intersection intersections = 3; } message Phase { enum Color { UNKNOWN = 0; RED = 1; YELLOW = 2; GREEN = 3; BLACK = 4; FLASH_GREEN = 5; }; optional int32 id = 1; optional Color color = 2; optional int32 color_remaining_time_s = 3; } message IntersectionState { optional int32 intersection_id = 1; repeated Phase Phases = 2; optional int32 moy = 3; optional int32 time_stamp_dsecond = 4; } message Spat { optional double time_stamp = 1; optional int32 msg_cnt = 2; repeated IntersectionState intersections = 3; } message PolicyData { optional Map map = 1; optional Spat spat = 2; }
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto/CMakeLists.txt
cmake_minimum_required(VERSION 2.8) #find_package(Protobuf REQUIRED) find_program(PROTOBUF_PROTOC_EXECUTABLE protoc) find_program(GRPC_CPP_PLUGIN grpc_cpp_plugin) include(${CMAKE_CURRENT_SOURCE_DIR}/protobuf.cmake) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) # Setup proto gen file directories set(PROTOBUF_GENERATE_CPP_PATH ${CMAKE_CURRENT_SOURCE_DIR}/include) file(MAKE_DIRECTORY ${PROTOBUF_GENERATE_CPP_PATH}) file(GLOB PROTO_FILES "${CMAKE_CURRENT_SOURCE_DIR}/*.proto") set(PROTOBUF_GENERATE_CPP_APPEND_PATH TRUE) V2X_PROTOBUF_GENERATE_CPP(${PROTOBUF_GENERATE_CPP_PATH} PROTOSRCS PROTOHDRS ${PROTO_FILES}) add_custom_target( generate_proto DEPENDS ${PROTOSRCS} ${PROTOHDRS} ) V2X_PROTOBUF_GENERATE_GRPC_CPP(${PROTOBUF_GENERATE_CPP_PATH} PROTOGRPCSRCS PROTOGRPCHDRS ${PROTO_FILES}) add_custom_target( generate_grpc DEPENDS ${PROTOGRPCSRCS} ${PROTOGRPCHDRS} ) add_library(proto SHARED ${PROTOSRCS} ${PROTOHDRS} ${PROTOGRPCSRCS} ${PROTOGRPCHDRS}) add_dependencies(proto generate_proto generate_grpc) target_link_libraries(proto protobuf grpc grpc++)
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto/chassis.proto
syntax = "proto2"; package apollo.canbus; import "header.proto"; import "vehicle_signal.proto"; import "drive_state.proto"; import "geometry.proto"; // next id :31 message Chassis { enum DrivingMode { COMPLETE_MANUAL = 0; // human drive COMPLETE_AUTO_DRIVE = 1; AUTO_STEER_ONLY = 2; // only steer AUTO_SPEED_ONLY = 3; // include throttle and brake // security mode when manual intervention happens, only response status EMERGENCY_MODE = 4; } enum ErrorCode { NO_ERROR = 0; CMD_NOT_IN_PERIOD = 1; // control cmd not in period // car chassis report error, like steer, brake, throttle, gear fault CHASSIS_ERROR = 2; MANUAL_INTERVENTION = 3; // human manual intervention // receive car chassis can frame not in period CHASSIS_CAN_NOT_IN_PERIOD = 4; UNKNOWN_ERROR = 5; } enum GearPosition { GEAR_NEUTRAL = 0; GEAR_DRIVE = 1; GEAR_REVERSE = 2; GEAR_PARKING = 3; GEAR_LOW = 4; GEAR_INVALID = 5; GEAR_NONE = 6; } optional bool engine_started = 3; // Engine speed in RPM. optional float engine_rpm = 4 [default = nan]; // Vehicle Speed in meters per second. optional float speed_mps = 5 [default = nan]; // Vehicle odometer in meters. optional float odometer_m = 6 [default = nan]; // Fuel range in meters. optional int32 fuel_range_m = 7; // Real throttle location in [%], ranging from 0 to 100. optional float throttle_percentage = 8 [default = nan]; // Real brake location in [%], ranging from 0 to 100. optional float brake_percentage = 9 [default = nan]; // Real gear location. // optional int32 gear_location = 10; deprecated use enum replace this [id 23] // Real steering location in [%], ranging from 0 to 100. optional float steering_percentage = 11 [default = nan]; // Applied steering torque in [Nm]. optional float steering_torque_nm = 12 [default = nan]; // Parking brake status. optional bool parking_brake = 13; // Light signals. optional bool high_beam_signal = 14 [deprecated = true]; optional bool low_beam_signal = 15 [deprecated = true]; optional bool left_turn_signal = 16 [deprecated = true]; optional bool right_turn_signal = 17 [deprecated = true]; optional bool horn = 18 [deprecated = true]; optional bool wiper = 19; optional bool disengage_status = 20 [deprecated = true]; optional DrivingMode driving_mode = 21 [default = COMPLETE_MANUAL]; optional ErrorCode error_code = 22 [default = NO_ERROR]; optional GearPosition gear_location = 23; // timestamp for steering module optional double steering_timestamp = 24; // In seconds, with 1e-6 accuracy // chassis also needs it own sending timestamp optional apollo.common.Header header = 25; optional int32 chassis_error_mask = 26 [default = 0]; optional apollo.common.VehicleSignal signal = 27; // Only available for Lincoln now optional ChassisGPS chassis_gps = 28; optional apollo.common.EngageAdvice engage_advice = 29; optional WheelSpeed wheel_speed = 30; optional Surround surround = 31; // Vehicle registration information optional License license = 32; } message ChassisGPS { optional double latitude = 1; optional double longitude = 2; optional bool gps_valid = 3; optional int32 year = 4; optional int32 month = 5; optional int32 day = 6; optional int32 hours = 7; optional int32 minutes = 8; optional int32 seconds = 9; optional double compass_direction = 10; optional double pdop = 11; optional bool is_gps_fault = 12; optional bool is_inferred = 13; optional double altitude = 14; optional double heading = 15; optional double hdop = 16; optional double vdop = 17; optional GpsQuality quality = 18; optional int32 num_satellites = 19; optional double gps_speed = 20; } enum GpsQuality { FIX_NO = 0; FIX_2D = 1; FIX_3D = 2; FIX_INVALID = 3; } message WheelSpeed { enum WheelSpeedType { FORWARD = 0; BACKWARD = 1; STANDSTILL = 2; INVALID = 3; } optional bool is_wheel_spd_rr_valid = 1 [default = false]; optional WheelSpeedType wheel_direction_rr = 2 [default = INVALID]; optional double wheel_spd_rr = 3 [default = 0.0]; optional bool is_wheel_spd_rl_valid = 4 [default = false]; optional WheelSpeedType wheel_direction_rl = 5 [default = INVALID]; optional double wheel_spd_rl = 6 [default = 0.0]; optional bool is_wheel_spd_fr_valid = 7 [default = false]; optional WheelSpeedType wheel_direction_fr = 8 [default = INVALID]; optional double wheel_spd_fr = 9 [default = 0.0]; optional bool is_wheel_spd_fl_valid = 10 [default = false]; optional WheelSpeedType wheel_direction_fl = 11 [default = INVALID]; optional double wheel_spd_fl = 12 [default = 0.0]; } message Sonar { optional double range = 1; // Meter optional apollo.common.Point3D translation = 2; // Meter optional apollo.common.Quaternion rotation = 3; } message Surround { optional bool cross_traffic_alert_left = 1; optional bool cross_traffic_alert_left_enabled = 2; optional bool blind_spot_left_alert = 3; optional bool blind_spot_left_alert_enabled = 4; optional bool cross_traffic_alert_right = 5; optional bool cross_traffic_alert_right_enabled = 6; optional bool blind_spot_right_alert = 7; optional bool blind_spot_right_alert_enabled = 8; optional double sonar00 = 9; optional double sonar01 = 10; optional double sonar02 = 11; optional double sonar03 = 12; optional double sonar04 = 13; optional double sonar05 = 14; optional double sonar06 = 15; optional double sonar07 = 16; optional double sonar08 = 17; optional double sonar09 = 18; optional double sonar10 = 19; optional double sonar11 = 20; optional bool sonar_enabled = 21; optional bool sonar_fault = 22; repeated double sonar_range = 23; repeated Sonar sonar = 24; } message License { optional string vin = 1; }
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto/protobuf.cmake
cmake_minimum_required(VERSION 2.8) function(V2X_PROTOBUF_GENERATE_CPP PATH SRCS HDRS) if(NOT ARGN) message(SEND_ERROR "Error: V2X_PROTOBUF_GENERATE_CPP() called without any proto files") return() endif() if(PROTOBUF_GENERATE_CPP_APPEND_PATH) # This variable is common for all types of output. # Create an include path for each file specified foreach(FIL ${ARGN}) get_filename_component(ABS_FIL ${FIL} ABSOLUTE) get_filename_component(ABS_PATH ${ABS_FIL} PATH) list(FIND _protobuf_include_path ${ABS_PATH} _contains_already) if(${_contains_already} EQUAL -1) list(APPEND _protobuf_include_path -I ${ABS_PATH}) endif() endforeach() else() set(_protobuf_include_path -I ${CMAKE_CURRENT_SOURCE_DIR}) endif() if(DEFINED PROTOBUF_IMPORT_DIRS) foreach(DIR ${PROTOBUF_IMPORT_DIRS}) get_filename_component(ABS_PATH ${DIR} ABSOLUTE) list(FIND _protobuf_include_path ${ABS_PATH} _contains_already) if(${_contains_already} EQUAL -1) list(APPEND _protobuf_include_path -I ${ABS_PATH}) endif() endforeach() endif() set(${SRCS}) set(${HDRS}) foreach(FIL ${ARGN}) get_filename_component(ABS_FIL ${FIL} ABSOLUTE) get_filename_component(FIL_WE ${FIL} NAME_WE) list(APPEND ${SRCS} "${PATH}/${FIL_WE}.pb.cc") list(APPEND ${HDRS} "${PATH}/${FIL_WE}.pb.h") #execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ${PATH}) add_custom_command( OUTPUT "${PATH}/${FIL_WE}.pb.cc" "${PATH}/${FIL_WE}.pb.h" # COMMAND ${Protobuf_PROTOC_EXECUTABLE} # /bin/sh: 1: -I: not found COMMAND ${PROTOBUF_PROTOC_EXECUTABLE} ARGS --cpp_out=${PATH} ${_protobuf_include_path} ${FIL} DEPENDS ${ABS_FIL} COMMENT "Running C++ protocol buffer compiler on ${FIL}" VERBATIM ) endforeach() set_source_files_properties(${${SRCS}} ${${HDRS}} PROPERTIES GENERATED TRUE) set(${SRCS} ${${SRCS}} PARENT_SCOPE) set(${HDRS} ${${HDRS}} PARENT_SCOPE) endfunction() ###### #grpc# ###### function(V2X_PROTOBUF_GENERATE_GRPC_CPP PATH SRCS HDRS) if(NOT ARGN) message(SEND_ERROR "Error: V2X_PROTOBUF_GENERATE_GRPC_CPP() called without any proto files") return() endif() if(PROTOBUF_GENERATE_CPP_APPEND_PATH) # This variable is common for all types of output. # Create an include path for each file specified foreach(FIL ${ARGN}) get_filename_component(ABS_FIL ${FIL} ABSOLUTE) get_filename_component(ABS_PATH ${ABS_FIL} PATH) list(FIND _protobuf_include_path ${ABS_PATH} _contains_already) if(${_contains_already} EQUAL -1) list(APPEND _protobuf_include_path -I ${ABS_PATH}) endif() endforeach() else() set(_protobuf_include_path -I ${CMAKE_CURRENT_SOURCE_DIR}) endif() if(DEFINED PROTOBUF_IMPORT_DIRS) foreach(DIR ${PROTOBUF_IMPORT_DIRS}) get_filename_component(ABS_PATH ${DIR} ABSOLUTE) list(FIND _protobuf_include_path ${ABS_PATH} _contains_already) if(${_contains_already} EQUAL -1) list(APPEND _protobuf_include_path -I ${ABS_PATH}) endif() endforeach() endif() set(${SRCS}) set(${HDRS}) foreach(FIL ${ARGN}) get_filename_component(ABS_FIL ${FIL} ABSOLUTE) get_filename_component(FIL_WE ${FIL} NAME_WE) list(APPEND ${SRCS} "${PATH}/${FIL_WE}.grpc.pb.cc") list(APPEND ${HDRS} "${PATH}/${FIL_WE}.grpc.pb.h") #execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ${PATH}) add_custom_command( OUTPUT "${PATH}/${FIL_WE}.grpc.pb.cc" "${PATH}/${FIL_WE}.grpc.pb.h" # COMMAND ${Protobuf_PROTOC_EXECUTABLE} # /bin/sh: 1: -I: not found COMMAND ${PROTOBUF_PROTOC_EXECUTABLE} ARGS --grpc_out=${PATH} --plugin=protoc-gen-grpc=${GRPC_CPP_PLUGIN} ${_protobuf_include_path} ${FIL} DEPENDS ${ABS_FIL} COMMENT "Running gRPC C++ protocol buffer compiler on ${FIL}" VERBATIM ) endforeach() set_source_files_properties(${${SRCS}} ${${HDRS}} PROPERTIES GENERATED TRUE) set(${SRCS} ${${SRCS}} PARENT_SCOPE) set(${HDRS} ${${HDRS}} PARENT_SCOPE) endfunction()
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto/perception_obstacle.proto
package apollo.perception; import "header.proto"; enum PerceptionErrorCode { ERROR_NONE = 0; ERROR_TF = 1; ERROR_PROCESS = 2; ERROR_UNKNOWN = 3; } message Point { optional double x = 1; // in meters. optional double y = 2; // in meters. optional double z = 3; // height in meters. } message BBox2D { optional double xmin = 1; // in pixels. optional double ymin = 2; // in pixels. optional double xmax = 3; // in pixels. optional double ymax = 4; // in pixels. } message LightStatus { optional double brake_visible = 1; optional double brake_switch_on = 2; optional double left_turn_visible = 3; optional double left_turn_switch_on = 4; optional double right_turn_visible = 5; optional double right_turn_switch_on = 6; } enum BrakeLight { BRAKE_DARK = 0; BRAKE_BRIGHT = 1; BRAKE_UNKNOWN = 2; } enum SubType { UNKNOWN = 0; UNKNOWN_MOVABLE = 1; UNKNOWN_UNMOVABLE = 2; CAR = 3; VAN = 4; TRUCK = 5; BUS = 6; CYCLIST = 7; MOTORCYCLIST = 8; TRICYCLIST = 9; PEDESTRIAN = 10; TRAFFICCONE = 11; } message SensorMeasurement { optional string sensor_id = 1; optional int32 id = 2; optional Point position = 3; optional double theta = 4; optional double length = 5; optional double width = 6; optional double height = 7; optional Point velocity = 8; enum Type { UNKNOWN = 0; UNKNOWN_MOVABLE = 1; UNKNOWN_UNMOVABLE = 2; PEDESTRIAN = 3; // Pedestrian, usually determined by moving behaviour. BICYCLE = 4; // bike, motor bike VEHICLE = 5; // Passenger car or truck. }; optional Type type = 9; optional SubType sub_type = 10; optional double timestamp = 11; optional BBox2D box = 12; // only for camera measurements } message PerceptionObstacle { optional int32 id = 1; // obstacle ID. optional Point position = 2; // obstacle position in the world coordinate system. optional double theta = 3; // heading in the world coordinate system. optional Point velocity = 4; // obstacle velocity. // Size of obstacle bounding box. optional double length = 5; // obstacle length. optional double width = 6; // obstacle width. optional double height = 7; // obstacle height. repeated Point polygon_point = 8; // obstacle corner points. optional double tracking_time = 9; // duration of an obstacle since detection in s. enum Type { UNKNOWN = 0; UNKNOWN_MOVABLE = 1; UNKNOWN_UNMOVABLE = 2; PEDESTRIAN = 3; // Pedestrian, usually determined by moving behaviour. BICYCLE = 4; // bike, motor bike VEHICLE = 5; // Passenger car or truck. }; optional Type type = 10; // obstacle type optional double timestamp = 11; // GPS time in seconds. // Just for offline debuging, onboard will not fill this field. // Format like : [x0, y0, z0, x1, y1, z1...] repeated double point_cloud = 12 [packed = true]; // a stable obstacle point in the world coordinate system // position defined above is the obstacle boundingbox ground center optional Point anchor_point = 13; // position covariance which is a row-majored 3x3 matrix repeated double position_covariance = 14 [packed = true]; // velocity covariance which is a row-majored 3x3 matrix repeated double velocity_covariance = 15 [packed = true]; // orthogonal distance between obstacle lowest point and ground plane optional double height_above_ground = 16 [default = nan]; optional BrakeLight brake_light = 17 [default = BRAKE_UNKNOWN]; optional LightStatus light_status = 18; optional BBox2D bbox2d = 19; optional SubType sub_type = 20; repeated SensorMeasurement measurements = 21; // sensor measurements optional Point acceleration = 22; // obstacle acceleration. // acceleration covariance which is a row-majored 3x3 matrix repeated double acceleration_covariance = 23 [packed = true]; } message PerceptionObstacles { repeated PerceptionObstacle perception_obstacle = 1; // An array of obstacles optional apollo.common.Header header = 2; // Header optional PerceptionErrorCode error_code = 3 [default = ERROR_NONE]; }
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto/v2x_traffic_light.proto
syntax = "proto2"; package apollo.v2x; import "header.proto"; message SingleTrafficLight { enum Color { UNKNOWN = 0; RED = 1; YELLOW = 2; GREEN = 3; BLACK = 4; FLASH_GREEN = 5; }; enum Type { STRAIGHT = 0; LEFT = 1; RIGHT = 2; U_TURN = 3; }; optional Color color = 1; repeated Type trafficlight_type = 2; // Traffic light string-ID in the map data. optional string id = 3; optional int32 color_remaining_time_s = 4; optional bool right_turn_light = 5; } message CurrentLaneTrafficLight { // Feature points of lane in the map reference frame. optional double gps_x_m = 1; optional double gps_y_m = 2; repeated SingleTrafficLight single_traffic_light = 3; } message IntersectionTrafficLightData { optional apollo.common.Header header = 1; optional CurrentLaneTrafficLight current_lane_trafficlight = 2; optional int32 intersection_id = 3; }
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto/chassis_detail.proto
syntax = "proto2"; package apollo.canbus; import "chassis.proto"; import "lexus.proto"; message ChassisDetail { enum Type { QIRUI_EQ_15 = 0; CHANGAN_RUICHENG = 1; } optional Type car_type = 1; // car type optional BasicInfo basic = 2; // basic info optional Safety safety = 3; // safety optional Gear gear = 4; // gear optional Ems ems = 5; // engine manager system optional Esp esp = 6; // Electronic Stability Program optional Gas gas = 7; // gas pedal optional Epb epb = 8; // Electronic parking brake optional Brake brake = 9; // brake pedal optional Deceleration deceleration = 10; // deceleration optional VehicleSpd vehicle_spd = 11; // vehicle speed optional Eps eps = 12; // Electronic Power Steering optional Light light = 13; // Light optional Battery battery = 14; // Battery info optional CheckResponseSignal check_response = 15; optional License license = 16; // License info optional Surround surround = 17; // Surround information optional Gem gem = 18; optional Lexus lexus = 19; } // CheckResponseSignal message CheckResponseSignal { optional bool is_eps_online = 1 [default = false]; // byd:0x34C qirui:0x505 optional bool is_epb_online = 2 [default = false]; // byd:0x218 optional bool is_esp_online = 3 [default = false]; // byd:0x122 qirui:0x451 optional bool is_vtog_online = 4 [default = false]; // byd:0x242 optional bool is_scu_online = 5 [default = false]; // byd:0x35C optional bool is_switch_online = 6 [default = false]; // byd:0x133 optional bool is_vcu_online = 7 [default = false]; // qirui:0x400 } // Battery message Battery { optional double battery_percent = 1; // unit:%, battery percentage left // lincoln fuellevel 72 optional double fuel_level = 2; } // light message Light { enum TurnLightType { TURN_LIGHT_OFF = 0; TURN_LEFT_ON = 1; TURN_RIGHT_ON = 2; TURN_LIGHT_ON = 3; } enum BeamLampType { BEAM_OFF = 0; HIGH_BEAM_ON = 1; LOW_BEAM_ON = 2; } enum LincolnLampType { BEAM_NULL = 0; BEAM_FLASH_TO_PASS = 1; BEAM_HIGH = 2; BEAM_INVALID = 3; } enum LincolnWiperType { WIPER_OFF = 0; WIPER_AUTO_OFF = 1; WIPER_OFF_MOVING = 2; WIPER_MANUAL_OFF = 3; WIPER_MANUAL_ON = 4; WIPER_MANUAL_LOW = 5; WIPER_MANUAL_HIGH = 6; WIPER_MIST_FLICK = 7; WIPER_WASH = 8; WIPER_AUTO_LOW = 9; WIPER_AUTO_HIGH = 10; WIPER_COURTESY_WIPE = 11; WIPER_AUTO_ADJUST = 12; WIPER_RESERVED = 13; WIPER_STALLED = 14; WIPER_NO_DATA = 15; } enum LincolnAmbientType { AMBIENT_DARK = 0; AMBIENT_LIGHT = 1; AMBIENT_TWILIGHT = 2; AMBIENT_TUNNEL_ON = 3; AMBIENT_TUNNEL_OFF = 4; AMBIENT_INVALID = 5; AMBIENT_NO_DATA = 7; } optional TurnLightType turn_light_type = 1; optional BeamLampType beam_lamp_type = 2; optional bool is_brake_lamp_on = 3; // byd switch 133 optional bool is_auto_light = 4; optional int32 wiper_gear = 5; optional int32 lotion_gear = 6; optional bool is_horn_on = 7; // lincoln misc 69 optional LincolnLampType lincoln_lamp_type = 8; optional LincolnWiperType lincoln_wiper = 9; optional LincolnAmbientType lincoln_ambient = 10; } // Electrical Power Steering message Eps { enum Type { NOT_AVAILABLE = 0; READY = 1; ACTIVE = 2; INVALID = 3; } // changan: eps 2a0 optional bool is_eps_fail = 1; // eps 2a0 optional Type eps_control_state = 2; // for changan to control steering optional double eps_driver_hand_torq = 3; // unit:Nm optional bool is_steering_angle_valid = 4; optional double steering_angle = 5; // unit:degree optional double steering_angle_spd = 6; // unit:degree/s // byd sas 11f optional bool is_trimming_status = 7; optional bool is_calibration_status = 8; optional bool is_failure_status = 9; optional int32 allow_enter_autonomous_mode = 10; optional int32 current_driving_mode = 11; // lincoln steering 65 optional double steering_angle_cmd = 12; optional double vehicle_speed = 13; optional double epas_torque = 14; optional bool steering_enabled = 15; optional bool driver_override = 16; optional bool driver_activity = 17; optional bool watchdog_fault = 18; optional bool channel_1_fault = 19; optional bool channel_2_fault = 20; optional bool calibration_fault = 21; optional bool connector_fault = 22; optional double timestamp_65 = 23; // lincoln version 7f optional int32 major_version = 24; optional int32 minor_version = 25; optional int32 build_number = 26; } message VehicleSpd { // esp 277 optional bool is_vehicle_standstill = 1; // esp 218 optional bool is_vehicle_spd_valid = 2; optional double vehicle_spd = 3 [default = 0]; // unit:m/s // esp 208 optional bool is_wheel_spd_rr_valid = 4; optional WheelSpeed.WheelSpeedType wheel_direction_rr = 5; optional double wheel_spd_rr = 6; optional bool is_wheel_spd_rl_valid = 7; optional WheelSpeed.WheelSpeedType wheel_direction_rl = 8; optional double wheel_spd_rl = 9; optional bool is_wheel_spd_fr_valid = 10; optional WheelSpeed.WheelSpeedType wheel_direction_fr = 11; optional double wheel_spd_fr = 12; optional bool is_wheel_spd_fl_valid = 13; optional WheelSpeed.WheelSpeedType wheel_direction_fl = 14; optional double wheel_spd_fl = 15; // byd esp 222 optional bool is_yaw_rate_valid = 16; optional double yaw_rate = 17; optional double yaw_rate_offset = 18; // byd esp 223 optional bool is_ax_valid = 19; optional double ax = 20; optional double ax_offset = 21; optional bool is_ay_valid = 22; optional double ay = 23; optional double ay_offset = 24; // lincoln accel 6b optional double lat_acc = 25; optional double long_acc = 26; optional double vert_acc = 27; // lincoln gyro 6c optional double roll_rate = 28; // lincoln brakeinfo 74 optional double acc_est = 29; // lincoln wheelspeed 6a optional double timestamp_sec = 30; } message Deceleration { // esp 277 optional bool is_deceleration_available = 1; // for changan to send deceleration value optional bool is_deceleration_active = 2; // for changan to send deceleration value optional double deceleration = 3 [default = 0]; optional double is_evb_fail = 4; optional double evb_pressure = 5 [default = 0]; // mpa, 0~25.5 optional double brake_pressure = 6 [default = 0]; optional double brake_pressure_spd = 7 [default = 0]; } message Brake { enum HSAStatusType { HSA_INACTIVE = 0; HSA_FINDING_GRADIENT = 1; HSA_ACTIVE_PRESSED = 2; HSA_ACTIVE_RELEASED = 3; HSA_FAST_RELEASE = 4; HSA_SLOW_RELEASE = 5; HSA_FAILED = 6; HSA_UNDEFINED = 7; } enum HSAModeType { HSA_OFF = 0; HSA_AUTO = 1; HSA_MANUAL = 2; HSA_MODE_UNDEFINED = 3; } // ems 255 optional bool is_brake_pedal_pressed = 1 [default = false]; // only manual brake // esp 277 optional bool is_brake_force_exist = 2; // no matter auto mode brake or manual brake optional bool is_brake_over_heat = 3; optional bool is_hand_brake_on = 4; // hand brake optional double brake_pedal_position = 5; // byd vtog 342 optional bool is_brake_valid = 6; // lincoln brake 61 optional double brake_input = 7; optional double brake_cmd = 8; optional double brake_output = 9; optional bool boo_input = 10; optional bool boo_cmd = 11; optional bool boo_output = 12; optional bool watchdog_applying_brakes = 13; optional int32 watchdog_source = 14; optional bool brake_enabled = 15; optional bool driver_override = 16; optional bool driver_activity = 17; optional bool watchdog_fault = 18; optional bool channel_1_fault = 19; optional bool channel_2_fault = 20; optional bool boo_fault = 21; optional bool connector_fault = 22; // lincoln brakeinfo 74 optional double brake_torque_req = 23; optional HSAStatusType hsa_status = 24; optional double brake_torque_act = 25; optional HSAModeType hsa_mode = 26; optional double wheel_torque_act = 27; // lincoln version 7f optional int32 major_version = 28; optional int32 minor_version = 29; optional int32 build_number = 30; } // Electrical Parking Brake message Epb { enum PBrakeType { PBRAKE_OFF = 0; PBRAKE_TRANSITION = 1; PBRAKE_ON = 2; PBRAKE_FAULT = 3; } // epb 256 optional bool is_epb_error = 1; optional bool is_epb_released = 2; // byd epb 218 optional int32 epb_status = 3; // lincoln brakeinfo 74 optional PBrakeType parking_brake_status = 4; } message Gas { // ems 255 optional bool is_gas_pedal_error = 1; // ems 26a optional bool is_gas_pedal_pressed_more = 2; // more than auto mode gas torq optional double gas_pedal_position = 3 [default = 0]; // manual gas // byd vtog 342 optional bool is_gas_valid = 4 [default = false]; // lincoln throttle 63 optional double throttle_input = 5; optional double throttle_cmd = 6; optional double throttle_output = 7; optional int32 watchdog_source = 8; optional bool throttle_enabled = 9; optional bool driver_override = 10; optional bool driver_activity = 11; optional bool watchdog_fault = 12; optional bool channel_1_fault = 13; optional bool channel_2_fault = 14; optional bool connector_fault = 15; // lincoln throttleinfo 75 optional double accelerator_pedal = 16; optional double accelerator_pedal_rate = 17; // lincoln version 7f optional int32 major_version = 18; optional int32 minor_version = 19; optional int32 build_number = 20; } // Electronic Stability Program message Esp { // esp 277 optional bool is_esp_acc_error = 1; // for changan to control car // esp 218 optional bool is_esp_on = 2; optional bool is_esp_active = 3; optional bool is_abs_error = 4; optional bool is_abs_active = 5; optional bool is_tcsvdc_fail = 6; // lincoln brakeinfo 74 optional bool is_abs_enabled = 7; optional bool is_stab_active = 8; optional bool is_stab_enabled = 9; optional bool is_trac_active = 10; optional bool is_trac_enabled = 11; } // Engine Manager System message Ems { enum Type { STOP = 0; CRANK = 1; RUNNING = 2; INVALID = 3; } // ems 26a optional bool is_engine_acc_available = 1; // for changan to control car optional bool is_engine_acc_error = 2; // for changan to control car // ems 265 optional Type engine_state = 3; optional double max_engine_torq_percent = 4; // for engine torq control, unit:% optional double min_engine_torq_percent = 5; // for engine torq control, unit:% optional int32 base_engine_torq_constant = 6; // for engine torq control, unit:Nm // ems 255 optional bool is_engine_speed_error = 7; optional double engine_speed = 8; // byd vtog 241 optional int32 engine_torque = 9; // byd vtog 242 optional bool is_over_engine_torque = 10; // lincoln mkz throttleinfo 75 optional double engine_rpm = 11; } message Gear { // tcu 268 optional bool is_shift_position_valid = 1; // chanan: tcu 268 optional Chassis.GearPosition gear_state = 2; // lincoln gear 67 optional bool driver_override = 3; optional Chassis.GearPosition gear_cmd = 4; optional bool canbus_fault = 5; } message Safety { // ip 270 optional bool is_driver_car_door_close = 1; // sas 50 optional bool is_driver_buckled = 2; // byd sws 4a8 optional int32 emergency_button = 3; // qirui:403 // when car chassis error, like system fault, or warning report optional bool has_error = 4 [default = false]; optional bool is_motor_invertor_fault = 5; optional bool is_system_fault = 6; optional bool is_power_battery_fault = 7; optional bool is_motor_invertor_over_temperature = 8; optional bool is_small_battery_charge_discharge_fault = 9; optional int32 driving_mode = 10; // lincoln misc 69 optional bool is_passenger_door_open = 11; optional bool is_rearleft_door_open = 12; optional bool is_rearright_door_open = 13; optional bool is_hood_open = 14; optional bool is_trunk_open = 15; optional bool is_passenger_detected = 16; optional bool is_passenger_airbag_enabled = 17; optional bool is_passenger_buckled = 18; // lincoln tirepressure 71 optional int32 front_left_tire_press = 19; optional int32 front_right_tire_press = 20; optional int32 rear_left_tire_press = 21; optional int32 rear_right_tire_press = 22; optional Chassis.DrivingMode car_driving_mode = 23; } message BasicInfo { enum Type { OFF = 0; ACC = 1; ON = 2; START = 3; INVALID = 4; } optional bool is_auto_mode = 1; optional Type power_state = 2; optional bool is_air_bag_deployed = 3; optional double odo_meter = 4; // odo meter, unit:km optional double drive_range = 5; // the meter left when drive continuously, unit:km optional bool is_system_error = 6; optional bool is_human_interrupt = 7; // human interrupt // lincoln misc 69 optional bool acc_on_button = 8; // acc on button pressed optional bool acc_off_button = 9; optional bool acc_res_button = 10; optional bool acc_cancel_button = 11; optional bool acc_on_off_button = 12; optional bool acc_res_cancel_button = 13; optional bool acc_inc_spd_button = 14; optional bool acc_dec_spd_button = 15; optional bool acc_inc_gap_button = 16; optional bool acc_dec_gap_button = 17; optional bool lka_button = 18; optional bool canbus_fault = 19; // lincoln gps 6d optional double latitude = 20; optional double longitude = 21; optional bool gps_valid = 22; // lincoln gps 6e optional int32 year = 23; optional int32 month = 24; optional int32 day = 25; optional int32 hours = 26; optional int32 minutes = 27; optional int32 seconds = 28; optional double compass_direction = 29; optional double pdop = 30; optional bool is_gps_fault = 31; optional bool is_inferred = 32; // lincoln gps 6f optional double altitude = 33; optional double heading = 34; optional double hdop = 35; optional double vdop = 36; optional GpsQuality quality = 37; optional int32 num_satellites = 38; optional double gps_speed = 39; } // Gem vehicle starts from here // TODO(QiL) : Re-factor needed here message Global_rpt_6a { // Report Message enum Pacmod_statusType { PACMOD_STATUS_CONTROL_DISABLED = 0; PACMOD_STATUS_CONTROL_ENABLED = 1; } enum Override_statusType { OVERRIDE_STATUS_NOT_OVERRIDDEN = 0; OVERRIDE_STATUS_OVERRIDDEN = 1; } enum Brk_can_timeoutType { BRK_CAN_TIMEOUT_NO_ACTIVE_CAN_TIMEOUT = 0; BRK_CAN_TIMEOUT_ACTIVE_CAN_TIMEOUT = 1; } // [] [0|1] optional Pacmod_statusType pacmod_status = 1; // [] [0|1] optional Override_statusType override_status = 2; // [] [0|1] optional bool veh_can_timeout = 3; // [] [0|1] optional bool str_can_timeout = 4; // [] [0|1] optional Brk_can_timeoutType brk_can_timeout = 5; // [] [0|1] optional bool usr_can_timeout = 6; // [] [0|65535] optional int32 usr_can_read_errors = 7; } message Brake_cmd_6b { // Report Message // [%] [0|1] optional double brake_cmd = 1; } message Brake_rpt_6c { // Report Message enum Brake_on_offType { BRAKE_ON_OFF_OFF = 0; BRAKE_ON_OFF_ON = 1; } // [%] [0|1] optional double manual_input = 1; // [%] [0|1] optional double commanded_value = 2; // [%] [0|1] optional double output_value = 3; // [] [0|1] optional Brake_on_offType brake_on_off = 4; } message Steering_cmd_6d { // Report Message // [radians] [-2147483.648|2147483.647] optional double position_value = 1; // [rad/s] [0|65.535] optional double speed_limit = 2; } message Steering_rpt_1_6e { // Report Message // [rad/s] [-32.768|32.767] optional double manual_input = 1; // [rad/s] [-32.768|32.767] optional double commanded_value = 2; // [rad/s] [-32.768|32.767] optional double output_value = 3; } message Wheel_speed_rpt_7a { // Report Message // [rad/s] [-32768|32767] optional int32 wheel_spd_rear_right = 1; // [rad/s] [-32768|32767] optional int32 wheel_spd_rear_left = 2; // [rad/s] [-32768|32767] optional int32 wheel_spd_front_right = 3; // [rad/s] [-32768|32767] optional int32 wheel_spd_front_left = 4; } message Date_time_rpt_83 { // Report Message // [sec] [0|60] optional int32 time_second = 1; // [min] [0|60] optional int32 time_minute = 2; // [hr] [0|23] optional int32 time_hour = 3; // [dy] [1|31] optional int32 date_day = 4; // [mon] [1|12] optional int32 date_month = 5; // [yr] [2000|2255] optional int32 date_year = 6; } message Brake_motor_rpt_1_70 { // Report Message // [amps] [0|4294967.295] optional double motor_current = 1; // [radians] [-2147483.648|2147483.647] optional double shaft_position = 2; } message Headlight_rpt_77 { // Report Message enum Output_valueType { OUTPUT_VALUE_HEADLIGHTS_OFF = 0; OUTPUT_VALUE_LOW_BEAMS = 1; OUTPUT_VALUE_HIGH_BEAMS = 2; } enum Manual_inputType { MANUAL_INPUT_HEADLIGHTS_OFF = 0; MANUAL_INPUT_LOW_BEAMS = 1; MANUAL_INPUT_HIGH_BEAMS = 2; } enum Commanded_valueType { COMMANDED_VALUE_HEADLIGHTS_OFF = 0; COMMANDED_VALUE_LOW_BEAMS = 1; COMMANDED_VALUE_HIGH_BEAMS = 2; } // [] [0|2] optional Output_valueType output_value = 1; // [] [0|2] optional Manual_inputType manual_input = 2; // [] [0|2] optional Commanded_valueType commanded_value = 3; } message Accel_rpt_68 { // Report Message // [%] [0|1] optional double manual_input = 1; // [%] [0|1] optional double commanded_value = 2; // [%] [0|1] optional double output_value = 3; } message Steering_motor_rpt_3_75 { // Report Message // [N-m] [-2147483.648|2147483.647] optional double torque_output = 1; // [N-m] [-2147483.648|2147483.647] optional double torque_input = 2; } message Turn_cmd_63 { // Report Message enum Turn_signal_cmdType { TURN_SIGNAL_CMD_RIGHT = 0; TURN_SIGNAL_CMD_NONE = 1; TURN_SIGNAL_CMD_LEFT = 2; TURN_SIGNAL_CMD_HAZARD = 3; } // [] [0|3] optional Turn_signal_cmdType turn_signal_cmd = 1; } message Turn_rpt_64 { // Report Message enum Manual_inputType { MANUAL_INPUT_RIGHT = 0; MANUAL_INPUT_NONE = 1; MANUAL_INPUT_LEFT = 2; MANUAL_INPUT_HAZARD = 3; } enum Commanded_valueType { COMMANDED_VALUE_RIGHT = 0; COMMANDED_VALUE_NONE = 1; COMMANDED_VALUE_LEFT = 2; COMMANDED_VALUE_HAZARD = 3; } enum Output_valueType { OUTPUT_VALUE_RIGHT = 0; OUTPUT_VALUE_NONE = 1; OUTPUT_VALUE_LEFT = 2; OUTPUT_VALUE_HAZARD = 3; } // [] [0|3] optional Manual_inputType manual_input = 1; // [] [0|3] optional Commanded_valueType commanded_value = 2; // [] [0|3] optional Output_valueType output_value = 3; } message Shift_cmd_65 { // Report Message enum Shift_cmdType { SHIFT_CMD_PARK = 0; SHIFT_CMD_REVERSE = 1; SHIFT_CMD_NEUTRAL = 2; SHIFT_CMD_FORWARD = 3; SHIFT_CMD_LOW = 4; } // FORWARD_is_also_LOW_on_vehicles_with_LOW/HIGH,_PARK_and_HIGH_only_available_on_certain_Vehicles // [] [0|4] optional Shift_cmdType shift_cmd = 1; } message Shift_rpt_66 { // Report Message enum Manual_inputType { MANUAL_INPUT_PARK = 0; MANUAL_INPUT_REVERSE = 1; MANUAL_INPUT_NEUTRAL = 2; MANUAL_INPUT_FORWARD = 3; MANUAL_INPUT_HIGH = 4; } enum Commanded_valueType { COMMANDED_VALUE_PARK = 0; COMMANDED_VALUE_REVERSE = 1; COMMANDED_VALUE_NEUTRAL = 2; COMMANDED_VALUE_FORWARD = 3; COMMANDED_VALUE_HIGH = 4; } enum Output_valueType { OUTPUT_VALUE_PARK = 0; OUTPUT_VALUE_REVERSE = 1; OUTPUT_VALUE_NEUTRAL = 2; OUTPUT_VALUE_FORWARD = 3; OUTPUT_VALUE_HIGH = 4; } // [] [0|4] optional Manual_inputType manual_input = 1; // [] [0|4] optional Commanded_valueType commanded_value = 2; // [] [0|4] optional Output_valueType output_value = 3; } message Accel_cmd_67 { // Report Message // [%] [0|1] optional double accel_cmd = 1; } message Lat_lon_heading_rpt_82 { // Report Message // [deg] [-327.68|327.67] optional double heading = 1; // [sec] [-128|127] optional int32 longitude_seconds = 2; // [min] [-128|127] optional int32 longitude_minutes = 3; // [deg] [-128|127] optional int32 longitude_degrees = 4; // [sec] [-128|127] optional int32 latitude_seconds = 5; // [min] [-128|127] optional int32 latitude_minutes = 6; // [deg] [-128|127] optional int32 latitude_degrees = 7; } message Global_cmd_69 { // Report Message enum Pacmod_enableType { PACMOD_ENABLE_CONTROL_DISABLED = 0; PACMOD_ENABLE_CONTROL_ENABLED = 1; } enum Clear_overrideType { CLEAR_OVERRIDE_DON_T_CLEAR_ACTIVE_OVERRIDES = 0; CLEAR_OVERRIDE_CLEAR_ACTIVE_OVERRIDES = 1; } enum Ignore_overrideType { IGNORE_OVERRIDE_DON_T_IGNORE_USER_OVERRIDES = 0; IGNORE_OVERRIDE_IGNORE_USER_OVERRIDES = 1; } // [] [0|1] optional Pacmod_enableType pacmod_enable = 1; // [] [0|1] optional Clear_overrideType clear_override = 2; // [] [0|1] optional Ignore_overrideType ignore_override = 3; } message Parking_brake_status_rpt_80 { // Report Message enum Parking_brake_enabledType { PARKING_BRAKE_ENABLED_OFF = 0; PARKING_BRAKE_ENABLED_ON = 1; } // [] [0|1] optional Parking_brake_enabledType parking_brake_enabled = 1; } message Yaw_rate_rpt_81 { // Report Message // [rad/s] [-327.68|327.67] optional double yaw_rate = 1; } message Horn_rpt_79 { // Report Message enum Output_valueType { OUTPUT_VALUE_OFF = 0; OUTPUT_VALUE_ON = 1; } enum Commanded_valueType { COMMANDED_VALUE_OFF = 0; COMMANDED_VALUE_ON = 1; } enum Manual_inputType { MANUAL_INPUT_OFF = 0; MANUAL_INPUT_ON = 1; } // [] [0|1] optional Output_valueType output_value = 1; // [] [0|1] optional Commanded_valueType commanded_value = 2; // [] [0|1] optional Manual_inputType manual_input = 3; } message Horn_cmd_78 { // Report Message enum Horn_cmdType { HORN_CMD_OFF = 0; HORN_CMD_ON = 1; } // [] [0|1] optional Horn_cmdType horn_cmd = 1; } message Wiper_rpt_91 { // Report Message enum Output_valueType { OUTPUT_VALUE_WIPERS_OFF = 0; OUTPUT_VALUE_INTERMITTENT_1 = 1; OUTPUT_VALUE_INTERMITTENT_2 = 2; OUTPUT_VALUE_INTERMITTENT_3 = 3; OUTPUT_VALUE_INTERMITTENT_4 = 4; OUTPUT_VALUE_INTERMITTENT_5 = 5; OUTPUT_VALUE_LOW = 6; OUTPUT_VALUE_HIGH = 7; } enum Commanded_valueType { COMMANDED_VALUE_WIPERS_OFF = 0; COMMANDED_VALUE_INTERMITTENT_1 = 1; COMMANDED_VALUE_INTERMITTENT_2 = 2; COMMANDED_VALUE_INTERMITTENT_3 = 3; COMMANDED_VALUE_INTERMITTENT_4 = 4; COMMANDED_VALUE_INTERMITTENT_5 = 5; COMMANDED_VALUE_LOW = 6; COMMANDED_VALUE_HIGH = 7; } enum Manual_inputType { MANUAL_INPUT_WIPERS_OFF = 0; MANUAL_INPUT_INTERMITTENT_1 = 1; MANUAL_INPUT_INTERMITTENT_2 = 2; MANUAL_INPUT_INTERMITTENT_3 = 3; MANUAL_INPUT_INTERMITTENT_4 = 4; MANUAL_INPUT_INTERMITTENT_5 = 5; MANUAL_INPUT_LOW = 6; MANUAL_INPUT_HIGH = 7; } // [] [0|7] optional Output_valueType output_value = 1; // [] [0|7] optional Commanded_valueType commanded_value = 2; // [] [0|7] optional Manual_inputType manual_input = 3; } message Vehicle_speed_rpt_6f { // Report Message enum Vehicle_speed_validType { VEHICLE_SPEED_VALID_INVALID = 0; VEHICLE_SPEED_VALID_VALID = 1; } // [m/s] [-327.68|327.67] optional double vehicle_speed = 1; // [] [0|1] optional Vehicle_speed_validType vehicle_speed_valid = 2; } message Headlight_cmd_76 { // Report Message enum Headlight_cmdType { HEADLIGHT_CMD_HEADLIGHTS_OFF = 0; HEADLIGHT_CMD_LOW_BEAMS = 1; HEADLIGHT_CMD_HIGH_BEAMS = 2; } // [] [0|2] optional Headlight_cmdType headlight_cmd = 1; } message Steering_motor_rpt_2_74 { // Report Message // [deg C] [-32808|32727] optional int32 encoder_temperature = 1; // [deg C] [-32808|32727] optional int32 motor_temperature = 2; // [rev/s] [-2147483.648|2147483.647] optional double angular_speed = 3; } message Brake_motor_rpt_2_71 { // Report Message // [deg C] [-32808|32727] optional int32 encoder_temperature = 1; // [deg C] [-32808|32727] optional int32 motor_temperature = 2; // [rev/s] [0|4294967.295] optional double angular_speed = 3; } message Steering_motor_rpt_1_73 { // Report Message // [amps] [0|4294967.295] optional double motor_current = 1; // [amps] [-2147483.648|2147483.647] optional double shaft_position = 2; } message Wiper_cmd_90 { // Report Message enum Wiper_cmdType { WIPER_CMD_WIPERS_OFF = 0; WIPER_CMD_INTERMITTENT_1 = 1; WIPER_CMD_INTERMITTENT_2 = 2; WIPER_CMD_INTERMITTENT_3 = 3; WIPER_CMD_INTERMITTENT_4 = 4; WIPER_CMD_INTERMITTENT_5 = 5; WIPER_CMD_LOW = 6; WIPER_CMD_HIGH = 7; } // [] [0|7] optional Wiper_cmdType wiper_cmd = 1; } message Brake_motor_rpt_3_72 { // Report Message // [N-m] [-2147483.648|2147483.647] optional double torque_output = 1; // [N-m] [-2147483.648|2147483.647] optional double torque_input = 2; } message Gem { optional Global_rpt_6a global_rpt_6a = 1; // report message optional Brake_cmd_6b brake_cmd_6b = 2; // report message optional Brake_rpt_6c brake_rpt_6c = 3; // report message optional Steering_cmd_6d steering_cmd_6d = 4; // report message optional Steering_rpt_1_6e steering_rpt_1_6e = 5; // report message optional Wheel_speed_rpt_7a wheel_speed_rpt_7a = 6; // report message optional Date_time_rpt_83 date_time_rpt_83 = 7; // report message optional Brake_motor_rpt_1_70 brake_motor_rpt_1_70 = 8; // report message optional Headlight_rpt_77 headlight_rpt_77 = 9; // report message optional Accel_rpt_68 accel_rpt_68 = 10; // report message optional Steering_motor_rpt_3_75 steering_motor_rpt_3_75 = 11; // report message optional Turn_cmd_63 turn_cmd_63 = 12; // report message optional Turn_rpt_64 turn_rpt_64 = 13; // report message optional Shift_cmd_65 shift_cmd_65 = 14; // report message optional Shift_rpt_66 shift_rpt_66 = 15; // report message optional Accel_cmd_67 accel_cmd_67 = 16; // report message optional Lat_lon_heading_rpt_82 lat_lon_heading_rpt_82 = 17; // report message optional Global_cmd_69 global_cmd_69 = 18; // report message optional Parking_brake_status_rpt_80 parking_brake_status_rpt_80 = 19; // report message optional Yaw_rate_rpt_81 yaw_rate_rpt_81 = 20; // report message optional Horn_rpt_79 horn_rpt_79 = 21; // report message optional Horn_cmd_78 horn_cmd_78 = 22; // report message optional Wiper_rpt_91 wiper_rpt_91 = 23; // report message optional Vehicle_speed_rpt_6f vehicle_speed_rpt_6f = 24; // report message optional Headlight_cmd_76 headlight_cmd_76 = 25; // report message optional Steering_motor_rpt_2_74 steering_motor_rpt_2_74 = 26; // report message optional Brake_motor_rpt_2_71 brake_motor_rpt_2_71 = 27; // report message optional Steering_motor_rpt_1_73 steering_motor_rpt_1_73 = 28; // report message optional Wiper_cmd_90 wiper_cmd_90 = 29; // report message optional Brake_motor_rpt_3_72 brake_motor_rpt_3_72 = 30; // report message }
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto/drive_event.proto
syntax = "proto2"; package apollo.common; import "header.proto"; import "pose.proto"; message DriveEvent { enum Type { CRITICAL = 0; PROBLEM = 1; DESIRED = 2; OUT_OF_SCOPE = 3; } optional apollo.common.Header header = 1; optional string event = 2; optional apollo.localization.Pose location = 3; repeated Type type = 4; }
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto/geometry.proto
syntax = "proto2"; package apollo.common; // A point in the map reference frame. The map defines an origin, whose // coordinate is (0, 0, 0). // Most modules, including localization, perception, and prediction, generate // results based on the map reference frame. // Currently, the map uses Universal Transverse Mercator (UTM) projection. See // the link below for the definition of map origin. // https://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system // The z field of PointENU can be omitted. If so, it is a 2D location and we do // not care its height. message PointENU { optional double x = 1 [default = nan]; // East from the origin, in meters. optional double y = 2 [default = nan]; // North from the origin, in meters. optional double z = 3 [default = 0.0]; // Up from the WGS-84 ellipsoid, in // meters. } // A point in the global reference frame. Similar to PointENU, PointLLH allows // omitting the height field for representing a 2D location. message PointLLH { // Longitude in degrees, ranging from -180 to 180. optional double lon = 1 [default = nan]; // Latitude in degrees, ranging from -90 to 90. optional double lat = 2 [default = nan]; // WGS-84 ellipsoid height in meters. optional double height = 3 [default = 0.0]; } // A general 2D point. Its meaning and units depend on context, and must be // explained in comments. message Point2D { optional double x = 1 [default = nan]; optional double y = 2 [default = nan]; } // A general 3D point. Its meaning and units depend on context, and must be // explained in comments. message Point3D { optional double x = 1 [default = nan]; optional double y = 2 [default = nan]; optional double z = 3 [default = nan]; } // A unit quaternion that represents a spatial rotation. See the link below for // details. // https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation // The scalar part qw can be omitted. In this case, qw should be calculated by // qw = sqrt(1 - qx * qx - qy * qy - qz * qz). message Quaternion { optional double qx = 1 [default = nan]; optional double qy = 2 [default = nan]; optional double qz = 3 [default = nan]; optional double qw = 4 [default = nan]; } // A general polygon, points are counter clockwise message Polygon { repeated Point3D point = 1; }
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto/v2x_service_obu_to_car.proto
syntax = "proto2"; package apollo.v2x; import "perception_obstacle.proto"; import "traffic_light_detection.proto"; import "v2x_traffic_light.proto"; service ObuToCar { // for onboard unit send perception obstacles (from rsu) results to car end rpc SendPerceptionObstacles (apollo.perception.PerceptionObstacles) returns (StatusResponse) {} // for onboard unit send perception trafficlights (from rsu) results to car end rpc SendPerceptionTrafficLight (apollo.perception.TrafficLightDetection) returns (StatusResponse) {} // for onboard unit send v2x trafficlights (from rsu) results to car end rpc SendV2xTrafficLight (apollo.v2x.IntersectionTrafficLightData) returns (StatusResponse) {} } // The response message containing the status. message StatusResponse { required bool status = 1 [default = false]; optional string info = 2; optional int64 error_code = 3; }
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto/vehicle_signal.proto
syntax = "proto2"; package apollo.common; message VehicleSignal { enum TurnSignal { TURN_NONE = 0; TURN_LEFT = 1; TURN_RIGHT = 2; }; optional TurnSignal turn_signal = 1; // lights enable command optional bool high_beam = 2; optional bool low_beam = 3; optional bool horn = 4; optional bool emergency_light = 5; }
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto/lexus.proto
syntax = "proto2"; package apollo.canbus; message Hazard_lights_rpt_214 { // Report Message // [] [0|1] optional bool output_value = 1; // [] [0|1] optional bool commanded_value = 2; // [] [0|1] optional bool manual_input = 3; // [] [0|1] optional bool vehicle_fault = 4; // [] [0|1] optional bool pacmod_fault = 5; // [] [0|1] optional bool override_active = 6; // [] [0|1] optional bool output_reported_fault = 7; // [] [0|1] optional bool input_output_fault = 8; // [] [0|1] optional bool enabled = 9; // [] [0|1] optional bool command_output_fault = 10; } message Steering_cmd_12c { // Report Message // [] [0|1] optional bool ignore_overrides = 1; // [] [0|1] optional bool enable = 2; // [] [0|1] optional bool clear_override = 3; // [] [0|1] optional bool clear_faults = 4; // [rad] [-32.768|32.767] optional double position = 5; // [rad/s] [0|65.535] optional double rotation_rate = 6; } message Dash_controls_right_rpt_210 { // Control Message enum Output_valueType { OUTPUT_VALUE_DASH_CONTROL_NONE = 0; OUTPUT_VALUE_DASH_CONTROL_OK = 1; OUTPUT_VALUE_DASH_CONTROL_LEFT = 2; OUTPUT_VALUE_DASH_CONTROL_RIGHT = 3; OUTPUT_VALUE_DASH_CONTROL_UP = 4; OUTPUT_VALUE_DASH_CONTROL_DOWN = 5; } enum Commanded_valueType { COMMANDED_VALUE_DASH_CONTROL_NONE = 0; COMMANDED_VALUE_DASH_CONTROL_OK = 1; COMMANDED_VALUE_DASH_CONTROL_LEFT = 2; COMMANDED_VALUE_DASH_CONTROL_RIGHT = 3; COMMANDED_VALUE_DASH_CONTROL_UP = 4; COMMANDED_VALUE_DASH_CONTROL_DOWN = 5; } enum Manual_inputType { MANUAL_INPUT_DASH_CONTROL_NONE = 0; MANUAL_INPUT_DASH_CONTROL_OK = 1; MANUAL_INPUT_DASH_CONTROL_LEFT = 2; MANUAL_INPUT_DASH_CONTROL_RIGHT = 3; MANUAL_INPUT_DASH_CONTROL_UP = 4; MANUAL_INPUT_DASH_CONTROL_DOWN = 5; } // [] [0|255] optional Output_valueType output_value = 1; // [] [0|255] optional Commanded_valueType commanded_value = 2; // [] [0|1] optional bool vehicle_fault = 3; // [] [0|1] optional bool pacmod_fault = 4; // [] [0|1] optional bool override_active = 5; // [] [0|1] optional bool output_reported_fault = 6; // [] [0|1] optional bool input_output_fault = 7; // [] [0|1] optional bool enabled = 8; // [] [0|1] optional bool command_output_fault = 9; // [] [0|255] optional Manual_inputType manual_input = 10; } message Dash_controls_left_cmd_10c { // Report Message enum Dash_controls_buttonType { DASH_CONTROLS_BUTTON_DASH_CONTROL_NONE = 0; DASH_CONTROLS_BUTTON_DASH_CONTROL_OK = 1; DASH_CONTROLS_BUTTON_DASH_CONTROL_LEFT = 2; DASH_CONTROLS_BUTTON_DASH_CONTROL_RIGHT = 3; DASH_CONTROLS_BUTTON_DASH_CONTROL_UP = 4; DASH_CONTROLS_BUTTON_DASH_CONTROL_DOWN = 5; } // [] [0|1] optional bool ignore_overrides = 1; // [] [0|1] optional bool enable = 2; // [] [0|1] optional bool clear_override = 3; // [] [0|1] optional bool clear_faults = 4; // [] [0|255] optional Dash_controls_buttonType dash_controls_button = 5; } message Steering_rpt_22c { // Report Message // [] [0|1] optional bool vehicle_fault = 1; // [] [0|1] optional bool pacmod_fault = 2; // [] [0|1] optional bool override_active = 3; // [] [0|1] optional bool output_reported_fault = 4; // [] [0|1] optional bool input_output_fault = 5; // [] [0|1] optional bool enabled = 6; // [] [0|1] optional bool command_output_fault = 7; // [rad] [-32.768|32.767] optional double manual_input = 8; // [rad] [-32.768|32.767] optional double commanded_value = 9; // [rad] [-32.768|32.767] optional double output_value = 10; } message Turn_aux_rpt_330 { // Report Message // [] [0|1] optional bool pass_blinker_bulb_on_is_valid = 1; // [] [0|1] optional bool pass_blinker_bulb_on = 2; // [] [0|1] optional bool driver_blinker_bulb_on_is_valid = 3; // [] [0|1] optional bool driver_blinker_bulb_on = 4; } message Headlight_rpt_218 { // Report Message enum Output_valueType { OUTPUT_VALUE_HEADLIGHTS_OFF = 0; OUTPUT_VALUE_LOW_BEAMS = 1; OUTPUT_VALUE_HIGH_BEAMS = 2; } enum Manual_inputType { MANUAL_INPUT_HEADLIGHTS_OFF = 0; MANUAL_INPUT_LOW_BEAMS = 1; MANUAL_INPUT_HIGH_BEAMS = 2; } enum Commanded_valueType { COMMANDED_VALUE_HEADLIGHTS_OFF = 0; COMMANDED_VALUE_LOW_BEAMS = 1; COMMANDED_VALUE_HIGH_BEAMS = 2; } // [] [0|1] optional bool vehicle_fault = 1; // [] [0|1] optional bool pacmod_fault = 2; // [] [0|1] optional bool override_active = 3; // [] [0|1] optional bool output_reported_fault = 4; // [] [0|1] optional bool input_output_fault = 5; // [] [0|1] optional bool enabled = 6; // [] [0|1] optional bool command_output_fault = 7; // [] [0|2] optional Output_valueType output_value = 8; // [] [0|2] optional Manual_inputType manual_input = 9; // [] [0|2] optional Commanded_valueType commanded_value = 10; } message Hazard_lights_cmd_114 { // Control Message // [] [0|1] optional bool hazard_lights_cmd = 1; // [] [0|1] optional bool ignore_overrides = 2; // [] [0|1] optional bool clear_override = 3; // [] [0|1] optional bool enable = 4; // [] [0|1] optional bool clear_faults = 5; } message Dash_controls_left_rpt_20c { // Report Message enum Output_valueType { OUTPUT_VALUE_DASH_CONTROL_NONE = 0; OUTPUT_VALUE_DASH_CONTROL_OK = 1; OUTPUT_VALUE_DASH_CONTROL_LEFT = 2; OUTPUT_VALUE_DASH_CONTROL_RIGHT = 3; OUTPUT_VALUE_DASH_CONTROL_UP = 4; OUTPUT_VALUE_DASH_CONTROL_DOWN = 5; } enum Commanded_valueType { COMMANDED_VALUE_DASH_CONTROL_NONE = 0; COMMANDED_VALUE_DASH_CONTROL_OK = 1; COMMANDED_VALUE_DASH_CONTROL_LEFT = 2; COMMANDED_VALUE_DASH_CONTROL_RIGHT = 3; COMMANDED_VALUE_DASH_CONTROL_UP = 4; COMMANDED_VALUE_DASH_CONTROL_DOWN = 5; } enum Manual_inputType { MANUAL_INPUT_DASH_CONTROL_NONE = 0; MANUAL_INPUT_DASH_CONTROL_OK = 1; MANUAL_INPUT_DASH_CONTROL_LEFT = 2; MANUAL_INPUT_DASH_CONTROL_RIGHT = 3; MANUAL_INPUT_DASH_CONTROL_UP = 4; MANUAL_INPUT_DASH_CONTROL_DOWN = 5; } // [] [0|255] optional Output_valueType output_value = 1; // [] [0|255] optional Commanded_valueType commanded_value = 2; // [] [0|255] optional Manual_inputType manual_input = 3; // [] [0|1] optional bool vehicle_fault = 4; // [] [0|1] optional bool pacmod_fault = 5; // [] [0|1] optional bool override_active = 6; // [] [0|1] optional bool output_reported_fault = 7; // [] [0|1] optional bool input_output_fault = 8; // [] [0|1] optional bool enabled = 9; // [] [0|1] optional bool command_output_fault = 10; } message Headlight_aux_rpt_318 { // Report Message enum Headlights_modeType { HEADLIGHTS_MODE_HEADLIGHTS_OFF = 0; HEADLIGHTS_MODE_PARKING_LIGHTS_ONLY = 1; HEADLIGHTS_MODE_HEADLIGHTS_ON_MANUAL_MODE = 2; HEADLIGHTS_MODE_HEADLIGHTS_ON_AUTO_MODE = 3; } // [] [0|1] optional bool headlights_mode_is_valid = 1; // [] [0|3] optional Headlights_modeType headlights_mode = 2; // [] [0|1] optional bool fog_lights_on_is_valid = 3; // [] [0|1] optional bool fog_lights_on = 4; // [] [0|1] optional bool headlights_on_bright_is_valid = 5; // [] [0|1] optional bool headlights_on_bright = 6; // [] [0|1] optional bool headlights_on_is_valid = 7; // [] [0|1] optional bool headlights_on = 8; } message Dash_controls_right_cmd_110 { // Report Message enum Dash_controls_buttonType { DASH_CONTROLS_BUTTON_DASH_CONTROL_NONE = 0; DASH_CONTROLS_BUTTON_DASH_CONTROL_OK = 1; DASH_CONTROLS_BUTTON_DASH_CONTROL_LEFT = 2; DASH_CONTROLS_BUTTON_DASH_CONTROL_RIGHT = 3; DASH_CONTROLS_BUTTON_DASH_CONTROL_UP = 4; DASH_CONTROLS_BUTTON_DASH_CONTROL_DOWN = 5; } // [] [0|1] optional bool ignore_overrides = 1; // [] [0|1] optional bool enable = 2; // [] [0|1] optional bool clear_override = 3; // [] [0|1] optional bool clear_faults = 4; // [] [0|255] optional Dash_controls_buttonType dash_controls_button = 5; } message Wiper_cmd_134 { // Control Message enum Wiper_cmdType { WIPER_CMD_WIPERS_OFF = 0; WIPER_CMD_INTERMITTENT_1 = 1; WIPER_CMD_INTERMITTENT_2 = 2; WIPER_CMD_INTERMITTENT_3 = 3; WIPER_CMD_INTERMITTENT_4 = 4; WIPER_CMD_INTERMITTENT_5 = 5; WIPER_CMD_LOW = 6; WIPER_CMD_HIGH = 7; } // [] [0|1] optional bool ignore_overrides = 1; // [] [0|1] optional bool enable = 2; // [] [0|1] optional bool clear_override = 3; // [] [0|7] optional Wiper_cmdType wiper_cmd = 4; // [] [0|1] optional bool clear_faults = 5; } message Wiper_rpt_234 { // Report Message enum Output_valueType { OUTPUT_VALUE_WIPERS_OFF = 0; OUTPUT_VALUE_INTERMITTENT_1 = 1; OUTPUT_VALUE_INTERMITTENT_2 = 2; OUTPUT_VALUE_INTERMITTENT_3 = 3; OUTPUT_VALUE_INTERMITTENT_4 = 4; OUTPUT_VALUE_INTERMITTENT_5 = 5; OUTPUT_VALUE_LOW = 6; OUTPUT_VALUE_HIGH = 7; } enum Commanded_valueType { COMMANDED_VALUE_WIPERS_OFF = 0; COMMANDED_VALUE_INTERMITTENT_1 = 1; COMMANDED_VALUE_INTERMITTENT_2 = 2; COMMANDED_VALUE_INTERMITTENT_3 = 3; COMMANDED_VALUE_INTERMITTENT_4 = 4; COMMANDED_VALUE_INTERMITTENT_5 = 5; COMMANDED_VALUE_LOW = 6; COMMANDED_VALUE_HIGH = 7; } enum Manual_inputType { MANUAL_INPUT_WIPERS_OFF = 0; MANUAL_INPUT_INTERMITTENT_1 = 1; MANUAL_INPUT_INTERMITTENT_2 = 2; MANUAL_INPUT_INTERMITTENT_3 = 3; MANUAL_INPUT_INTERMITTENT_4 = 4; MANUAL_INPUT_INTERMITTENT_5 = 5; MANUAL_INPUT_LOW = 6; MANUAL_INPUT_HIGH = 7; } // [] [0|1] optional bool vehicle_fault = 1; // [] [0|1] optional bool pacmod_fault = 2; // [] [0|1] optional bool override_active = 3; // [] [0|1] optional bool output_reported_fault = 4; // [] [0|1] optional bool input_output_fault = 5; // [] [0|1] optional bool enabled = 6; // [] [0|1] optional bool command_output_fault = 7; // [] [0|7] optional Output_valueType output_value = 8; // [] [0|7] optional Commanded_valueType commanded_value = 9; // [] [0|7] optional Manual_inputType manual_input = 10; } message Turn_rpt_230 { // Report Message enum Manual_inputType { MANUAL_INPUT_RIGHT = 0; MANUAL_INPUT_NONE = 1; MANUAL_INPUT_LEFT = 2; MANUAL_INPUT_HAZARD = 3; } enum Commanded_valueType { COMMANDED_VALUE_RIGHT = 0; COMMANDED_VALUE_NONE = 1; COMMANDED_VALUE_LEFT = 2; COMMANDED_VALUE_HAZARD = 3; } enum Output_valueType { OUTPUT_VALUE_RIGHT = 0; OUTPUT_VALUE_NONE = 1; OUTPUT_VALUE_LEFT = 2; OUTPUT_VALUE_HAZARD = 3; } // [] [0|1] optional bool vehicle_fault = 1; // [] [0|1] optional bool pacmod_fault = 2; // [] [0|1] optional bool override_active = 3; // [] [0|1] optional bool output_reported_fault = 4; // [] [0|1] optional bool input_output_fault = 5; // [] [0|1] optional bool enabled = 6; // [] [0|1] optional bool command_output_fault = 7; // [] [0|3] optional Manual_inputType manual_input = 8; // [] [0|3] optional Commanded_valueType commanded_value = 9; // [] [0|3] optional Output_valueType output_value = 10; } message Headlight_cmd_118 { // Control Message enum Headlight_cmdType { HEADLIGHT_CMD_HEADLIGHTS_OFF = 0; HEADLIGHT_CMD_LOW_BEAMS = 1; HEADLIGHT_CMD_HIGH_BEAMS = 2; } // [] [0|1] optional bool ignore_overrides = 1; // [] [0|1] optional bool enable = 2; // [] [0|1] optional bool clear_override = 3; // [] [0|1] optional bool clear_faults = 4; // [] [0|2] optional Headlight_cmdType headlight_cmd = 5; } message Door_rpt_417 { // Report Message // [] [0|1] optional bool fuel_door_open_is_valid = 1; // [] [0|1] optional bool trunk_open_is_valid = 2; // [] [0|1] optional bool hood_open_is_valid = 3; // [] [0|1] optional bool rear_pass_door_open_is_valid = 4; // [] [0|1] optional bool rear_driver_door_open_is_valid = 5; // [] [0|1] optional bool pass_door_open_is_valid = 6; // [] [0|1] optional bool driver_door_open_is_valid = 7; // [] [0|1] optional bool fuel_door_open = 8; // [] [0|1] optional bool trunk_open = 9; // [] [0|1] optional bool hood_open = 10; // [] [0|1] optional bool rear_pass_door_open = 11; // [] [0|1] optional bool rear_driver_door_open = 12; // [] [0|1] optional bool pass_door_open = 13; // [] [0|1] optional bool driver_door_open = 14; } message Component_rpt_20 { // Report Message enum Component_typeType { COMPONENT_TYPE_PACMOD = 0; COMPONENT_TYPE_PACMINI = 1; COMPONENT_TYPE_PACMICRO = 2; } enum Component_funcType { COMPONENT_FUNC_PACMOD = 0; COMPONENT_FUNC_STEERING_AND_STEERING_COLUMN = 1; COMPONENT_FUNC_ACCELERATOR_AND_BRAKING = 2; COMPONENT_FUNC_BRAKING = 3; COMPONENT_FUNC_SHIFTING = 4; COMPONENT_FUNC_STEERING = 5; COMPONENT_FUNC_E_SHIFTER = 6; COMPONENT_FUNC_WATCHDOG = 7; } // [] [0|255] optional Component_typeType component_type = 1; // [] [0|255] optional Component_funcType component_func = 2; // [] [0|15] optional int32 counter = 3; // [] [0|15] optional int32 complement = 4; // [] [0|1] optional bool config_fault = 5; } message Wheel_speed_rpt_407 { // Report Message // [rad/s] [-327.68|327.67] optional double wheel_spd_rear_right = 1; // [rad/s] [-327.68|327.67] optional double wheel_spd_rear_left = 2; // [rad/s] [-327.68|327.67] optional double wheel_spd_front_right = 3; // [rad/s] [-327.68|327.67] optional double wheel_spd_front_left = 4; } message Steering_motor_rpt_3_406 { // Report Message // [N-m] [-2147483.648|2147483.647] optional double torque_output = 1; // [N-m] [-2147483.648|2147483.647] optional double torque_input = 2; } message Steering_motor_rpt_2_405 { // Report Message // [deg C] [-32808|32727] optional int32 encoder_temperature = 1; // [deg C] [-32808|32727] optional int32 motor_temperature = 2; // [rev/s] [-2147483.648|2147483.647] optional double angular_speed = 3; } message Steering_motor_rpt_1_404 { // Report Message // [amps] [0|4294967.295] optional double motor_current = 1; // [amps] [-2147483.648|2147483.647] optional double shaft_position = 2; } message Brake_motor_rpt_3_403 { // Report Message // [N-m] [-2147483.648|2147483.647] optional double torque_output = 1; // [N-m] [-2147483.648|2147483.647] optional double torque_input = 2; } message Brake_motor_rpt_2_402 { // Report Message // [deg C] [-32808|32727] optional int32 encoder_temperature = 1; // [deg C] [-32808|32727] optional int32 motor_temperature = 2; // [rev/s] [0|4294967.295] optional double angular_speed = 3; } message Brake_motor_rpt_1_401 { // Report Message // [amps] [0|4294967.295] optional double motor_current = 1; // [radians] [-2147483.648|2147483.647] optional double shaft_position = 2; } message Wiper_aux_rpt_334 { // Report Message // [] [0|1] optional bool spray_empty_is_valid = 1; // [] [0|1] optional bool spray_empty = 2; // [] [0|1] optional bool spray_near_empty_is_valid = 3; // [] [0|1] optional bool spray_near_empty = 4; // [] [0|1] optional bool rear_spraying_is_valid = 5; // [] [0|1] optional bool rear_spraying = 6; // [] [0|1] optional bool rear_wiping_is_valid = 7; // [] [0|1] optional bool rear_wiping = 8; // [] [0|1] optional bool front_spraying_is_valid = 9; // [] [0|1] optional bool front_spraying = 10; // [] [0|1] optional bool front_wiping_is_valid = 11; // [] [0|1] optional bool front_wiping = 12; } message Shift_aux_rpt_328 { // Report Message // [] [0|1] optional bool speed_interlock_active_is_valid = 1; // [] [0|1] optional bool speed_interlock_active = 2; // [] [0|1] optional bool brake_interlock_active_is_valid = 3; // [] [0|1] optional bool brake_interlock_active = 4; // [] [0|1] optional bool stay_in_neutral_mode_is_valid = 5; // [] [0|1] optional bool stay_in_neutral_mode = 6; // [] [0|1] optional bool between_gears_is_valid = 7; // [] [0|1] optional bool between_gears = 8; } message Accel_rpt_200 { // Report Message // [] [0|1] optional bool vehicle_fault = 1; // [] [0|1] optional bool pacmod_fault = 2; // [] [0|1] optional bool output_reported_fault = 3; // [] [0|1] optional bool input_output_fault = 4; // [] [0|1] optional bool command_output_fault = 5; // [] [0|1] optional bool override_active = 6; // [] [0|1] optional bool enabled = 7; // [] [0|1] optional double manual_input = 8; // [] [0|1] optional double commanded_value = 9; // [] [0|1] optional double output_value = 10; } message Brake_rpt_204 { // Report Message // [] [0|1] optional bool command_output_fault = 1; // [] [0|1] optional bool vehicle_fault = 2; // [] [0|1] optional bool pacmod_fault = 3; // [] [0|1] optional bool override_active = 4; // [] [0|1] optional bool output_reported_fault = 5; // [] [0|1] optional bool input_output_fault = 6; // [] [0|1] optional bool enabled = 7; // [] [0|1] optional double manual_input = 8; // [] [0|1] optional double commanded_value = 9; // [] [0|1] optional double output_value = 10; } message Horn_cmd_11c { // Report Message enum Horn_cmdType { HORN_CMD_OFF = 0; HORN_CMD_ON = 1; } // [] [0|1] optional bool ignore_overrides = 1; // [] [0|1] optional bool enable = 2; // [] [0|1] optional bool clear_override = 3; // [] [0|1] optional bool clear_faults = 4; // [] [0|1] optional Horn_cmdType horn_cmd = 5; } message Global_rpt_10 { // Report Message enum Pacmod_system_enabledType { PACMOD_SYSTEM_ENABLED_CONTROL_DISABLED = 0; PACMOD_SYSTEM_ENABLED_CONTROL_ENABLED = 1; } enum Pacmod_system_override_activeType { PACMOD_SYSTEM_OVERRIDE_ACTIVE_NOT_OVERRIDDEN = 0; PACMOD_SYSTEM_OVERRIDE_ACTIVE_OVERRIDDEN = 1; } enum Brk_can_timeoutType { BRK_CAN_TIMEOUT_NO_ACTIVE_CAN_TIMEOUT = 0; BRK_CAN_TIMEOUT_ACTIVE_CAN_TIMEOUT = 1; } // [] [0|1] optional bool config_fault_active = 1; // [] [0|1] optional bool pacmod_subsystem_timeout = 2; // [] [0|1] optional Pacmod_system_enabledType pacmod_system_enabled = 3; // [] [0|1] optional Pacmod_system_override_activeType pacmod_system_override_active = 4; // [] [0|1] optional bool pacmod_system_fault_active = 5; // [] [0|1] optional bool veh_can_timeout = 6; // [] [0|1] optional bool str_can_timeout = 7; // [] [0|1] optional Brk_can_timeoutType brk_can_timeout = 8; // [] [0|1] optional bool usr_can_timeout = 9; // [] [0|65535] optional int32 usr_can_read_errors = 10; } message Accel_aux_rpt_300 { // Report Message // [] [0|1] optional bool user_interaction_is_valid = 1; // [] [0|1] optional bool user_interaction = 2; // [] [0|1] optional bool raw_pedal_force_is_valid = 3; // [] [-32.768|32.767] optional double raw_pedal_force = 4; // [] [0|1] optional bool raw_pedal_pos_is_valid = 5; // [] [-32.768|32.767] optional double raw_pedal_pos = 6; } message Cruise_control_buttons_rpt_208 { // Report Message enum Output_valueType { OUTPUT_VALUE_CRUISE_CONTROL_NONE = 0; OUTPUT_VALUE_CRUISE_CONTROL_CNCL = 1; OUTPUT_VALUE_CRUISE_CONTROL_ACC_FURTHER = 2; OUTPUT_VALUE_CRUISE_CONTROL_ACC_CLOSER = 3; OUTPUT_VALUE_CRUISE_CONTROL_SET_DEC = 4; OUTPUT_VALUE_CRUISE_CONTROL_RES_INC = 5; OUTPUT_VALUE_CRUISE_CONTROL_ON_OFF = 6; } enum Manual_inputType { MANUAL_INPUT_CRUISE_CONTROL_NONE = 0; MANUAL_INPUT_CRUISE_CONTROL_CNCL = 1; MANUAL_INPUT_CRUISE_CONTROL_ACC_FURTHER = 2; MANUAL_INPUT_CRUISE_CONTROL_ACC_CLOSER = 3; MANUAL_INPUT_CRUISE_CONTROL_SET_DEC = 4; MANUAL_INPUT_CRUISE_CONTROL_RES_INC = 5; MANUAL_INPUT_CRUISE_CONTROL_ON_OFF = 6; } enum Commanded_valueType { COMMANDED_VALUE_CRUISE_CONTROL_NONE = 0; COMMANDED_VALUE_CRUISE_CONTROL_CNCL = 1; COMMANDED_VALUE_CRUISE_CONTROL_ACC_FURTHER = 2; COMMANDED_VALUE_CRUISE_CONTROL_ACC_CLOSER = 3; COMMANDED_VALUE_CRUISE_CONTROL_SET_DEC = 4; COMMANDED_VALUE_CRUISE_CONTROL_RES_INC = 5; COMMANDED_VALUE_CRUISE_CONTROL_ON_OFF = 6; } // [] [0|255] optional Output_valueType output_value = 1; // [] [0|255] optional Manual_inputType manual_input = 2; // [] [0|255] optional Commanded_valueType commanded_value = 3; // [] [0|1] optional bool vehicle_fault = 4; // [] [0|1] optional bool pacmod_fault = 5; // [] [0|1] optional bool override_active = 6; // [] [0|1] optional bool output_reported_fault = 7; // [] [0|1] optional bool input_output_fault = 8; // [] [0|1] optional bool enabled = 9; // [] [0|1] optional bool command_output_fault = 10; } message Vehicle_speed_rpt_400 { // Report Message enum Vehicle_speed_validType { VEHICLE_SPEED_VALID_INVALID = 0; VEHICLE_SPEED_VALID_VALID = 1; } // [m/s] [-327.68|327.67] optional double vehicle_speed = 1; // [] [0|1] optional Vehicle_speed_validType vehicle_speed_valid = 2; } message Brake_aux_rpt_304 { // Report Message // [] [0|1] optional bool brake_on_off_is_valid = 1; // [] [0|1] optional bool brake_on_off = 2; // [] [0|1] optional bool user_interaction_is_valid = 3; // [] [0|1] optional bool user_interaction = 4; // [] [0|1] optional bool raw_brake_pressure_is_valid = 5; // [] [-32.768|32.767] optional double raw_brake_pressure = 6; // [] [0|1] optional bool raw_pedal_force_is_valid = 7; // [] [-32.768|32.767] optional double raw_pedal_force = 8; // [] [0|1] optional bool raw_pedal_pos_is_valid = 9; // [] [-32.768|32.767] optional double raw_pedal_pos = 10; } message Media_controls_cmd_120 { // Report Message enum Media_controls_cmdType { MEDIA_CONTROLS_CMD_MEDIA_CONTROL_NONE = 0; MEDIA_CONTROLS_CMD_MEDIA_CONTROL_VOICE_COMMAND = 1; MEDIA_CONTROLS_CMD_MEDIA_CONTROL_MUTE = 2; MEDIA_CONTROLS_CMD_MEDIA_CONTROL_PREV_TRACK_ANSWER = 3; MEDIA_CONTROLS_CMD_MEDIA_CONTROL_NEXT_TRACK_HANG_UP = 4; MEDIA_CONTROLS_CMD_MEDIA_CONTROL_VOL_UP = 5; MEDIA_CONTROLS_CMD_MEDIA_CONTROL_VOL_DOWN = 6; } // [] [0|255] optional Media_controls_cmdType media_controls_cmd = 1; // [] [0|1] optional bool ignore_overrides = 2; // [] [0|1] optional bool clear_override = 3; // [] [0|1] optional bool clear_faults = 4; // [] [0|1] optional bool enable = 5; } message Cruise_control_buttons_cmd_108 { // Control Message enum Cruise_control_buttonType { CRUISE_CONTROL_BUTTON_CRUISE_CONTROL_NONE = 0; CRUISE_CONTROL_BUTTON_CRUISE_CONTROL_CNCL = 1; CRUISE_CONTROL_BUTTON_CRUISE_CONTROL_ACC_FURTHER = 2; CRUISE_CONTROL_BUTTON_CRUISE_CONTROL_ACC_CLOSER = 3; CRUISE_CONTROL_BUTTON_CRUISE_CONTROL_SET_DEC = 4; CRUISE_CONTROL_BUTTON_CRUISE_CONTROL_RES_INC = 5; CRUISE_CONTROL_BUTTON_CRUISE_CONTROL_ON_OFF = 6; } // [] [0|255] optional Cruise_control_buttonType cruise_control_button = 1; // [] [0|1] optional bool ignore_overrides = 2; // [] [0|1] optional bool clear_override = 3; // [] [0|1] optional bool enable = 4; // [] [0|1] optional bool clear_faults = 5; } message Parking_brake_cmd_124 { // Control Message // [] [0|1] optional bool ignore_overrides = 1; // [] [0|1] optional bool enable = 2; // [] [0|1] optional bool clear_override = 3; // [] [0|1] optional bool parking_brake_cmd = 4; // [] [0|1] optional bool clear_faults = 5; } message Horn_rpt_21c { // Report Message enum Output_valueType { OUTPUT_VALUE_OFF = 0; OUTPUT_VALUE_ON = 1; } enum Commanded_valueType { COMMANDED_VALUE_OFF = 0; COMMANDED_VALUE_ON = 1; } enum Manual_inputType { MANUAL_INPUT_OFF = 0; MANUAL_INPUT_ON = 1; } // [] [0|1] optional bool vehicle_fault = 1; // [] [0|1] optional bool pacmod_fault = 2; // [] [0|1] optional bool override_active = 3; // [] [0|1] optional bool output_reported_fault = 4; // [] [0|1] optional bool input_output_fault = 5; // [] [0|1] optional bool enabled = 6; // [] [0|1] optional bool command_output_fault = 7; // [] [0|1] optional Output_valueType output_value = 8; // [] [0|1] optional Commanded_valueType commanded_value = 9; // [] [0|1] optional Manual_inputType manual_input = 10; } message Shift_rpt_228 { // Report Message enum Manual_inputType { MANUAL_INPUT_PARK = 0; MANUAL_INPUT_REVERSE = 1; MANUAL_INPUT_NEUTRAL = 2; MANUAL_INPUT_FORWARD_HIGH = 3; MANUAL_INPUT_LOW = 4; MANUAL_INPUT_BETWEEN_GEARS = 5; MANUAL_INPUT_ERROR = 6; MANUAL_INPUT_NONE = 7; } enum Commanded_valueType { COMMANDED_VALUE_PARK = 0; COMMANDED_VALUE_REVERSE = 1; COMMANDED_VALUE_NEUTRAL = 2; COMMANDED_VALUE_FORWARD_HIGH = 3; COMMANDED_VALUE_LOW = 4; COMMANDED_VALUE_NONE = 7; } enum Output_valueType { OUTPUT_VALUE_PARK = 0; OUTPUT_VALUE_REVERSE = 1; OUTPUT_VALUE_NEUTRAL = 2; OUTPUT_VALUE_FORWARD_HIGH = 3; OUTPUT_VALUE_LOW = 4; OUTPUT_VALUE_BETWEEN_GEARS = 5; OUTPUT_VALUE_ERROR = 6; OUTPUT_VALUE_NONE = 7; } // [] [0|1] optional bool vehicle_fault = 1; // [] [0|1] optional bool pacmod_fault = 2; // [] [0|1] optional bool override_active = 3; // [] [0|1] optional bool output_reported_fault = 4; // [] [0|1] optional bool input_output_fault = 5; // [] [0|1] optional bool enabled = 6; // [] [0|1] optional bool command_output_fault = 7; // [] [0|4] optional Manual_inputType manual_input = 8; // [] [0|4] optional Commanded_valueType commanded_value = 9; // [] [0|4] optional Output_valueType output_value = 10; } message Shift_cmd_128 { // Control Message enum Shift_cmdType { SHIFT_CMD_PARK = 0; SHIFT_CMD_REVERSE = 1; SHIFT_CMD_NEUTRAL = 2; SHIFT_CMD_FORWARD_HIGH = 3; SHIFT_CMD_LOW = 4; SHIFT_CMD_NONE = 7; } // [] [0|1] optional bool ignore_overrides = 1; // [] [0|1] optional bool enable = 2; // [] [0|1] optional bool clear_override = 3; // [] [0|1] optional bool clear_faults = 4; // FORWARD is also HIGH on vehicles with LOW/HIGH, PARK and LOW only available on certain Vehicles. [] [0|4] optional Shift_cmdType shift_cmd = 5; } message Accel_cmd_100 { // Control Message // [] [0|1] optional bool ignore_overrides = 1; // [] [0|1] optional bool enable = 2; // [] [0|1] optional bool clear_override = 3; // [] [0|1] optional bool clear_faults = 4; // [] [0|1] optional double accel_cmd = 5; } message Parking_brake_rpt_224 { // Report Message // [] [0|1] optional bool vehicle_fault = 1; // [] [0|1] optional bool pacmod_fault = 2; // [] [0|1] optional bool override_active = 3; // [] [0|1] optional bool output_reported_fault = 4; // [] [0|1] optional bool input_output_fault = 5; // [] [0|1] optional bool enabled = 6; // [] [0|1] optional bool command_output_fault = 7; // [] [0|1] optional bool output_value = 8; // [] [0|1] optional bool commanded_value = 9; // [] [0|1] optional bool manual_input = 10; } message Brake_cmd_104 { // Control Message // [] [0|1] optional bool ignore_overrides = 1; // [] [0|1] optional bool enable = 2; // [] [0|1] optional bool clear_override = 3; // [] [0|1] optional bool clear_faults = 4; // [] [0|1] optional double brake_cmd = 5; } message Media_controls_rpt_220 { // Report Message enum Output_valueType { OUTPUT_VALUE_MEDIA_CONTROL_NONE = 0; OUTPUT_VALUE_MEDIA_CONTROL_VOICE_COMMAND = 1; OUTPUT_VALUE_MEDIA_CONTROL_MUTE = 2; OUTPUT_VALUE_MEDIA_CONTROL_PREV_TRACK_ANSWER = 3; OUTPUT_VALUE_MEDIA_CONTROL_NEXT_TRACK_HANG_UP = 4; OUTPUT_VALUE_MEDIA_CONTROL_VOL_UP = 5; OUTPUT_VALUE_MEDIA_CONTROL_VOL_DOWN = 6; } enum Commanded_valueType { COMMANDED_VALUE_MEDIA_CONTROL_NONE = 0; COMMANDED_VALUE_MEDIA_CONTROL_VOICE_COMMAND = 1; COMMANDED_VALUE_MEDIA_CONTROL_MUTE = 2; COMMANDED_VALUE_MEDIA_CONTROL_PREV_TRACK_ANSWER = 3; COMMANDED_VALUE_MEDIA_CONTROL_NEXT_TRACK_HANG_UP = 4; COMMANDED_VALUE_MEDIA_CONTROL_VOL_UP = 5; COMMANDED_VALUE_MEDIA_CONTROL_VOL_DOWN = 6; } enum Manual_inputType { MANUAL_INPUT_MEDIA_CONTROL_NONE = 0; MANUAL_INPUT_MEDIA_CONTROL_VOICE_COMMAND = 1; MANUAL_INPUT_MEDIA_CONTROL_MUTE = 2; MANUAL_INPUT_MEDIA_CONTROL_PREV_TRACK_ANSWER = 3; MANUAL_INPUT_MEDIA_CONTROL_NEXT_TRACK_HANG_UP = 4; MANUAL_INPUT_MEDIA_CONTROL_VOL_UP = 5; MANUAL_INPUT_MEDIA_CONTROL_VOL_DOWN = 6; } // [] [0|255] optional Output_valueType output_value = 1; // [] [0|255] optional Commanded_valueType commanded_value = 2; // [] [0|255] optional Manual_inputType manual_input = 3; // [] [0|1] optional bool vehicle_fault = 4; // [] [0|1] optional bool pacmod_fault = 5; // [] [0|1] optional bool override_active = 6; // [] [0|1] optional bool output_reported_fault = 7; // [] [0|1] optional bool input_output_fault = 8; // [] [0|1] optional bool enabled = 9; // [] [0|1] optional bool command_output_fault = 10; } message Steering_aux_rpt_32c { // Report Message // [] [0|1] optional bool user_interaction_is_valid = 1; // [] [0|1] optional bool user_interaction = 2; // [] [0|1] optional bool rotation_rate_is_valid = 3; // [rad/s] [0|65.535] optional double rotation_rate = 4; // [] [0|1] optional bool raw_torque_is_valid = 5; // [] [-32.768|32.767] optional double raw_torque = 6; // [] [0|1] optional bool raw_position_is_valid = 7; // [] [-32.768|32.767] optional double raw_position = 8; } message Lat_lon_heading_rpt_40e { // Report Message // [deg] [-327.68|327.67] optional double heading = 1; // [sec] [-128|127] optional int32 longitude_seconds = 2; // [min] [-128|127] optional int32 longitude_minutes = 3; // [deg] [-128|127] optional int32 longitude_degrees = 4; // [sec] [-128|127] optional int32 latitude_seconds = 5; // [min] [-128|127] optional int32 latitude_minutes = 6; // [deg] [-128|127] optional int32 latitude_degrees = 7; } message Yaw_rate_rpt_40d { // Report Message // [rad/s] [-327.68|327.67] optional double yaw_rate = 1; } message Date_time_rpt_40f { // Report Message // [sec] [0|60] optional int32 time_second = 1; // [min] [0|60] optional int32 time_minute = 2; // [hr] [0|23] optional int32 time_hour = 3; // [dy] [1|31] optional int32 date_day = 4; // [mon] [1|12] optional int32 date_month = 5; // [yr] [2000|2255] optional int32 date_year = 6; } message Vin_rpt_414 { // Report Message // [] [0|0] optional int32 veh_serial = 1; // [] [0|0] optional int32 veh_my_code = 2; // [] [0|0] optional int32 veh_mfg_code = 3; } message Occupancy_rpt_415 { // Report Message // [] [0|1] optional bool rear_seatbelt_buckled_is_valid = 1; // [] [0|1] optional bool pass_seatbelt_buckled_is_valid = 2; // [] [0|1] optional bool driver_seatbelt_buckled_is_valid = 3; // [] [0|1] optional bool rear_seat_occupied_is_valid = 4; // [] [0|1] optional bool pass_seat_occupied_is_valid = 5; // [] [0|1] optional bool driver_seat_occupied_is_valid = 6; // [] [0|1] optional bool rear_seatbelt_buckled = 7; // [] [0|1] optional bool pass_seatbelt_buckled = 8; // [] [0|1] optional bool driver_seatbelt_buckled = 9; // [] [0|1] optional bool rear_seat_occupied = 10; // [] [0|1] optional bool pass_seat_occupied = 11; // [] [0|1] optional bool driver_seat_occupied = 12; } message Interior_lights_rpt_416 { // Report Message enum Dim_levelType { DIM_LEVEL_DIM_LEVEL_MIN = 0; DIM_LEVEL_DIM_LEVEL_1 = 1; DIM_LEVEL_DIM_LEVEL_2 = 2; DIM_LEVEL_DIM_LEVEL_3 = 3; DIM_LEVEL_DIM_LEVEL_4 = 4; DIM_LEVEL_DIM_LEVEL_5 = 5; DIM_LEVEL_DIM_LEVEL_6 = 6; DIM_LEVEL_DIM_LEVEL_7 = 7; DIM_LEVEL_DIM_LEVEL_8 = 8; DIM_LEVEL_DIM_LEVEL_9 = 9; DIM_LEVEL_DIM_LEVEL_10 = 10; DIM_LEVEL_DIM_LEVEL_11 = 11; DIM_LEVEL_DIM_LEVEL_MAX = 12; } // [] [0|1] optional bool dim_level_is_valid = 1; // [] [0|1] optional bool mood_lights_on_is_valid = 2; // [] [0|1] optional bool rear_dome_lights_on_is_valid = 3; // [] [0|1] optional bool front_dome_lights_on_is_valid = 4; // [] [0|12] optional Dim_levelType dim_level = 5; // [] [0|1] optional bool mood_lights_on = 6; // [] [0|1] optional bool rear_dome_lights_on = 7; // [] [0|1] optional bool front_dome_lights_on = 8; } message Turn_cmd_130 { // Control Message enum Turn_signal_cmdType { TURN_SIGNAL_CMD_RIGHT = 0; TURN_SIGNAL_CMD_NONE = 1; TURN_SIGNAL_CMD_LEFT = 2; TURN_SIGNAL_CMD_HAZARD = 3; } // [] [0|1] optional bool ignore_overrides = 1; // [] [0|1] optional bool enable = 2; // [] [0|1] optional bool clear_override = 3; // [] [0|1] optional bool clear_faults = 4; // [] [0|3] optional Turn_signal_cmdType turn_signal_cmd = 5; } message Detected_object_rpt_411 { // Report Message // [m] [0|16777.215] optional double front_object_distance_high_res = 1; // [m] [0|16777.215] optional double front_object_distance_low_res = 2; } message Veh_specific_rpt_1_412 { // Report Message // [] [0|0] optional int32 shift_pos_2 = 1; // [] [0|0] optional int32 shift_pos_1 = 2; } message Veh_dynamics_rpt_413 { // Report Message // [] [-32.768|32.767] optional double veh_g_forces = 1; } message Rear_lights_rpt_418 { // Report Message // [] [0|1] optional bool reverse_lights_on_is_valid = 1; // [] [0|1] optional bool brake_lights_on_is_valid = 2; // [] [0|1] optional bool reverse_lights_on = 3; // [] [0|1] optional bool brake_lights_on = 4; } message Lexus { optional Hazard_lights_rpt_214 hazard_lights_rpt_214 = 1; // report message optional Steering_cmd_12c steering_cmd_12c = 2; // report message optional Dash_controls_right_rpt_210 dash_controls_right_rpt_210 = 3; // control message optional Dash_controls_left_cmd_10c dash_controls_left_cmd_10c = 4; // report message optional Steering_rpt_22c steering_rpt_22c = 5; // report message optional Turn_aux_rpt_330 turn_aux_rpt_330 = 6; // report message optional Headlight_rpt_218 headlight_rpt_218 = 7; // report message optional Hazard_lights_cmd_114 hazard_lights_cmd_114 = 8; // control message optional Dash_controls_left_rpt_20c dash_controls_left_rpt_20c = 9; // report message optional Headlight_aux_rpt_318 headlight_aux_rpt_318 = 10; // report message optional Dash_controls_right_cmd_110 dash_controls_right_cmd_110 = 11; // report message optional Wiper_cmd_134 wiper_cmd_134 = 12; // control message optional Wiper_rpt_234 wiper_rpt_234 = 13; // report message optional Turn_rpt_230 turn_rpt_230 = 14; // report message optional Headlight_cmd_118 headlight_cmd_118 = 15; // control message optional Door_rpt_417 door_rpt_417 = 16; // report message optional Component_rpt_20 component_rpt_20 = 17; // report message optional Wheel_speed_rpt_407 wheel_speed_rpt_407 = 18; // report message optional Steering_motor_rpt_3_406 steering_motor_rpt_3_406 = 19; // report message optional Steering_motor_rpt_2_405 steering_motor_rpt_2_405 = 20; // report message optional Steering_motor_rpt_1_404 steering_motor_rpt_1_404 = 21; // report message optional Brake_motor_rpt_3_403 brake_motor_rpt_3_403 = 22; // report message optional Brake_motor_rpt_2_402 brake_motor_rpt_2_402 = 23; // report message optional Brake_motor_rpt_1_401 brake_motor_rpt_1_401 = 24; // report message optional Wiper_aux_rpt_334 wiper_aux_rpt_334 = 25; // report message optional Shift_aux_rpt_328 shift_aux_rpt_328 = 26; // report message optional Accel_rpt_200 accel_rpt_200 = 27; // report message optional Brake_rpt_204 brake_rpt_204 = 28; // report message optional Horn_cmd_11c horn_cmd_11c = 29; // report message optional Global_rpt_10 global_rpt_10 = 30; // report message optional Accel_aux_rpt_300 accel_aux_rpt_300 = 31; // report message optional Cruise_control_buttons_rpt_208 cruise_control_buttons_rpt_208 = 32; // report message optional Vehicle_speed_rpt_400 vehicle_speed_rpt_400 = 33; // report message optional Brake_aux_rpt_304 brake_aux_rpt_304 = 34; // report message optional Media_controls_cmd_120 media_controls_cmd_120 = 35; // report message optional Cruise_control_buttons_cmd_108 cruise_control_buttons_cmd_108 = 36; // control message optional Parking_brake_cmd_124 parking_brake_cmd_124 = 37; // control message optional Horn_rpt_21c horn_rpt_21c = 38; // report message optional Shift_rpt_228 shift_rpt_228 = 39; // report message optional Shift_cmd_128 shift_cmd_128 = 40; // control message optional Accel_cmd_100 accel_cmd_100 = 41; // control message optional Parking_brake_rpt_224 parking_brake_rpt_224 = 42; // report message optional Brake_cmd_104 brake_cmd_104 = 43; // control message optional Media_controls_rpt_220 media_controls_rpt_220 = 44; // report message optional Steering_aux_rpt_32c steering_aux_rpt_32c = 45; // report message optional Lat_lon_heading_rpt_40e lat_lon_heading_rpt_40e = 46; // report message optional Yaw_rate_rpt_40d yaw_rate_rpt_40d = 47; // report message optional Date_time_rpt_40f date_time_rpt_40f = 48; // report message optional Vin_rpt_414 vin_rpt_414 = 49; // report message optional Occupancy_rpt_415 occupancy_rpt_415 = 50; // report message optional Interior_lights_rpt_416 interior_lights_rpt_416 = 51; // report message optional Turn_cmd_130 turn_cmd_130 = 52; // control message optional Detected_object_rpt_411 detected_object_rpt_411 = 53; // report message optional Veh_specific_rpt_1_412 veh_specific_rpt_1_412 = 54; // report message optional Veh_dynamics_rpt_413 veh_dynamics_rpt_413 = 55; // report message optional Rear_lights_rpt_418 rear_lights_rpt_418 = 56; // report message }
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto/pnc_point.proto
syntax = "proto2"; // Defined Point types that are commonly used in PnC (Planning and Control) // modules. package apollo.common; message SLPoint { optional double s = 1; optional double l = 2; } message FrenetFramePoint { optional double s = 1; optional double l = 2; optional double dl = 3; optional double ddl = 4; } message SpeedPoint { optional double s = 1; optional double t = 2; // speed (m/s) optional double v = 3; // acceleration (m/s^2) optional double a = 4; // jerk (m/s^3) optional double da = 5; } message PathPoint { // coordinates optional double x = 1; optional double y = 2; optional double z = 3; // direction on the x-y plane optional double theta = 4; // curvature on the x-y planning optional double kappa = 5; // accumulated distance from beginning of the path optional double s = 6; // derivative of kappa w.r.t s. optional double dkappa = 7; // derivative of derivative of kappa w.r.t s. optional double ddkappa = 8; // The lane ID where the path point is on optional string lane_id = 9; // derivative of x and y w.r.t parametric parameter t in CosThetareferenceline optional double x_derivative = 10; optional double y_derivative = 11; } message Path { optional string name = 1; repeated PathPoint path_point = 2; } message TrajectoryPoint { // path point optional PathPoint path_point = 1; // linear velocity optional double v = 2; // in [m/s] // linear acceleration optional double a = 3; // relative time from beginning of the trajectory optional double relative_time = 4; }
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto/localization.proto
syntax = "proto2"; package apollo.localization; import "header.proto"; import "pose.proto"; import "geometry.proto"; import "pnc_point.proto"; message Uncertainty { // Standard deviation of position, east/north/up in meters. optional apollo.common.Point3D position_std_dev = 1; // Standard deviation of quaternion qx/qy/qz, unitless. optional apollo.common.Point3D orientation_std_dev = 2; // Standard deviation of linear velocity, east/north/up in meters per second. optional apollo.common.Point3D linear_velocity_std_dev = 3; // Standard deviation of linear acceleration, right/forward/up in meters per // square second. optional apollo.common.Point3D linear_acceleration_std_dev = 4; // Standard deviation of angular velocity, right/forward/up in radians per // second. optional apollo.common.Point3D angular_velocity_std_dev = 5; // TODO: Define covariance items when needed. } message LocalizationEstimate { optional apollo.common.Header header = 1; optional apollo.localization.Pose pose = 2; optional Uncertainty uncertainty = 3; // The time of pose measurement, seconds since the GPS epoch (Jan 6, 1980). optional double measurement_time = 4; // In seconds. // Future trajectory acturally driven by the drivers repeated apollo.common.TrajectoryPoint trajectory_point = 5; } enum MeasureState { NOT_VALID = 0; NOT_STABLE = 1; OK = 2; VALID = 3; } message LocalizationStatus { optional apollo.common.Header header = 1; optional MeasureState fusion_status = 2; optional MeasureState gnss_status = 3; optional MeasureState lidar_status = 4; // The time of pose measurement, seconds since the GPS epoch (Jan 6, 1980). optional double measurement_time = 5; // In seconds. }
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto/v2x_carstatus.proto
syntax = "proto2"; package apollo.v2x; import "localization.proto"; import "chassis_detail.proto"; message CarStatus { optional apollo.localization.LocalizationEstimate localization = 1; optional apollo.canbus.ChassisDetail chassis_detail = 2; }
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto/drive_state.proto
syntax = "proto2"; package apollo.common; // This is the engage advice that published by critical runtime modules. message EngageAdvice { enum Advice { UNKNOWN = 0; DISALLOW_ENGAGE = 1; READY_TO_ENGAGE = 2; KEEP_ENGAGED = 3; PREPARE_DISENGAGE = 4; } optional Advice advice = 1 [default = DISALLOW_ENGAGE]; optional string reason = 2; }
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto/v2x_service_car_to_obu.proto
syntax = "proto2"; package apollo.v2x; import "perception_obstacle.proto"; import "v2x_carstatus.proto"; service CarToObu { rpc PushCarStatus (apollo.v2x.CarStatus) returns (UpdateStatus) {} rpc PushPerceptionResult (apollo.perception.PerceptionObstacles) returns (UpdateStatus) {} } message UpdateStatus { required bool updated = 1 [default = false]; }
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto/error_code.proto
syntax = "proto2"; package apollo.common; // Error codes enum for API's categorized by modules. enum ErrorCode { // No error, reutrns on success. OK = 0; // Control module error codes start from here. CONTROL_ERROR = 1000; CONTROL_INIT_ERROR = 1001; CONTROL_COMPUTE_ERROR = 1002; // Canbus module error codes start from here. CANBUS_ERROR = 2000; CAN_CLIENT_ERROR_BASE = 2100; CAN_CLIENT_ERROR_OPEN_DEVICE_FAILED = 2101; CAN_CLIENT_ERROR_FRAME_NUM = 2102; CAN_CLIENT_ERROR_SEND_FAILED = 2103; CAN_CLIENT_ERROR_RECV_FAILED = 2104; // Localization module error codes start from here. LOCALIZATION_ERROR = 3000; LOCALIZATION_ERROR_MSG = 3100; LOCALIZATION_ERROR_LIDAR = 3200; LOCALIZATION_ERROR_INTEG = 3300; LOCALIZATION_ERROR_GNSS = 3400; // Perception module error codes start from here. PERCEPTION_ERROR = 4000; PERCEPTION_ERROR_TF = 4001; PERCEPTION_ERROR_PROCESS = 4002; PERCEPTION_FATAL = 4003; // Prediction module error codes start from here. PREDICTION_ERROR = 5000; // Planning module error codes start from here PLANNING_ERROR = 6000; // HDMap module error codes start from here HDMAP_DATA_ERROR = 7000; // Routing module error codes ROUTING_ERROR = 8000; ROUTING_ERROR_REQUEST = 8001; ROUTING_ERROR_RESPONSE = 8002; ROUTING_ERROR_NOT_READY = 8003; // Indicates an input has been exhausted. END_OF_INPUT = 9000; // HTTP request error codes. HTTP_LOGIC_ERROR = 10000; HTTP_RUNTIME_ERROR = 10001; // Relative Map error codes. RELATIVE_MAP_ERROR = 11000; // general relative map error code RELATIVE_MAP_NOT_READY = 11001; // Driver error codes. DRIVER_ERROR_GNSS = 12000; DRIVER_ERROR_VELODYNE = 13000; } message StatusPb { optional ErrorCode error_code = 1 [default = OK]; optional string msg = 2; }
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto/pose.proto
syntax = "proto2"; package apollo.localization; import "geometry.proto"; message Pose { // Position of the vehicle reference point (VRP) in the map reference frame. // The VRP is the center of rear axle. optional apollo.common.PointENU position = 1; // A quaternion that represents the rotation from the IMU coordinate // (Right/Forward/Up) to the // world coordinate (East/North/Up). optional apollo.common.Quaternion orientation = 2; // Linear velocity of the VRP in the map reference frame. // East/north/up in meters per second. optional apollo.common.Point3D linear_velocity = 3; // Linear acceleration of the VRP in the map reference frame. // East/north/up in meters per second. optional apollo.common.Point3D linear_acceleration = 4; // Angular velocity of the vehicle in the map reference frame. // Around east/north/up axes in radians per second. optional apollo.common.Point3D angular_velocity = 5; // Heading // The heading is zero when the car is facing East and positive when facing // North. optional double heading = 6; // Linear acceleration of the VRP in the vehicle reference frame. // Right/forward/up in meters per square second. optional apollo.common.Point3D linear_acceleration_vrf = 7; // Angular velocity of the VRP in the vehicle reference frame. // Around right/forward/up axes in radians per second. optional apollo.common.Point3D angular_velocity_vrf = 8; // Roll/pitch/yaw that represents a rotation with intrinsic sequence z-x-y. // in world coordinate (East/North/Up) // The roll, in (-pi/2, pi/2), corresponds to a rotation around the y-axis. // The pitch, in [-pi, pi), corresponds to a rotation around the x-axis. // The yaw, in [-pi, pi), corresponds to a rotation around the z-axis. // The direction of rotation follows the right-hand rule. optional apollo.common.Point3D euler_angles = 9; }
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/proto-apollo/compile-apollo-proto.bash
#!/usr/bin/env bash ############################################################################### # Copyright 2020 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. ############################################################################### readonly PWD0="$(readlink -fn "$(dirname "$0")")" readonly OUTPUT_DIR="${PWD0}" readonly APOLLO_DIR="/apollo" ############################################################################### if [[ ! -e "${PROTOC_FILEPATH}" || ! -x "${PROTOC_FILEPATH}" ]]; then echo "Failed to get protoc." exit 1 fi if [[ ! -e "${GRPC_CPP_PLUGIN_FILEPATH}" || ! -x "${GRPC_CPP_PLUGIN_FILEPATH}" ]]; then echo "Failed to get grpc_cpp_plugin." exit 1 fi if ! ${PROTOC_FILEPATH} --version </dev/null >/dev/null; then echo "Failed to execute protoc." exit 1 fi if ! ${GRPC_CPP_PLUGIN_FILEPATH} </dev/null >/dev/null; then echo "Failed to execute grpc_cpp_plugin." exit 1 fi set -e find "${APOLLO_DIR}/modules" -type f -name "*.proto" | while read line; do ${PROTOC_FILEPATH} --cpp_out "${OUTPUT_DIR}" -I /apollo "${line}" ${PROTOC_FILEPATH} --grpc_out "${OUTPUT_DIR}" -I /apollo "${line}" \ "--plugin=protoc-gen-grpc=${GRPC_CPP_PLUGIN_FILEPATH}" done
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/policies/CMakeLists.txt
cmake_minimum_required(VERSION 2.8) add_subdirectory(trafficlight_process)
0
apollo_public_repos/apollo-contrib/obu/app/policies
apollo_public_repos/apollo-contrib/obu/app/policies/trafficlight_process/v2x_traffic_light.cc
/****************************************************************************** * 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. *****************************************************************************/ /** * @file v2x_traffic_light.cc * @brief The traffic light program for the v2x module */ #include "v2x_traffic_light.h" // namespace apollo { namespace v2x { Trafficlight::Trafficlight() {} void Trafficlight::Init() { current_year_moy_ = GetCurrentYearMoy(); } ErrorInfo Trafficlight::TrafficLightApp( const MapData_t* map, const SPAT_t* spat, const std::shared_ptr<apollo::v2x::CarStatus>& car_status_receive, std::shared_ptr<apollo::v2x::obu::ObuTrafficLight>& intersection_trafficlight_msg) { apollo::v2x::PolicyData policy_data_pb; apollo::v2x::Map* map_pb = policy_data_pb.mutable_map(); apollo::v2x::Spat* spat_pb = policy_data_pb.mutable_spat(); bool read_map_flag = ReadMap(map, map_pb); if (!read_map_flag) { return ReadMapFailed; } bool read_spat_flag = ReadSpat(spat, spat_pb); if (!read_spat_flag) { return ReadSpatFailed; } if (debug_flag_) { LOG(INFO) << policy_data_pb.DebugString(); } bool traffic_light_policy_flag = TrafficLightPolicy( policy_data_pb, *car_status_receive, intersection_trafficlight_msg); if (!traffic_light_policy_flag) { return PolicyFailed; } return Successful; } bool Trafficlight::TrafficLightPolicy( const apollo::v2x::PolicyData& policy_data, const apollo::v2x::CarStatus& car_status, std::shared_ptr<apollo::v2x::obu::ObuTrafficLight>& intersection_trafficlights) { self_position_x_ = car_status.localization().pose().position().x(); self_position_y_ = car_status.localization().pose().position().y(); double linear_velocity_x = car_status.localization().pose().linear_velocity().x(); double linear_velocity_y = car_status.localization().pose().linear_velocity().y(); if (fabs(linear_velocity_x) < 0.01) { linear_velocity_x = 0.0; } if (fabs(linear_velocity_y) < 0.01) { linear_velocity_y = 0.0; } if (!self_position_x_ || !self_position_y_) { LOG(ERROR) << "ERROR: Failed to get carstatus position"; return false; } const apollo::v2x::Map& map_msg = policy_data.map(); const apollo::v2x::Spat& spat_msg = policy_data.spat(); // Orientation to the current lane distance_among_two_min_ = kReferenceValue; int intersection_index = 0; for (int i = 0; i < map_msg.intersections_size(); i++) { const apollo::v2x::Intersection& intersection_msg = map_msg.intersections(i); intersection_position_x_ = intersection_msg.position().x(); intersection_position_y_ = intersection_msg.position().y(); if ((intersection_position_x_ - self_position_x_) * linear_velocity_x >= 0.0 && (intersection_position_y_ - self_position_y_) * linear_velocity_y >= 0.0) { distance_among_two_ = sqrt(pow(intersection_position_x_ - self_position_x_, 2) + pow(intersection_position_y_ - self_position_y_, 2)); if (distance_among_two_ < distance_among_two_min_) { distance_among_two_min_ = distance_among_two_; intersection_index = i; } } } const apollo::v2x::Intersection& intersection_current = map_msg.intersections(intersection_index); distance_among_two_min_ = kReferenceValue; int road_index = 0; int lane_index = 0; if (intersection_current.roads_size() == 0) { LOG(ERROR) << "ERROR: map info deficiency, no road info"; return false; } for (int j = 0; j < intersection_current.roads_size(); j++) { const apollo::v2x::Road& road_msg = intersection_current.roads(j); if (road_msg.lanes_size() == 0) { LOG(ERROR) << "ERROR: map info deficiency, no lane info"; return false; } for (int k = 0; k < road_msg.lanes_size(); k++) { const apollo::v2x::Lane& lane_msg = road_msg.lanes(k); if (lane_msg.position_offset_size() == 0) { LOG(ERROR) << "ERROR: map info deficiency, no lane position_offset info"; return false; } const apollo::v2x::Position2D& lane_stop_position = lane_msg.position_offset(lane_msg.position_offset_size() - 1); distance_among_two_ = sqrt(pow(lane_stop_position.x() - self_position_x_, 2) + pow(lane_stop_position.y() - self_position_y_, 2)); if (distance_among_two_ < distance_among_two_min_) { distance_among_two_min_ = distance_among_two_; road_index = j; lane_index = k; } } } const apollo::v2x::Lane& lane_current = intersection_current.roads(road_index).lanes(lane_index); // Matching phase information of the current lane for (int m = 0; m < spat_msg.intersections_size(); m++) { const apollo::v2x::IntersectionState& intersection_state = spat_msg.intersections(m); if (intersection_state.intersection_id() == intersection_current.id()) { if (debug_flag_) { std::cout << "The match of intersection is successful " << std::endl; } // To determine whether a timestamp is lag if (intersection_state.has_moy() && intersection_state.has_time_stamp_dsecond()) { present_moy_ = intersection_state.moy(); present_dsecond_ = intersection_state.time_stamp_dsecond(); timestamp_ = (present_moy_ + current_year_moy_) * 60 + static_cast<double>(present_dsecond_ / 1000.0); if (!(present_moy_ >= previous_moy_ && present_dsecond_ >= previous_dsecond_)) { previous_moy_ = present_moy_; previous_dsecond_ = present_dsecond_; LOG(ERROR) << "Message delay, Timestamp smaller"; return false; } } else { timestamp_ = GetSystemTime(); } // Add Header apollo::common::Header* msg_header = intersection_trafficlights->mutable_header(); msg_header->set_timestamp_sec(timestamp_); msg_header->set_sequence_num(sequence_num_); msg_header->set_module_name("v2x"); // Add current_lane_trafficlight information auto* road_tl1 = intersection_trafficlights->add_road_traffic_light(); for (int n = 0; n < intersection_state.phases_size(); n++) { const ::apollo::v2x::Phase& intersection_phase = intersection_state.phases(n); for (int p = 0; p < lane_current.connections_size(); p++) { const ::apollo::v2x::Connection& connections_data = lane_current.connections(p); // bool matching_flag = false; // switch (connections_data.allow_driving_behavior()) { // case ::apollo::v2x::Connection::STRAIGHT: // if (car_status.chassis_detail().light().turn_light_type() == // apollo::canbus::Light::TURN_LIGHT_OFF) { // matching_flag = true; // }; // break; // case ::apollo::v2x::Connection::LEFT: // if (car_status.chassis_detail().light().turn_light_type() == // apollo::canbus::Light::TURN_LEFT_ON) { // matching_flag = true; // }; // break; // case ::apollo::v2x::Connection::RIGHT: // if (car_status.chassis_detail().light().turn_light_type() == // apollo::canbus::Light::TURN_RIGHT_ON) { // matching_flag = true; // }; // break; // case ::apollo::v2x::Connection::U_TURN: // if (car_status.chassis_detail().light().turn_light_type() == // apollo::canbus::Light::TURN_LEFT_ON) { // matching_flag = true; // }; // break; // default: // break; // } if (intersection_phase.id() == connections_data.phase_id()) { if (debug_flag_) { std::cout << "The match of current lane phase is successful " << std::endl; } // Add single_trafficlight information auto* lane_tl1 = road_tl1->add_lane_traffic_light(); lane_tl1->set_gps_x_m( lane_current .position_offset(lane_current.position_offset_size() - 1) .x()); lane_tl1->set_gps_y_m( lane_current .position_offset(lane_current.position_offset_size() - 1) .y()); auto* single_trafficlight = lane_tl1->add_single_traffic_light(); // switch (connections_data.allow_driving_behavior()) { // case ::apollo::v2x::Connection::STRAIGHT: // single_trafficlight->add_trafficlight_type( // apollo::v2x::SingleTrafficLight::STRAIGHT); // break; // case ::apollo::v2x::Connection::LEFT: // single_trafficlight->add_trafficlight_type( // apollo::v2x::SingleTrafficLight::LEFT); // break; // case ::apollo::v2x::Connection::RIGHT: // single_trafficlight->add_trafficlight_type( // apollo::v2x::SingleTrafficLight::RIGHT); // break; // case ::apollo::v2x::Connection::U_TURN: // single_trafficlight->add_trafficlight_type( // apollo::v2x::SingleTrafficLight::U_TURN); // break; // default: // break; // } switch (intersection_phase.color()) { case ::apollo::v2x::Phase::UNKNOWN: single_trafficlight->set_color( apollo::v2x::SingleTrafficLight::UNKNOWN); break; case ::apollo::v2x::Phase::RED: single_trafficlight->set_color( apollo::v2x::SingleTrafficLight::RED); break; case ::apollo::v2x::Phase::YELLOW: single_trafficlight->set_color( apollo::v2x::SingleTrafficLight::YELLOW); break; case ::apollo::v2x::Phase::GREEN: single_trafficlight->set_color( apollo::v2x::SingleTrafficLight::GREEN); break; case ::apollo::v2x::Phase::BLACK: single_trafficlight->set_color( apollo::v2x::SingleTrafficLight::BLACK); break; case ::apollo::v2x::Phase::FLASH_GREEN: single_trafficlight->set_color( apollo::v2x::SingleTrafficLight::FLASH_GREEN); break; default: break; } // single_trafficlight->set_color_remaining_time_s( // intersection_phase.color_remaining_time_s()); } } } sequence_num_++; return true; } } return false; } bool Trafficlight::ReadMapPosition(const RoadPoint_t* road_point, apollo::v2x::Position2D* points) { if (road_point == nullptr) { LOG(ERROR) << "Error: Map node info is empty!"; return false; } switch (road_point->posOffset.offsetLL.present) { case 1: latitude_ = (double)(road_point->posOffset.offsetLL.choice.position_LL1.lat) / kResolutionRatio; longitude_ = (double)(road_point->posOffset.offsetLL.choice.position_LL1.lon) / kResolutionRatio; coordinate_ransition_.LatLonToUTMXY(latitude_, longitude_, point_x_, point_y_); points->set_x(point_x_); points->set_y(point_y_); break; case 2: latitude_ = (double)(road_point->posOffset.offsetLL.choice.position_LL2.lat) / kResolutionRatio; longitude_ = (double)(road_point->posOffset.offsetLL.choice.position_LL2.lon) / kResolutionRatio; coordinate_ransition_.LatLonToUTMXY(latitude_, longitude_, point_x_, point_y_); points->set_x(point_x_); points->set_y(point_y_); break; case 3: latitude_ = (double)(road_point->posOffset.offsetLL.choice.position_LL3.lat) / kResolutionRatio; longitude_ = (double)(road_point->posOffset.offsetLL.choice.position_LL3.lon) / kResolutionRatio; coordinate_ransition_.LatLonToUTMXY(latitude_, longitude_, point_x_, point_y_); points->set_x(point_x_); points->set_y(point_y_); break; case 4: latitude_ = (double)(road_point->posOffset.offsetLL.choice.position_LL4.lat) / kResolutionRatio; longitude_ = (double)(road_point->posOffset.offsetLL.choice.position_LL4.lon) / kResolutionRatio; coordinate_ransition_.LatLonToUTMXY(latitude_, longitude_, point_x_, point_y_); points->set_x(point_x_); points->set_y(point_y_); break; case 5: latitude_ = (double)(road_point->posOffset.offsetLL.choice.position_LL5.lat) / kResolutionRatio; longitude_ = (double)(road_point->posOffset.offsetLL.choice.position_LL5.lon) / kResolutionRatio; coordinate_ransition_.LatLonToUTMXY(latitude_, longitude_, point_x_, point_y_); points->set_x(point_x_); points->set_y(point_y_); break; case 6: latitude_ = (double)(road_point->posOffset.offsetLL.choice.position_LL6.lat) / kResolutionRatio; longitude_ = (double)(road_point->posOffset.offsetLL.choice.position_LL6.lon) / kResolutionRatio; coordinate_ransition_.LatLonToUTMXY(latitude_, longitude_, point_x_, point_y_); points->set_x(point_x_); points->set_y(point_y_); break; case 7: latitude_ = (double)(road_point->posOffset.offsetLL.choice.position_LatLon.lat) / kResolutionRatio; longitude_ = (double)(road_point->posOffset.offsetLL.choice.position_LatLon.lon) / kResolutionRatio; coordinate_ransition_.LatLonToUTMXY(latitude_, longitude_, point_x_, point_y_); points->set_x(point_x_); points->set_y(point_y_); break; default: LOG(ERROR) << "points.present" << road_point->posOffset.offsetLL.present; return false; break; } return true; } bool Trafficlight::ReadMapConnectsTo(const Connection_t* connects_to, apollo::v2x::Connection* connections) { if (connects_to == nullptr) { LOG(ERROR) << "Error: Map connectsTo info empty !"; return false; } // connectingLane maneuver if (connects_to->connectingLane != nullptr) { int maneuvers = 0; memcpy(&maneuvers, connects_to->connectingLane->maneuver->buf, sizeof(uint8_t) * connects_to->connectingLane->maneuver->size); if (connects_to->connectingLane->maneuver->size > 1) { maneuvers = ntohs(maneuvers); } switch (maneuvers) { case 0: connections->set_allow_driving_behavior( ::apollo::v2x::Connection::STRAIGHT); break; case 1: connections->set_allow_driving_behavior( ::apollo::v2x::Connection::LEFT); break; case 2: connections->set_allow_driving_behavior( ::apollo::v2x::Connection::RIGHT); break; case 3: connections->set_allow_driving_behavior( ::apollo::v2x::Connection::U_TURN); break; default: LOG(ERROR) << "AllowedManeuvers" << maneuvers; return false; break; } } // phaseID if (connects_to->phaseId != nullptr) { connections->set_phase_id(*(connects_to->phaseId)); } return true; } bool Trafficlight::ReadMapLane(const Lane_t* plane, apollo::v2x::Lane* lanes) { if (plane == nullptr) { LOG(ERROR) << "Error: Map lane info is empty!"; return false; } lanes->set_lane_id(plane->laneID); if (plane->maneuvers != nullptr) { int lane_maneuvers = 0; memcpy(&lane_maneuvers, plane->maneuvers->buf, sizeof(uint8_t) * plane->maneuvers->size); if (plane->maneuvers->size > 1) { lane_maneuvers = ntohs(lane_maneuvers); } } if (plane->connectsTo != nullptr) { for (int m = 0; m < plane->connectsTo->list.count; m++) { bool connect_falg = ReadMapConnectsTo(plane->connectsTo->list.array[m], lanes->add_connections()); if (!connect_falg) { LOG(ERROR) << "Error: Map_connects_Fill failed "; return false; } } } if (plane->points != nullptr) { for (int n = 0; n < plane->points->list.count; n++) { bool points_flag = ReadMapPosition(plane->points->list.array[n], lanes->add_position_offset()); if (!points_flag) { LOG(ERROR) << "Error: Map_connects_Fill failed "; return false; } } } return true; } bool Trafficlight::ReadMapRoad(const Link_t* pInlink_j, apollo::v2x::Road* roads) { roads->set_upstream_node_id(pInlink_j->upstreamNodeId.id); for (int k = 0; k < pInlink_j->lanes.list.count; k++) { bool lane_falg = ReadMapLane(pInlink_j->lanes.list.array[k], roads->add_lanes()); if (!lane_falg) { LOG(ERROR) << "Error: Map_LaneInfo_Fill failed"; return false; } } return true; } bool Trafficlight::ReadMapIntersection( const Node_t* nodes, apollo::v2x::Intersection* intersections) { intersections->set_id(nodes->id.id); latitude_ = (double)(nodes->refPos.lat) / kResolutionRatio; longitude_ = (double)(nodes->refPos.Long) / kResolutionRatio; apollo::v2x::Position2D* refpos = intersections->mutable_position(); coordinate_ransition_.LatLonToUTMXY(latitude_, longitude_, point_x_, point_y_); refpos->set_x(point_x_); refpos->set_y(point_y_); for (int j = 0; j < nodes->inLinks->list.count; j++) { bool road_falg = ReadMapRoad(nodes->inLinks->list.array[j], intersections->add_roads()); if (!road_falg) { LOG(ERROR) << "Error: Map_RoadInfo_Fill failed"; return false; } } return true; } bool Trafficlight::ReadMap(const MapData_t* rsu_map, apollo::v2x::Map* map) { if (nullptr == rsu_map) { LOG(ERROR) << "Error: Map info is empty!"; return false; } // nodes, means intersection or road segment map->set_msg_cnt(rsu_map->msgCnt); for (int i = 0; i < rsu_map->nodes.list.count; i++) { bool intersection_flag = ReadMapIntersection(rsu_map->nodes.list.array[i], map->add_intersections()); if (!intersection_flag) { LOG(ERROR) << "Error: Map_IntersectionInfo_Fill failed"; return false; } } return true; } bool Trafficlight::ReadSpat(const SPAT_t* rsu_spat, apollo::v2x::Spat* spat) { IntersectionState_t* intersection_state = nullptr; Phase_t* phase = nullptr; PhaseState_t* phase_state = nullptr; if (rsu_spat == nullptr) { LOG(ERROR) << "Error: Spat info is empty!"; return false; } spat->set_msg_cnt(rsu_spat->msgCnt); for (int i = 0; i < rsu_spat->intersections.list.count; i++) { if (rsu_spat->intersections.list.array[i] == nullptr) { LOG(ERROR) << "rsu_spat->intersections.list.array[i] == nullptr"; return false; } intersection_state = rsu_spat->intersections.list.array[i]; apollo::v2x::IntersectionState* pb_intersection_state = spat->add_intersections(); pb_intersection_state->set_intersection_id( intersection_state->intersectionId.id); if (intersection_state->moy == nullptr || intersection_state->timeStamp == nullptr) { LOG(WARNING) << "intersection_state->moy || " "intersection_state->timeStamp == nullptr"; } else { pb_intersection_state->set_moy(*(intersection_state->moy)); pb_intersection_state->set_time_stamp_dsecond( *(intersection_state->timeStamp)); } for (int j = 0; j < intersection_state->phases.list.count; j++) { if (intersection_state->phases.list.array[j] == nullptr) { LOG(ERROR) << "intersection_state->phases.list.array[j] == nullptr"; return false; } phase = intersection_state->phases.list.array[j]; ::apollo::v2x::Phase* pb_phase_state = pb_intersection_state->add_phases(); pb_phase_state->set_id(phase->id); for (int k = 0; k < phase->phaseStates.list.count; k++) { if (phase->phaseStates.list.array[k] == nullptr) { LOG(ERROR) << "phase->phaseStates.list.array[%d] == nullptr"; return false; } phase_state = phase->phaseStates.list.array[k]; // Timing if (phase_state->timing->startTime == 0) { switch (phase_state->light) { case 0: pb_phase_state->set_color(::apollo::v2x::Phase::UNKNOWN); break; case 1: pb_phase_state->set_color(::apollo::v2x::Phase::BLACK); break; case 3: pb_phase_state->set_color(::apollo::v2x::Phase::RED); break; case 7: pb_phase_state->set_color(::apollo::v2x::Phase::YELLOW); break; case 5: pb_phase_state->set_color(::apollo::v2x::Phase::GREEN); break; case 6: pb_phase_state->set_color(::apollo::v2x::Phase::GREEN); break; case 8: pb_phase_state->set_color(::apollo::v2x::Phase::FLASH_GREEN); break; default: LOG(ERROR) << "phase_state->light: " << phase_state->light; return false; break; } // likelyTime int color_remaining_time_s = (int)(phase_state->timing->likelyEndTime / 10); pb_phase_state->set_color_remaining_time_s(color_remaining_time_s); } } } } return true; } } // namespace v2x //} // namespace apollo
0
apollo_public_repos/apollo-contrib/obu/app/policies
apollo_public_repos/apollo-contrib/obu/app/policies/trafficlight_process/CMakeLists.txt
cmake_minimum_required(VERSION 2.8) #project(v2x_trafficlight) ########### ## Build ## ########### #SET( CMAKE_CXX_FLAGS "-std=c++11 -O3 -Wall -lgflags -pthread") #include_directories( # ../../proto/include #) #include_directories( # ../../msg_sets/asn1_source #) #include_directories( # ../../proxy #) #include_directories( # ${CMAKE_CURRENT_SOURCE_DIR} # ${CMAKE_CURRENT_SOURCE_DIR}/../../ # ${CMAKE_CURRENT_SOURCE_DIR}/../../../utils #) #link_directories( # ${CMAKE_CURRENT_BINARY_DIR}../../build/proto # ${CMAKE_CURRENT_BINARY_DIR}../../build/msg_sets #) #include_directories("/usr/local/include") #link_directories("/usr/local/lib") #include_directories("/usr/include/x86_64-linux-gnu") #link_directories("/usr/lib/x86_64-linux-gnu") add_library(policy v2x_traffic_light.cc) target_link_libraries(policy protobuf gflags proto utils obu_conf glog) add_executable(v2x_test ./test/v2x_traffic_light_test.cc) target_link_libraries(v2x_test protobuf gflags grpc grpc++ proto policy proxy) ############# ## Install ## #############
0
apollo_public_repos/apollo-contrib/obu/app/policies
apollo_public_repos/apollo-contrib/obu/app/policies/trafficlight_process/v2x_traffic_light.h
/****************************************************************************** * 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. *****************************************************************************/ /** * @file v2x_traffic_light.h * @brief The traffic light program for the v2x module */ #ifndef APP_POLICIES_TRAFFICLIGHT_V2X_TRAFFIC_LIGHT_H #define APP_POLICIES_TRAFFICLIGHT_V2X_TRAFFIC_LIGHT_H #include <math.h> #include <netinet/in.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/timeb.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include <cmath> #include <iostream> #include <string> #include <thread> #include <vector> #include "MapData.h" #include "SPAT.h" #include "coordinate_transition/coordinate_transition.h" #include "glog/logging.h" #include "modules/v2x/proto/v2x_car_status.pb.h" #include "modules/v2x/proto/v2x_obu_traffic_light.pb.h" #include "modules/v2x/proto/v2x_traffic_light.pb.h" #include "modules/v2x/proto/v2x_traffic_light_policy.pb.h" // namespace apollo { namespace v2x { typedef enum ErrorInfo { Successful, ReadMapFailed, ReadSpatFailed, PolicyFailed } ErrorInfo; class Trafficlight { public: Trafficlight(); ~Trafficlight() {} // Function that init void Init(); // interface Function for traffic light app. The return value represents // the meaning of : 0 for true ; 1 for decode map error ; // 2 for decode spat error; 3 for policy error. ErrorInfo TrafficLightApp( const MapData_t* map, const SPAT_t* spat, const std::shared_ptr<apollo::v2x::CarStatus>& car_status_receive, std::shared_ptr<apollo::v2x::obu::ObuTrafficLight>& intersection_trafficlight_msg); // Function that orientation to the current lane traffic light info bool TrafficLightPolicy(const apollo::v2x::PolicyData& policy_data, const apollo::v2x::CarStatus& car_status, std::shared_ptr<apollo::v2x::obu::ObuTrafficLight>& intersection_trafficlights); // Function that acquisition system timestamp double GetSystemTime() { struct timeb t; ftime(&t); return t.time + t.millitm / 1000.0; } // Function that get the current year int GetCurrentYearMoy() { struct tm* local; time_t now; now = time(NULL); local = localtime(&now); return (local->tm_year + 1900 - 2018) * 525600 + 25245600; } // Constant PI const double kPi = 3.14159265358979323846; // Longitude and Latitude resolution ratio const double kResolutionRatio = 10000000.0; // The reference value of minimum distance const double kReferenceValue = 5000.0; double timestamp_ = 0.0; int sequence_num_ = 0; private: // Function that extract Map information bool ReadMap(const MapData_t* rsu_map, apollo::v2x::Map* map); // Function that extract Map intersection information bool ReadMapIntersection(const Node_t* nodes, apollo::v2x::Intersection* intersections); // Function that extract Map road information bool ReadMapRoad(const Link_t* pInlink_j, apollo::v2x::Road* roads); // Function that extract Map lane information bool ReadMapLane(const Lane_t* plane, apollo::v2x::Lane* lanes); // Function that extract Map connects to information bool ReadMapConnectsTo(const Connection_t* connects_to, apollo::v2x::Connection* connections); // Function that extract Map position information bool ReadMapPosition(const RoadPoint_t* road_point, apollo::v2x::Position2D* points); // Function that extract Spat information bool ReadSpat(const SPAT_t* rsu_spat, apollo::v2x::Spat* spat); // Invocation coordinate ransitions v2x::CoordinateTransition coordinate_ransition_; double self_position_x_ = 0.0; double self_position_y_ = 0.0; double intersection_position_x_ = 0.0; double intersection_position_y_ = 0.0; double distance_among_two_ = 0.0; double distance_among_two_min_ = 0.0; double longitude_ = 0.0; double latitude_ = 0.0; double point_x_ = 0.0; double point_y_ = 0.0; int previous_moy_ = 0; int present_moy_ = 0; int previous_dsecond_ = 0; int present_dsecond_ = 0; int current_year_moy_ = 0; bool debug_flag_ = FLAGS_debug_flag; }; } // namespace v2x //} // namespace apollo #endif // APP_POLICIES_TRAFFICLIGHT_V2X_TRAFFIC_LIGHT_H
0
apollo_public_repos/apollo-contrib/obu/app/policies/trafficlight_process
apollo_public_repos/apollo-contrib/obu/app/policies/trafficlight_process/test/v2x_traffic_light_test.cc
/****************************************************************************** * 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. *****************************************************************************/ /** * @file v2x_traffic_light_test.cc * @brief The traffic light program for the v2x module */ #include "policies/trafficlight_process/v2x_traffic_light.h" #include "proxy/proxy.h" #include "gflags/gflags.h" int g_color_remaining_time = 30; void set_policy(apollo::v2x::PolicyData& policy_data_pb) { apollo::v2x::Map* map_pb = policy_data_pb.mutable_map(); apollo::v2x::Spat* spat_pb = policy_data_pb.mutable_spat(); map_pb->set_msg_cnt(0); apollo::v2x::Intersection* intersection0 = map_pb->add_intersections(); intersection0->set_id(0); intersection0->mutable_position()->set_x(437544.060390); intersection0->mutable_position()->set_y(4432885.512208); apollo::v2x::Road* road0 = intersection0->add_roads(); apollo::v2x::Lane* lane0_0 = road0->add_lanes(); lane0_0->set_lane_id(0); apollo::v2x::Position2D* point0 = lane0_0->add_position_offset(); point0->set_x(437563.244215); point0->set_y(4432817.089782); apollo::v2x::Position2D* point1 = lane0_0->add_position_offset(); point1->set_x(437556.260441); point1->set_y(4432849.670223); apollo::v2x::Position2D* point2 = lane0_0->add_position_offset(); point2->set_x(437552.949001); point2->set_y(4432872.341472); apollo::v2x::Connection* connection0_0 = lane0_0->add_connections(); connection0_0->set_allow_driving_behavior(apollo::v2x::Connection::STRAIGHT); connection0_0->set_phase_id(2); apollo::v2x::Road* road1 = intersection0->add_roads(); apollo::v2x::Lane* lane1_0 = road1->add_lanes(); lane1_0->set_lane_id(1); apollo::v2x::Position2D* point3 = lane1_0->add_position_offset(); point3->set_x(437633.397056); point3->set_y(4432913.749621); apollo::v2x::Position2D* point4 = lane1_0->add_position_offset(); point4->set_x(437589.964083); point4->set_y(4432902.229316); apollo::v2x::Position2D* point5 = lane1_0->add_position_offset(); point5->set_x(437561.583178); point5->set_y(4432895.247529); apollo::v2x::Connection* connection1_0 = lane1_0->add_connections(); connection1_0->set_allow_driving_behavior(apollo::v2x::Connection::STRAIGHT); connection1_0->set_phase_id(1); apollo::v2x::Road* road2 = intersection0->add_roads(); apollo::v2x::Lane* lane2_0 = road2->add_lanes(); lane2_0->set_lane_id(2); apollo::v2x::Position2D* point6 = lane2_0->add_position_offset(); point6->set_x(437525.616799); point6->set_y(4432992.890378); apollo::v2x::Position2D* point7 = lane2_0->add_position_offset(); point7->set_x(437533.279508); point7->set_y(4432949.537297); apollo::v2x::Position2D* point8 = lane2_0->add_position_offset(); point8->set_x(437540.543593); point8->set_y(4432899.194496); apollo::v2x::Connection* connection2_0 = lane2_0->add_connections(); connection2_0->set_allow_driving_behavior(apollo::v2x::Connection::STRAIGHT); connection2_0->set_phase_id(2); apollo::v2x::Road* road3 = intersection0->add_roads(); apollo::v2x::Lane* lane3_0 = road3->add_lanes(); lane3_0->set_lane_id(3); apollo::v2x::Position2D* point9 = lane3_0->add_position_offset(); point9->set_x(437465.898447); point9->set_y(4432858.072548); apollo::v2x::Position2D* point10 = lane3_0->add_position_offset(); point10->set_x(437506.914988); point10->set_y(4432866.171025); apollo::v2x::Position2D* point11 = lane3_0->add_position_offset(); point11->set_x(437539.151270); point11->set_y(4432875.118913); apollo::v2x::Connection* connection3_0 = lane3_0->add_connections(); connection3_0->set_allow_driving_behavior(apollo::v2x::Connection::STRAIGHT); connection3_0->set_phase_id(1); // spat spat_pb->set_msg_cnt(0); apollo::v2x::IntersectionState* intersection_state0 = spat_pb->add_intersections(); intersection_state0->set_intersection_id(0); apollo::v2x::Phase* phase_date1 = intersection_state0->add_phases(); phase_date1->set_id(1); phase_date1->set_color(apollo::v2x::Phase::GREEN); phase_date1->set_color_remaining_time_s(g_color_remaining_time); apollo::v2x::Phase* phase_date2 = intersection_state0->add_phases(); phase_date2->set_id(2); phase_date2->set_color(apollo::v2x::Phase::RED); phase_date2->set_color_remaining_time_s(g_color_remaining_time); g_color_remaining_time--; if (g_color_remaining_time < 0) { g_color_remaining_time = 60; } } int main(int argc, char** argv) { GOOGLE_PROTOBUF_VERIFY_VERSION; google::ParseCommandLineFlags(&argc, &argv, true); v2x::V2xProxy proxy("192.168.10.121:50100", "192.168.10.6:50101"); v2x::Trafficlight tl; while (true) { std::shared_ptr<apollo::v2x::IntersectionTrafficLightData> intersection_trafficlights( new apollo::v2x::IntersectionTrafficLightData); apollo::v2x::PolicyData policy_data; // SPAT_t* spat = new SPAT_t; // SPAT_t* spat = (SPAT_t*)malloc(sizeof(SPAT_t)); // MapData_t* map = new MapData_t; set_policy(policy_data); // std::cout << policy_data.DebugString() << std::endl; double x = 0.0; double y = 0.0; std::cout.unsetf(std::ios::scientific); std::cout.setf(std::ios::fixed); std::cout.precision(11); std::cout << "x: " << x << std::endl; std::cout << "y: " << y << std::endl; std::shared_ptr<apollo::v2x::CarStatus> car_status = proxy.GetCarStatus(); bool policy_falg = tl.TrafficLightPolicy(policy_data, *car_status, intersection_trafficlights); if (!policy_falg) { std::cout << "policy error or msg : " << std::endl; } proxy.SendTrafficLights(*intersection_trafficlights); // sleep(1); } google::protobuf::ShutdownProtobufLibrary(); return 0; }
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/network_adapter/CMakeLists.txt
cmake_minimum_required(VERSION 2.8) add_library(ntw_adapter pc5/adapter_pc5.cc uu/adapter_uu.cc uu/uu_send.cc) #add_subdirectory(uu) #add_subdirectory(pc5)
0
apollo_public_repos/apollo-contrib/obu/app/network_adapter
apollo_public_repos/apollo-contrib/obu/app/network_adapter/uu/uu_send.cc
/****************************************************************************** * 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. *****************************************************************************/ /** * @file uu_send.cc * @brief adaptation module send the data to remote server via uu interface. */ #include "uu_send.h" #include <arpa/inet.h> #include <sys/socket.h> #include <sys/timerfd.h> #include <sys/types.h> #include <time.h> #include <iostream> #include <string> #include "cv2x_app_layer/cv2x_message_frame.h" #include "cv2x_app.h" #include "database/v2x_db.h" #include "glog/logging.h" #include "msg_sets/uu_message_set.h" #include "network_adapter/pc5/adapter_pc5.h" #include "platform_auth/auth_manager.h" #include "platform_auth/encrypt_utils.h" #include "coordinate_transition/coordinate_transition.h" #include "proxy/proxy.h" namespace v2x { UuSend::UuSend(std::string src_addr, uint32_t src_port, uint32_t interval) : OsThread("UuSendThread", OS_THREAD_PRIORITY_NORMAL, OS_THREAD_DEFAULT_STACK_SIZE, true), src_addr_(src_addr), src_port_(src_port), interval_(interval) { int timerfd = ::timerfd_create(CLOCK_MONOTONIC, 0); if (timerfd < 0) { LOG(ERROR) << "Failed in timerfd_create"; return; } timer_fd_ = timerfd; is_cyclical_ = true; Initialize(); } UuSend::~UuSend(void) { // close socket close(send_socket_); // close timer close(timer_fd_); } void UuSend::Initialize() { send_addr_.sin_family = AF_INET; send_addr_.sin_addr.s_addr = inet_addr(src_addr_.c_str()); send_addr_.sin_port = htons(src_port_); send_socket_ = socket(AF_INET, SOCK_DGRAM, 0); if (send_socket_ < 0) { LOG(ERROR) << "create sending socket error!"; return; } // struct timeval tv_out; // tv_out.tv_sec = 1; // tv_out.tv_usec = 0; // setsockopt(send_socket_, SOL_SOCKET, SO_RCVTIMEO, &tv_out, sizeof(tv_out)); return; } int UuSend::GetSocketFd() { return send_socket_; } bool UuSend::SendData(char *buf, uint32_t len) { int slen = sendto(send_socket_, buf, len, 0, (struct sockaddr *)&send_addr_, sizeof(send_addr_)); if (slen < 0) { LOG(ERROR) << "send got error: " << slen << ", " << strerror(errno); return false; } return true; } void UuSend::TimerExpired() { BaseAuthManager *auth_manager = BaseAuthManagerSingleton::Instance(); uint32_t len = GetNetworkMtu(); std::shared_ptr<UuMessageSet> message_set = std::shared_ptr<UuMessageSet>(new UuMessageSet()); V2xProxy *grpc = V2xProxySingleton::Instance(); // get position from carstatus auto car_status = grpc->GetCarStatus(); if (car_status == nullptr) { LOG(INFO) << "can't get car status"; if (!v2x::fLB::FLAGS_uu_debug) { return; } } BsmConfig_t bsm_config; memset(&bsm_config, 0x00, sizeof(BsmConfig_t)); bsm_config.token = 4; message_set->SetBSMCfg(&bsm_config); BsmParam_t *bsm_para = new BsmParam_t; memset(bsm_para, 0x00, sizeof(BsmParam_t)); std::string device_id = auth_manager->GetDeviceId(); uint8_t id[8]; uint32_t i; for (i = 0; i < (device_id.length() / 2); i++) { sscanf(device_id.c_str() + (2 * i), "%2hhx", id + i); } memcpy(&(bsm_para->id), id, 8); message_set->SetBSMPara(bsm_para); static int32_t msg_cnt = 0; if (msg_cnt == 127) { msg_cnt = 0; } bsm_para->msgCnt = msg_cnt++; double position_x = 0.0; double position_y = 0.0; if (!v2x::fLB::FLAGS_uu_debug) { position_x = car_status->localization().pose().position().x(); position_y = car_status->localization().pose().position().y(); } else { // this position is in Haidianjiaxiao position_x = 423915.980284080; position_y = 4437985.401765677; } LOG(INFO) << "Position x:y=" << std::fixed << std::setprecision(10) << position_x<<", " << position_y; double lat = 0; double lon = 0; CoordinateTransition coord_trans; coord_trans.UTMXYToLatLon(position_x, position_y, lat, lon); if (v2x::fLB::FLAGS_uu_debug) { // for test, real position in Wuxi lat = 31.4825152; lon = 120.319680; } LOG(INFO) << "Position x:y=" << std::fixed << std::setprecision(10) << lat<<", " << lon; bsm_para->pos_lat = static_cast<int32_t>(lat * 10000000); bsm_para->pos_lon = static_cast<int32_t>(lon * 10000000); LOG(INFO) << "BSM parameter, " << bsm_para->pos_lat << ", " << bsm_para->pos_lon; std::string auth_token = auth_manager->GetToken(); uint8_t token[4]; for (i = 0; i < (auth_token.length() / 2); i++) { sscanf(auth_token.c_str() + (2 * i), "%2hhx", token + i); } memcpy(&(bsm_para->token), token, 4); int encode_size; uint8_t *pbuf = nullptr; try { pbuf = new uint8_t[len]; } catch (const std::bad_alloc &e) { LOG(ERROR) << "memory malloc failed for bsm_encrypt."; delete bsm_para; return; } message_set->EncodeBSM(&pbuf, len, &encode_size); if (encode_size < 0) { LOG(ERROR) << "encode failed."; delete[] pbuf; delete bsm_para; return; } LOG(INFO) << "encode size." << encode_size; // encypt char *bsm_encrypt = nullptr; // PKCS5 padding is lesss than 16bytes. try { bsm_encrypt = new char[encode_size + 16]; } catch (const std::bad_alloc &e) { LOG(ERROR) << "memory malloc failed for bsm_encrypt."; delete[] pbuf; delete bsm_para; return; } memset(bsm_encrypt, 0x00, encode_size + 16); int bsm_encrypt_len = AESECButil::EncryptPKCS5( reinterpret_cast<unsigned char *>(pbuf), encode_size, reinterpret_cast<unsigned char *>(bsm_encrypt), auth_manager->GetKey()); if (bsm_encrypt_len > 0) { if (!SendData(bsm_encrypt, bsm_encrypt_len)) { LOG(ERROR) << "send data failed."; } } else { LOG(ERROR) << "encrypt failed."; } delete[] pbuf; delete[] bsm_encrypt; delete bsm_para; return; } void UuSend::Run() { struct itimerspec timer_interval = {0}; timer_interval.it_value.tv_sec = interval_ / 1000; timer_interval.it_value.tv_nsec = (interval_ % 1000) * 1000000LLU; timer_interval.it_interval.tv_sec = timer_interval.it_value.tv_sec; timer_interval.it_interval.tv_nsec = timer_interval.it_value.tv_nsec; BaseAuthManager *auth_manager = BaseAuthManagerSingleton::Instance(); AUTH_STATUS auth_status = auth_manager->GetAuthStatus(); while (auth_status != AUTH_STATUS::AUTHED) { sleep(1); auth_status = auth_manager->GetAuthStatus(); } LOG(INFO) << "auth passed."; if (timerfd_settime(timer_fd_, 0, &timer_interval, NULL) == -1) { LOG(ERROR) << "timerfd_settime failed " << strerror(errno); return; } uint64_t howmany = 0; ssize_t size = 0; while (1) { size = ::read(timer_fd_, &howmany, sizeof(howmany)); if (size != sizeof(howmany)) { LOG(ERROR) << "Periodical timer reads " << size << "bytes"; } TimerExpired(); } return; } } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app/network_adapter
apollo_public_repos/apollo-contrib/obu/app/network_adapter/uu/CMakeLists.txt
cmake_minimum_required(VERSION 2.8) aux_source_directory(. DIRSRCS) add_library(Uu ${DIRSRCS})
0
apollo_public_repos/apollo-contrib/obu/app/network_adapter
apollo_public_repos/apollo-contrib/obu/app/network_adapter/uu/adapter_uu.cc
/****************************************************************************** * 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. *****************************************************************************/ /** * @file adapter_uu.cc * @brief adaptation module recieves the data from network layer * via uu interface. */ #include "adapter_uu.h" #include <arpa/inet.h> #include <sys/socket.h> #include <sys/types.h> #include <iostream> #include <string> #include "cv2x_app.h" #include "database/v2x_db.h" #include "glog/logging.h" #include "msg_sets/message_set.h" #include "platform_auth/auth_manager.h" #include "platform_auth/encrypt_utils.h" namespace v2x { AdapterUu::AdapterUu(int fd) : OsThread("adapter_uu", OS_THREAD_PRIORITY_NORMAL, OS_THREAD_DEFAULT_STACK_SIZE, true), recv_socket_(fd) {} AdapterUu::~AdapterUu(void) {} // recv will get all data one time void AdapterUu::RecvData() { char* data; try { data = new char[1024]; } catch (const std::bad_alloc& e) { LOG(ERROR) << "alloc memory failed"; return; } memset(data, 0, 1024); uint32_t appid = 0; int ret = 0; MessageFrame_t* pMsgFrm = NULL; V2xDb* data_base_inst = V2xDbSingleton::Instance(); #ifdef COMPUTE_COST struct timespec time_start = {0, 0}, time_end = {0, 0}; clock_gettime(CLOCK_REALTIME, &time_start); #endif int rlen = recvfrom(recv_socket_, data, 1024, 0, nullptr, nullptr); #ifdef COMPUTE_COST clock_gettime(CLOCK_REALTIME, &time_end); long cost = (time_end.tv_sec - time_start.tv_sec) * 1000000 + (time_end.tv_nsec - time_start.tv_nsec) / 1000; std::cout << "===========cost time:" << cost << "us===========" << std::endl; #endif if (rlen < 0) { LOG(ERROR) << "recvfrom got error: " << rlen << ", error " << strerror(errno); delete[] data; return; } LOG(INFO) << "Get data successfully from server, length:" << rlen; // decode the message to get the type ret = cv2x_message_frame_decode(&pMsgFrm, UPER_CODE_TYPE, data, rlen); if (ret != CV2X_SUCCESS) { LOG(ERROR) << "decode failed, ret(" << ret << ")"; delete[] data; return; } if (pMsgFrm->present == MessageFrame_PR_mapFrame) { appid = 29; } else if (pMsgFrm->present == MessageFrame_PR_spatFrame) { appid = 30; } else { LOG(INFO) << "the message type " << pMsgFrm->present; ret = cv2x_message_frame_free(pMsgFrm, 0); if (ret != 0) { LOG(ERROR) << "free message failed (" << ret << ")"; } delete[] data; return; } ret = cv2x_message_frame_free(pMsgFrm, 0); if (ret != 0) { LOG(ERROR) << "free message failed (" << ret << ")"; } data_base_inst->SubmitData(data, rlen, appid); return; } void AdapterUu::Run() { BaseAuthManager* auth_manager = BaseAuthManagerSingleton::Instance(); AUTH_STATUS auth_status = NONE; while (1) { while (auth_status != AUTHED) { usleep(5000); auth_status = auth_manager->GetAuthStatus(); } RecvData(); } } } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app/network_adapter
apollo_public_repos/apollo-contrib/obu/app/network_adapter/uu/uu_send.h
/****************************************************************************** * 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. *****************************************************************************/ /** * @file uu_send.h * @brief define Adapter class as a thread */ #pragma once #include <arpa/inet.h> #include <sys/socket.h> #include <string> #include "os_thread.h" namespace v2x { class UuSend final : public OsThread { public: UuSend(std::string src_addr, uint32_t src_port, uint32_t interval); virtual ~UuSend(); void Initialize(); virtual void Run(); int GetSocketFd(); private: void TimerExpired(); bool SendData(char* buf, uint32_t len); std::string src_addr_; uint32_t src_port_ = 0; sockaddr_in send_addr_; int send_socket_ = 0; uint32_t interval_ = 0; int timer_fd_ = 0; bool is_cyclical_ = false; }; } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app/network_adapter
apollo_public_repos/apollo-contrib/obu/app/network_adapter/uu/adapter_uu.h
/****************************************************************************** * 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. *****************************************************************************/ /** * @file adapter_uu.h * @brief define Adapter class as a thread */ #pragma once #include <arpa/inet.h> #include <sys/socket.h> #include "os_thread.h" namespace v2x { class AdapterUu final : public OsThread { public: AdapterUu(int fd); virtual ~AdapterUu(); void Initialize(); virtual void Run(); private: void RecvData(); std::string dst_addr_; uint32_t dst_port_ = 0; int recv_socket_ = 0; sockaddr_in recv_addr_; }; } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app/network_adapter
apollo_public_repos/apollo-contrib/obu/app/network_adapter/pc5/CMakeLists.txt
cmake_minimum_required(VERSION 2.8) aux_source_directory(. DIRSRCS) add_library(PC5 ${DIRSRCS}) #add_dependencies(v2x_db proto)
0
apollo_public_repos/apollo-contrib/obu/app/network_adapter
apollo_public_repos/apollo-contrib/obu/app/network_adapter/pc5/adapter_pc5.cc
/****************************************************************************** * 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. *****************************************************************************/ /** * @file adapter_pc5.cc * @brief adaptation module recieves the data from pc5 interface. */ #include "adapter_pc5.h" #include <iostream> #include "cv2x_app.h" #include "database/v2x_db.h" #include "glog/logging.h" #include "security.h" namespace v2x { eMsgType GetMsgType(uint32_t appid) { return get_msg_type(appid); } uint32_t GetNetworkMtu() { return get_mtu(); } char* Adapter::MallocStr(uint32_t buf_size) { try { char* buf = new char[buf_size]; memset(buf, 0, buf_size); return buf; } catch (const std::bad_alloc& e) { LOG(ERROR) << "memory malloc failed for buf"; return nullptr; } } int Adapter::RecvPackage(char* buf, uint32_t len, tDSMRxParm* dsmRxParm) { int cnt = 0; cnt = v2x_system_read(buf, len, dsmRxParm); if (cnt <= 0) { LOG(ERROR) << "recv wrong(" << cnt << ")"; return -1; } return cnt; } void Adapter::ProcessUnsecured() { char* buf = nullptr; uint32_t len = GetNetworkMtu(); int cnt = 0; tDSMRxParm dsmRxParm = {0}; V2xDb* data_base_inst = V2xDbSingleton::Instance(); while (1) { buf = MallocStr(len); if (buf == nullptr) { continue; } cnt = RecvPackage(buf, len, &dsmRxParm); if (cnt > 0) { data_base_inst->SubmitData(buf, cnt, dsmRxParm.appId); } else { delete[] buf; } } } void Adapter::ProcessSecured() { uint32_t len = GetNetworkMtu(); char* buf = nullptr; int cnt = 0; tDSMRxParm dsmRxParm = {0}; Security security(root_ca_, self_ca_); char* data = nullptr; uint32_t data_len = 0; V2xDb* data_base_inst = V2xDbSingleton::Instance(); if (security.Init() != 0) { LOG(ERROR) << "Security init failed"; return; } try { buf = new char[len]; } catch (const std::bad_alloc& e) { LOG(ERROR) << "memory malloc failed for buf"; return; } while (1) { memset(buf, 0, len); data = MallocStr(len); if (data == nullptr) { continue; } cnt = RecvPackage(buf, len, &dsmRxParm); if (cnt <= 0) { delete[] data; continue; } if (security.VerifyAndStrip((uint8_t*)buf, cnt, (uint8_t*)data, &data_len) != 0) { LOG(ERROR) << "Security verify failed"; delete[] data; continue; } data_base_inst->SubmitData(data, data_len, dsmRxParm.appId); } } void Adapter::Run() { int32_t ret = 0; ret = v2x_system_init(); if (ret != 0) { LOG(ERROR) << "V2X system init failed"; return; } if (!security_flag_) { return ProcessUnsecured(); } else { return ProcessSecured(); } } } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app/network_adapter
apollo_public_repos/apollo-contrib/obu/app/network_adapter/pc5/adapter_pc5.h
/****************************************************************************** * 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. *****************************************************************************/ /** * @file adapter_pc5.h * @brief define Adapter class as a thread */ #pragma once #include "cv2x_app.h" #include "os_thread.h" namespace v2x { eMsgType GetMsgType(uint32_t appid); uint32_t GetNetworkMtu(); class Adapter final : public OsThread { public: Adapter(bool security_flag, std::string root_ca, std::string self_ca) : OsThread("adapter", OS_THREAD_PRIORITY_NORMAL, OS_THREAD_DEFAULT_STACK_SIZE, true), security_flag_(security_flag), root_ca_(root_ca), self_ca_(self_ca){}; virtual ~Adapter() = default; virtual void Run(); // eMsgType GetMsgType(uint32_t appid); // uint32_t GetNetworkMtu(); private: char* MallocStr(uint32_t buf_size); int RecvPackage(char* buf, uint32_t len, tDSMRxParm* dsmRxParm); void ProcessSecured(); void ProcessUnsecured(); bool security_flag_ = false; std::string root_ca_; std::string self_ca_; }; } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/scenario/CMakeLists.txt
cmake_minimum_required(VERSION 2.8) add_subdirectory(traffic_light) add_subdirectory(shared_sensor)
0
apollo_public_repos/apollo-contrib/obu/app/scenario
apollo_public_repos/apollo-contrib/obu/app/scenario/shared_sensor/CMakeLists.txt
cmake_minimum_required(VERSION 2.8) aux_source_directory(. DIRSRCS) add_library(ssm ${DIRSRCS}) add_dependencies(ssm proto policy)
0
apollo_public_repos/apollo-contrib/obu/app/scenario
apollo_public_repos/apollo-contrib/obu/app/scenario/shared_sensor/shared_sensor_thread.cc
/****************************************************************************** * Copyright 2020 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. *****************************************************************************/ /** * @file shared_sensor_thread.cc * @brief shared sensor thread. */ #include "shared_sensor_thread.h" #include <cstring> #include "apollo_ssm_decoder.h" #include "database/v2x_db.h" #include "glog/logging.h" #include "msg_sets/message_set.h" #include "network_adapter/pc5/adapter_pc5.h" #include "proxy/proxy.h" namespace v2x { void SharedSensorThread::Run() { bool flag = false; uint32_t mtu = GetNetworkMtu(); uint32_t ssm_buf_len = mtu; char* ssm_buf = nullptr; int ret = 0; V2xProxy* grpc = V2xProxySingleton::Instance(); V2xDb* data_base_inst = V2xDbSingleton::Instance(); try { ssm_buf = new char[ssm_buf_len]; } catch (const std::bad_alloc& e) { LOG(ERROR) << "memory malloc failed for ssm msg buf"; return; } auto v2x_obstacles = std::make_shared<apollo::v2x::V2XObstacles>(); if (!v2x_obstacles) { LOG(ERROR) << "failed to create obstacles"; return; } while (1) { v2x_obstacles->Clear(); ssm_buf_len = mtu; std::memset(ssm_buf, 0, ssm_buf_len); // Read the ssm message flag = data_base_inst->GetData(ssm_buf, &ssm_buf_len, MSG_TYPE_SSM); if (!flag) { LOG(ERROR) << "get the ssm msg is null"; continue; } LOG(INFO) << "recieved the ssm message with " << ssm_buf_len; std::string proto_str; if (::apollo::v2x::obu::conv::DecodeSSM(ssm_buf, ssm_buf_len, &proto_str)) { LOG(ERROR) << "Failed to decode SSM"; continue; } if (!v2x_obstacles->ParsePartialFromString(proto_str)) { LOG(ERROR) << "Failed to call ParsePartialFromString"; continue; } grpc->SendObstacles(*v2x_obstacles); } delete[] ssm_buf; } } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app/scenario
apollo_public_repos/apollo-contrib/obu/app/scenario/shared_sensor/shared_sensor_thread.h
/****************************************************************************** * Copyright 2020 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. *****************************************************************************/ /** * @file shared_sensor_thread.h * @brief define shared sensor class as a thread */ #pragma once #include "os_thread.h" namespace v2x { class SharedSensorThread final : public OsThread { public: SharedSensorThread() : OsThread("ssm_user_thrd", OS_THREAD_PRIORITY_NORMAL, OS_THREAD_DEFAULT_STACK_SIZE, true) {} virtual ~SharedSensorThread() {} virtual void Run(); }; } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app/scenario
apollo_public_repos/apollo-contrib/obu/app/scenario/traffic_light/CMakeLists.txt
cmake_minimum_required(VERSION 2.8) #project(v2x) # set the cross compiling #set(CMAKE_SYSTEM_NAME Linux) # cross_compiler for C #set(CMAKE_C_COMPILER "arm-poky-linux-gnueabi-gcc") # cross_compiler for C++ #set(CMAKE_CXX_COMPILER "arm-poky-linux-gnueabi-g++") #add_compile_options(-std=c++11) # where is the target environment #set(CMAKE_FIND_ROOT_PATH "/opt/fsl-imx-fb/4.9.88-2.0.0/sysroots/cortexa9hf-neon-poky-linux-gnueabi/usr" ) # "./3rdLibs/glfags/lib" # "./3rdLibs/glog/lib" # "./3rdLibs/grpc/lib" # "./3rdLibs/protobuf/lib") # search for programs in the build host directories #set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) # for libraries and headers in the target directories #set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) #set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) # where to find header files #include_directories(.) #include_directories(../../3rdLibs/gflags/include) #include_directories(../../3rdLibs/glog/include) #include_directories(../../3rdLibs/grpc/include) #include_directories(../../3rdLibs/protobuf/include) #include_directories # sub directories #add_subdirectory(gps) aux_source_directory(. DIRSRCS) add_library(tl ${DIRSRCS}) add_dependencies(tl proto policy) #target_link_libraries(v2x app util driver pal)
0
apollo_public_repos/apollo-contrib/obu/app/scenario
apollo_public_repos/apollo-contrib/obu/app/scenario/traffic_light/traffic_light_thread.cc
/****************************************************************************** * 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. *****************************************************************************/ /** * @file traffic_light_thread.cc * @brief traffic light thread. */ #include "traffic_light_thread.h" #include "database/v2x_db.h" #include "glog/logging.h" #include "msg_sets/message_set.h" #include "network_adapter/pc5/adapter_pc5.h" #include "policies/trafficlight_process/v2x_traffic_light.h" #include "proxy/proxy.h" namespace v2x { void TrafficLightThread::Run() { bool flag = false; char* map_buf = nullptr; char* spat_buf = nullptr; uint32_t mtu = GetNetworkMtu(); uint32_t spat_buf_len = mtu; uint32_t map_buf_len = mtu; MessageSet map_msg; MessageSet spat_msg; int ret = 0; SPAT_t* spat = nullptr; MapData_t* map = nullptr; V2xProxy* grpc = V2xProxySingleton::Instance(); V2xDb* data_base_inst = V2xDbSingleton::Instance(); v2x::Trafficlight tl; tl.Init(); try { map_buf = new char[map_buf_len]; } catch (const std::bad_alloc& e) { LOG(ERROR) << "memory malloc failed for map msg buf"; return; } try { spat_buf = new char[spat_buf_len]; } catch (const std::bad_alloc& e) { LOG(ERROR) << "memory malloc failed for spat msg buf"; delete[] map_buf; return; } while (1) { spat_buf_len = mtu; map_buf_len = mtu; memset(map_buf, 0, map_buf_len); memset(spat_buf, 0, spat_buf_len); // Read the spat message flag = data_base_inst->GetData(spat_buf, &spat_buf_len, MSG_TYPE_SPAT); if (!flag) { LOG(ERROR) << "get the spat msg is null"; continue; } LOG(INFO) << "recieved the spat message with " << spat_buf_len; ret = spat_msg.CreateSpat(); if (ret != 0) { LOG(ERROR) << "create spat message failed (" << ret << ")"; continue; } ret = spat_msg.DecodeSpat(spat_buf, UPER_CODE_TYPE, spat_buf_len); if (ret != 0) { LOG(ERROR) << "decode spat message failed (" << ret << ")"; continue; } spat = spat_msg.GetSpat(); if (spat == nullptr) { LOG(ERROR) << "spat message is nullptr"; continue; } // Read the map message flag = data_base_inst->GetData(map_buf, &map_buf_len, MSG_TYPE_MAP); if (!flag) { LOG(ERROR) << "get the map msg is null"; spat_msg.FreeAll(); continue; } LOG(INFO) << "recieved the map message with " << map_buf_len; ret = map_msg.CreateMap(); if (ret != 0) { LOG(ERROR) << "create the map message failed (" << ret << ")"; spat_msg.FreeAll(); continue; } ret = map_msg.DecodeMap(map_buf, UPER_CODE_TYPE, map_buf_len); if (ret != 0) { LOG(ERROR) << "decode the map message failed (" << ret << ")"; spat_msg.FreeAll(); continue; } map = map_msg.GetMap(); if (map == nullptr) { LOG(ERROR) << "map message is nullptr"; spat_msg.FreeAll(); continue; } auto car_status = grpc->GetCarStatus(); if (car_status == nullptr) { spat_msg.FreeAll(); map_msg.FreeAll(); continue; } std::shared_ptr<apollo::v2x::obu::ObuTrafficLight> intersection_trafficlight_msg(new apollo::v2x::obu::ObuTrafficLight); ret = tl.TrafficLightApp(map, spat, car_status, intersection_trafficlight_msg); if (ret != 0) { LOG(ERROR) << "get traffic light failed (" << ret << ")"; spat_msg.FreeAll(); map_msg.FreeAll(); continue; } grpc->SendTrafficLights(*intersection_trafficlight_msg); spat_msg.FreeAll(); map_msg.FreeAll(); } delete[] spat_buf; delete[] map_buf; } } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app/scenario
apollo_public_repos/apollo-contrib/obu/app/scenario/traffic_light/traffic_light_thread.h
/****************************************************************************** * 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. *****************************************************************************/ /** * @file traffic_light_thread.h * @brief define traffic light class as a thread */ #pragma once #include "os_thread.h" namespace v2x { class TrafficLightThread final : public OsThread { public: TrafficLightThread() : OsThread("tl_user_thrd", OS_THREAD_PRIORITY_NORMAL, OS_THREAD_DEFAULT_STACK_SIZE, true) {} virtual ~TrafficLightThread() {} virtual void Run(); }; } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/platform_auth/CMakeLists.txt
cmake_minimum_required(VERSION 2.8) include_directories(${CMAKE_CURRENT_SOURCE_DIR}) include_directories(../../third_party/openssl/include/) include_directories(../../third_party/cJSON/include/) include_directories(../../third_party/curl/include/) include_directories(../msg_sets) include_directories(../../utils) add_library(uu_auth encrypt_utils.cc auth_manager.cc)
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/platform_auth/auth_manager.h
/****************************************************************************** * 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. *****************************************************************************/ /** * @file * * @brief This library provides register and authentication to platform */ #ifndef APP_PLATFORM_AUTH_AUTH_MANAGER_H #define APP_PLATFORM_AUTH_AUTH_MANAGER_H #include <iostream> #include <memory> #include <string> #include "auth_manager.h" #include "auth_para.h" #include "device_info.h" #include "os_thread.h" #include "singleton.h" /** * @namespace v2x * @brief v2x */ namespace v2x { // vendor code enum PLATFORM_VENDOR { CMCC_V2X }; // authentication status enum AUTH_STATUS { NONE = 0, REGISTED, AUTHED, INVALID_ALL = 100, INVALID_KEY, INVALID_TOKEN }; /** * @class BaseAuthManager * * @brief base class of authentication manager */ class BaseAuthManager : public OsThread { public: /** * @brief constructor */ BaseAuthManager() : OsThread("BaseAuthManager", OS_THREAD_PRIORITY_NORMAL, OS_THREAD_DEFAULT_STACK_SIZE, true) { } /** * @brief destructor */ virtual ~BaseAuthManager() {} /** * @brief create an authentication manager * @param vendor_code: the code standing for platform vendor * auth_para: reference to an AuthPara object * device_info: reference to a DeviceInfo object * @return pointer to an BaseAuthManager object */ static BaseAuthManager *Create(int vendor_code, AuthPara &auth_para, DeviceInfo &device_info); /** * @brief send request to platform to register the device * @param void * @return true if success, otherwise false returned */ virtual bool DeviceRegister() = 0; /** * @brief send request to platform to authenticate the device * @param void * @return true if success, otherwise false returned */ virtual bool DeviceAuth() = 0; /** * @brief set authentication status * @param status: authentication status * @return void */ virtual void SetAuthStatus(AUTH_STATUS status) = 0; /** * @brief get the authentication status * @param void * @return authentication status */ virtual AUTH_STATUS GetAuthStatus() = 0; /** * @brief update authentication status * @param void * @return void */ virtual void UpdateAuthStatus() = 0; /** * @brief get the key to encrypt bsm message * @param void * @return the key */ virtual std::string GetKey() = 0; /** * @brief get the valid time of the key * @param void * @return the valid time */ virtual std::string GetKeyValidTime() = 0; /** * @brief get the token to fill bsm message * @param void * @return the token */ virtual std::string GetToken() = 0; /** * @brief get the valid time of the token * @param void * @return the valid time */ virtual std::string GetTokenValidTime() = 0; /** * @brief get id of the device * @param void * @return id of the device */ virtual std::string GetDeviceId() = 0; /** * @brief process authentication * @param void * @return void */ virtual void AuthProc() = 0; /** * @brief run function * @param void * @return void */ virtual void Run() { AuthProc(); } }; /** * @class AuthManager * * @brief auth manager for platform */ class AuthManager : public BaseAuthManager { public: /** * @brief constructor */ AuthManager(AuthPara &auth_para, DeviceInfo &device_info); /** * @brief destructor */ ~AuthManager() {} /** * @brief send request to platform to register the device * @param void * @return true if success, otherwise false returned */ bool DeviceRegister(); /** * @brief send request to platform to authenticate the device * @param void * @return true if success, otherwise false returned */ bool DeviceAuth(); /** * @brief set authentication status * @param status: authentication status * @return void */ void SetAuthStatus(AUTH_STATUS status); /** * @brief get the authentication status * @param void * @return AUTH_STATUS */ AUTH_STATUS GetAuthStatus(); /** * @brief update authentication status * @param void * @return void */ void UpdateAuthStatus(); /** * @brief get the key to encrypt bsm message * @param void * @return the key */ std::string GetKey() { return auth_para_.GetKey(); } /** * @brief get the valid time of the key * @param void * @return the valid time */ std::string GetKeyValidTime() { return auth_para_.GetKeyValidTime(); } /** * @brief get the token to fill bsm message * @param void * @return the token */ std::string GetToken() { return auth_para_.GetToken(); } /** * @brief get the valid time of the token * @param void * @return the valid time */ std::string GetTokenValidTime() { return auth_para_.GetTokenValidTime(); } /** * @brief get id of the device * @param void * @return id of the device */ std::string GetDeviceId() { return device_info_.GetDeviceId(); } /** * @brief process authentication * @param void * @return void */ virtual void AuthProc(); private: /** * @brief constructor */ AuthManager(const AuthManager &auth_manager); /** * @brief operator= */ void operator=(const AuthManager &auth_manager); /** * @brief get authentication type * @param void * @return authentication type: 0 is to request for token and key, * 1 is to request for token, and 2 is request for key */ int AuthType(); /** * @brief parse the authentication response data from platform * @param response: response data * @return ture if success */ bool ParseResponseBody(std::string response); /** * @brief get current time * @param void * @return current time in "YYYYMMDDhhmmsssss" */ std::string CurrentTime(); /** * @brief get body of request to platform * @param void * @return body of request */ std::string RequestBody(); /** * @brief parsing time in string * @param time: time in "YYYYMMDDhhmmsssss" * @return time in sturct timeval */ struct timeval ParseStringTime(std::string time); /** * @brief get seconds to valid time * @param valid_time: valid time in "YYYYMMDDhhmmsssss" * @return seconds */ time_t SecFromValidTime(std::string valid_time); /** * @brief check if over the valid time * @param valid_time: valid time in "YYYYMMDDhhmmsssss" * @return true if not over the valid time */ bool CheckValidTime(std::string valid_time); /** * @brief check if the key is in the valid time * @param void * @return true if in the valid time */ bool CheckKeyValid(); /** * @brief check if the token is in the valid time * @param void * @return true if in the valid time */ bool CheckTokenValid(); /** * @brief authenticate the device according to the authentication status * @param void * @return void */ void DoDeviceAuth(); static const int VALID_TIME_INTERVAL = 30; AuthPara &auth_para_; DeviceInfo &device_info_; AUTH_STATUS auth_status_; }; typedef SingletonService<BaseAuthManager> BaseAuthManagerSingleton; } // namespace v2x #endif /* APP_PLATFORM_AUTH_AUTH_MANAGER_H */
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/platform_auth/auth_manager.cc
/****************************************************************************** * 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. *****************************************************************************/ #include "sys/time.h" #include "time.h" #include "auth_manager.h" #include "cJSON.h" #include "curl.h" #include "encrypt_utils.h" #include "glog/logging.h" namespace v2x { /** * @brief format an integer to decmical string * @param input: the integer to be formatted * size: number of the integer * @return interger formatted */ std::string ToDecString(int input, int size) { if (size > 6) { size = 6; } char format[5]; sprintf(format, "%c", '%'); sprintf(format + 1, "%d", 0); sprintf(format + 2, "%d", size); sprintf(format + 3, "%c", 'd'); format[4] = '\0'; char tmp[6]; sprintf(tmp, format, input); std::string out(tmp, size); #if 0 int i = 0; for (i = 0; i < size; i++) { out.push_back(tmp[i]); } #endif return out; } /** * @brief write a buffer to string * @param buffer: pointer to buffer to be written to string * @return interger formatted */ static size_t WriteToString(void *buffer, size_t size, size_t nmemb, void *userp) { *((std::string *)userp) += (char *)buffer; return size * nmemb; } /** * @class BaseAuthManager * * @brief base class of authentication manager */ BaseAuthManager *BaseAuthManager::Create(int vendor_code, AuthPara &auth_para, DeviceInfo &device_info) { switch (vendor_code) { case (int)(PLATFORM_VENDOR::CMCC_V2X): return new AuthManager(auth_para, device_info); default: break; } return nullptr; } /** * @class AuthManager * * @brief auth manager for platform */ AuthManager::AuthManager(AuthPara &auth_para, DeviceInfo &device_info) : auth_para_(auth_para), device_info_(device_info), auth_status_(NONE) {} bool AuthManager::DeviceRegister() { // register off line // reserved return true; } bool AuthManager::DeviceAuth() { std::string request_body = this->RequestBody(); // Http CURL *curl = curl_easy_init(); std::string token; if (curl) { std::string url = auth_para_.GetAuthUrl(); struct curl_slist *header = nullptr; header = curl_slist_append(header, "Content-Type: application/json;charset=utf-8"); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_POST, 1); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request_body.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteToString); std::string str_data; curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&str_data); // curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); // curl_easy_setopt(curl, CURLOPT_HEADER, 1); CURLcode res = curl_easy_perform(curl); curl_slist_free_all(header); curl_easy_cleanup(curl); if (res == CURLcode::CURLE_OK) { // std::cout << "str_data= " << str_data << std::endl; LOG(INFO) << "str_data= " << str_data; } else { LOG(ERROR) << "curl POST failed!"; return false; } size_t pos = str_data.find("{"); if (ParseResponseBody(str_data.substr(pos, str_data.size() - pos))) { return true; } else { LOG(ERROR) << "parse the http response failed!"; return false; } } else { LOG(ERROR) << "curl is null"; return false; } } void AuthManager::UpdateAuthStatus() { // check token valid time if (CheckTokenValid() == 0) { // invalid token SetAuthStatus(/*AUTH_STATUS::*/ INVALID_TOKEN); if (CheckKeyValid() == 0) { SetAuthStatus(AUTH_STATUS::INVALID_ALL); } DeviceAuth(); } else if (CheckKeyValid() == 0) { SetAuthStatus(AUTH_STATUS::INVALID_KEY); DeviceAuth(); } } AUTH_STATUS AuthManager::GetAuthStatus() { return auth_status_; } void AuthManager::SetAuthStatus(AUTH_STATUS status) { auth_status_ = status; } std::string AuthManager::CurrentTime() { struct timeval cmtm; gettimeofday(&cmtm, NULL); struct tm *ctm = localtime(&(cmtm.tv_sec)); return ToDecString(ctm->tm_year + 1900, 4) + ToDecString(ctm->tm_mon + 1, 2) + ToDecString(ctm->tm_mday, 2) + ToDecString(ctm->tm_hour, 2) + ToDecString(ctm->tm_min, 2) + ToDecString(ctm->tm_sec, 2) + ToDecString((int)(cmtm.tv_usec / 1000), 3); } struct timeval AuthManager::ParseStringTime(std::string time) { struct tm the_tm = {0}; int the_mili_sec = 0; sscanf(time.c_str(), "%4d%2d%2d%2d%2d%2d%3d", &(the_tm.tm_year), &(the_tm.tm_mon), &(the_tm.tm_mday), &(the_tm.tm_hour), &(the_tm.tm_min), &(the_tm.tm_sec), &(the_mili_sec)); the_tm.tm_year -= 1900; // years from 1900 the_tm.tm_mon--; // 0 ~ 11 timeval time_val; time_val.tv_sec = mktime(&the_tm); time_val.tv_usec = the_mili_sec * 1000; return time_val; } time_t AuthManager::SecFromValidTime(std::string valid_time) { struct timeval valid_micro_time = ParseStringTime(valid_time); struct timeval current_micro_tm; gettimeofday(&current_micro_tm, NULL); return valid_micro_time.tv_sec - current_micro_tm.tv_sec + 1; } bool AuthManager::CheckValidTime(std::string valid_time) { struct timeval valid_micro_time = ParseStringTime(valid_time); struct timeval current_micro_tm; gettimeofday(&current_micro_tm, NULL); if (valid_micro_time.tv_sec - current_micro_tm.tv_sec < 0) { return false; } else if (valid_micro_time.tv_sec - current_micro_tm.tv_sec == 0) { if (valid_micro_time.tv_usec - current_micro_tm.tv_usec <= 0) { return false; } else { return true; } } else { return true; } } bool AuthManager::CheckKeyValid() { return CheckValidTime(auth_para_.GetKeyValidTime()); } bool AuthManager::CheckTokenValid() { return CheckValidTime(auth_para_.GetTokenValidTime()); } std::string AuthManager::RequestBody() { std::string id = device_info_.GetDeviceId(); std::string mac = device_info_.GetMac(); int req_auth_type = AuthType(); std::string timestamp = CurrentTime(); std::string hash_info = MD5util::GetMD516(id + mac + timestamp); // JSON cJSON *root = cJSON_CreateObject(); cJSON_AddItemToObject(root, "id", cJSON_CreateString(id.c_str())); cJSON_AddItemToObject(root, "type", cJSON_CreateNumber(req_auth_type)); cJSON_AddItemToObject(root, "hashInfo", cJSON_CreateString(hash_info.c_str())); cJSON_AddItemToObject(root, "timestamp", cJSON_CreateString(timestamp.c_str())); std::string request_body = cJSON_PrintUnformatted(root); cJSON_Delete(root); return request_body; } bool AuthManager::ParseResponseBody(std::string response) { cJSON *root = NULL; cJSON *result = NULL; cJSON *token = NULL; cJSON *token_valid_time = NULL; cJSON *key = NULL; cJSON *key_valid_time = NULL; cJSON *timestamp = NULL; root = cJSON_Parse(response.c_str()); result = cJSON_GetObjectItem(root, "result"); int response_result = result->valueint; if (response_result != 0) { cJSON_Delete(root); LOG(ERROR) << "Post return failed"; return false; } token = cJSON_GetObjectItem(root, "token"); // in base64 token_valid_time = cJSON_GetObjectItem(root, "tokenvalidtime"); key = cJSON_GetObjectItem(root, "key"); // in base64 key_valid_time = cJSON_GetObjectItem(root, "keyvalidtime"); timestamp = cJSON_GetObjectItem(root, "timestamp"); // decypt // get keys from MD5 std::string id = device_info_.GetDeviceId(); std::string mac = device_info_.GetMac(); std::string key_token = MD5util::GetMD516(id + mac + std::string(token_valid_time->valuestring)); std::string key_key = MD5util::GetMD516(id + mac + key_valid_time->valuestring); // get text from base64 std::string encypted_token = Base64util::ParseBase64(token->valuestring); std::string encypted_key = Base64util::ParseBase64(key->valuestring); // aes decypt auth_para_.SetToken(AESECButil::DecryptPKCS5(encypted_token, key_token)); auth_para_.SetTokenValidTime(token_valid_time->valuestring); auth_para_.SetKey(AESECButil::DecryptPKCS5(encypted_key, key_key)); auth_para_.SetKeyValidTime(key_valid_time->valuestring); cJSON_Delete(root); // only need to delete root return true; } int AuthManager::AuthType() { switch (auth_status_) { case (int)(AUTH_STATUS::INVALID_ALL): return 0; case (int)(AUTH_STATUS::INVALID_TOKEN): return 1; case (int)(AUTH_STATUS::INVALID_KEY): return 2; default: break; } return 0; } void AuthManager::DoDeviceAuth() { if (DeviceAuth()) { if (CheckKeyValid()) { if (!CheckTokenValid()) { LOG(INFO) << "Valid key && Invalid token"; SetAuthStatus(AUTH_STATUS::INVALID_TOKEN); } else { LOG(INFO) << "Valid key && Valid token"; SetAuthStatus(AUTH_STATUS::AUTHED); } } else { LOG(INFO) << "Invalid key"; if (!CheckTokenValid()) { LOG(INFO) << "Invalid token && Invalid key"; SetAuthStatus(AUTH_STATUS::INVALID_ALL); } SetAuthStatus(AUTH_STATUS::INVALID_KEY); } } else { // set_auth_status(AUTH_STATUS::AUTHED); LOG(INFO) << "because not gettinng the correct result from server, " "keep the auth status NONE"; } } void AuthManager::AuthProc() { AUTH_STATUS auth_status; while (1) { auth_status = GetAuthStatus(); if (auth_status == AUTH_STATUS::NONE) { // DeviceRegister(); DoDeviceAuth(); } else if (auth_status == AUTH_STATUS::AUTHED) { time_t time_to_key = SecFromValidTime(GetKeyValidTime()); time_t time_to_token = SecFromValidTime(GetTokenValidTime()); if (time_to_key < VALID_TIME_INTERVAL) { DoDeviceAuth(); sleep(1); } else if (time_to_token < VALID_TIME_INTERVAL) { DoDeviceAuth(); sleep(1); } else { time_to_key < time_to_token ? sleep(time_to_key - VALID_TIME_INTERVAL) : sleep(time_to_token - VALID_TIME_INTERVAL); } // TODO before the authentication is expired, renew it } else if (auth_status == AUTH_STATUS::INVALID_ALL || auth_status == AUTH_STATUS::INVALID_KEY || auth_status == AUTH_STATUS::INVALID_TOKEN) { DoDeviceAuth(); } } } } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/platform_auth/encrypt_utils.h
/****************************************************************************** * 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. *****************************************************************************/ /** * @file * * @brief This library provides the basic encryption and decryption utils, * including aes, md5 and base64. */ #ifndef PLATFORM_AUTH_ENCRYPT_UTILS_H #define PLATFORM_AUTH_ENCRYPT_UTILS_H #include <string> /** * @namespace v2x * @brief v2x */ namespace v2x { /** * @class AESECButil * * @brief aes ecb encryption utils */ class AESECButil { public: /** * @brief constructor */ AESECButil() {} /** * @brief destructor */ ~AESECButil() {} /** * @brief encrypt with PKCS5Padding * @param content: plain text * key: the key * @return if encryption successes, cipher text returned, if not, the plain * text returned */ static std::string EncryptPKCS5(std::string content, std::string key); /** * @brief encrypt with PKCS5Padding * @param content: pointer to plain text * length: length of the content * out: pointer to the cipher * key: the key * @return if encryption successes, the length of cipher returned , if not, 0 * returned */ static int EncryptPKCS5(unsigned char *content, int length, unsigned char *out, std::string key); /** * @brief encrypt with PKCS5Padding * @param content: cipher text * key: the key * @return if decryption successes, plain text returned, if not, the cipher * text returned */ static std::string DecryptPKCS5(std::string content, std::string key); /** * @brief encrypt with PKCS5Padding * @param content: pointer to cipher text * length: length of the content * out: pointer to the plain text * key: the key * @return if decryption successes, the length of plain text returned , if * not, 0 returned */ static int DecryptPKCS5(unsigned char *content, int length, unsigned char *out, std::string key); private: /** * @brief constructor */ AESECButil(const AESECButil &aes); /** * @brief operator= */ void operator=(const AESECButil &aes); }; /** * @class MD5util * * @brief MD5 utils */ class MD5util { public: /** * @brief constructor */ MD5util() {} /** * @brief constructor */ ~MD5util() {} /** * @brief get the MD5 value with 32 bytes * @param input: plain text * @return the MD5 value */ static std::string GetMD532(std::string input); /** * @brief get the MD5 value with 16 bytes * @param input: plain text * @return the MD5 value */ static std::string GetMD516(std::string input); private: /** * @brief constructor */ MD5util(const MD5util &md5); /** * @brief operator= */ void operator=(const MD5util &md5); }; /** * @class Base64util * * @brief base64 utils */ class Base64util { public: /** * @brief constructor */ Base64util() {} /** * @brief denstructor */ ~Base64util() {} /** * @brief get the base64 value * @param input: plain text * @return the base64 value */ static std::string GetBase64(std::string input); /** * @brief parse the base64 value * @param input: base64 value * @return plain text */ static std::string ParseBase64(std::string input); private: /** * @brief constructor */ Base64util(const Base64util &base64); /** * @brief operator= */ void operator=(const Base64util &base64); }; } // namespace v2x #endif /* PLATFORM_AUTH_ENCRYPT_UTILS_H */
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/platform_auth/encrypt.h
/****************************************************************************** * 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. *****************************************************************************/ /** * @file * * @brief This library provides the basic encryption and decryption utils, * including aes, md5 and base64. */ #ifndef PLATFORM_AUTH_ENCRYPT_H #define PLATFORM_AUTH_ENCRYPT_H #include "openssl/aes.h" #include "openssl/bio.h" #include "openssl/buffer.h" #include "openssl/evp.h" #include "openssl/md5.h" /** * @brief encrypt * @param in: plain text input * len: length of in * key: the key * out: cipher text * @return if encryption successes, 1 returned, if not, 0 returned */ int AesEncrypt(unsigned char *in, int len, unsigned char *key, unsigned char *out) { if (!in || !key || !out) return 0; AES_KEY aes; if (AES_set_encrypt_key(key, 128, &aes) < 0) { return 0; } int en_len = 0; while (en_len < len) { AES_encrypt(in, out, &aes); in += AES_BLOCK_SIZE; out += AES_BLOCK_SIZE; en_len += AES_BLOCK_SIZE; } return 1; } /** * @brief decrypt * @param in: cipher text input * len: length of in * key: the key * out: plain text * @return if decryption successes, 1 returned, if not, 0 returned */ int AesDecrypt(unsigned char *in, int len, unsigned char *key, unsigned char *out) { if (!in || !key || !out) return 0; AES_KEY aes; if (AES_set_decrypt_key(key, 128, &aes) < 0) { return 0; } int en_len = 0; while (en_len < len) { AES_decrypt(in, out, &aes); if ((en_len+AES_BLOCK_SIZE) <= len) { in += AES_BLOCK_SIZE; out += AES_BLOCK_SIZE; en_len += AES_BLOCK_SIZE; } else { in += (len % AES_BLOCK_SIZE); out+= (len % AES_BLOCK_SIZE); en_len += (len % AES_BLOCK_SIZE); } } return 1; } /** * @brief get the MD5 value with 32 bytes * @param input: plain text input * buf: MD5 value buffer * @return if encryption successes, 1 returned, if not, 0 returned */ int MD5Encode(const char *input, char *buf) { unsigned char md[16]; char tmp[3] = {'\0'}; int i = 0; MD5_CTX ctx; MD5_Init(&ctx); MD5_Update(&ctx, input, strlen(input)); MD5_Final(md, &ctx); for (i = 0; i < 16; i++) { sprintf(tmp, "%02X", md[i]); strcat(buf, tmp); } return 1; } /** * @brief encode to base64 value * @param buf: plain text buffer * length: the length of buffer * output: the buffer for encoding * @return the length of the output buffer */ size_t Base64Encode(const char *buffer, int length, char* output) { BIO *bmem = NULL; BIO *b64 = NULL; BUF_MEM *bptr; b64 = BIO_new(BIO_f_base64()); BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); bmem = BIO_new(BIO_s_mem()); b64 = BIO_push(b64, bmem); BIO_write(b64, buffer, length); BIO_flush(b64); BIO_get_mem_ptr(b64, &bptr); BIO_set_close(b64, BIO_NOCLOSE); memcpy(output, bptr->data, bptr->length); output[bptr->length] = '\0'; BIO_free_all(b64); return bptr->length;; } /** * @brief decode from base64 value * @param input: base64 buffer * length: the length of buffer * output: output buffer * @return the length of the output buffer */ int Base64Decode(const char *input, int length, char* output) { BIO *b64 = NULL; BIO *bmem = NULL; int size = 0; //char *buffer = (char *)malloc(length); //memset(buffer, 0, length); b64 = BIO_new(BIO_f_base64()); BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); bmem = BIO_new_mem_buf((void *)input, length); bmem = BIO_push(b64, bmem); size = BIO_read(bmem, output, length); output[size] = '\0'; BIO_free_all(bmem); return size; } #endif /* PLATFORM_AUTH_ENCRYP_ENCRYPT_H */
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/platform_auth/encrypt_utils.cc
/****************************************************************************** * 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. *****************************************************************************/ /** * @file * * @brief This library provides the basic encryption and decryption utils, * including aes, md5 and base64. */ #include "encrypt_utils.h" #include <stdlib.h> #include <string.h> #include <memory> #include "encrypt.h" #include <iostream> #include "glog/logging.h" namespace v2x { /** * @class AESECButil * * @brief aes ecb encryption utils */ std::string AESECButil::EncryptPKCS5(std::string content, std::string key) { // PKCS5Padding int n = 16 - (content.length() % 16); std::string padding; int i = 0; char tmp = n; for (i = 0; i < n; i++) { padding.push_back(tmp); } std::string input = content + padding; std::string out; unsigned char *uc_input = new unsigned char[input.length() + 1]; unsigned char *uc_key = new unsigned char[key.length() + 1]; unsigned char *uc_out = new unsigned char[input.length() + 1]; memset(uc_input, 0x00, input.length() + 1); memset(uc_key, 0x00, key.length() + 1); memset(uc_out, 0x00, content.length()); memcpy(uc_input, input.c_str(), input.length()); memcpy(uc_key, key.c_str(), key.length()); if (AesEncrypt(uc_input, input.length(), uc_key, uc_out)) { unsigned int i = 0; for (i = 0; i < input.length(); i++) { out.push_back(uc_out[i]); } delete[] uc_input; delete[] uc_key; delete[] uc_out; return out; } else { // if encryption failed, return the content delete[] uc_input; delete[] uc_key; delete[] uc_out; return content; } } int AESECButil::EncryptPKCS5(unsigned char *content, int length, unsigned char *out, std::string key) { // PKCS5Padding int n = 16 - (length % 16); int i = 0; unsigned char tmp = n; for (i = 0; i < n; i++) { memcpy(content + length + i, &tmp, 1); } std::shared_ptr<void> uc_key(malloc(key.length()), free); memset(uc_key.get(), 0x00, key.length()); memcpy(uc_key.get(), key.c_str(), key.length()); if (AesEncrypt(content, length + n, reinterpret_cast<unsigned char*>(uc_key.get()), out)) { return length + n; } else { // if encryption failed, return 0 return 0; } } std::string AESECButil::DecryptPKCS5(std::string content, std::string key) { char *uc_out = new char[content.length()]; memset(uc_out, 0x00, content.length()); if (AesDecrypt(( unsigned char *)(content.c_str()), content.length(), (unsigned char *)(key.c_str()), (unsigned char*)uc_out) == 1) { std::string out(uc_out, content.length() - uc_out[content.length() - 1]); delete[] uc_out; return out; } else { delete[] uc_out; return content; } } int AESECButil::DecryptPKCS5(unsigned char *content, int length, unsigned char *out, std::string key) { if (AesDecrypt(content, length, (unsigned char *)key.c_str(), out)) { char padding = *(out + length - 1); return length - padding; } else { return 0; } } /** * @class MD5util * * @brief MD5 utils */ std::string MD5util::GetMD532(std::string input) { char buf[33] = {'\0'}; MD5Encode(input.c_str(), buf); return buf; } std::string MD5util::GetMD516(std::string input) { return GetMD532(input).substr(8, 16); } /** * @class Base64util * * @brief base64 utils */ std::string Base64util::GetBase64(std::string input) { uint32_t byte_num = (input.length()*8 + 24 - input.length()*8 % 24)/6; char *buf = reinterpret_cast<char*>(malloc(byte_num)); if (buf == nullptr) { LOG(ERROR) << "Alloc the memory failed"; return input; } size_t len = Base64Encode(input.c_str(), input.length(), buf); std::string out(buf, len); free(buf); return out; } std::string Base64util::ParseBase64(std::string input) { int output_size = 0; char* buf = (char*)malloc(input.length()); if (buf == nullptr) { LOG(ERROR) << "Alloc the memory failed"; return input; } output_size = Base64Decode(input.c_str(), input.length(), buf); std::string out(buf, output_size); free(buf); return out; } } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/platform_auth/device_info.h
/****************************************************************************** * 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. *****************************************************************************/ /** * @file * * @brief This library provides device information. */ #pragma once #include <string> /** * @namespace v2x * @brief v2x */ namespace v2x { /** * @class DeviceInfo * * @brief information about the device */ class DeviceInfo { public: /** * @brief constructor */ DeviceInfo(const std::string &device_id, const std::string &mac, const std::string phone_num) { device_id_ = device_id; mac_ = mac; phone_num_ = phone_num; }; /** * @brief destructor */ ~DeviceInfo(){}; /** * @brief get id of the device * @param void * @return id of the device */ std::string GetDeviceId() { return device_id_; } /** * @brief get mac address of the device * @param void * @return mac address of the device */ std::string GetMac() { return mac_; } /** * @brief get phone number of the device * @param void * @return phone number of the device */ std::string GetPhoneNum() { return phone_num_; } private: /** * @brief constructor */ DeviceInfo(const DeviceInfo &device_info); /** * @brief operator= */ void operator=(const DeviceInfo &device_info); std::string device_id_; std::string mac_; std::string phone_num_; }; } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/platform_auth/auth_para.h
/****************************************************************************** * 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. *****************************************************************************/ /** * @file * * @brief This library provides authentication parameters. */ #ifndef AUTH_PARA_H_ #define AUTH_PARA_H_ #include <memory> #include <string> /** * @namespace v2x * @brief v2x */ namespace v2x { /** * @class AuthPara * * @brief authentication parameter */ class AuthPara { public: /** * @brief constructor */ AuthPara(std::string auth_url) : auth_url_(auth_url), key_(""), token_(""), key_valid_time_(""), token_valid_time_("") {} /** * @brief destructor */ ~AuthPara() {} // /** // * @brief create shared pointer containing an AuhtPara object // * @param auth_url: url of the authentication platform // * @return shared pointer containing an AuhtPara object // */ // static std::shared_ptr<AuthPara> Create(std::string auth_url) { // return std::shared_ptr<AuthPara>(new AuthPara(auth_url)); // } /** * @brief get url of the authentication platform * @param void * @return url of the authentication platform */ std::string GetAuthUrl() { return auth_url_; } /** * @brief get the key to encrypt bsm message * @param void * @return the key */ std::string GetKey() { return key_; } /** * @brief get the token to fill bsm message * @param void * @return the token */ std::string GetToken() { return token_; } /** * @brief get the valid time of the key * @param void * @return the valid time */ std::string GetKeyValidTime() { return key_valid_time_; } /** * @brief get the valid time of the token * @param void * @return the valid time */ std::string GetTokenValidTime() { return token_valid_time_; } /** * @brief set the key to encrypt bsm message * @param key: the key * @return void */ void SetKey(std::string key) { key_ = key; } /** * @brief set the key filling in bsm message * @param token: the token * @return void */ void SetToken(std::string token) { token_ = token; } /** * @brief set the valid time of the key * @param time: the valid time * @return void */ void SetKeyValidTime(std::string time) { key_valid_time_ = time; } /** * @brief set the valid time of the token * @param time: the valid time * @return void */ void SetTokenValidTime(std::string time) { token_valid_time_ = time; } private: /** * @brief constructor */ AuthPara(const AuthPara &auth_para); /** * @brief operator= */ void operator=(const AuthPara &auth_para); const std::string auth_url_; std::string key_; std::string token_; std::string key_valid_time_; std::string token_valid_time_; }; } // namespace v2x #endif /* AUTH_PARA_H_ */
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/msg_sets/CMakeLists.txt
cmake_minimum_required(VERSION 2.8) #include_directories(${CMAKE_CURRENT_SOURCE_DIR}) #include_directories( # ./asn1_source #) #add_subdirectory(asn1_source) #add_subdirectory(ctfo) #set(CMAKE_CXX_FLAGS "-std=c++11") add_library(msg_set message_set.cc uu_message_set.cc) #for uu_message_set include_directories(${CMAKE_CURRENT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../third_party/obu/include/asn1_source/) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../) # include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../vendor) # include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../vendor/cmcc) # include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../vendor/cmcc/include) #link_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../vendor/cmcc/build) #add_library(uu_msg_set uu_message_set.cc) #target_link_libraries(uu_msg_set cmcc)
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/msg_sets/uu_message_set.cc
/****************************************************************************** * 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. *****************************************************************************/ /**uu_message_set * @file * * @brief LTE-V message set for platform. */ #include "uu_message_set.h" namespace v2x { int UuMessageSet::CreateBSM() { present_ = MessageFrame_PR_bsmFrame; int ret = 0; ret = GbBSMCreate(&uu_bsm_, pBsmCfg_, GB_CREAT_ALL); return ret; } int UuMessageSet::EncodeBSM(uint8_t **ppBuf, const int bufSize, int *pCodeSize) { int ret = 0; ret = GbBSMFill(&uu_bsm_, pBsmCfg_, pBsmPara_); if (ret != 0) { return ret; } ret = GbBSMEncode(uu_bsm_, ppBuf, bufSize, pCodeSize); return ret; } int UuMessageSet::FreeBSM(const GBFreeOption_t freeOption) { int ret = 0; ret = GbBSMFree(uu_bsm_, freeOption); return ret; } int UuMessageSet::SetBSMCfg(BsmConfig_t *pBsmCfg) { if (pBsmCfg == nullptr) { return ERR_INPUT_NULL; } pBsmCfg_ = pBsmCfg; return 0; } int UuMessageSet::SetBSMPara(BsmParam_t *pBsmPara) { if (pBsmPara == nullptr) { return ERR_INPUT_NULL; } pBsmPara_ = pBsmPara; return 0; } } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/msg_sets/message_set_lib.h
/****************************************************************************** * 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. *****************************************************************************/ #ifndef APP_MSG_SETS_MESSAGE_SET_LIB_H #define APP_MSG_SETS_MESSAGE_SET_LIB_H #include "cv2x_app_layer/cv2x_message_frame.h" #endif /* APP_MSG_SETS_MESSAGE_SET_LIB_H */
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/msg_sets/message_set.cc
/****************************************************************************** * 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. *****************************************************************************/ #include "message_set.h" #include "glog/logging.h" namespace v2x { /** * @class MessageSet * @brief Provides 2 kinds of message frame: SPAT and MAP. * A message frame will be create and then decode from asn.1 code. */ MessageSet::MessageSet() : message_frame_(nullptr),map_(nullptr), spat_(nullptr), present_(0) {} MessageSet::~MessageSet() { FreeAll(); } int MessageSet::CreateMap() { // reset(); present_ = MessageFrame_PR_mapFrame; // using ctfo int ret = 0; ret = cv2x_message_frame_create(&message_frame_); // get MapData_t pointer from messageFrame created by ctfo map_ = &(message_frame_->choice.mapFrame); return ret; } int MessageSet::CreateSpat() { // reset(); present_ = MessageFrame_PR_spatFrame; // using ctfo int ret = 0; ret = cv2x_message_frame_create(&message_frame_); // get SPAT_t pointer from messageFrame created by ctfo spat_ = &(message_frame_->choice.spatFrame); return ret; } int MessageSet::DecodeMap(char* buf, const eCodeType code_type, const int buf_size) { // using ctfo int ret = 0; ret = cv2x_message_frame_decode(&message_frame_, code_type, buf, buf_size); // for test PrintMessageFrame(); return ret; } int MessageSet::DecodeSpat(char* buf, const eCodeType code_type, const int buf_size) { // using ctfo int ret = 0; ret = cv2x_message_frame_decode(&message_frame_, code_type, buf, buf_size); // for test PrintMessageFrame(); return ret; } MapData_t* MessageSet::GetMap() { if (present_ == MessageFrame_PR_mapFrame) { return map_; } else { return nullptr; } } SPAT_t* MessageSet::GetSpat() { if (present_ == MessageFrame_PR_spatFrame) { return spat_; } else { return nullptr; } } void MessageSet::FreeAll() { // using ctfo int ret = 0; if (message_frame_ != nullptr) { ret = cv2x_message_frame_free(message_frame_, 0); } if (ret != 0) { LOG(ERROR) << "free message failed(" << ret << ")"; } return; } int MessageSet::Reset() { present_ = 0; int ret = 0; FreeAll(); // if (ret == 0) { message_frame_ = nullptr; map_ = nullptr; spat_ = nullptr; // } return ret; } void MessageSet::PrintMessageFrame() { // xer_fprint(stdout, &asn_DEF_MessageFrame, _messageFrame); } } // namespace v2x
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/msg_sets/message_set.h
/****************************************************************************** * 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. *****************************************************************************/ #ifndef APP_MSG_SETS_MESSAGESET_H #define APP_MSG_SETS_MESSAGESET_H #include "message_set_lib.h" #include "stdio.h" /** * @namespace v2x * @brief v2x */ namespace v2x { /** * @class MessageSet * @brief Provides 2 kinds of message frame: SPAT and MAP. * A message frame will be create and then decode from asn.1 code. */ class MessageSet { public: /** * @brief constructor */ MessageSet(); /** * @brief destructor */ ~MessageSet(); /** * @brief Create a MAP message frame. * @param void * @return v2x error number, 0 is success. */ int CreateMap(); /** * @brief Create a SPAT message frame. * @param void * @return v2x error number, 0 is success. */ int CreateSpat(); /** * @brief Decode a MAP message frame from asn.1 code. * @param * @return v2x error number, 0 is success. */ int DecodeMap(char *buf, const eCodeType code_type, const int buf_size); /** * @brief Decode a SPAT message frame from asn.1 code. * @param * @return v2x error number, 0 is success. */ int DecodeSpat(char *buf, const eCodeType code_type, const int buf_size); /** * @brief Get a MAP message frame. * @param void * @return Pointer to MAP message frame. */ MapData_t *GetMap(); /** * @brief Get a SPAT message frame. * @param void * @return Pointer to SPAT message frame. */ SPAT_t *GetSpat(); /** * @brief Free the memory of message frame. * @param void * @return v2x error number, 0 is success. */ void FreeAll(); private: /** * @brief constructor */ MessageSet(const MessageSet &messgeSet); /** * @brief operator= */ void operator=(const MessageSet &messgeSet); #if 0 /** * @brief Free the memory of message frame. * @param void * @return v2x error number, 0 is success. */ int free_all(); #endif /** * @brief Reset all the variable. * @param void * @return v2x error number, 0 is success. */ int Reset(); /** * @brief Print messageFrame. * @param void * @return void */ void PrintMessageFrame(); MessageFrame_t *message_frame_; MapData_t *map_; SPAT_t *spat_; int present_; }; } // namespace v2x #endif /* MESSAGESET_H_ */
0
apollo_public_repos/apollo-contrib/obu/app
apollo_public_repos/apollo-contrib/obu/app/msg_sets/uu_message_set.h
/****************************************************************************** * 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. *****************************************************************************/ /**uu_message_set * @file * * @brief LTE-V message set for platform. */ #ifndef APP_MSG_SETS_UU_MESSAGE_SET_H #define APP_MSG_SETS_UU_MESSAGE_SET_H #include "vendor/cmcc/gb_bsm.h" /** * @namespace v2x * @brief v2x */ namespace v2x { /** * @class UuMessageSet * * @brief message set for platform */ class UuMessageSet { public: /** * @brief constructor */ UuMessageSet() : present_(0), uu_bsm_(nullptr), pBsmPara_(nullptr), pBsmCfg_(nullptr) {} /** * @brief destructor */ ~UuMessageSet() { FreeBSM(GB_FREE_ALL); } /** * @brief Create BSM frame. * @param void * @return 0 if success */ int CreateBSM(); /** * @brief Encode BSM frame. * @param ppBuf: second rank pointer to the buffer * bufSize: size of the buffer * pCodeSize: pointer to size of the code encoded * @return 0 if success */ int EncodeBSM(uint8_t **ppBuf, const int bufSize, int *pCodeSize); /** * @brief Free BSM frame. * @param freeOption: free option * @return 0 if success */ int FreeBSM(const GBFreeOption_t freeOption); /** * @brief Set bsm configuration data. * @param pBsmCfg: pointer to the bsm configuration structure * @return 0 if success */ int SetBSMCfg(BsmConfig_t *pBsmCfg); /** * @brief Set bsm parameter to fill in the BSM message. * @param pBsmCfg: pointer to the bsm parameter structure * @return 0 if success */ int SetBSMPara(BsmParam_t *pBsmPara); private: /** * @brief constructor */ UuMessageSet(const UuMessageSet &msg_set); /** * @brief operator= */ void operator=(const UuMessageSet &msg_set); int present_; BasicSafetyMessage_t *uu_bsm_; BsmParam_t *pBsmPara_; BsmConfig_t *pBsmCfg_; }; } // namespace v2x #endif /* APP_MSG_SETS_UU_MESSAGE_SET_H */
0
apollo_public_repos/apollo-contrib/obu
apollo_public_repos/apollo-contrib/obu/security/common.c
/****************************************************************************** * 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. *****************************************************************************/ /** * @file common.c * @brief This is a common file for v2x security. */ #include <openssl/bio.h> #include <openssl/bn.h> #include <openssl/buffer.h> #include <openssl/ec.h> #include <openssl/ecdh.h> #include <openssl/ecdsa.h> #include <openssl/evp.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <time.h> #include <unistd.h> #include "Certificate.h" #include "ToBeSigned.h" #include "common.h" #include "sm2.h" #include "sm3.h" const char *key_title = "-----BEGIN PRIVATE KEY-----\n"; const char *key_end = "-----END PRIVATE KEY-----\n"; const char *cert_title = "-----BEGIN CERTIFICATE-----\n"; const char *cert_end = "-----END CERTIFICATE-----\n"; time_t GetTimeSec(int year, int month, int day, int hour, int min, int sec) { struct tm tmval; time_t tmsec; memset(&tmval, 0, sizeof(tmval)); tmval.tm_year = year; tmval.tm_mon = month, tmval.tm_mday = day; tmval.tm_hour = hour; tmval.tm_min = min; tmval.tm_sec = sec; tmsec = mktime(&tmval); return tmsec; } void printChar(uint8_t *buffer, int len) { int i = 0; if (buffer == NULL) { return; } printf("len %d\n", len); for (i = 0; i < len; i++) { printf("%02x ", buffer[i]); } printf("\n"); } void Base64Encode(const uint8_t *input, int length, uint8_t *output, int *out_len) { EVP_ENCODE_CTX ectx; int total_len = 0; int tmp_len = 0; int size = length * 2; if (input == NULL || output == NULL || out_len == NULL) { printf("Parameters error\n"); return; } size = size > 64 ? size : 64; EVP_EncodeInit(&ectx); EVP_EncodeUpdate(&ectx, output, &tmp_len, input, length); total_len += tmp_len; EVP_EncodeFinal(&ectx, output + total_len, &tmp_len); total_len += tmp_len; *out_len = total_len; } void Base64Decode(const uint8_t *input, int length, uint8_t *output, int *out_len) { EVP_ENCODE_CTX ectx; int total_len = 0; int tmp_len = 0; if (input == NULL || output == NULL || out_len == NULL) { printf("Parameters error\n"); return; } EVP_DecodeInit(&ectx); EVP_DecodeUpdate(&ectx, output, &tmp_len, input, length); total_len += tmp_len; EVP_DecodeFinal(&ectx, output + total_len, &tmp_len); total_len += tmp_len; *out_len = total_len; } static EC_KEY *SetupKey(char *pri_key, char *pub_key_x, char *pub_key_y) { EC_KEY *eckey = NULL; BIGNUM *x = NULL; BIGNUM *y = NULL; BIGNUM *z = NULL; y = BN_new(); z = BN_new(); if (!y || !z) { printf("New bn failed\n"); goto end; } if (pri_key != NULL) { x = BN_new(); if (!x) { printf("New bn failed\n"); goto end; } } BN_bin2bn(pri_key, 32, x); BN_bin2bn(pub_key_x, 32, y); BN_bin2bn(pub_key_y, 32, z); eckey = SM2SetupKey(x, y, z); if (eckey == NULL) { printf("Setup key fail\n"); } end: if (x != NULL) { BN_free(x); } if (y != NULL) { BN_free(y); } if (z != NULL) { BN_free(z); } return eckey; } static EC_KEY *SetupKeyFromCA(char * ca, int ca_len, char * pri_key) { Certificate_t *cert = NULL; EC_KEY *eckey = NULL; ber_decode(NULL, &asn_DEF_Certificate, (void **)&cert, ca, ca_len); if (cert == NULL) { printf("Get Public Key failed\n"); return NULL; } eckey = SetupKey(pri_key, cert->subjectAttributes.verificationKey->choice.signKey.buf, cert->subjectAttributes.verificationKey->choice.signKey.buf + 32); SEQUENCE_free(&asn_DEF_Certificate, cert, 0); return eckey; } EC_KEY *GetKey(const char *ca_file) { char buf[1024] = {0}; char b64[512] = {0}; char ca[512] = {0}; FILE *f = NULL; Certificate_t *cert = NULL; EC_KEY *eckey = NULL; if (ca_file == NULL) { printf("Parameters error\n"); return NULL; } f = fopen(ca_file, "r"); if (f == NULL) { printf("Open file %s failed\n", ca_file); return NULL; } fread(buf, sizeof(buf) - 1, 1, f); // Get Private Key char *r = strstr(buf, key_title); char *s = strstr(buf, key_end); char ckey[128] = {0}; char key[128] = {0}; int key_len = 0; if (r != NULL && s != NULL) { int ckey_len = s - r - strlen(key_title); strncpy(ckey, r + strlen(key_title), ckey_len); Base64Decode((uint8_t *)ckey, ckey_len, (uint8_t *)key, &key_len); } // Get Public Key char *p = strstr(buf, cert_title); char *q = strstr(buf, cert_end); int b64_len = q - p - strlen(cert_title); int ca_len = 0; if (p == NULL || q == NULL) { printf("Fail read public key\n"); fclose(f); return NULL; } strncpy(b64, p + strlen(cert_title), b64_len); Base64Decode((uint8_t *)b64, b64_len, (uint8_t *)ca, &ca_len); fclose(f); return SetupKeyFromCA(ca, ca_len, key); } int GetCert(const char *ca_file, uint8_t *cert, size_t *cert_len) { char buf[1024] = {0}; char b64[512] = {0}; FILE *f = NULL; if (ca_file == NULL || cert == NULL || cert_len == NULL) { printf("Parameters error\n"); return -1; } f = fopen(ca_file, "r"); if (f == NULL) { printf("Open file %s failed\n", ca_file); return -1; } fread(buf, sizeof(buf) - 1, 1, f); char *p = strstr(buf, cert_title); char *q = strstr(buf, cert_end); if (p == NULL || q == NULL) { printf("Could not find certification\n"); fclose(f); return -1; } int b64_len = q - p - strlen(cert_title); strncpy(b64, p + strlen(cert_title), b64_len); Base64Decode((uint8_t *)b64, b64_len, cert, cert_len); fclose(f); return 0; } EC_KEY *GetPubKey(uint8_t *ca_buf, int ca_len, EC_KEY *root_key) { char buf[1024] = {0}; char tbs_data[512] = {0}; char signature[128] = {0}; char digest[32] = {0}; int buf_len = 0; int sig_len = 0; int rc = 0; Certificate_t *cert = NULL; ToBeSigned_t *tbs = NULL; EC_KEY *self_key = NULL; asn_enc_rval_t ret; BIGNUM *y = NULL; BIGNUM *z = NULL; if (ca_buf == NULL || root_key == NULL) { printf("Parameters error\n"); goto end; } ber_decode(NULL, &asn_DEF_Certificate, (void **)&cert, ca_buf, ca_len); if (cert == NULL) { printf("Decode CA failed\n"); goto end; } ber_decode(NULL, &asn_DEF_ToBeSigned, (void **)&tbs, ca_buf, ca_len); if (tbs == NULL) { printf("Decode CA failed\n"); goto end; } ret = der_encode_to_buffer(&asn_DEF_ToBeSigned, tbs, tbs_data, sizeof(tbs_data)); if (ret.encoded == 0) { printf("Encode failed\n"); goto end; } SM3(tbs_data, ret.encoded, digest); rc = SM2Verify(digest, 32, cert->signature.choice.signature.buf, cert->signature.choice.signature.size, root_key); if (rc != 1) { printf("Verify failed. Ret %d\n", rc); goto end; } // Setup eckey y = BN_new(); z = BN_new(); if (!y || !z) { printf("New bn failed\n"); goto end; } BN_bin2bn(cert->subjectAttributes.verificationKey->choice.signKey.buf, 32, y); BN_bin2bn(cert->subjectAttributes.verificationKey->choice.signKey.buf + 32, 32, z); self_key = SM2SetupKey(NULL, y, z); if (self_key == NULL) { printf("Setup key fail\n"); goto end; } end: if (cert != NULL) { SEQUENCE_free(&asn_DEF_Certificate, cert, 0); } if (tbs != NULL) { SEQUENCE_free(&asn_DEF_ToBeSigned, tbs, 0); } if (y != NULL) { BN_free(y); } if (z != NULL) { BN_free(z); } return self_key; } int WriteToFile(char *ca_file, Certificate_t *cert, const char *pri_key, const char *signer_info_digest) { const char *sign_digest_title = "-----BEGIN SIGNATURE DIGEST-----\n"; const char *sign_digest_end = "-----END SIGNATURE DIGEST-----\n"; FILE *f; uint8_t ca[256] = {0}; uint8_t b64[512] = {0}; uint8_t tmp[512] = {0}; int b64_len; int out_len; asn_enc_rval_t ret; if (ca_file == NULL || cert == NULL || pri_key == NULL) { printf("Parameters error\n"); return -1; } f = fopen(ca_file, "w"); if (f == NULL) { printf("Open file %s failed\n", ca_file); return -1; } ret = der_encode_to_buffer(&asn_DEF_Certificate, cert, ca, sizeof(ca)); if (ret.encoded == 0) { fclose(f); printf("Encode certification failed\n"); return -1; } Base64Encode(ca, ret.encoded, b64, &b64_len); Base64Encode(pri_key, strlen(pri_key), tmp, &out_len); fwrite(key_title, strlen(key_title), 1, f); fwrite(tmp, out_len, 1, f); fwrite(key_end, strlen(key_end), 1, f); fwrite(cert_title, strlen(cert_title), 1, f); fwrite(b64, b64_len, 1, f); fwrite(cert_end, strlen(cert_end), 1, f); if (signer_info_digest != NULL) { fwrite(sign_digest_title, strlen(sign_digest_title), 1, f); fwrite(signer_info_digest, strlen(signer_info_digest), 1, f); fwrite(sign_digest_end, strlen(sign_digest_end), 1, f); } fclose(f); return 0; }
0
apollo_public_repos/apollo-contrib/obu
apollo_public_repos/apollo-contrib/obu/security/CMakeLists.txt
cmake_minimum_required(VERSION 2.8) include_directories(../third_party/security/include) add_library(security security.cc common.c) target_link_libraries(security cncrypto cert cncrypto crypto glog)
0
apollo_public_repos/apollo-contrib/obu
apollo_public_repos/apollo-contrib/obu/security/security.h
/****************************************************************************** * 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. *****************************************************************************/ /** * @file security.h * @brief This is for data security. It will add a header and a tail to input * data. The header includes CA and the tail includes signature. * The functions: * Secured: add signature. * VerifyAndStrip: verify signature then strip the header and tail. * * The public key cryptographic algorithm we use is SM2. * The description is at * http://www.sca.gov.cn/sca/xwdt/2010-12/17/1002386/files/b791a9f908bb4803875ab6aeeb7b4e03.pdf. * The cryptographic hash algorithm is SM3 and the description is at * http://www.sca.gov.cn/sca/xwdt/2010-12/17/1002389/files/302a3ada057c4a73830536d03e683110.pdf. * The certification format is followed the standard * "Intelligent transport - Certificate application interface". The document is at http://www.mot.gov.cn/yijianzhengji/lishizhengji/201711/P020171101362371804539.pdf. * * Note: you must call Init first. */ #ifndef APOLLO_V2X_SECURITY_SECURITY_H #define APOLLO_V2X_SECURITY_SECURITY_H #include <openssl/ec.h> #include <string> #include "SecuredMessage.h" namespace v2x { #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&); \ TypeName& operator=(const TypeName&) class Security { public: explicit Security(std::string root_ca_file, std::string self_ca_file); ~Security(); /** * @brief Initialize. * @return return 0 successed, * -1 failed */ int Init(); /** * @brief Sign the data. * @param data (input) * @param data_len (input) * @param sign_data (output) * @param sign_len (output) */ virtual void Sign(uint8_t* data, size_t data_len, uint8_t* sign_data, size_t* sign_len); /** * @brief Sign and add a header and tail(includes signature) the data. * @param data (input) * @param data_len (input) * @param secured_data (output) * @param secured_len (output) */ virtual void Secured(uint8_t* data, size_t data_len, uint8_t* secured_data, size_t secured_buf_size, size_t* secured_len); /** * @brief Verify the signature, strip the header and tail. * @param secured_data (input) * @param secured_len (input) * @param data (output) * @param data_len (output) * @return 0 not secured or verified successfully * -1 parameters error * -2 decode failed * -3 get public key in the data failed * -4 verify failed */ virtual int VerifyAndStrip(uint8_t* secured_data, size_t secured_len, uint8_t* data, size_t* data_len); private: DISALLOW_COPY_AND_ASSIGN(Security); std::string root_ca_file_; std::string self_ca_file_; uint8_t self_ca_buf_[1024] = {0}; size_t self_ca_len_; EC_KEY* root_key_; EC_KEY* self_key_; }; } // namespace v2x #endif // APOLLO_V2X_SECURITY_SECURITY_H
0
apollo_public_repos/apollo-contrib/obu
apollo_public_repos/apollo-contrib/obu/security/security.cc
/****************************************************************************** * 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. *****************************************************************************/ /** * @file Security.cc * @brief This is for data security. It will add a header and a tail to input * data. The header includes CA and the tail includes signature. * The functions: * Secured: add header and tail. * VerifyAndStrip: verify signature then strip the header and tail. * * Note: you must call Init first. */ #include "security.h" #include <openssl/bn.h> #include <openssl/ec.h> #include <openssl/ecdh.h> #include <openssl/ecdsa.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/rand.h> #include "common.h" #include "glog/logging.h" #include "sm2.h" #include "sm3.h" namespace v2x { Security::Security(std::string root_ca_file, std::string self_ca_file) : root_ca_file_(root_ca_file), self_ca_file_(self_ca_file), root_key_(nullptr), self_key_(nullptr) {} Security::~Security() { if (root_key_ != nullptr) { EC_KEY_free(root_key_); } if (self_key_ != nullptr) { EC_KEY_free(self_key_); } } int Security::Init() { if(!root_ca_file_.empty()) { root_key_ = GetKey(root_ca_file_.c_str()); if (root_key_ == nullptr) { LOG(ERROR) << "Get root key failed"; return -1; } } if(!self_ca_file_.empty()) { int ret = 0; self_key_ = GetKey(self_ca_file_.c_str()); if (self_key_ == nullptr) { LOG(ERROR) << "Get self key failed"; return -1; } ret = GetCert(self_ca_file_.c_str(), self_ca_buf_, &self_ca_len_); if (ret != 0) { LOG(ERROR) << "Get self certification failed"; return -1; } } return 0; } void Security::Sign(uint8_t *data, size_t data_len, uint8_t *sign_data, size_t *sign_len) { uint8_t digest[64] = {0}; SM3(data, data_len, digest); SM2Sign(digest, 32, sign_data, sign_len, self_key_); } void Security::Secured(uint8_t *data, size_t data_len, uint8_t *secured_data, size_t secured_buf_size, size_t *secured_len) { SecuredMessage_t secured_msg; uint8_t signature[128] = {0}; size_t sig_len = 0; memset(&secured_msg, 0, sizeof(secured_msg)); secured_msg.protocolVersion = 2; secured_msg.headerFields.signerinfo = (SignerInfo_t *)malloc(sizeof(SignerInfo_t)); memset(secured_msg.headerFields.signerinfo, 0, sizeof(SignerInfo_t)); secured_msg.headerFields.signerinfo->present = SignerInfo_PR_certificateStr; secured_msg.headerFields.signerinfo->choice.certificateStr.size = self_ca_len_; secured_msg.headerFields.signerinfo->choice.certificateStr.buf = (uint8_t *)malloc(self_ca_len_); memcpy(secured_msg.headerFields.signerinfo->choice.certificateStr.buf, self_ca_buf_, self_ca_len_); secured_msg.payloadField.present = Payload_PR_signed; secured_msg.payloadField.choice.Signed.size = data_len; secured_msg.payloadField.choice.Signed.buf = (uint8_t *)malloc(data_len); memcpy(secured_msg.payloadField.choice.Signed.buf, data, data_len); Sign(data, data_len, signature, &sig_len); secured_msg.trailerFields.present = TrailerField_PR_signature; secured_msg.trailerFields.choice.signature.present = Signature_PR_signature; secured_msg.trailerFields.choice.signature.choice.signature.size = sig_len; secured_msg.trailerFields.choice.signature.choice.signature.buf = (uint8_t *)malloc(sig_len); memcpy(secured_msg.trailerFields.choice.signature.choice.signature.buf, signature, sig_len); asn_enc_rval_t ret; ret = der_encode_to_buffer(&asn_DEF_SecuredMessage, &secured_msg, secured_data, secured_buf_size); *secured_len = ret.encoded; } int Security::VerifyAndStrip(uint8_t *secured_data, size_t secured_len, uint8_t *data, size_t *data_len) { SecuredMessage_t *secured_msg = nullptr; EC_KEY *pub_key = NULL; uint8_t digest[64] = {0}; if (secured_data == nullptr || data == nullptr || data_len == nullptr) { LOG(ERROR) << "Parameters error"; return -1; } ber_decode(NULL, &asn_DEF_SecuredMessage, (void **)&secured_msg, secured_data, secured_len); if (secured_msg == nullptr) { return -2; } pub_key = GetPubKey(secured_msg->headerFields.signerinfo->choice.certificateStr.buf, secured_msg->headerFields.signerinfo->choice.certificateStr.size, root_key_); if (pub_key == NULL) { return -3; } SM3(secured_msg->payloadField.choice.Signed.buf, secured_msg->payloadField.choice.Signed.size, digest); if (!SM2Verify( digest, 32, secured_msg->trailerFields.choice.signature.choice.signature.buf, secured_msg->trailerFields.choice.signature.choice.signature.size, pub_key)) { EC_KEY_free(pub_key); return -4; } memcpy(data, secured_msg->payloadField.choice.Signed.buf, secured_msg->payloadField.choice.Signed.size); *data_len = secured_msg->payloadField.choice.Signed.size; EC_KEY_free(pub_key); return 0; } } // End of namespace v2x
0
apollo_public_repos/apollo-contrib/obu
apollo_public_repos/apollo-contrib/obu/security/common.h
/****************************************************************************** * 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. *****************************************************************************/ /** * @file common.h * @brief This is a common file for v2x security. */ #ifndef APOLLO_V2X_SECURITY_COMMON_H #define APOLLO_V2X_SECURITY_COMMON_H #ifdef __cplusplus extern "C" { #endif /** * @brief Get the second by time. It's the second after 1970, Jan 1st, 00:00:00. * @param year * @param month * @param day * @param hour * @param min * @param sec * @return second count */ time_t GetTimeSec(int year, int month, int day, int hour, int min, int sec); /** * @brief Print string with %02x format. * @param buffer * @param len */ void printChar(uint8_t *buffer, int len); /** * @brief Encode data with base64 format. * @param input * @param inlen * @param output * @param outlen */ void Base64Encode(const uint8_t *input, int inlen, uint8_t *output, int *outlen); /** * @brief Decode base64 format data. * @param input * @param inlen * @param output * @param outlen */ void Base64Decode(const uint8_t *input, int inlen, uint8_t *output, int *outlen); /** * @brief Get ECKEY from CA file. It must has public key, but private key is optional. * @param ca_file CA file name * @return EC_KEY eckey or NULL */ EC_KEY *GetKey(const char *ca_file); /** * @brief Get content of the CA file. * @param ca_file CA file name * @param cert certification content * @param cert_len * @return 0 for success -1 for fail */ int GetCert(const char *ca_file, uint8_t *cert, size_t *cert_len); /** * @brief Get public key from a ca. The public key would be verified by root key * @param ca_buf CA buffer * @param ca_len * @param root_key root CA key * @return eckey or NULL */ EC_KEY *GetPubKey(uint8_t *ca_buf, int ca_len, EC_KEY *root_key); /** * @brief Write certification to CA file. * @param ca_file CA file name * @param cert certification structure * @param pri_key private key * @param signer_info_digest optional signer certification digest(8 Bytes) * @return 0 for succes -1 for fail */ int WriteToFile(char *ca_file, Certificate_t *cert, const char *pri_key, const char *signer_info_digest); #ifdef __cplusplus } #endif #endif // APOLLO_V2X_SECURITY_COMMON_H
0
apollo_public_repos/apollo-contrib/obu
apollo_public_repos/apollo-contrib/obu/security/child_cert.pem
-----BEGIN PRIVATE KEY----- E6nJQnU0MrEO7WTA/ENgcjqrU23RGjKTrWjQcmngKQM= -----END PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIHAgAECoRKBEGM4MmUzODI3NTM2OWNlNmOiDYABAYEIQmFpZHVDbwCjRKBCgEAf 6/BVtEejg9VULVsV0vyi4S0DJNhl8BCndHaNB4AuHEg6uyGYRMMd8s+P5uXnckSK AG9teDFw3APfqXQlp5HBpAaABB4YfgClSoBIMEYCIQCwZTDGXrmCYjRyURioGSP0 MyiiCbiRutnGABixYT2y9wIhANHMfLn7Yj5084l6tkSpXkd57UN/wp99JRp2mwKv kxYP -----END CERTIFICATE----- -----BEGIN SIGNATURE DIGEST----- c82e38275369ce6c -----END SIGNATURE DIGEST-----
0