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/modules/drivers/microphone
apollo_public_repos/apollo/modules/drivers/microphone/dag/microphone.dag
module_config { module_library : "/apollo/bazel-bin/modules/drivers/microphone/libmicrophone_component.so" components { class_name : "MicrophoneComponent" config { name : "respeaker" config_file_path : "/apollo/modules/drivers/microphone/conf/respeaker.pb.txt" } } }
0
apollo_public_repos/apollo/modules/drivers/microphone
apollo_public_repos/apollo/modules/drivers/microphone/conf/respeaker.pb.txt
microphone_model: RESPEAKER chunk: 8192 sample_rate: 48000 record_seconds: 0.17 sample_width: 2 channel_name: "/apollo/sensor/microphone" frame_id: "respeaker" mic_distance: 0.065 channel_type: ASR channel_type: RAW channel_type: RAW channel_type: RAW channel_type: RAW channel_type: PLAYBACK
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/smartereye/smartereye_component.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. *****************************************************************************/ #include "modules/drivers/smartereye/smartereye_component.h" #include "modules/drivers/smartereye/smartereye_handler.h" #include "modules/common/adapters/adapter_gflags.h" namespace apollo { namespace drivers { namespace smartereye { SmartereyeComponent::~SmartereyeComponent() { if (running_.load()) { running_.exchange(false); async_result_.wait(); } } bool SmartereyeComponent::Init() { camera_config_ = std::make_shared<Config>(); if (!apollo::cyber::common::GetProtoFromFile(config_file_path_, camera_config_.get())) { return false; } AINFO << "SmartereyeDevice config: " << camera_config_->DebugString(); camera_device_.reset(new SmartereyeDevice()); camera_device_->init(camera_config_); device_wait_ = camera_config_->device_wait_ms(); spin_rate_ = static_cast<uint32_t>((1.0 / camera_config_->spin_rate()) * 1e6); b_ispolling_ = false; SetCallback(); writer_ = node_->CreateWriter<Image>(camera_config_->channel_name_image()); SmartereyeObstacles_writer_ = node_->CreateWriter<SmartereyeObstacles>( FLAGS_smartereye_obstacles_topic); SmartereyeLanemark_writer_ = node_->CreateWriter<SmartereyeLanemark>( FLAGS_smartereye_lanemark_topic); async_result_ = cyber::Async(&SmartereyeComponent::run, this); return true; } void SmartereyeComponent::run() { running_.exchange(true); while (!cyber::IsShutdown()) { camera_device_->poll(); cyber::SleepFor(std::chrono::microseconds(spin_rate_)); } } bool SmartereyeComponent::SetCallback() { CallbackFunc fun = std::bind(&SmartereyeComponent::Callback, this, std::placeholders::_1); camera_device_->SetCallback(fun); return true; } bool SmartereyeComponent::Callback(RawImageFrame *rawFrame) { if (rawFrame->frameId == FrameId::Compound || rawFrame->frameId == FrameId::LaneExt) { processFrame(rawFrame->frameId, reinterpret_cast<char *>(rawFrame) + sizeof(RawImageFrame), reinterpret_cast<char *>(rawFrame) + rawFrame->dataSize + sizeof(RawImageFrame), rawFrame->time, rawFrame->width, rawFrame->height); } else { processFrame(rawFrame->frameId, reinterpret_cast<char *>(rawFrame) + sizeof(RawImageFrame), rawFrame->dataSize, rawFrame->width, rawFrame->height, rawFrame->format); } return true; } void SmartereyeComponent::processFrame(int frameId, char *image, char *extended, int64_t time, int width, int height) { switch (frameId) { case FrameId::Compound: { FrameDataExtHead *header = reinterpret_cast<FrameDataExtHead *>(extended); int blockNum = (reinterpret_cast<int *>(header->data))[0]; OutputObstacles *obsDataPack = reinterpret_cast<OutputObstacles *>( ((reinterpret_cast<int *>(header->data)) + 2)); SmartereyeObstacles pbSmartereyeObstacles; pbSmartereyeObstacles.mutable_header()->set_frame_id( FLAGS_smartereye_obstacles_topic); pbSmartereyeObstacles.set_num_obstacles(blockNum); OutputObstacle pbOutputObstacle; for (int j = 0; j < blockNum; j++) { pbOutputObstacle.set_currentspeed(obsDataPack[j].currentSpeed); pbOutputObstacle.set_framerate(obsDataPack[j].frameRate); pbOutputObstacle.set_trackid(obsDataPack[j].trackId); pbOutputObstacle.set_trackframenum(obsDataPack[j].trackFrameNum); pbOutputObstacle.set_statelabel(obsDataPack[j].stateLabel); pbOutputObstacle.set_classlabel(obsDataPack[j].classLabel); pbOutputObstacle.set_continuouslabel(obsDataPack[j].continuousLabel); pbOutputObstacle.set_fuzzyestimationvalid( obsDataPack[j].fuzzyEstimationValid); pbOutputObstacle.set_obstacletype( (OutputObstacle_RecognitionType)obsDataPack[j].obstacleType); pbOutputObstacle.set_avgdisp(obsDataPack[j].avgDistanceZ); pbOutputObstacle.set_avgdistancez(obsDataPack[j].avgDistanceZ); pbOutputObstacle.set_neardistancez(obsDataPack[j].nearDistanceZ); pbOutputObstacle.set_fardistancez(obsDataPack[j].farDistanceZ); pbOutputObstacle.set_real3dleftx(obsDataPack[j].real3DLeftX); pbOutputObstacle.set_real3drightx(obsDataPack[j].real3DRightX); pbOutputObstacle.set_real3dcenterx(obsDataPack[j].real3DCenterX); pbOutputObstacle.set_real3dupy(obsDataPack[j].real3DUpY); pbOutputObstacle.set_real3dlowy(obsDataPack[j].real3DLowY); pbOutputObstacle.set_firstpointx(obsDataPack[j].firstPointX); pbOutputObstacle.set_firstpointy(obsDataPack[j].firstPointY); pbOutputObstacle.set_secondpointx(obsDataPack[j].secondPointX); pbOutputObstacle.set_secondpointy(obsDataPack[j].secondPointY); pbOutputObstacle.set_thirdpointx(obsDataPack[j].thirdPointX); pbOutputObstacle.set_thirdpointy(obsDataPack[j].thirdPointY); pbOutputObstacle.set_fourthpointx(obsDataPack[j].fourthPointX); pbOutputObstacle.set_fourthpointy(obsDataPack[j].fourthPointY); pbOutputObstacle.set_fuzzyrelativedistancez( obsDataPack[j].fuzzyRelativeDistanceZ); pbOutputObstacle.set_fuzzyrelativespeedz( obsDataPack[j].fuzzyRelativeSpeedZ); pbOutputObstacle.set_fuzzycollisiontimez( obsDataPack[j].fuzzyCollisionTimeZ); pbOutputObstacle.set_fuzzycollisionx(obsDataPack[j].fuzzyCollisionX); pbOutputObstacle.set_fuzzy3dwidth(obsDataPack[j].fuzzy3DWidth); pbOutputObstacle.set_fuzzy3dcenterx(obsDataPack[j].fuzzy3DCenterX); pbOutputObstacle.set_fuzzy3dleftx(obsDataPack[j].fuzzy3DLeftX); pbOutputObstacle.set_fuzzy3drightx(obsDataPack[j].fuzzy3DRightX); pbOutputObstacle.set_fuzzy3dheight(obsDataPack[j].fuzzy3DHeight); pbOutputObstacle.set_fuzzy3dupy(obsDataPack[j].fuzzy3DUpY); pbOutputObstacle.set_fuzzy3dlowy(obsDataPack[j].fuzzy3DLowY); pbOutputObstacle.set_fuzzyrelativespeedcenterx( obsDataPack[j].fuzzyRelativeSpeedCenterX); pbOutputObstacle.set_fuzzyrelativespeedleftx( obsDataPack[j].fuzzyRelativeSpeedLeftX); pbOutputObstacle.set_fuzzyrelativespeedrightx( obsDataPack[j].fuzzyRelativeSpeedRightX); (*pbSmartereyeObstacles.mutable_output_obstacles())[j] = pbOutputObstacle; } SmartereyeObstacles_writer_->Write(pbSmartereyeObstacles); static unsigned char *rgbBuf = new unsigned char[width * height * 3]; RoadwayPainter::imageGrayToRGB((unsigned char *)image, rgbBuf, width, height); ObstaclePainter::paintObstacle(header->data, rgbBuf, width, height, true, false); Image pb_image; pb_image.mutable_header()->set_frame_id( camera_config_->channel_name_image()); pb_image.set_width(width); pb_image.set_height(height); pb_image.set_data(rgbBuf, width * height * 3); pb_image.set_encoding("rgb8"); pb_image.set_step(width * 3); pb_image.mutable_header()->set_timestamp_sec( cyber::Time::Now().ToSecond()); pb_image.set_measurement_time(time); writer_->Write(pb_image); } break; case FrameId::LaneExt: { FrameDataExtHead *header = reinterpret_cast<FrameDataExtHead *>(extended); LdwDataPack *ldwDataPack = reinterpret_cast<LdwDataPack *>(header->data); AINFO << "ldw degree is: " << ldwDataPack->roadway.left_Lane.left_Boundary.degree; SmartereyeLanemark pbSmartereyeLanemark; pbSmartereyeLanemark.mutable_lane_road_data() ->mutable_roadway() ->set_width_0(ldwDataPack->roadway.width[0]); pbSmartereyeLanemark.mutable_lane_road_data() ->mutable_roadway() ->set_width_1(ldwDataPack->roadway.width[1]); pbSmartereyeLanemark.mutable_lane_road_data() ->mutable_roadway() ->set_width_2(ldwDataPack->roadway.width[2]); pbSmartereyeLanemark.mutable_lane_road_data() ->mutable_roadway() ->set_is_tracking(ldwDataPack->roadway.isTracking); pbSmartereyeLanemark.mutable_lane_road_data()->set_softstatus( (LdwSoftStatus)ldwDataPack->softStatus); pbSmartereyeLanemark.mutable_lane_road_data()->set_steerstatus( (LdwSteerStatus)ldwDataPack->steerStatus); pbSmartereyeLanemark.mutable_lane_road_data() ->mutable_lens() ->set_x_image_focal(ldwDataPack->lens.xImageFocal); pbSmartereyeLanemark.mutable_lane_road_data() ->mutable_lens() ->set_y_image_focal(ldwDataPack->lens.yImageFocal); pbSmartereyeLanemark.mutable_lane_road_data() ->mutable_lens() ->set_xratio_focal_pixel(ldwDataPack->lens.xRatioFocalToPixel); pbSmartereyeLanemark.mutable_lane_road_data() ->mutable_lens() ->set_yratio_focal_pixel(ldwDataPack->lens.yRatioFocalToPixel); pbSmartereyeLanemark.mutable_lane_road_data() ->mutable_lens() ->set_mountingheight(ldwDataPack->lens.mountingHeight); pbSmartereyeLanemark.mutable_lane_road_data()->mutable_lens()->set_mcosrx( ldwDataPack->lens.mCosRx); pbSmartereyeLanemark.mutable_lane_road_data()->mutable_lens()->set_msinrx( ldwDataPack->lens.mSinRx); pbSmartereyeLanemark.mutable_lane_road_data()->mutable_lens()->set_mcosry( ldwDataPack->lens.mCosRy); pbSmartereyeLanemark.mutable_lane_road_data()->mutable_lens()->set_msinry( ldwDataPack->lens.mSinRy); SmartereyeLanemark_writer_->Write(pbSmartereyeLanemark); static unsigned char *rgbBuf = new unsigned char[width * height * 3]; RoadwayPainter::imageGrayToRGB((unsigned char *)image, rgbBuf, width, height); bool mIsLaneDetected = RoadwayPainter::paintRoadway(header->data, rgbBuf, width, height); AINFO << mIsLaneDetected; Image pb_image; pb_image.mutable_header()->set_frame_id( camera_config_->channel_name_image()); pb_image.set_width(width); pb_image.set_height(height); pb_image.set_data(rgbBuf, width * height * 3); pb_image.set_encoding("rgb8"); pb_image.set_step(width * 3); pb_image.mutable_header()->set_timestamp_sec( cyber::Time::Now().ToSecond()); pb_image.set_measurement_time(time); writer_->Write(pb_image); } default: break; } } void SmartereyeComponent::processFrame(int frameId, char *image, uint32_t dataSize, int width, int height, int frameFormat) { switch (frameId) { case FrameId::Lane: { AINFO << "case FrameId::Lane:"; LdwDataPack *ldwDataPack = reinterpret_cast<LdwDataPack *>(image); int degree = ldwDataPack->roadway.left_Lane.left_Boundary.degree; AINFO << "ldw degree is: " << degree; } break; case FrameId::Obstacle: { AINFO << "case FrameId::Obstacle:"; int blockNum = (reinterpret_cast<int *>(image))[0]; AINFO << "blockNum is: " << blockNum; } break; case FrameId::Disparity: { AINFO << "case FrameId::Disparity:"; } break; case FrameId::CalibLeftCamera: { AINFO << "case FrameId::CalibLeftCamera:"; } break; default: break; } } } // namespace smartereye } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/smartereye/compress_component.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. *****************************************************************************/ #pragma once #include <memory> #include "cyber/base/concurrent_object_pool.h" #include "cyber/cyber.h" #include "modules/common_msgs/sensor_msgs/sensor_image.pb.h" #include "modules/drivers/smartereye/proto/config.pb.h" namespace apollo { namespace drivers { namespace smartereye { using apollo::cyber::Component; using apollo::cyber::Writer; using apollo::cyber::base::CCObjectPool; using apollo::drivers::Image; using apollo::drivers::smartereye::config::Config; class CompressComponent : public Component<Image> { public: bool Init() override; bool Proc(const std::shared_ptr<Image>& image) override; private: std::shared_ptr<CCObjectPool<CompressedImage>> image_pool_ = nullptr; std::shared_ptr<Writer<CompressedImage>> writer_ = nullptr; Config config_; }; CYBER_REGISTER_COMPONENT(CompressComponent) } // namespace smartereye } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/smartereye/smartereye_component.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. *****************************************************************************/ #pragma once #include <atomic> #include <future> #include <memory> #include <vector> #include "cyber/cyber.h" #include "modules/common_msgs/sensor_msgs/sensor_image.pb.h" #include "modules/common_msgs/sensor_msgs/smartereye.pb.h" #include "modules/drivers/smartereye/proto/config.pb.h" #include "modules/drivers/smartereye/smartereye_device.h" #include "third_party/camera_library/smartereye/include/frameext.h" #include "third_party/camera_library/smartereye/include/obstacleData.h" #include "third_party/camera_library/smartereye/include/obstaclepainter.h" #include "third_party/camera_library/smartereye/include/roadwaypainter.h" #include "third_party/camera_library/smartereye/include/yuv2rgb.h" namespace apollo { namespace drivers { namespace smartereye { using apollo::cyber::Component; using apollo::cyber::Reader; using apollo::cyber::Writer; using apollo::drivers::Image; using apollo::drivers::smartereye::config::Config; class SmartereyeComponent : public Component<> { public: bool Init() override; ~SmartereyeComponent(); protected: void run(); bool SetCallback(); bool Callback(RawImageFrame *rawFrame); void processFrame(int frameId, char *image, char *extended, int64_t time, int width, int height); void processFrame(int frameId, char *image, uint32_t dataSize, int width, int height, int frameFormat); private: std::shared_ptr<Writer<Image>> writer_ = nullptr; std::shared_ptr<Writer<SmartereyeObstacles>> SmartereyeObstacles_writer_ = nullptr; std::shared_ptr<Writer<SmartereyeLanemark>> SmartereyeLanemark_writer_ = nullptr; std::unique_ptr<SmartereyeDevice> camera_device_ = nullptr; std::shared_ptr<Config> camera_config_ = nullptr; uint32_t spin_rate_ = 200; uint32_t device_wait_ = 2000; std::future<void> async_result_; std::atomic<bool> running_ = {false}; bool b_ispolling_ = false; }; CYBER_REGISTER_COMPONENT(SmartereyeComponent) } // namespace smartereye } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/smartereye/compress_component.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. *****************************************************************************/ #include "modules/drivers/smartereye/compress_component.h" #include <exception> #include <vector> #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" namespace apollo { namespace drivers { namespace smartereye { bool CompressComponent::Init() { if (!GetProtoConfig(&config_)) { AERROR << "Parse config file failed: " << ConfigFilePath(); return false; } AINFO << "Camera config: \n" << config_.DebugString(); try { image_pool_.reset(new CCObjectPool<CompressedImage>( config_.compress_conf().image_pool_size())); image_pool_->ConstructAll(); } catch (const std::bad_alloc& e) { AERROR << e.what(); return false; } writer_ = node_->CreateWriter<CompressedImage>( config_.compress_conf().output_channel()); return true; } bool CompressComponent::Proc(const std::shared_ptr<Image>& image) { ADEBUG << "procing compressed"; auto compressed_image = image_pool_->GetObject(); compressed_image->mutable_header()->CopyFrom(image->header()); compressed_image->set_frame_id(image->frame_id()); compressed_image->set_measurement_time(image->measurement_time()); compressed_image->set_format(image->encoding() + "; jpeg compressed bgr8"); std::vector<int> params; params.resize(3, 0); params[0] = cv::IMWRITE_JPEG_QUALITY; params[1] = 95; try { cv::Mat mat_image(image->height(), image->width(), CV_8UC3, const_cast<char*>(image->data().data()), image->step()); cv::Mat tmp_mat; cv::cvtColor(mat_image, tmp_mat, cv::COLOR_RGB2BGR); std::vector<uint8_t> compress_buffer; if (!cv::imencode(".jpg", tmp_mat, compress_buffer, params)) { AERROR << "cv::imencode (jpeg) failed on input image"; return false; } compressed_image->set_data(compress_buffer.data(), compress_buffer.size()); writer_->Write(compressed_image); } catch (std::exception& e) { AERROR << "cv::imencode (jpeg) exception :" << e.what(); return false; } return true; } } // namespace smartereye } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/smartereye/smartereye_handler.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. *****************************************************************************/ #pragma once #include <functional> #include <iostream> #include <string> #include "cyber/cyber.h" #include "third_party/camera_library/smartereye/include/calibrationparams.h" #include "third_party/camera_library/smartereye/include/camerahandler.h" #include "third_party/camera_library/smartereye/include/rotationmatrix.h" namespace apollo { namespace drivers { namespace smartereye { typedef std::function<bool(RawImageFrame *rawFrame)> CallbackFunc; class SmartereyeHandler : public CameraHandler { public: explicit SmartereyeHandler(std::string name); ~SmartereyeHandler(); void handleRawFrame(const RawImageFrame *rawFrame); bool SetCallback(CallbackFunc ptr); void handleUpdateFinished(Result result) {} protected: void handleDisparityPointByPoint(unsigned char *image, int width, int height, int bitNum) {} void handleDisparityByLookupTable(unsigned char *image, int width, int height, int bitNum) {} private: std::string mName = nullptr; CallbackFunc pCallbackFunc = nullptr; }; } // namespace smartereye } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/smartereye/smartereye_handler.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. *****************************************************************************/ #include "modules/drivers/smartereye/smartereye_handler.h" #include <math.h> #include <iostream> #include <string> #include "third_party/camera_library/smartereye/include/LdwDataInterface.h" #include "third_party/camera_library/smartereye/include/disparityconvertor.h" #include "third_party/camera_library/smartereye/include/frameid.h" #include "third_party/camera_library/smartereye/include/obstacleData.h" #include "third_party/camera_library/smartereye/include/satpext.h" namespace apollo { namespace drivers { namespace smartereye { SmartereyeHandler::SmartereyeHandler(std::string name) : mName(name) { pCallbackFunc = nullptr; } SmartereyeHandler::~SmartereyeHandler() { pCallbackFunc = nullptr; } bool SmartereyeHandler::SetCallback(CallbackFunc ptr) { pCallbackFunc = ptr; return true; } void SmartereyeHandler::handleRawFrame(const RawImageFrame *rawFrame) { pCallbackFunc(const_cast<RawImageFrame *>(rawFrame)); } } // namespace smartereye } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/smartereye/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") load("//tools/install:install.bzl", "install") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) CAMERA_COPTS = ['-DMODULE_NAME=\\"camera\\"'] install( name = "install", data_dest = "drivers/addition_data/smartereye", library_dest = "drivers/lib/smartereye", data = [ ":runtime_data", ], targets = [ ":libsmartereye_component.so", ], ) filegroup( name = "runtime_data", srcs = glob([ "conf/*.txt", "dag/*.dag", "launch/*.launch", ]), ) cc_binary( name = "libsmartereye_component.so", linkshared = True, linkstatic = True, deps = [ ":compress_component_lib", ":smartereye_component_lib", ], ) cc_library( name = "smartereye_component_lib", srcs = ["smartereye_component.cc"], hdrs = ["smartereye_component.h"], alwayslink = True, copts = CAMERA_COPTS, deps = [ ":smartereye_device", ":smartereye_handler", "//cyber", "//modules/common/adapters:adapter_gflags", "//modules/common_msgs/basic_msgs:error_code_cc_proto", "//modules/common_msgs/basic_msgs:header_cc_proto", "//modules/common_msgs/sensor_msgs:sensor_image_cc_proto", "//modules/common_msgs/sensor_msgs:smartereye_cc_proto", "//third_party/camera_library/smartereye", ], ) cc_library( name = "smartereye_device", srcs = ["smartereye_device.cc"], hdrs = ["smartereye_device.h"], copts = CAMERA_COPTS, deps = [ ":smartereye_handler", "//cyber", "//modules/drivers/smartereye/proto:config_cc_proto", "//third_party/camera_library/smartereye", ], ) cc_library( name = "smartereye_handler", srcs = ["smartereye_handler.cc"], hdrs = ["smartereye_handler.h"], copts = CAMERA_COPTS, deps = [ "//cyber", "//third_party/camera_library/smartereye", ], ) cc_library( name = "compress_component_lib", srcs = ["compress_component.cc"], hdrs = ["compress_component.h"], copts = CAMERA_COPTS, alwayslink = True, deps = [ "//cyber", "//modules/common_msgs/basic_msgs:error_code_cc_proto", "//modules/common_msgs/basic_msgs:header_cc_proto", "//modules/common_msgs/sensor_msgs:sensor_image_cc_proto", "//modules/common_msgs/sensor_msgs:smartereye_cc_proto", "//modules/drivers/smartereye/proto:config_cc_proto", "@opencv//:highgui", ], ) cpplint()
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/smartereye/smartereye_device.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. *****************************************************************************/ #include "modules/drivers/smartereye/smartereye_device.h" #include <time.h> #include <cmath> #include <string> #define CLEAR(x) memset(&(x), 0, sizeof(x)) namespace apollo { namespace drivers { namespace smartereye { SmartereyeDevice::SmartereyeDevice() {} SmartereyeDevice::~SmartereyeDevice() { uninit(); } bool SmartereyeDevice::init(const std::shared_ptr<Config>& camera_config) { pcamera_ = StereoCamera::connect("192.168.1.251"); pcameraHandler_ = new SmartereyeHandler("camera A"); pcamera_->enableTasks(TaskId::ObstacleTask | TaskId::DisplayTask); inited_ = true; return true; } bool SmartereyeDevice::SetCallback(CallbackFunc ptr) { pcameraHandler_->SetCallback(ptr); return true; } int SmartereyeDevice::poll() { pcamera_->requestFrame(pcameraHandler_, FrameId::Compound); is_capturing_ = true; return 1; } int SmartereyeDevice::uninit() { if (!inited_) { return 1; } pcamera_->disconnectFromServer(); is_capturing_ = false; inited_ = false; return 1; } bool SmartereyeDevice::is_capturing() { return is_capturing_; } bool SmartereyeDevice::wait_for_device() { if (is_capturing_) { ADEBUG << "is capturing"; return true; } return true; } } // namespace smartereye } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/smartereye/smartereye_device.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. *****************************************************************************/ #pragma once #include <math.h> #include <stdio.h> #include <iostream> #include <memory> #include <sstream> #include <string> #include "cyber/cyber.h" #include "modules/drivers/smartereye/proto/config.pb.h" #include "modules/drivers/smartereye/smartereye_handler.h" #include "third_party/camera_library/smartereye/include/LdwDataInterface.h" #include "third_party/camera_library/smartereye/include/calibrationparams.h" #include "third_party/camera_library/smartereye/include/camerahandler.h" #include "third_party/camera_library/smartereye/include/disparityconvertor.h" #include "third_party/camera_library/smartereye/include/frameid.h" #include "third_party/camera_library/smartereye/include/obstacleData.h" #include "third_party/camera_library/smartereye/include/rotationmatrix.h" #include "third_party/camera_library/smartereye/include/satpext.h" #include "third_party/camera_library/smartereye/include/stereocamera.h" #include "third_party/camera_library/smartereye/include/taskiddef.h" namespace apollo { namespace drivers { namespace smartereye { using apollo::drivers::smartereye::config::Config; class SmartereyeDevice { public: SmartereyeDevice(); virtual ~SmartereyeDevice(); virtual bool init(const std::shared_ptr<Config> &camera_config); bool is_capturing(); bool wait_for_device(); int uninit(); bool SetCallback(CallbackFunc ptr); int poll(); private: bool is_capturing_ = false; bool inited_ = false; std::shared_ptr<Config> config_; StereoCamera *pcamera_ = nullptr; SmartereyeHandler *pcameraHandler_ = nullptr; }; } // namespace smartereye } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/smartereye
apollo_public_repos/apollo/modules/drivers/smartereye/proto/BUILD
## Auto generated by `proto_build_generator.py` load("@rules_proto//proto:defs.bzl", "proto_library") load("@rules_cc//cc:defs.bzl", "cc_proto_library") load("//tools:python_rules.bzl", "py_proto_library") package(default_visibility = ["//visibility:public"]) cc_proto_library( name = "config_cc_proto", deps = [ ":config_proto", ], ) proto_library( name = "config_proto", srcs = ["config.proto"], ) py_proto_library( name = "config_py_pb2", deps = [ ":config_proto", ], )
0
apollo_public_repos/apollo/modules/drivers/smartereye
apollo_public_repos/apollo/modules/drivers/smartereye/proto/config.proto
syntax = "proto2"; package apollo.drivers.smartereye.config; enum IOMethod { IO_METHOD_UNKNOWN = 0; IO_METHOD_READ = 1; IO_METHOD_MMAP = 2; IO_METHOD_USERPTR = 3; } enum OutputType { YUYV = 0; RGB = 1; } message Config { optional string camera_dev = 1; optional string frame_id = 2; // v4l pixel format optional string pixel_format = 3 [default = "yuyv"]; // mmap, userptr, read optional IOMethod io_method = 4; optional uint32 width = 5; optional uint32 height = 6; optional uint32 frame_rate = 7; optional bool monochrome = 8 [default = false]; optional int32 brightness = 9 [default = -1]; optional int32 contrast = 10 [default = -1]; optional int32 saturation = 11 [default = -1]; optional int32 sharpness = 12 [default = -1]; optional int32 gain = 13 [default = -1]; optional bool auto_focus = 14 [default = false]; optional int32 focus = 15 [default = -1]; optional bool auto_exposure = 16 [default = true]; optional int32 exposure = 17 [default = 100]; optional bool auto_white_balance = 18 [default = true]; optional int32 white_balance = 19 [default = 4000]; optional uint32 bytes_per_pixel = 20 [default = 3]; optional uint32 trigger_internal = 21 [default = 0]; optional uint32 trigger_fps = 22 [default = 30]; optional string channel_name = 23; optional string channel_name_image = 24; optional string channel_name_image_compressed = 25; // wait time when camera select timeout optional uint32 device_wait_ms = 26 [default = 2000]; // camera select spin time optional uint32 spin_rate = 27 [default = 200]; optional OutputType output_type = 28; message CompressConfig { optional string output_channel = 1; optional uint32 image_pool_size = 2 [default = 20]; } optional CompressConfig compress_conf = 29; }
0
apollo_public_repos/apollo/modules/drivers/smartereye
apollo_public_repos/apollo/modules/drivers/smartereye/launch/smartereye.launch
<cyber> <module> <name>smartereye</name> <dag_conf>/apollo/modules/drivers/smartereye/dag/smartereye.dag</dag_conf> <process_name>smartereye</process_name> </module> </cyber>
0
apollo_public_repos/apollo/modules/drivers/smartereye
apollo_public_repos/apollo/modules/drivers/smartereye/dag/smartereye.dag
# Define all coms in DAG streaming. module_config { module_library : "/apollo/bazel-bin/modules/drivers/smartereye/libsmartereye_component.so" components { class_name : "SmartereyeComponent" config { name : "smartereye" config_file_path : "/apollo/modules/drivers/smartereye/conf/smartereye.pb.txt" } } components { class_name : "CompressComponent" config { name : "smartereye_compress" config_file_path : "/apollo/modules/drivers/smartereye/conf/smartereye.pb.txt" readers { channel: "/apollo/sensor/smartereye/image" pending_queue_size: 10 } } } }
0
apollo_public_repos/apollo/modules/drivers/smartereye
apollo_public_repos/apollo/modules/drivers/smartereye/conf/smartereye.pb.txt
camera_dev: "/dev/camera/smartereye" frame_id: "smartereye" pixel_format: "yuyv" io_method: IO_METHOD_MMAP width: 1280 height: 720 frame_rate: 20 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 2 trigger_internal: 0 trigger_fps: 20 channel_name: "/apollo/sensor/smartereye" channel_name_image: "/apollo/sensor/smartereye/image" channel_name_image_compressed: "/apollo/sensor/smartereye/image/compressed" device_wait_ms: 2000 spin_rate: 200 output_type: RGB compress_conf { output_channel: "/apollo/sensor/smartereye/image/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/camera/AUTHORS.md
Original Authors ---------------- * [Benjamin Pitzer] (benjamin.pitzer@bosch.com) Contributors ------------ * [Russell Toris](http://users.wpi.edu/~rctoris/) (rctoris@wpi.edu)
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/camera/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3) project(usb_cam) ## Find catkin macros and libraries ## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz) ## is used, also find other catkin packages find_package(catkin REQUIRED COMPONENTS image_transport roscpp std_msgs std_srvs sensor_msgs camera_info_manager cv_bridge) #find_package(CUDA REQUIRED) find_package(Boost 1.54 REQUIRED COMPONENTS system thread) ## pkg-config libraries find_package(PkgConfig REQUIRED) pkg_check_modules(avcodec libavcodec REQUIRED) pkg_check_modules(swscale libswscale REQUIRED) SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --std=c++11 -O2 -fopenmp -mavx2 -fPIC") ################################################### ## Declare things to be passed to other projects ## ################################################### ## LIBRARIES: libraries you create in this project that dependent projects also need ## CATKIN_DEPENDS: catkin_packages dependent projects also need ## DEPENDS: system dependencies of this project that dependent projects also need catkin_package( CATKIN_DEPENDS INCLUDE_DIRS include LIBRARIES ${PROJECT_NAME} ) ########### ## Build ## ########### link_directories( /usr/local/apollo/jsoncpp/lib /usr/local/apollo/adv_plat/lib ${catkin_LIB_DIRS} ) include_directories(include /usr/local/apollo/adv_plat ${catkin_INCLUDE_DIRS} ${avcodec_INCLUDE_DIRS} ${swscale_INCLUDE_DIRS} ) # Build the USB camera library add_library(${PROJECT_NAME} src/usb_cam.cpp) target_link_libraries(${PROJECT_NAME} yaml-cpp libadv_trigger_ctl.a libjsoncpp.so libadv_plat_common.a ${avcodec_LIBRARIES} ${swscale_LIBRARIES} ${catkin_LIBRARIES} ) ## Build the USB camera nodelet add_library(${PROJECT_NAME}_nodelet nodes/usb_cam_nodelet.cpp nodes/usb_cam_wrapper.cpp) target_link_libraries(${PROJECT_NAME}_nodelet ${PROJECT_NAME} libadv_trigger_ctl.a libjsoncpp.so libadv_plat_common.a ${avcodec_LIBRARIES} ${swscale_LIBRARIES} ${catkin_LIBRARIES} ) ## Declare USB camera cpp executable add_executable(${PROJECT_NAME}_node nodes/usb_cam_node.cpp nodes/usb_cam_wrapper.cpp) target_link_libraries(${PROJECT_NAME}_node ${PROJECT_NAME} libadv_trigger_ctl.a libjsoncpp.so libadv_plat_common.a ${avcodec_LIBRARIES} ${swscale_LIBRARIES} ${catkin_LIBRARIES} ) ############# ## Install ## ############# ## Mark executables and/or libraries for installation install(TARGETS ${PROJECT_NAME} ${PROJECT_NAME}_node ${PROJECT_NAME}_nodelet RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} ) ## Copy launch files install(DIRECTORY launch/ DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/launch FILES_MATCHING PATTERN "*.launch" ) # Copy libjsoncpp.so install( DIRECTORY /usr/local/apollo/jsoncpp/lib DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}/.. FILES_MATCHING PATTERN "*.so*" ) install(DIRECTORY params/ DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/params FILES_MATCHING PATTERN "*.yaml" ) install(FILES nodelets.xml DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} ) install(DIRECTORY include/${PROJECT_NAME}/ DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} FILES_MATCHING PATTERN "*.h" PATTERN "*.hpp" )
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/camera/LICENSE
Software License Agreement (BSD License) Copyright (c) 2014, Robert Bosch LLC. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Robert Bosch LLC. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/camera/mainpage.dox
/** \mainpage \b usb_cam is a ROS driver for V4L USB cameras. */
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/camera/camera_component.h
/****************************************************************************** * Copyright 2017 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. *****************************************************************************/ #pragma once #include <atomic> #include <future> #include <memory> #include <vector> #include "cyber/cyber.h" #include "modules/drivers/camera/proto/config.pb.h" #include "modules/common_msgs/sensor_msgs/sensor_image.pb.h" #include "modules/drivers/camera/usb_cam.h" namespace apollo { namespace drivers { namespace camera { using apollo::cyber::Component; using apollo::cyber::Reader; using apollo::cyber::Writer; using apollo::drivers::Image; using apollo::drivers::camera::config::Config; class CameraComponent : public Component<> { public: bool Init() override; ~CameraComponent(); private: void run(); std::shared_ptr<Writer<Image>> writer_ = nullptr; std::unique_ptr<UsbCam> camera_device_; std::shared_ptr<Config> camera_config_; CameraImagePtr raw_image_ = nullptr; std::vector<std::shared_ptr<Image>> pb_image_buffer_; uint32_t spin_rate_ = 200; uint32_t device_wait_ = 2000; int index_ = 0; int buffer_size_ = 16; const int32_t MAX_IMAGE_SIZE = 20 * 1024 * 1024; std::future<void> async_result_; std::atomic<bool> running_ = {false}; }; CYBER_REGISTER_COMPONENT(CameraComponent) } // namespace camera } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/camera/compress_component.h
/****************************************************************************** * Copyright 2017 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. *****************************************************************************/ #pragma once #include <memory> #include "cyber/base/concurrent_object_pool.h" #include "cyber/cyber.h" #include "modules/drivers/camera/proto/config.pb.h" #include "modules/common_msgs/sensor_msgs/sensor_image.pb.h" namespace apollo { namespace drivers { namespace camera { using apollo::cyber::Component; using apollo::cyber::Writer; using apollo::cyber::base::CCObjectPool; using apollo::drivers::Image; using apollo::drivers::camera::config::Config; class CompressComponent : public Component<Image> { public: bool Init() override; bool Proc(const std::shared_ptr<Image>& image) override; private: std::shared_ptr<CCObjectPool<CompressedImage>> image_pool_; std::shared_ptr<Writer<CompressedImage>> writer_ = nullptr; Config config_; }; CYBER_REGISTER_COMPONENT(CompressComponent) } // namespace camera } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/camera/README.md
####Driver for V4L USB Cameras This package is based on V4L devices specifically instead of just UVC. ### License usb_cam is released with a BSD license. For full terms and conditions, see the [LICENSE](LICENSE) file. ### Authors See the [AUTHORS](AUTHORS.md) file for a full list of contributors.
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/camera/README_cn.md
## Camera camera包是基于V4L USB相机设备实现封装,提供图像采集及发布的功能。本驱动中使用了一台长焦相机和一台短焦相机。 ### Output channels * /apollo/sensor/camera/front_12mm/image * /apollo/sensor/camera/front_6mm/image * /apollo/sensor/camera/front_fisheye/image * /apollo/sensor/camera/left_fisheye/image * /apollo/sensor/camera/right_fisheye/image * /apollo/sensor/camera/rear_6mm/image ### 启动camera驱动 **请先修改并确认launch文件中的参数与实际车辆相对应** ```bash # in docker bash /apollo/scripts/camera.sh # or cd /apollo && cyber_launch start modules/drivers/camera/launch/camera.launch ``` ### 启动camera + video compression驱动 **请先修改并确认launch文件中的参数与实际车辆相对应** ```bash # in docker bash /apollo/scripts/camera_and_video.sh # or cd /apollo && cyber_launch start modules/drivers/camera/launch/camera_and_video.launch ### 常见问题 1. 如果出现报错“sh: 1: v4l2-ctl: not found”,需要安装v4l2库。 ```bash sudo apt-get install v4l-utils ```
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/camera/compress_component.cc
/****************************************************************************** * Copyright 2017 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 "modules/drivers/camera/compress_component.h" #include <exception> #include <vector> #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" namespace apollo { namespace drivers { namespace camera { bool CompressComponent::Init() { if (!GetProtoConfig(&config_)) { AERROR << "Parse config file failed: " << ConfigFilePath(); return false; } AINFO << "Camera config: \n" << config_.DebugString(); try { image_pool_.reset(new CCObjectPool<CompressedImage>( config_.compress_conf().image_pool_size())); image_pool_->ConstructAll(); } catch (const std::bad_alloc& e) { AERROR << e.what(); return false; } writer_ = node_->CreateWriter<CompressedImage>( config_.compress_conf().output_channel()); return true; } bool CompressComponent::Proc(const std::shared_ptr<Image>& image) { ADEBUG << "procing compressed"; auto compressed_image = image_pool_->GetObject(); compressed_image->mutable_header()->CopyFrom(image->header()); compressed_image->set_frame_id(image->frame_id()); compressed_image->set_measurement_time(image->measurement_time()); compressed_image->set_format(image->encoding() + "; jpeg compressed bgr8"); std::vector<int> params; params.resize(3, 0); params[0] = cv::IMWRITE_JPEG_QUALITY; params[1] = 95; try { cv::Mat mat_image(image->height(), image->width(), CV_8UC3, const_cast<char*>(image->data().data()), image->step()); cv::Mat tmp_mat; cv::cvtColor(mat_image, tmp_mat, cv::COLOR_RGB2BGR); std::vector<uint8_t> compress_buffer; if (!cv::imencode(".jpg", tmp_mat, compress_buffer, params)) { AERROR << "cv::imencode (jpeg) failed on input image"; return false; } compressed_image->set_data(compress_buffer.data(), compress_buffer.size()); writer_->Write(compressed_image); } catch (std::exception& e) { AERROR << "cv::imencode (jpeg) exception :" << e.what(); return false; } return true; } } // namespace camera } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/camera/camera_component.cc
/****************************************************************************** * Copyright 2017 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 "modules/drivers/camera/camera_component.h" namespace apollo { namespace drivers { namespace camera { bool CameraComponent::Init() { camera_config_ = std::make_shared<Config>(); if (!apollo::cyber::common::GetProtoFromFile(config_file_path_, camera_config_.get())) { return false; } AINFO << "UsbCam config: " << camera_config_->DebugString(); camera_device_.reset(new UsbCam()); camera_device_->init(camera_config_); raw_image_.reset(new CameraImage); raw_image_->width = camera_config_->width(); raw_image_->height = camera_config_->height(); raw_image_->bytes_per_pixel = camera_config_->bytes_per_pixel(); device_wait_ = camera_config_->device_wait_ms(); spin_rate_ = static_cast<uint32_t>((1.0 / camera_config_->spin_rate()) * 1e6); if (camera_config_->output_type() == YUYV) { raw_image_->image_size = raw_image_->width * raw_image_->height * 2; } else if (camera_config_->output_type() == RGB) { raw_image_->image_size = raw_image_->width * raw_image_->height * 3; } if (raw_image_->image_size > MAX_IMAGE_SIZE) { AERROR << "image size is too big ,must less than " << MAX_IMAGE_SIZE << " bytes."; return false; } raw_image_->is_new = 0; // free memory in this struct desturctor raw_image_->image = reinterpret_cast<char*>(calloc(raw_image_->image_size, sizeof(char))); if (raw_image_->image == nullptr) { AERROR << "system calloc memory error, size:" << raw_image_->image_size; return false; } for (int i = 0; i < buffer_size_; ++i) { auto pb_image = std::make_shared<Image>(); pb_image->mutable_header()->set_frame_id(camera_config_->frame_id()); pb_image->set_width(raw_image_->width); pb_image->set_height(raw_image_->height); pb_image->mutable_data()->reserve(raw_image_->image_size); if (camera_config_->output_type() == YUYV) { pb_image->set_encoding("yuyv"); pb_image->set_step(2 * raw_image_->width); } else if (camera_config_->output_type() == RGB) { pb_image->set_encoding("rgb8"); pb_image->set_step(3 * raw_image_->width); } pb_image_buffer_.push_back(pb_image); } writer_ = node_->CreateWriter<Image>(camera_config_->channel_name()); async_result_ = cyber::Async(&CameraComponent::run, this); return true; } void CameraComponent::run() { running_.exchange(true); while (!cyber::IsShutdown()) { if (!camera_device_->wait_for_device()) { // sleep for next check cyber::SleepFor(std::chrono::milliseconds(device_wait_)); continue; } if (!camera_device_->poll(raw_image_)) { AERROR << "camera device poll failed"; continue; } cyber::Time image_time(raw_image_->tv_sec, 1000 * raw_image_->tv_usec); if (index_ >= buffer_size_) { index_ = 0; } auto pb_image = pb_image_buffer_.at(index_++); pb_image->mutable_header()->set_timestamp_sec( cyber::Time::Now().ToSecond()); pb_image->set_measurement_time(image_time.ToSecond()); pb_image->set_data(raw_image_->image, raw_image_->image_size); writer_->Write(pb_image); cyber::SleepFor(std::chrono::microseconds(spin_rate_)); } } CameraComponent::~CameraComponent() { if (running_.load()) { running_.exchange(false); async_result_.wait(); } } } // namespace camera } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/camera/util.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 "modules/drivers/camera/util.h" #include <cstdarg> #include <cstdint> namespace apollo { namespace drivers { namespace camera { void print_m256(__m256i a) { unsigned char snoop[32]; bool dst_align = Aligned(reinterpret_cast<void*>(snoop)); if (dst_align) Store<true>(reinterpret_cast<__m256i*>(snoop), a); else Store<false>(reinterpret_cast<__m256i*>(snoop), a); for (int i = 0; i < 32; ++i) { printf("DEBUG8 %d %u \n", i, snoop[i]); } } void print_m256_i32(const __m256i a) { unsigned int snoop[8]; bool dst_align = Aligned(reinterpret_cast<void*>(snoop)); if (dst_align) Store<true>(reinterpret_cast<__m256i*>(snoop), a); else Store<false>(reinterpret_cast<__m256i*>(snoop), a); for (int i = 0; i < 8; ++i) { printf("DEBUG32 %d %u \n", i, snoop[i]); } } void print_m256_i16(const __m256i a) { uint16_t snoop[16]; bool dst_align = Aligned(reinterpret_cast<void*>(snoop)); if (dst_align) Store<true>(reinterpret_cast<__m256i*>(snoop), a); else Store<false>(reinterpret_cast<__m256i*>(snoop), a); for (int i = 0; i < 16; ++i) { printf("DEBUG16 %d %u \n", i, snoop[i]); } } template <bool align> SIMD_INLINE void yuv_separate_avx2(uint8_t* y, __m256i* y0, __m256i* y1, __m256i* u0, __m256i* v0) { __m256i yuv_m256[4]; if (align) { yuv_m256[0] = Load<true>(reinterpret_cast<__m256i*>(y)); yuv_m256[1] = Load<true>(reinterpret_cast<__m256i*>(y) + 1); yuv_m256[2] = Load<true>(reinterpret_cast<__m256i*>(y) + 2); yuv_m256[3] = Load<true>(reinterpret_cast<__m256i*>(y) + 3); } else { yuv_m256[0] = Load<false>(reinterpret_cast<__m256i*>(y)); yuv_m256[1] = Load<false>(reinterpret_cast<__m256i*>(y) + 1); yuv_m256[2] = Load<false>(reinterpret_cast<__m256i*>(y) + 2); yuv_m256[3] = Load<false>(reinterpret_cast<__m256i*>(y) + 3); } *y0 = _mm256_or_si256(_mm256_permute4x64_epi64( _mm256_shuffle_epi8(yuv_m256[0], Y_SHUFFLE0), 0xD8), _mm256_permute4x64_epi64( _mm256_shuffle_epi8(yuv_m256[1], Y_SHUFFLE1), 0xD8)); *y1 = _mm256_or_si256(_mm256_permute4x64_epi64( _mm256_shuffle_epi8(yuv_m256[2], Y_SHUFFLE0), 0xD8), _mm256_permute4x64_epi64( _mm256_shuffle_epi8(yuv_m256[3], Y_SHUFFLE1), 0xD8)); *u0 = _mm256_permutevar8x32_epi32( _mm256_or_si256( _mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[0], U_SHUFFLE0), _mm256_shuffle_epi8(yuv_m256[1], U_SHUFFLE1)), _mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[2], U_SHUFFLE2), _mm256_shuffle_epi8(yuv_m256[3], U_SHUFFLE3))), U_SHUFFLE4); *v0 = _mm256_permutevar8x32_epi32( _mm256_or_si256( _mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[0], V_SHUFFLE0), _mm256_shuffle_epi8(yuv_m256[1], V_SHUFFLE1)), _mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[2], V_SHUFFLE2), _mm256_shuffle_epi8(yuv_m256[3], V_SHUFFLE3))), U_SHUFFLE4); } template <bool align> void yuv2rgb_avx2(__m256i y0, __m256i u0, __m256i v0, uint8_t* rgb) { __m256i r0 = YuvToRed(y0, v0); __m256i g0 = YuvToGreen(y0, u0, v0); __m256i b0 = YuvToBlue(y0, u0); Store<align>(reinterpret_cast<__m256i*>(rgb) + 0, InterleaveBgr<0>(r0, g0, b0)); Store<align>(reinterpret_cast<__m256i*>(rgb) + 1, InterleaveBgr<1>(r0, g0, b0)); Store<align>(reinterpret_cast<__m256i*>(rgb) + 2, InterleaveBgr<2>(r0, g0, b0)); } template <bool align> void yuv2rgb_avx2(uint8_t* yuv, uint8_t* rgb) { __m256i y0, y1, u0, v0; yuv_separate_avx2<align>(yuv, &y0, &y1, &u0, &v0); __m256i u0_u0 = _mm256_permute4x64_epi64(u0, 0xD8); __m256i v0_v0 = _mm256_permute4x64_epi64(v0, 0xD8); yuv2rgb_avx2<align>(y0, _mm256_unpacklo_epi8(u0_u0, u0_u0), _mm256_unpacklo_epi8(v0_v0, v0_v0), rgb); yuv2rgb_avx2<align>(y1, _mm256_unpackhi_epi8(u0_u0, u0_u0), _mm256_unpackhi_epi8(v0_v0, v0_v0), rgb + 3 * sizeof(__m256i)); } void yuyv2rgb_avx(unsigned char* YUV, unsigned char* RGB, int NumPixels) { assert(NumPixels == (1920 * 1080)); bool align = Aligned(YUV) & Aligned(RGB); uint8_t* yuv_offset = YUV; uint8_t* rgb_offset = RGB; if (align) { for (int i = 0; i < NumPixels; i = i + static_cast<int>(2 * sizeof(__m256i)), yuv_offset += 4 * static_cast<int>(sizeof(__m256i)), rgb_offset += 6 * static_cast<int>(sizeof(__m256i))) { yuv2rgb_avx2<true>(yuv_offset, rgb_offset); } } else { for (int i = 0; i < NumPixels; i = i + static_cast<int>(2 * sizeof(__m256i)), yuv_offset += 4 * static_cast<int>(sizeof(__m256i)), rgb_offset += 6 * static_cast<int>(sizeof(__m256i))) { yuv2rgb_avx2<false>(yuv_offset, rgb_offset); } } } } // namespace camera } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/camera/util.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. *****************************************************************************/ #pragma once #include <fcntl.h> /* low-level i/o */ #include <malloc.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <cassert> #include <cerrno> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> #include <immintrin.h> #include <x86intrin.h> namespace apollo { namespace drivers { namespace camera { void yuyv2rgb_avx(unsigned char *YUV, unsigned char *RGB, int NumPixels); #define SIMD_INLINE inline __attribute__((always_inline)) void print_m256(const __m256i a); void print_m256_i32(const __m256i a); void print_m256_i16(const __m256i a); template <class T> SIMD_INLINE char GetChar(T value, size_t index) { return (reinterpret_cast<char *>(&value))[index]; } #define SIMD_CHAR_AS_LONGLONG(a) (((int64_t)a) & 0xFF) #define SIMD_SHORT_AS_LONGLONG(a) (((int64_t)a) & 0xFFFF) #define SIMD_INT_AS_LONGLONG(a) (((int64_t)a) & 0xFFFFFFFF) #define SIMD_LL_SET1_EPI8(a) \ SIMD_CHAR_AS_LONGLONG(a) | (SIMD_CHAR_AS_LONGLONG(a) << 8) | \ (SIMD_CHAR_AS_LONGLONG(a) << 16) | (SIMD_CHAR_AS_LONGLONG(a) << 24) | \ (SIMD_CHAR_AS_LONGLONG(a) << 32) | (SIMD_CHAR_AS_LONGLONG(a) << 40) | \ (SIMD_CHAR_AS_LONGLONG(a) << 48) | (SIMD_CHAR_AS_LONGLONG(a) << 56) #define SIMD_LL_SET2_EPI8(a, b) \ SIMD_CHAR_AS_LONGLONG(a) | (SIMD_CHAR_AS_LONGLONG(b) << 8) | \ (SIMD_CHAR_AS_LONGLONG(a) << 16) | (SIMD_CHAR_AS_LONGLONG(b) << 24) | \ (SIMD_CHAR_AS_LONGLONG(a) << 32) | (SIMD_CHAR_AS_LONGLONG(b) << 40) | \ (SIMD_CHAR_AS_LONGLONG(a) << 48) | (SIMD_CHAR_AS_LONGLONG(b) << 56) #define SIMD_LL_SETR_EPI8(a, b, c, d, e, f, g, h) \ SIMD_CHAR_AS_LONGLONG(a) | (SIMD_CHAR_AS_LONGLONG(b) << 8) | \ (SIMD_CHAR_AS_LONGLONG(c) << 16) | (SIMD_CHAR_AS_LONGLONG(d) << 24) | \ (SIMD_CHAR_AS_LONGLONG(e) << 32) | (SIMD_CHAR_AS_LONGLONG(f) << 40) | \ (SIMD_CHAR_AS_LONGLONG(g) << 48) | (SIMD_CHAR_AS_LONGLONG(h) << 56) #define SIMD_LL_SET1_EPI16(a) \ SIMD_SHORT_AS_LONGLONG(a) | (SIMD_SHORT_AS_LONGLONG(a) << 16) | \ (SIMD_SHORT_AS_LONGLONG(a) << 32) | (SIMD_SHORT_AS_LONGLONG(a) << 48) #define SIMD_LL_SET2_EPI16(a, b) \ SIMD_SHORT_AS_LONGLONG(a) | (SIMD_SHORT_AS_LONGLONG(b) << 16) | \ (SIMD_SHORT_AS_LONGLONG(a) << 32) | (SIMD_SHORT_AS_LONGLONG(b) << 48) #define SIMD_LL_SETR_EPI16(a, b, c, d) \ SIMD_SHORT_AS_LONGLONG(a) | (SIMD_SHORT_AS_LONGLONG(b) << 16) | \ (SIMD_SHORT_AS_LONGLONG(c) << 32) | (SIMD_SHORT_AS_LONGLONG(d) << 48) #define SIMD_LL_SET1_EPI32(a) \ SIMD_INT_AS_LONGLONG(a) | (SIMD_INT_AS_LONGLONG(a) << 32) #define SIMD_LL_SET2_EPI32(a, b) \ SIMD_INT_AS_LONGLONG(a) | (SIMD_INT_AS_LONGLONG(b) << 32) #define SIMD_MM256_SET1_EPI8(a) \ { \ SIMD_LL_SET1_EPI8(a) \ , SIMD_LL_SET1_EPI8(a), SIMD_LL_SET1_EPI8(a), SIMD_LL_SET1_EPI8(a) \ } #define SIMD_MM256_SET2_EPI8(a0, a1) \ { \ SIMD_LL_SET2_EPI8(a0, a1) \ , SIMD_LL_SET2_EPI8(a0, a1), SIMD_LL_SET2_EPI8(a0, a1), \ SIMD_LL_SET2_EPI8(a0, a1) \ } #define SIMD_MM256_SETR_EPI8(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, aa, ab, \ ac, ad, ae, af, b0, b1, b2, b3, b4, b5, b6, b7, \ b8, b9, ba, bb, bc, bd, be, bf) \ { \ SIMD_LL_SETR_EPI8(a0, a1, a2, a3, a4, a5, a6, a7) \ , SIMD_LL_SETR_EPI8(a8, a9, aa, ab, ac, ad, ae, af), \ SIMD_LL_SETR_EPI8(b0, b1, b2, b3, b4, b5, b6, b7), \ SIMD_LL_SETR_EPI8(b8, b9, ba, bb, bc, bd, be, bf) \ } #define SIMD_MM256_SET1_EPI16(a) \ { \ SIMD_LL_SET1_EPI16(a) \ , SIMD_LL_SET1_EPI16(a), SIMD_LL_SET1_EPI16(a), SIMD_LL_SET1_EPI16(a) \ } #define SIMD_MM256_SET2_EPI16(a0, a1) \ { \ SIMD_LL_SET2_EPI16(a0, a1) \ , SIMD_LL_SET2_EPI16(a0, a1), SIMD_LL_SET2_EPI16(a0, a1), \ SIMD_LL_SET2_EPI16(a0, a1) \ } #define SIMD_MM256_SETR_EPI16(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, aa, ab, \ ac, ad, ae, af) \ { \ SIMD_LL_SETR_EPI16(a0, a1, a2, a3) \ , SIMD_LL_SETR_EPI16(a4, a5, a6, a7), SIMD_LL_SETR_EPI16(a8, a9, aa, ab), \ SIMD_LL_SETR_EPI16(ac, ad, ae, af) \ } #define SIMD_MM256_SET1_EPI32(a) \ { \ SIMD_LL_SET1_EPI32(a) \ , SIMD_LL_SET1_EPI32(a), SIMD_LL_SET1_EPI32(a), SIMD_LL_SET1_EPI32(a) \ } #define SIMD_MM256_SET2_EPI32(a0, a1) \ { \ SIMD_LL_SET2_EPI32(a0, a1) \ , SIMD_LL_SET2_EPI32(a0, a1), SIMD_LL_SET2_EPI32(a0, a1), \ SIMD_LL_SET2_EPI32(a0, a1) \ } #define SIMD_MM256_SETR_EPI32(a0, a1, a2, a3, a4, a5, a6, a7) \ { \ SIMD_LL_SET2_EPI32(a0, a1) \ , SIMD_LL_SET2_EPI32(a2, a3), SIMD_LL_SET2_EPI32(a4, a5), \ SIMD_LL_SET2_EPI32(a6, a7) \ } const size_t A = sizeof(__m256i); const size_t DA = 2 * A; const size_t QA = 4 * A; const size_t OA = 8 * A; const size_t HA = A / 2; const __m256i K_ZERO = SIMD_MM256_SET1_EPI8(0); const __m256i K_INV_ZERO = SIMD_MM256_SET1_EPI8(0xFF); const __m256i K8_01 = SIMD_MM256_SET1_EPI8(0x01); const __m256i K8_02 = SIMD_MM256_SET1_EPI8(0x02); const __m256i K8_04 = SIMD_MM256_SET1_EPI8(0x04); const __m256i K8_08 = SIMD_MM256_SET1_EPI8(0x08); const __m256i K8_10 = SIMD_MM256_SET1_EPI8(0x10); const __m256i K8_20 = SIMD_MM256_SET1_EPI8(0x20); const __m256i K8_40 = SIMD_MM256_SET1_EPI8(0x40); const __m256i K8_80 = SIMD_MM256_SET1_EPI8(0x80); const __m256i K8_01_FF = SIMD_MM256_SET2_EPI8(0x01, 0xFF); const __m256i K16_0001 = SIMD_MM256_SET1_EPI16(0x0001); const __m256i K16_0002 = SIMD_MM256_SET1_EPI16(0x0002); const __m256i K16_0003 = SIMD_MM256_SET1_EPI16(0x0003); const __m256i K16_0004 = SIMD_MM256_SET1_EPI16(0x0004); const __m256i K16_0005 = SIMD_MM256_SET1_EPI16(0x0005); const __m256i K16_0006 = SIMD_MM256_SET1_EPI16(0x0006); const __m256i K16_0008 = SIMD_MM256_SET1_EPI16(0x0008); const __m256i K16_0010 = SIMD_MM256_SET1_EPI16(0x0010); const __m256i K16_0018 = SIMD_MM256_SET1_EPI16(0x0018); const __m256i K16_0020 = SIMD_MM256_SET1_EPI16(0x0020); const __m256i K16_0080 = SIMD_MM256_SET1_EPI16(0x0080); const __m256i K16_00FF = SIMD_MM256_SET1_EPI16(0x00FF); const __m256i K16_FF00 = SIMD_MM256_SET1_EPI16(0xFF00); const __m256i K32_00000001 = SIMD_MM256_SET1_EPI32(0x00000001); const __m256i K32_00000002 = SIMD_MM256_SET1_EPI32(0x00000002); const __m256i K32_00000004 = SIMD_MM256_SET1_EPI32(0x00000004); const __m256i K32_00000008 = SIMD_MM256_SET1_EPI32(0x00000008); const __m256i K32_000000FF = SIMD_MM256_SET1_EPI32(0x000000FF); const __m256i K32_0000FFFF = SIMD_MM256_SET1_EPI32(0x0000FFFF); const __m256i K32_00010000 = SIMD_MM256_SET1_EPI32(0x00010000); const __m256i K32_01000000 = SIMD_MM256_SET1_EPI32(0x01000000); const __m256i K32_FFFFFF00 = SIMD_MM256_SET1_EPI32(0xFFFFFF00); const __m256i K8_SHUFFLE_BGR0_TO_BLUE = SIMD_MM256_SETR_EPI8( 0x0, 0x3, 0x6, 0x9, 0xC, 0xF, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x2, 0x5, 0x8, 0xB, 0xE, -1, -1, -1, -1, -1); const __m256i K8_SHUFFLE_BGR1_TO_BLUE = SIMD_MM256_SETR_EPI8( -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x1, 0x4, 0x7, 0xA, 0xD, 0x0, 0x3, 0x6, 0x9, 0xC, 0xF, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1); const __m256i K8_SHUFFLE_BGR2_TO_BLUE = SIMD_MM256_SETR_EPI8( -1, -1, -1, -1, -1, -1, 0x2, 0x5, 0x8, 0xB, 0xE, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x1, 0x4, 0x7, 0xA, 0xD); const __m256i Y_SHUFFLE0 = SIMD_MM256_SETR_EPI8( 0x0, 0x2, 0x4, 0x6, 0x8, 0xa, 0xc, 0xe, -1, -1, -1, -1, -1, -1, -1, -1, 0x0, 0x2, 0x4, 0x6, 0x8, 0xa, 0xc, 0xe, -1, -1, -1, -1, -1, -1, -1, -1); const __m256i Y_SHUFFLE1 = SIMD_MM256_SETR_EPI8( -1, -1, -1, -1, -1, -1, -1, -1, 0x0, 0x2, 0x4, 0x6, 0x8, 0xa, 0xc, 0xe, -1, -1, -1, -1, -1, -1, -1, -1, 0x0, 0x2, 0x4, 0x6, 0x8, 0xa, 0xc, 0xe); const __m256i U_SHUFFLE0 = SIMD_MM256_SETR_EPI8( 0x1, 0x5, 0x9, 0xd, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x1, 0x5, 0x9, 0xd, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1); const __m256i U_SHUFFLE1 = SIMD_MM256_SETR_EPI8( -1, -1, -1, -1, 0x1, 0x5, 0x9, 0xd, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x1, 0x5, 0x9, 0xd, -1, -1, -1, -1, -1, -1, -1, -1); const __m256i U_SHUFFLE2 = SIMD_MM256_SETR_EPI8( -1, -1, -1, -1, -1, -1, -1, -1, 0x1, 0x5, 0x9, 0xd, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x1, 0x5, 0x9, 0xd, -1, -1, -1, -1); const __m256i U_SHUFFLE3 = SIMD_MM256_SETR_EPI8( -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x1, 0x5, 0x9, 0xd, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x1, 0x5, 0x9, 0xd); const __m256i U_SHUFFLE4 = SIMD_MM256_SETR_EPI8(0x0, 0x0, 0x0, 0x0, 0x4, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x5, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x6, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x7, 0x0, 0x0, 0x0); const __m256i V_SHUFFLE0 = SIMD_MM256_SETR_EPI8( 0x3, 0x7, 0xb, 0xf, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x3, 0x7, 0xb, 0xf, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1); const __m256i V_SHUFFLE1 = SIMD_MM256_SETR_EPI8( -1, -1, -1, -1, 0x3, 0x7, 0xb, 0xf, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x3, 0x7, 0xb, 0xf, -1, -1, -1, -1, -1, -1, -1, -1); const __m256i V_SHUFFLE2 = SIMD_MM256_SETR_EPI8( -1, -1, -1, -1, -1, -1, -1, -1, 0x3, 0x7, 0xb, 0xf, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x3, 0x7, 0xb, 0xf, -1, -1, -1, -1); const __m256i V_SHUFFLE3 = SIMD_MM256_SETR_EPI8( -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x3, 0x7, 0xb, 0xf, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x3, 0x7, 0xb, 0xf); const __m256i K8_SHUFFLE_PERMUTED_BLUE_TO_BGR0 = SIMD_MM256_SETR_EPI8( 0x0, -1, -1, 0x1, -1, -1, 0x2, -1, -1, 0x3, -1, -1, 0x4, -1, -1, 0x5, -1, -1, 0x6, -1, -1, 0x7, -1, -1, 0x8, -1, -1, 0x9, -1, -1, 0xA, -1); const __m256i K8_SHUFFLE_PERMUTED_BLUE_TO_BGR1 = SIMD_MM256_SETR_EPI8( -1, 0x3, -1, -1, 0x4, -1, -1, 0x5, -1, -1, 0x6, -1, -1, 0x7, -1, -1, 0x8, -1, -1, 0x9, -1, -1, 0xA, -1, -1, 0xB, -1, -1, 0xC, -1, -1, 0xD); const __m256i K8_SHUFFLE_PERMUTED_BLUE_TO_BGR2 = SIMD_MM256_SETR_EPI8( -1, -1, 0x6, -1, -1, 0x7, -1, -1, 0x8, -1, -1, 0x9, -1, -1, 0xA, -1, -1, 0xB, -1, -1, 0xC, -1, -1, 0xD, -1, -1, 0xE, -1, -1, 0xF, -1, -1); const __m256i K8_SHUFFLE_PERMUTED_GREEN_TO_BGR0 = SIMD_MM256_SETR_EPI8( -1, 0x0, -1, -1, 0x1, -1, -1, 0x2, -1, -1, 0x3, -1, -1, 0x4, -1, -1, 0x5, -1, -1, 0x6, -1, -1, 0x7, -1, -1, 0x8, -1, -1, 0x9, -1, -1, 0xA); const __m256i K8_SHUFFLE_PERMUTED_GREEN_TO_BGR1 = SIMD_MM256_SETR_EPI8( -1, -1, 0x3, -1, -1, 0x4, -1, -1, 0x5, -1, -1, 0x6, -1, -1, 0x7, -1, -1, 0x8, -1, -1, 0x9, -1, -1, 0xA, -1, -1, 0xB, -1, -1, 0xC, -1, -1); const __m256i K8_SHUFFLE_PERMUTED_GREEN_TO_BGR2 = SIMD_MM256_SETR_EPI8( 0x5, -1, -1, 0x6, -1, -1, 0x7, -1, -1, 0x8, -1, -1, 0x9, -1, -1, 0xA, -1, -1, 0xB, -1, -1, 0xC, -1, -1, 0xD, -1, -1, 0xE, -1, -1, 0xF, -1); const __m256i K8_SHUFFLE_PERMUTED_RED_TO_BGR0 = SIMD_MM256_SETR_EPI8( -1, -1, 0x0, -1, -1, 0x1, -1, -1, 0x2, -1, -1, 0x3, -1, -1, 0x4, -1, -1, 0x5, -1, -1, 0x6, -1, -1, 0x7, -1, -1, 0x8, -1, -1, 0x9, -1, -1); const __m256i K8_SHUFFLE_PERMUTED_RED_TO_BGR1 = SIMD_MM256_SETR_EPI8( 0x2, -1, -1, 0x3, -1, -1, 0x4, -1, -1, 0x5, -1, -1, 0x6, -1, -1, 0x7, -1, -1, 0x8, -1, -1, 0x9, -1, -1, 0xA, -1, -1, 0xB, -1, -1, 0xC, -1); const __m256i K8_SHUFFLE_PERMUTED_RED_TO_BGR2 = SIMD_MM256_SETR_EPI8( -1, 0x5, -1, -1, 0x6, -1, -1, 0x7, -1, -1, 0x8, -1, -1, 0x9, -1, -1, 0xA, -1, -1, 0xB, -1, -1, 0xC, -1, -1, 0xD, -1, -1, 0xE, -1, -1, 0xF); const __m256i K8_SHUFFLE_BGR0_TO_GREEN = SIMD_MM256_SETR_EPI8( 0x1, 0x4, 0x7, 0xA, 0xD, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x0, 0x3, 0x6, 0x9, 0xC, 0xF, -1, -1, -1, -1, -1); const __m256i K8_SHUFFLE_BGR1_TO_GREEN = SIMD_MM256_SETR_EPI8( -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x2, 0x5, 0x8, 0xB, 0xE, 0x1, 0x4, 0x7, 0xA, 0xD, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1); const __m256i K8_SHUFFLE_BGR2_TO_GREEN = SIMD_MM256_SETR_EPI8( -1, -1, -1, -1, -1, 0x0, 0x3, 0x6, 0x9, 0xC, 0xF, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x2, 0x5, 0x8, 0xB, 0xE); const __m256i K8_SHUFFLE_BGR0_TO_RED = SIMD_MM256_SETR_EPI8( 0x2, 0x5, 0x8, 0xB, 0xE, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x1, 0x4, 0x7, 0xA, 0xD, -1, -1, -1, -1, -1, -1); const __m256i K8_SHUFFLE_BGR1_TO_RED = SIMD_MM256_SETR_EPI8( -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x0, 0x3, 0x6, 0x9, 0xC, 0xF, 0x2, 0x5, 0x8, 0xB, 0xE, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1); const __m256i K8_SHUFFLE_BGR2_TO_RED = SIMD_MM256_SETR_EPI8( -1, -1, -1, -1, -1, 0x1, 0x4, 0x7, 0xA, 0xD, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x0, 0x3, 0x6, 0x9, 0xC, 0xF); const __m256i K16_Y_ADJUST = SIMD_MM256_SET1_EPI16(0); const __m256i K16_UV_ADJUST = SIMD_MM256_SET1_EPI16(128); const int Y_ADJUST = 0; const int UV_ADJUST = 128; const int YUV_TO_BGR_AVERAGING_SHIFT = 13; const int YUV_TO_BGR_ROUND_TERM = 0; // 1 << (YUV_TO_BGR_AVERAGING_SHIFT); const int Y_TO_RGB_WEIGHT = static_cast<int>((((1 << YUV_TO_BGR_AVERAGING_SHIFT)))); const int U_TO_BLUE_WEIGHT = static_cast<int>((2.041 * (1 << YUV_TO_BGR_AVERAGING_SHIFT))); const int U_TO_GREEN_WEIGHT = -static_cast<int>((0.3455 * (1 << YUV_TO_BGR_AVERAGING_SHIFT))); const int V_TO_GREEN_WEIGHT = -static_cast<int>((0.7169 * (1 << YUV_TO_BGR_AVERAGING_SHIFT))); const int V_TO_RED_WEIGHT = static_cast<int>((1.4065 * (1 << YUV_TO_BGR_AVERAGING_SHIFT))); const __m256i K16_YRGB_RT = SIMD_MM256_SET2_EPI16(Y_TO_RGB_WEIGHT, YUV_TO_BGR_ROUND_TERM); const __m256i K16_VR_0 = SIMD_MM256_SET2_EPI16(V_TO_RED_WEIGHT, 0); const __m256i K16_UG_VG = SIMD_MM256_SET2_EPI16(U_TO_GREEN_WEIGHT, V_TO_GREEN_WEIGHT); const __m256i K16_UB_0 = SIMD_MM256_SET2_EPI16(U_TO_BLUE_WEIGHT, 0); template <bool align> SIMD_INLINE __m256i Load(const __m256i *p); template <> SIMD_INLINE __m256i Load<false>(const __m256i *p) { return _mm256_loadu_si256(p); } template <> SIMD_INLINE __m256i Load<true>(const __m256i *p) { return _mm256_load_si256(p); } SIMD_INLINE void *AlignLo(const void *ptr, size_t align) { return reinterpret_cast<void *>(((size_t)ptr) & ~(align - 1)); } SIMD_INLINE bool Aligned(const void *ptr, size_t align = sizeof(__m256)) { return ptr == AlignLo(ptr, align); } template <bool align> SIMD_INLINE void Store(__m256i *p, __m256i a); template <> SIMD_INLINE void Store<false>(__m256i *p, __m256i a) { _mm256_storeu_si256(p, a); } template <> SIMD_INLINE void Store<true>(__m256i *p, __m256i a) { _mm256_store_si256(p, a); } SIMD_INLINE __m256i SaturateI16ToU8(__m256i value) { return _mm256_min_epi16(K16_00FF, _mm256_max_epi16(value, K_ZERO)); } SIMD_INLINE __m256i AdjustY16(__m256i y16) { return _mm256_subs_epi16(y16, K16_Y_ADJUST); } SIMD_INLINE __m256i AdjustUV16(__m256i uv16) { return _mm256_subs_epi16(uv16, K16_UV_ADJUST); } SIMD_INLINE __m256i AdjustedYuvToRed32(__m256i y16_1, __m256i v16_0) { // print_m256_i16(y16_1); // print_m256_i16(v16_0); // print_m256_i32(_mm256_madd_epi16(y16_1, K16_YRGB_RT)); // print_m256_i32(_mm256_madd_epi16(v16_0, K16_VR_0)); return _mm256_srai_epi32( _mm256_add_epi32(_mm256_madd_epi16(y16_1, K16_YRGB_RT), _mm256_madd_epi16(v16_0, K16_VR_0)), YUV_TO_BGR_AVERAGING_SHIFT); } SIMD_INLINE __m256i AdjustedYuvToRed16(__m256i y16, __m256i v16) { // print_m256_i32(AdjustedYuvToRed32(_mm256_unpacklo_epi16(y16, K16_0001), // _mm256_unpacklo_epi16(v16, K_ZERO))); // print_m256_i16(_mm256_unpacklo_epi16(y16, K16_0001)); return SaturateI16ToU8(_mm256_packs_epi32( AdjustedYuvToRed32(_mm256_unpacklo_epi16(y16, K16_0001), _mm256_unpacklo_epi16(v16, K_ZERO)), AdjustedYuvToRed32(_mm256_unpackhi_epi16(y16, K16_0001), _mm256_unpackhi_epi16(v16, K_ZERO)))); } SIMD_INLINE __m256i AdjustedYuvToGreen32(__m256i y16_1, __m256i u16_v16) { return _mm256_srai_epi32( _mm256_add_epi32(_mm256_madd_epi16(y16_1, K16_YRGB_RT), _mm256_madd_epi16(u16_v16, K16_UG_VG)), YUV_TO_BGR_AVERAGING_SHIFT); } SIMD_INLINE __m256i AdjustedYuvToGreen16(__m256i y16, __m256i u16, __m256i v16) { return SaturateI16ToU8(_mm256_packs_epi32( AdjustedYuvToGreen32(_mm256_unpacklo_epi16(y16, K16_0001), _mm256_unpacklo_epi16(u16, v16)), AdjustedYuvToGreen32(_mm256_unpackhi_epi16(y16, K16_0001), _mm256_unpackhi_epi16(u16, v16)))); } SIMD_INLINE __m256i AdjustedYuvToBlue32(__m256i y16_1, __m256i u16_0) { return _mm256_srai_epi32( _mm256_add_epi32(_mm256_madd_epi16(y16_1, K16_YRGB_RT), _mm256_madd_epi16(u16_0, K16_UB_0)), YUV_TO_BGR_AVERAGING_SHIFT); } SIMD_INLINE __m256i AdjustedYuvToBlue16(__m256i y16, __m256i u16) { return SaturateI16ToU8(_mm256_packs_epi32( AdjustedYuvToBlue32(_mm256_unpacklo_epi16(y16, K16_0001), _mm256_unpacklo_epi16(u16, K_ZERO)), AdjustedYuvToBlue32(_mm256_unpackhi_epi16(y16, K16_0001), _mm256_unpackhi_epi16(u16, K_ZERO)))); } SIMD_INLINE __m256i YuvToRed(__m256i y, __m256i v) { __m256i lo = AdjustedYuvToRed16(_mm256_unpacklo_epi8(y, K_ZERO), AdjustUV16(_mm256_unpacklo_epi8(v, K_ZERO))); __m256i hi = AdjustedYuvToRed16((_mm256_unpackhi_epi8(y, K_ZERO)), AdjustUV16(_mm256_unpackhi_epi8(v, K_ZERO))); // print_m256_i16(lo); // print_m256_i16(hi); return _mm256_packus_epi16(lo, hi); } SIMD_INLINE __m256i YuvToGreen(__m256i y, __m256i u, __m256i v) { __m256i lo = AdjustedYuvToGreen16((_mm256_unpacklo_epi8(y, K_ZERO)), AdjustUV16(_mm256_unpacklo_epi8(u, K_ZERO)), AdjustUV16(_mm256_unpacklo_epi8(v, K_ZERO))); __m256i hi = AdjustedYuvToGreen16((_mm256_unpackhi_epi8(y, K_ZERO)), AdjustUV16(_mm256_unpackhi_epi8(u, K_ZERO)), AdjustUV16(_mm256_unpackhi_epi8(v, K_ZERO))); return _mm256_packus_epi16(lo, hi); } SIMD_INLINE __m256i YuvToBlue(__m256i y, __m256i u) { __m256i lo = AdjustedYuvToBlue16((_mm256_unpacklo_epi8(y, K_ZERO)), AdjustUV16(_mm256_unpacklo_epi8(u, K_ZERO))); __m256i hi = AdjustedYuvToBlue16((_mm256_unpackhi_epi8(y, K_ZERO)), AdjustUV16(_mm256_unpackhi_epi8(u, K_ZERO))); return _mm256_packus_epi16(lo, hi); } template <int index> __m256i InterleaveBgr(__m256i blue, __m256i green, __m256i red); template <> SIMD_INLINE __m256i InterleaveBgr<0>(__m256i blue, __m256i green, __m256i red) { return _mm256_or_si256( _mm256_shuffle_epi8(_mm256_permute4x64_epi64(blue, 0x44), K8_SHUFFLE_PERMUTED_BLUE_TO_BGR0), _mm256_or_si256(_mm256_shuffle_epi8(_mm256_permute4x64_epi64(green, 0x44), K8_SHUFFLE_PERMUTED_GREEN_TO_BGR0), _mm256_shuffle_epi8(_mm256_permute4x64_epi64(red, 0x44), K8_SHUFFLE_PERMUTED_RED_TO_BGR0))); } template <> SIMD_INLINE __m256i InterleaveBgr<1>(__m256i blue, __m256i green, __m256i red) { return _mm256_or_si256( _mm256_shuffle_epi8(_mm256_permute4x64_epi64(blue, 0x99), K8_SHUFFLE_PERMUTED_BLUE_TO_BGR1), _mm256_or_si256(_mm256_shuffle_epi8(_mm256_permute4x64_epi64(green, 0x99), K8_SHUFFLE_PERMUTED_GREEN_TO_BGR1), _mm256_shuffle_epi8(_mm256_permute4x64_epi64(red, 0x99), K8_SHUFFLE_PERMUTED_RED_TO_BGR1))); } template <> SIMD_INLINE __m256i InterleaveBgr<2>(__m256i blue, __m256i green, __m256i red) { return _mm256_or_si256( _mm256_shuffle_epi8(_mm256_permute4x64_epi64(blue, 0xEE), K8_SHUFFLE_PERMUTED_BLUE_TO_BGR2), _mm256_or_si256(_mm256_shuffle_epi8(_mm256_permute4x64_epi64(green, 0xEE), K8_SHUFFLE_PERMUTED_GREEN_TO_BGR2), _mm256_shuffle_epi8(_mm256_permute4x64_epi64(red, 0xEE), K8_SHUFFLE_PERMUTED_RED_TO_BGR2))); } SIMD_INLINE __m256i BgrToBlue(__m256i bgr[3]) { __m256i b0 = _mm256_shuffle_epi8(bgr[0], K8_SHUFFLE_BGR0_TO_BLUE); __m256i b2 = _mm256_shuffle_epi8(bgr[2], K8_SHUFFLE_BGR2_TO_BLUE); return _mm256_or_si256( _mm256_permute2x128_si256(b0, b2, 0x20), _mm256_or_si256(_mm256_shuffle_epi8(bgr[1], K8_SHUFFLE_BGR1_TO_BLUE), _mm256_permute2x128_si256(b0, b2, 0x31))); } SIMD_INLINE __m256i BgrToGreen(__m256i bgr[3]) { __m256i g0 = _mm256_shuffle_epi8(bgr[0], K8_SHUFFLE_BGR0_TO_GREEN); __m256i g2 = _mm256_shuffle_epi8(bgr[2], K8_SHUFFLE_BGR2_TO_GREEN); return _mm256_or_si256( _mm256_permute2x128_si256(g0, g2, 0x20), _mm256_or_si256(_mm256_shuffle_epi8(bgr[1], K8_SHUFFLE_BGR1_TO_GREEN), _mm256_permute2x128_si256(g0, g2, 0x31))); } SIMD_INLINE __m256i BgrToRed(__m256i bgr[3]) { __m256i r0 = _mm256_shuffle_epi8(bgr[0], K8_SHUFFLE_BGR0_TO_RED); __m256i r2 = _mm256_shuffle_epi8(bgr[2], K8_SHUFFLE_BGR2_TO_RED); return _mm256_or_si256( _mm256_permute2x128_si256(r0, r2, 0x20), _mm256_or_si256(_mm256_shuffle_epi8(bgr[1], K8_SHUFFLE_BGR1_TO_RED), _mm256_permute2x128_si256(r0, r2, 0x31))); } template <bool align> SIMD_INLINE __m256i LoadPermuted(const __m256i *p) { return _mm256_permute4x64_epi64(Load<align>(p), 0xD8); } } // namespace camera } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/camera/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") load("//tools/install:install.bzl", "install") load("//tools:cpplint.bzl", "cpplint") load("//tools/platform:build_defs.bzl", "if_x86_64") package(default_visibility = ["//visibility:public"]) CAMERA_COPTS = ['-DMODULE_NAME=\\"camera\\"'] cc_binary( name = "libcamera_component.so", linkopts = [ "-latomic", ], linkshared = True, linkstatic = True, deps = [ ":camera_component_lib", ":compress_component_lib", "@ffmpeg//:avcodec", "@ffmpeg//:avformat", "@ffmpeg//:swscale", ], ) filegroup( name = "runtime_data", srcs = glob([ "conf/*.txt", "dag/*.dag", "launch/*.launch", ]), ) install( name = "install", data_dest = "drivers/addition_data/camera", library_dest = "drivers/lib/camera", data = [ ":runtime_data", ], targets = [ ":libcamera_component.so", ], ) cc_library( name = "camera_component_lib", srcs = ["camera_component.cc"], hdrs = ["camera_component.h"], alwayslink = True, copts = CAMERA_COPTS, deps = [ ":camera", "//cyber", "//modules/common_msgs/basic_msgs:error_code_cc_proto", "//modules/common_msgs/basic_msgs:header_cc_proto", "//modules/common_msgs/sensor_msgs:sensor_image_cc_proto", ], ) cc_library( name = "compress_component_lib", srcs = ["compress_component.cc"], hdrs = ["compress_component.h"], copts = CAMERA_COPTS, alwayslink = True, deps = [ "//cyber", "//modules/common_msgs/basic_msgs:error_code_cc_proto", "//modules/common_msgs/basic_msgs:header_cc_proto", "//modules/drivers/camera/proto:config_cc_proto", "//modules/common_msgs/sensor_msgs:sensor_image_cc_proto", "@opencv//:core", "@opencv//:highgui", "@opencv//:imgcodecs", "@opencv//:imgproc", ], ) cc_library( name = "camera", srcs = select( { "@platforms//cpu:x86_64": [ "usb_cam.cc", "util.cc", ], "@platforms//cpu:aarch64": [ "usb_cam.cc", ], }, no_match_error = "Please Build with an ARM or Linux x86_64 platform", ), hdrs = select( { "@platforms//cpu:x86_64": [ "usb_cam.h", "util.h", ], "@platforms//cpu:aarch64": [ "usb_cam.h", ], }, no_match_error = "Please Build with an ARM or Linux x86_64 platform", ), deps = [ "//cyber", "//modules/drivers/camera/proto:config_cc_proto", "@ffmpeg//:avcodec", ] + if_x86_64( ["@adv_plat"], ), ) cpplint()
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/camera/CHANGELOG.rst
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Changelog for package usb_cam ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 0.3.4 (2015-08-18) ------------------ * Installs launch files * Merge pull request #37 from tzutalin/develop Add a launch file for easy test * Add a launch file for easy test * Contributors: Russell Toris, tzu.ta.lin 0.3.3 (2015-05-14) ------------------ * Merge pull request #36 from jsarrett/develop add gain parameter * add gain parameter * Contributors: James Sarrett, Russell Toris 0.3.2 (2015-03-24) ------------------ * Merge pull request #34 from eliasm/develop fixed check whether calibration file exists * fixed check whether calibration file exists * Contributors: Elias Mueggler, Russell Toris 0.3.1 (2015-02-20) ------------------ * Merge pull request #32 from kmhallen/mono8 Publish YUVMONO10 images as mono8 instead of rgb8 * Publish YUVMONO10 images as mono8 instead of rgb8 * Contributors: Kevin Hallenbeck, Russell Toris 0.3.0 (2015-01-26) ------------------ * Merge pull request #30 from mitchellwills/develop Removed global state from usb_cam by encapsulating it inside an object * Made device name a std::string instead of const char* * Added usb_cam namespace * Added underscore sufix to class fields * Removed camera_ prefix from methods * Moved methods to parse pixel_format and io_method from string to UsbCam * Moved camera_image_t struct to be private in UsbCam * Cleaned up parameter assignment * Made set_v4l_parameters a non-static function * Moved set_v4l_parameters to UsbCam object * Removed global state from usb_cam by encapsulating it inside an object function and structions in usb_cam.h became public and everything else is private * Merge pull request #28 from mitchellwills/develop Fix installation of header files * Fix installation of header files * Contributors: Mitchell Wills, Russell Toris 0.2.0 (2015-01-16) ------------------ * Bug fix in camera info settings. * Update .travis.yml * Merge pull request #27 from bosch-ros-pkg/default_camera_info sets default camera info * sets default camera info * Contributors: Russell Toris 0.1.13 (2014-12-02) ------------------- * Merge pull request #25 from blutack/patch-1 Warn rather than error if framerate can't be set * Warn rather than error if framerate can't be set The driver doesn't currently work with em28xx based devices as they don't allow the framerate to be set directly and the node exits with an error. Changing to a warning allows these devices to be used. * Update README.md * Merge pull request #24 from rjw57/do-not-touch-parameters-unless-asked do not modify parameters unless explicitly set * do not modify parameters unless explicitly set The contrast, saturation, brightness, sharpness and focus parameters were recently added to usb_cam. This caused a regression (sigproc/robotic_surgery#17) whereby the default settings for a webcam are overridden in all cases by the hard-coded defaults in usb_cam. In the absence of a know good set of "default" values, leave the parameters unset unless the user has explicitly set them in the launch file. * Contributors: Rich Wareham, Russell Toris, blutack 0.1.12 (2014-11-05) ------------------- * Merge pull request #22 from dekent/develop White balance parameters * Parameter to enable/disable auto white balance * Added parameters for white balance * uses version major to check for av_codec * uses version header to check for AV_CODEC_ID_MJPEG * Contributors: David Kent, Russell Toris 0.1.11 (2014-10-30) ------------------- * Merge pull request #20 from dekent/develop More Parameters * bug fix * Setting focus when autofocus is disabled * Parameter adjusting * Added parameter setting for absolute focus, brightness, contrast, saturation, and sharpness * Contributors: David Kent, Russell Toris 0.1.10 (2014-10-24) ------------------- * Merge pull request #19 from bosch-ros-pkg/av_codec_id Removed deprecated CODEC_ID * added legacy macro constants for libav 10 * Renamed deprecated CODEC_ID constants to AV_CODEC_ID to fix compilation for libav 10 * Contributors: Andrzej Pronobis, Russell Toris 0.1.9 (2014-08-26) ------------------ * Uses ros::Rate to enforce software framerate instead of custom time check * Merge pull request #16 from liangfok/feature/app_level_framerate_control Modified to enforce framerate control at the application level in additi... * Modified to enforce framerate control at the application level in addition to at the driver level. This is necessary since the drivers for my webcam did not obey the requested framerate. * Contributors: Russell Toris, liang 0.1.8 (2014-08-21) ------------------ * autoexposure and exposure settings now exposed via ROS parameters * added ability to call v4l-utils as well as correctly set autofocus * cleanup of output * Merge pull request #15 from mistoll/develop added support for RGB24 pixel format * Added RGB24 as pixel format * Contributors: Michael Stoll, Russell Toris 0.1.7 (2014-08-20) ------------------ * changelog fixed * minor cleanup and ability to change camera name and info * Contributors: Russell Toris 0.1.6 (2014-08-15) ------------------ * Merge pull request #14 from KaijenHsiao/master added support for 10-bit mono cameras advertising as YUV * added support for 10-bit mono cameras advertising as YUV (such as Leopard Imaging's LI-USB30-V034) * Update CHANGELOG.rst * changelog updated * Merge pull request #13 from vrabaud/develop add a a ros::spinOnce to get set_camera_info working * add a a ros::spinOnce to get set_camera_info working This is explained in the docs of CameraInfoManager https://github.com/ros-perception/image_common/blob/hydro-devel/camera_info_manager/include/camera_info_manager/camera_info_manager.h#L71 Also, this fixes https://github.com/ros-perception/image_pipeline/issues/78 * Contributors: Kaijen Hsiao, Russell Toris, Vincent Rabaud, sosentos 0.1.5 (2014-07-28) ------------------ * auto format * cleanup of readme and such * Merge branch 'hydro-devel' of github.com:bosch-ros-pkg/usb_cam * Merge pull request #11 from pronobis/hydro-devel Fixed a bug with av_free missing by adding a proper include. * Fixed a bug with av_free missing by adding a proper include on Ubuntu 14.04. * Merge pull request #7 from cottsay/groovy-devel Use pkg-config to find avcodec and swscale * Merge pull request #5 from FriedCircuits/hydro-devel Remove requirments for self_test * Use pkg-config to find avcodec and swscale * Update package.xml * Remove selftest * Remove selftest * Update usb_cam_node.cpp * Merge pull request #2 from jonbinney/7_17 swap out deprecated libavcodec functions * swap out deprecated libavcodec functions * Contributors: Andrzej Pronobis, Jon Binney, Russell Toris, Scott K Logan, William 0.1.3 (2013-07-11) ------------------ * Merge pull request #1 from jonbinney/rosify Bag of improvements * add framerate parameter * use ROS_* for output * use camera_info_manager * Contributors: Jon Binney, Russell Toris 0.1.2 (2013-05-06) ------------------ * installs usb_cam_node * Contributors: Russell Toris 0.1.1 (2013-05-02) ------------------ * cmake fixed * ffmpeg added * Contributors: Russell Toris 0.1.0 (2013-05-01) ------------------ * Update package.xml * minor cleanup * inital merge * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update CLONE_SETUP.sh * Update README.md * Updated the README.md. * Updated the installation instructions. * Fixed syntax in the README. * Updated README for ARDUINO support. * Fixed update script. * Updated the readme and updating scripts. * Updating for installation on Robot. * Updated installs and README for ROS. * Make sure the User knows to source the devel/setup.sh. * Getting rid of subtrees and Catkinized USB CAM. * Updating home to use ROSWS. * Fixing the launch file for video1. * Merge commit '0bc3322966e4c0ed259320827dd1f5cc8460efce' Conflicts: src/sofie_ros/package.xml * Removed unnecessary file. * Compiles. * Adding the Catkin build scripts. * Merge commit 'b2c739cb476e1e01425947e46dc2431464f241b3' as 'src/ar_track_alvar' * Squashed 'src/ar_track_alvar/' content from commit 9ecca95 git-subtree-dir: src/ar_track_alvar git-subtree-split: 9ecca9558edc7d3a9e692eacc93e082bf1e9a3e6 * Merge commit '9feb470d0ebdaa51e426be4d58f419b45928a671' as 'src/sofie_ros' * Squashed 'src/sofie_ros/' content from commit 3ca5edf git-subtree-dir: src/sofie_ros git-subtree-split: 3ca5edfba496840b41bfe01dfdff883cacff1a97 * Removing stackts. * Removing submodules. * Fixed submodules. * Removing old package. * Merge branch 'catkin' Conflicts: README.md cmake_install.cmake * Brancing package down to stack base. * Catkininizing. * (catkin)Catkininizing. * Modifying the setup of roshome. * Starting to Catkininize the project. * (catkin)Starting to Catkininize the project. * Going to catinize it. * (catkin)Going to catinize it. * Modified to new version of sofie_ros. * Renamed import_csv_data.py to fileUtils.py, because it does more now. * (catkin)Renamed import_csv_data.py to fileUtils.py, because it does more now. * Updating to use a csv file specified by the user. Separating PyTables path manipulation into SOFIEHDFFORMAT. * (catkin)Updating to use a csv file specified by the user. Separating PyTables path manipulation into SOFIEHDFFORMAT. * Merge branch 'release/0.0.2' * Created the install script. * Removed the Python Packages as submodules. * Merge branch 'release/0.0.1' * Update the Git submodules. * Modified the README and CLONE_SETUP.sh * Added SOFIEHDFFORMAT as a submodule. * Added the ExperimentControl Repo as a submodule. * Working the CLONE install. * Modifiying install script. * Added a script to update the gitmodules for read-only clones. * Merge branch 'master' of github.com:agcooke/roshome * Initial commit * Added the modules. * Added usb_cam, * Updating to Groovy. * (catkin)Updating to Groovy. * Added another potential launch file for exporting video from rosbag. * (catkin)Added another potential launch file for exporting video from rosbag. * Added a launcher to ros bag the usb_cam, for later playback. * (catkin)Added a launcher to ros bag the usb_cam, for later playback. * Added some files that were possibly not correct * (catkin)Added some files that were possibly not correct * Fixed bugs with the importing. * (catkin)Fixed bugs with the importing. * Added forgotten __init__.py file and changed to importdata sofiehdfformat funciton. * (catkin)Added forgotten __init__.py file and changed to importdata sofiehdfformat funciton. * Refractoring to make it possible to log to CSV. There were problems handling concurrent writing to pytables files. The package now logs to CSV and then provides a function to post import the data into SOFIEHDFFORMAT. * (catkin)Refractoring to make it possible to log to CSV. There were problems handling concurrent writing to pytables files. The package now logs to CSV and then provides a function to post import the data into SOFIEHDFFORMAT. * Exporting to a CSV. Does not work yet. * (catkin)Exporting to a CSV. Does not work yet. * Added a close on terminate signal handler. * (catkin)Added a close on terminate signal handler. * Made the marker size be set via a parameter to the launch file. * (catkin)Made the marker size be set via a parameter to the launch file. * Changed the Callibration data. * (catkin)Changed the Callibration data. * The ar_pose listener. * (catkin)The ar_pose listener. * Changed the sofie driver to directly safe the ar_pose data. We are going to perform experiments and this means that the extra data might be useful at a later stage. * (catkin)Changed the sofie driver to directly safe the ar_pose data. We are going to perform experiments and this means that the extra data might be useful at a later stage. * Changed the size of the marker. * Updated the usb_cam config to work for home camera. * Added callibration files and launch files. * Turned off history. * (catkin)Added some comments and renamed. * Added some comments and renamed. * (catkin)The Quaternions were mixed around. Fixed the launch file to log to file instead of screen. * The Quaternions were mixed around. Fixed the launch file to log to file instead of screen. * (catkin)Updating the README's. * Updating the README's. * Updated the launch file to launch ar_pose and rviz for debugging. * (catkin)Added arguments to the launch script. * Added arguments to the launch script. * Added the Stack formating files. * (catkin)Organising into a stack instead of separate packages. * Organising into a stack instead of separate packages. * Trying to figure out how to start and stop the node. * Adding simple parameters. * Added the ROS files. * Basic driver now works for listening on a channel that broadcasts geometry_msgs.msg.QuaternionStamped messages. * Working on the listerner that will write to HDFFormat. * Creating a listerner that can write to sofiehdfformat files. * Initial commit * Contributors: Adrian Cooke, Russell Toris, ¨Adrian
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/camera/usb_cam.cc
/********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2014, Robert Bosch LLC. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Robert Bosch nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * *********************************************************************/ #include <cmath> #include <string> #ifndef __aarch64__ #include "adv_trigger.h" #include "modules/drivers/camera/util.h" #endif #include "modules/drivers/camera/usb_cam.h" #define __STDC_CONSTANT_MACROS #define CLEAR(x) memset(&(x), 0, sizeof(x)) namespace apollo { namespace drivers { namespace camera { UsbCam::UsbCam() : fd_(-1), buffers_(NULL), n_buffers_(0), is_capturing_(false), image_seq_(0), device_wait_sec_(2), last_nsec_(0), frame_drop_interval_(0.0) {} UsbCam::~UsbCam() { stop_capturing(); uninit_device(); close_device(); } bool UsbCam::init(const std::shared_ptr<Config>& cameraconfig) { config_ = cameraconfig; if (config_->pixel_format() == "yuyv") { pixel_format_ = V4L2_PIX_FMT_YUYV; } else if (config_->pixel_format() == "uyvy") { pixel_format_ = V4L2_PIX_FMT_UYVY; } else if (config_->pixel_format() == "mjpeg") { pixel_format_ = V4L2_PIX_FMT_MJPEG; } else if (config_->pixel_format() == "yuvmono10") { pixel_format_ = V4L2_PIX_FMT_YUYV; config_->set_monochrome(true); } else if (config_->pixel_format() == "rgb24") { pixel_format_ = V4L2_PIX_FMT_RGB24; } else { pixel_format_ = V4L2_PIX_FMT_YUYV; AERROR << "Wrong pixel fromat:" << config_->pixel_format() << ",must be yuyv | uyvy | mjpeg | yuvmono10 | rgb24"; return false; } if (pixel_format_ == V4L2_PIX_FMT_MJPEG) { init_mjpeg_decoder(config_->width(), config_->height()); } // Warning when diff with last > 1.5* interval frame_warning_interval_ = static_cast<float>(1.5 / config_->frame_rate()); // now max fps 30, we use an appox time 0.9 to drop image. frame_drop_interval_ = static_cast<float>(0.9 / config_->frame_rate()); return true; } int UsbCam::init_mjpeg_decoder(int image_width, int image_height) { avcodec_register_all(); avcodec_ = avcodec_find_decoder(AV_CODEC_ID_MJPEG); if (!avcodec_) { AERROR << "Could not find MJPEG decoder"; return 0; } avcodec_context_ = avcodec_alloc_context3(avcodec_); #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 0, 0) avframe_camera_ = av_frame_alloc(); avframe_rgb_ = av_frame_alloc(); avpicture_alloc(reinterpret_cast<AVPicture*>(avframe_rgb_), AV_PIX_FMT_RGB24, image_width, image_height); #else avframe_camera_ = avcodec_alloc_frame(); avframe_rgb_ = avcodec_alloc_frame(); avpicture_alloc(reinterpret_cast<AVPicture*>(avframe_rgb_), PIX_FMT_RGB24, image_width, image_height); #endif avcodec_context_->codec_id = AV_CODEC_ID_MJPEG; avcodec_context_->width = image_width; avcodec_context_->height = image_height; #if LIBAVCODEC_VERSION_MAJOR > 52 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 0, 0) avcodec_context_->pix_fmt = AV_PIX_FMT_YUV422P; #else avcodec_context_->pix_fmt = PIX_FMT_YUV422P; #endif avcodec_context_->codec_type = AVMEDIA_TYPE_VIDEO; #endif #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 0, 0) avframe_camera_size_ = avpicture_get_size(AV_PIX_FMT_YUV422P, image_width, image_height); avframe_rgb_size_ = avpicture_get_size(AV_PIX_FMT_RGB24, image_width, image_height); #else avframe_camera_size_ = avpicture_get_size(PIX_FMT_YUV422P, image_width, image_height); avframe_rgb_size_ = avpicture_get_size(PIX_FMT_RGB24, image_width, image_height); #endif /* open it */ if (avcodec_open2(avcodec_context_, avcodec_, &avoptions_) < 0) { AERROR << "Could not open MJPEG Decoder"; return 0; } return 1; } void UsbCam::mjpeg2rgb(char* mjpeg_buffer, int len, char* rgb_buffer, int NumPixels) { (void)NumPixels; int got_picture = 0; memset(rgb_buffer, 0, avframe_rgb_size_); #if LIBAVCODEC_VERSION_MAJOR > 52 int decoded_len; AVPacket avpkt; av_init_packet(&avpkt); avpkt.size = len; avpkt.data = (unsigned char*)mjpeg_buffer; decoded_len = avcodec_decode_video2(avcodec_context_, avframe_camera_, &got_picture, &avpkt); if (decoded_len < 0) { AERROR << "Error while decoding frame."; return; } #else avcodec_decode_video(avcodec_context_, avframe_camera_, &got_picture, reinterpret_cast<uint8_t*>(mjpeg_buffer), len); #endif if (!got_picture) { AERROR << "Camera: expected picture but didn't get it..."; return; } int xsize = avcodec_context_->width; int ysize = avcodec_context_->height; int pic_size = avpicture_get_size(avcodec_context_->pix_fmt, xsize, ysize); if (pic_size != avframe_camera_size_) { AERROR << "outbuf size mismatch. pic_size:" << pic_size << ",buffer_size:" << avframe_camera_size_; return; } #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 0, 0) video_sws_ = sws_getContext(xsize, ysize, avcodec_context_->pix_fmt, xsize, ysize, AV_PIX_FMT_RGB24, SWS_BILINEAR, nullptr, nullptr, nullptr); #else video_sws_ = sws_getContext(xsize, ysize, avcodec_context_->pix_fmt, xsize, ysize, PIX_FMT_RGB24, SWS_BILINEAR, nullptr, nullptr, nullptr); #endif sws_scale(video_sws_, avframe_camera_->data, avframe_camera_->linesize, 0, ysize, avframe_rgb_->data, avframe_rgb_->linesize); sws_freeContext(video_sws_); #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 0, 0) int size = avpicture_layout( reinterpret_cast<AVPicture*>(avframe_rgb_), AV_PIX_FMT_RGB24, xsize, ysize, reinterpret_cast<uint8_t*>(rgb_buffer), avframe_rgb_size_); #else int size = avpicture_layout( reinterpret_cast<AVPicture*>(avframe_rgb_), PIX_FMT_RGB24, xsize, ysize, reinterpret_cast<uint8_t*>(rgb_buffer), avframe_rgb_size_); #endif if (size != avframe_rgb_size_) { AERROR << "webcam: avpicture_layout error: " << size; return; } } bool UsbCam::poll(const CameraImagePtr& raw_image) { raw_image->is_new = 0; // free memory in this struct desturctor memset(raw_image->image, 0, raw_image->image_size * sizeof(char)); fd_set fds; struct timeval tv; int r = 0; FD_ZERO(&fds); FD_SET(fd_, &fds); /* Timeout. */ tv.tv_sec = 2; tv.tv_usec = 0; r = select(fd_ + 1, &fds, nullptr, nullptr, &tv); if (-1 == r) { if (EINTR == errno) { return false; } // errno_exit("select"); reconnect(); } if (0 == r) { AERROR << "select timeout"; reconnect(); } int get_new_image = read_frame(raw_image); if (!get_new_image) { return false; } raw_image->is_new = 1; return true; } bool UsbCam::open_device(void) { struct stat st; if (-1 == stat(config_->camera_dev().c_str(), &st)) { AERROR << "Cannot identify '" << config_->camera_dev() << "': " << errno << ", " << strerror(errno); return false; } if (!S_ISCHR(st.st_mode)) { AERROR << config_->camera_dev() << " is no device"; return false; } fd_ = open(config_->camera_dev().c_str(), O_RDWR /* required */ | O_NONBLOCK, 0); if (-1 == fd_) { AERROR << "Cannot open '" << config_->camera_dev() << "': " << errno << ", " << strerror(errno); return false; } return true; } bool UsbCam::init_device(void) { struct v4l2_capability cap; struct v4l2_cropcap cropcap; struct v4l2_crop crop; struct v4l2_format fmt; unsigned int min = 0; if (-1 == xioctl(fd_, VIDIOC_QUERYCAP, &cap)) { if (EINVAL == errno) { AERROR << config_->camera_dev() << " is no V4L2 device"; return false; } AERROR << "VIDIOC_QUERYCAP"; return false; } if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) { AERROR << config_->camera_dev() << " is no video capture device"; return false; } switch (config_->io_method()) { case IO_METHOD_READ: if (!(cap.capabilities & V4L2_CAP_READWRITE)) { AERROR << config_->camera_dev() << " does not support read i/o"; return false; } break; case IO_METHOD_MMAP: case IO_METHOD_USERPTR: if (!(cap.capabilities & V4L2_CAP_STREAMING)) { AERROR << config_->camera_dev() << " does not support streaming i/o"; return false; } break; case IO_METHOD_UNKNOWN: AERROR << config_->camera_dev() << " does not support unknown i/o"; return false; break; } /* Select video input, video standard and tune here. */ CLEAR(cropcap); cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (0 == xioctl(fd_, VIDIOC_CROPCAP, &cropcap)) { crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; crop.c = cropcap.defrect; /* reset to default */ if (-1 == xioctl(fd_, VIDIOC_S_CROP, &crop)) { switch (errno) { case EINVAL: /* Cropping not supported. */ break; } } } CLEAR(fmt); fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; fmt.fmt.pix.width = config_->width(); fmt.fmt.pix.height = config_->height(); fmt.fmt.pix.pixelformat = pixel_format_; fmt.fmt.pix.field = V4L2_FIELD_INTERLACED; if (-1 == xioctl(fd_, VIDIOC_S_FMT, &fmt)) { AERROR << "VIDIOC_S_FMT"; return false; } /* Note VIDIOC_S_FMT may change width and height. */ /* Buggy driver paranoia. */ min = fmt.fmt.pix.width * 2; if (fmt.fmt.pix.bytesperline < min) { fmt.fmt.pix.bytesperline = min; } min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height; if (fmt.fmt.pix.sizeimage < min) { fmt.fmt.pix.sizeimage = min; } config_->set_width(fmt.fmt.pix.width); config_->set_height(fmt.fmt.pix.height); struct v4l2_streamparm stream_params; memset(&stream_params, 0, sizeof(stream_params)); stream_params.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; // if (xioctl(fd_, VIDIOC_G_PARM, &stream_params) < 0) { // // errno_exit("Couldn't query v4l fps!"); // AERROR << "Couldn't query v4l fps!"; // // reconnect(); // return false; // } AINFO << "Capability flag: 0x" << stream_params.parm.capture.capability; stream_params.parm.capture.timeperframe.numerator = 1; stream_params.parm.capture.timeperframe.denominator = config_->frame_rate(); if (xioctl(fd_, VIDIOC_S_PARM, &stream_params) < 0) { AINFO << "Couldn't set camera framerate"; } else { AINFO << "Set framerate to be " << config_->frame_rate(); } switch (config_->io_method()) { case IO_METHOD_READ: init_read(fmt.fmt.pix.sizeimage); break; case IO_METHOD_MMAP: init_mmap(); break; case IO_METHOD_USERPTR: init_userp(fmt.fmt.pix.sizeimage); break; case IO_METHOD_UNKNOWN: AERROR << " does not support unknown i/o"; break; } return true; } #ifndef __aarch64__ bool UsbCam::set_adv_trigger() { AINFO << "Trigger enable, dev:" << config_->camera_dev() << ", fps:" << config_->trigger_fps() << ", internal:" << config_->trigger_internal(); int ret = adv_trigger_enable( config_->camera_dev().c_str(), static_cast<unsigned char>(config_->trigger_fps()), static_cast<unsigned char>(config_->trigger_internal())); if (ret != 0) { AERROR << "trigger failed:" << ret; return false; } return true; } #endif int UsbCam::xioctl(int fd, int request, void* arg) { int r = 0; do { r = ioctl(fd, request, arg); } while (-1 == r && EINTR == errno); return r; } bool UsbCam::init_read(unsigned int buffer_size) { buffers_ = reinterpret_cast<buffer*>(calloc(1, sizeof(*buffers_))); if (!buffers_) { AERROR << "Out of memory"; // exit(EXIT_FAILURE); // reconnect(); return false; } buffers_[0].length = buffer_size; buffers_[0].start = malloc(buffer_size); if (!buffers_[0].start) { AERROR << "Out of memory"; return false; } return true; } bool UsbCam::init_mmap(void) { struct v4l2_requestbuffers req; CLEAR(req); req.count = 1; req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; req.memory = V4L2_MEMORY_MMAP; if (-1 == xioctl(fd_, VIDIOC_REQBUFS, &req)) { if (EINVAL == errno) { AERROR << config_->camera_dev() << " does not support memory mapping"; return false; } return false; } buffers_ = reinterpret_cast<buffer*>(calloc(req.count, sizeof(*buffers_))); if (!buffers_) { AERROR << "Out of memory"; return false; } for (n_buffers_ = 0; n_buffers_ < req.count; ++n_buffers_) { struct v4l2_buffer buf; CLEAR(buf); buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; buf.index = n_buffers_; if (-1 == xioctl(fd_, VIDIOC_QUERYBUF, &buf)) { AERROR << "VIDIOC_QUERYBUF"; return false; } buffers_[n_buffers_].length = buf.length; buffers_[n_buffers_].start = mmap(NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, buf.m.offset); if (MAP_FAILED == buffers_[n_buffers_].start) { AERROR << "mmap"; return false; } } return true; } bool UsbCam::init_userp(unsigned int buffer_size) { struct v4l2_requestbuffers req; unsigned int page_size = 0; page_size = getpagesize(); buffer_size = (buffer_size + page_size - 1) & ~(page_size - 1); CLEAR(req); req.count = 4; req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; req.memory = V4L2_MEMORY_USERPTR; if (-1 == xioctl(fd_, VIDIOC_REQBUFS, &req)) { if (EINVAL == errno) { AERROR << config_->camera_dev() << " does not support " "user pointer i/o"; return false; } AERROR << "VIDIOC_REQBUFS"; return false; } buffers_ = reinterpret_cast<buffer*>(calloc(4, sizeof(*buffers_))); if (!buffers_) { AERROR << "Out of memory"; return false; } for (n_buffers_ = 0; n_buffers_ < 4; ++n_buffers_) { buffers_[n_buffers_].length = buffer_size; buffers_[n_buffers_].start = memalign(/* boundary */ page_size, buffer_size); if (!buffers_[n_buffers_].start) { AERROR << "Out of memory"; return false; } } return true; } bool UsbCam::start_capturing(void) { if (is_capturing_) { return true; } unsigned int i = 0; enum v4l2_buf_type type; switch (config_->io_method()) { case IO_METHOD_READ: /* Nothing to do. */ break; case IO_METHOD_MMAP: for (i = 0; i < n_buffers_; ++i) { struct v4l2_buffer buf; CLEAR(buf); buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; buf.index = i; if (-1 == xioctl(fd_, VIDIOC_QBUF, &buf)) { AERROR << "VIDIOC_QBUF"; return false; } } type = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (-1 == xioctl(fd_, VIDIOC_STREAMON, &type)) { AERROR << "VIDIOC_STREAMON"; return false; } break; case IO_METHOD_USERPTR: for (i = 0; i < n_buffers_; ++i) { struct v4l2_buffer buf; CLEAR(buf); buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_USERPTR; buf.index = i; buf.m.userptr = reinterpret_cast<uint64_t>(buffers_[i].start); buf.length = static_cast<unsigned int>(buffers_[i].length); if (-1 == xioctl(fd_, VIDIOC_QBUF, &buf)) { AERROR << "VIDIOC_QBUF"; return false; } } type = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (-1 == xioctl(fd_, VIDIOC_STREAMON, &type)) { AERROR << "VIDIOC_STREAMON"; return false; } break; case IO_METHOD_UNKNOWN: AERROR << "unknown IO"; return false; break; } is_capturing_ = true; return true; } void UsbCam::set_device_config() { if (config_->brightness() >= 0) { set_v4l_parameter("brightness", config_->brightness()); } if (config_->contrast() >= 0) { set_v4l_parameter("contrast", config_->contrast()); } if (config_->saturation() >= 0) { set_v4l_parameter("saturation", config_->saturation()); } if (config_->sharpness() >= 0) { set_v4l_parameter("sharpness", config_->sharpness()); } if (config_->gain() >= 0) { set_v4l_parameter("gain", config_->gain()); } // check auto white balance if (config_->auto_white_balance()) { set_v4l_parameter("white_balance_temperature_auto", 1); } else { set_v4l_parameter("white_balance_temperature_auto", 0); set_v4l_parameter("white_balance_temperature", config_->white_balance()); } // check auto exposure if (!config_->auto_exposure()) { // turn down exposure control (from max of 3) set_v4l_parameter("auto_exposure", 1); // change the exposure level set_v4l_parameter("exposure_absolute", config_->exposure()); } // check auto focus if (config_->auto_focus()) { set_auto_focus(1); set_v4l_parameter("focus_auto", 1); } else { set_v4l_parameter("focus_auto", 0); if (config_->focus() >= 0) { set_v4l_parameter("focus_absolute", config_->focus()); } } } bool UsbCam::uninit_device(void) { unsigned int i = 0; switch (config_->io_method()) { case IO_METHOD_READ: free(buffers_[0].start); break; case IO_METHOD_MMAP: for (i = 0; i < n_buffers_; ++i) { if (-1 == munmap(buffers_[i].start, buffers_[i].length)) { AERROR << "munmap"; return false; } } break; case IO_METHOD_USERPTR: for (i = 0; i < n_buffers_; ++i) { free(buffers_[i].start); } break; case IO_METHOD_UNKNOWN: AERROR << "unknown IO"; break; } return true; } bool UsbCam::close_device(void) { if (-1 == close(fd_)) { AERROR << "close"; return false; } fd_ = -1; return true; } bool UsbCam::stop_capturing(void) { if (!is_capturing_) { return true; } is_capturing_ = false; enum v4l2_buf_type type; switch (config_->io_method()) { case IO_METHOD_READ: /* Nothing to do. */ break; case IO_METHOD_MMAP: case IO_METHOD_USERPTR: type = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (-1 == xioctl(fd_, VIDIOC_STREAMOFF, &type)) { AERROR << "VIDIOC_STREAMOFF"; return false; } break; case IO_METHOD_UNKNOWN: AERROR << "unknown IO"; return false; break; } return true; } bool UsbCam::read_frame(CameraImagePtr raw_image) { struct v4l2_buffer buf; unsigned int i = 0; int len = 0; timeval sample_ts_monotonic; timespec current_ts_monotonic; uint64_t sample_ts_monotonic_ns, current_ts_monotonic_ns, diff_ns, sample_in_systme_time_ns; switch (config_->io_method()) { case IO_METHOD_READ: len = static_cast<int>(read(fd_, buffers_[0].start, buffers_[0].length)); if (len == -1) { switch (errno) { case EAGAIN: AINFO << "EAGAIN"; return false; case EIO: /* Could ignore EIO, see spec. */ /* fall through */ default: AERROR << "read"; return false; } } process_image(buffers_[0].start, len, raw_image); break; case IO_METHOD_MMAP: CLEAR(buf); buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; if (-1 == xioctl(fd_, VIDIOC_DQBUF, &buf)) { switch (errno) { case EAGAIN: return false; case EIO: /* Could ignore EIO, see spec. */ /* fall through */ default: AERROR << "VIDIOC_DQBUF"; reconnect(); return false; } } assert(buf.index < n_buffers_); len = buf.bytesused; if(!config_->hardware_trigger()){ sample_ts_monotonic.tv_sec = static_cast<int>(buf.timestamp.tv_sec); sample_ts_monotonic.tv_usec = static_cast<int>(buf.timestamp.tv_usec); clock_gettime(CLOCK_MONOTONIC,&current_ts_monotonic); sample_ts_monotonic_ns = static_cast<uint64_t>(sample_ts_monotonic.tv_sec*(1000000000)) + static_cast<uint64_t>(sample_ts_monotonic.tv_usec*(1000)); current_ts_monotonic_ns = static_cast<uint64_t>(current_ts_monotonic.tv_sec*(1000000000)) + static_cast<uint64_t>(current_ts_monotonic.tv_nsec); diff_ns = static_cast<uint64_t>(current_ts_monotonic_ns - sample_ts_monotonic_ns); sample_in_systme_time_ns = static_cast<uint64_t>(cyber::Time::Now().ToNanosecond() - diff_ns); raw_image->tv_sec = static_cast<int>((sample_in_systme_time_ns)/1000000000); raw_image->tv_usec = static_cast<int>(((sample_in_systme_time_ns)%1000000000)/1000); } else{ raw_image->tv_sec = static_cast<int>(buf.timestamp.tv_sec); raw_image->tv_usec = static_cast<int>(buf.timestamp.tv_usec); } { cyber::Time image_time(raw_image->tv_sec, 1000 * raw_image->tv_usec); uint64_t camera_timestamp = image_time.ToNanosecond(); if (last_nsec_ == 0) { last_nsec_ = camera_timestamp; } else { double diff = static_cast<double>(camera_timestamp - last_nsec_) / 1e9; // drop image by frame_rate if (diff < frame_drop_interval_) { AINFO << "drop image:" << camera_timestamp; if (-1 == xioctl(fd_, VIDIOC_QBUF, &buf)) { AERROR << "VIDIOC_QBUF ERROR"; } return false; } if (frame_warning_interval_ < diff) { AWARN << "stamp jump.last stamp:" << last_nsec_ << " current stamp:" << camera_timestamp; } last_nsec_ = camera_timestamp; } double now_s = static_cast<double>(cyber::Time::Now().ToSecond()); double image_s = static_cast<double>(camera_timestamp) / 1e9; double diff = now_s - image_s; if (diff > 0.5 || diff < 0) { std::stringstream warning_stream; std::string warning_str; warning_stream << "camera time diff exception,diff:" << diff << ";dev:" << config_->camera_dev(); warning_stream >> warning_str; AWARN << warning_str; } } if (len < raw_image->width * raw_image->height) { AERROR << "Wrong Buffer Len: " << len << ", dev: " << config_->camera_dev(); } else { process_image(buffers_[buf.index].start, len, raw_image); } if (-1 == xioctl(fd_, VIDIOC_QBUF, &buf)) { AERROR << "VIDIOC_QBUF"; return false; } break; case IO_METHOD_USERPTR: CLEAR(buf); buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_USERPTR; if (-1 == xioctl(fd_, VIDIOC_DQBUF, &buf)) { switch (errno) { case EAGAIN: return false; case EIO: /* Could ignore EIO, see spec. */ /* fall through */ default: AERROR << "VIDIOC_DQBUF"; return false; } } for (i = 0; i < n_buffers_; ++i) { if (buf.m.userptr == reinterpret_cast<uint64_t>(buffers_[i].start) && buf.length == buffers_[i].length) { break; } } assert(i < n_buffers_); len = buf.bytesused; process_image(reinterpret_cast<void*>(buf.m.userptr), len, raw_image); if (-1 == xioctl(fd_, VIDIOC_QBUF, &buf)) { AERROR << "VIDIOC_QBUF"; return false; } break; case IO_METHOD_UNKNOWN: AERROR << "unknown IO"; return false; break; } return true; } bool UsbCam::process_image(void* src, int len, CameraImagePtr dest) { if (src == nullptr || dest == nullptr) { AERROR << "process image error. src or dest is null"; return false; } if (pixel_format_ == V4L2_PIX_FMT_YUYV || pixel_format_ == V4L2_PIX_FMT_UYVY) { if (pixel_format_ == V4L2_PIX_FMT_UYVY) { unsigned char yuyvbuf[len]; unsigned char uyvybuf[len]; memcpy(yuyvbuf, src, len); for (int index = 0; index < len; index = index + 2) { uyvybuf[index] = yuyvbuf[index + 1]; uyvybuf[index + 1] = yuyvbuf[index]; } memcpy(src, uyvybuf, len); } if (config_->output_type() == YUYV) { memcpy(dest->image, src, dest->width * dest->height * 2); } else if (config_->output_type() == RGB) { #ifdef __aarch64__ convert_yuv_to_rgb_buffer((unsigned char*)src, (unsigned char*)dest->image, dest->width, dest->height); #else yuyv2rgb_avx((unsigned char*)src, (unsigned char*)dest->image, dest->width * dest->height); #endif } else { AERROR << "unsupported output format:" << config_->output_type(); return false; } } else { AERROR << "unsupported pixel format:" << pixel_format_; return false; } return true; } bool UsbCam::is_capturing() { return is_capturing_; } // enables/disables auto focus void UsbCam::set_auto_focus(int value) { struct v4l2_queryctrl queryctrl; struct v4l2_ext_control control; memset(&queryctrl, 0, sizeof(queryctrl)); queryctrl.id = V4L2_CID_FOCUS_AUTO; if (-1 == xioctl(fd_, VIDIOC_QUERYCTRL, &queryctrl)) { if (errno != EINVAL) { perror("VIDIOC_QUERYCTRL"); return; } else { AINFO << "V4L2_CID_FOCUS_AUTO is not supported"; return; } } else if (queryctrl.flags & V4L2_CTRL_FLAG_DISABLED) { AINFO << "V4L2_CID_FOCUS_AUTO is not supported"; return; } else { memset(&control, 0, sizeof(control)); control.id = V4L2_CID_FOCUS_AUTO; control.value = value; if (-1 == xioctl(fd_, VIDIOC_S_CTRL, &control)) { perror("VIDIOC_S_CTRL"); return; } } } /** * Set video device parameter via call to v4l-utils. * * @param param The name of the parameter to set * @param param The value to assign */ void UsbCam::set_v4l_parameter(const std::string& param, int value) { set_v4l_parameter(param, std::to_string(value)); } /** * Set video device parameter via call to v4l-utils. * * @param param The name of the parameter to set * @param param The value to assign */ void UsbCam::set_v4l_parameter(const std::string& param, const std::string& value) { // build the command std::stringstream ss; ss << "v4l2-ctl --device=" << config_->camera_dev() << " -c " << param << "=" << value << " 2>&1"; std::string cmd = ss.str(); // capture the output std::string output; char buffer[256]; FILE* stream = popen(cmd.c_str(), "r"); if (stream) { while (!feof(stream)) { if (fgets(buffer, 256, stream) != nullptr) { output.append(buffer); } } pclose(stream); // any output should be an error if (output.length() > 0) { AERROR << output.c_str(); } } else { AERROR << "usb_cam_node could not run " << cmd.c_str(); } } bool UsbCam::wait_for_device() { if (is_capturing_) { ADEBUG << "is capturing"; return true; } if (!open_device()) { return false; } if (!init_device()) { close_device(); return false; } if (!start_capturing()) { uninit_device(); close_device(); return false; } #ifndef __aarch64__ // will continue when trigger failed for self-trigger camera set_adv_trigger(); #endif return true; } void UsbCam::reconnect() { stop_capturing(); uninit_device(); close_device(); } #ifdef __aarch64__ int UsbCam::convert_yuv_to_rgb_pixel(int y, int u, int v) { unsigned int pixel32 = 0; unsigned char* pixel = (unsigned char*)&pixel32; int r, g, b; r = (int)((double)y + (1.370705 * ((double)v - 128.0))); g = (int)((double)y - (0.698001 * ((double)v - 128.0)) - (0.337633 * ((double)u - 128.0))); b = (int)((double)y + (1.732446 * ((double)u - 128.0))); if (r > 255) r = 255; if (g > 255) g = 255; if (b > 255) b = 255; if (r < 0) r = 0; if (g < 0) g = 0; if (b < 0) b = 0; pixel[0] = (unsigned char)r; pixel[1] = (unsigned char)g; pixel[2] = (unsigned char)b; return pixel32; } int UsbCam::convert_yuv_to_rgb_buffer(unsigned char* yuv, unsigned char* rgb, unsigned int width, unsigned int height) { unsigned int in, out = 0; unsigned int pixel_16; unsigned char pixel_24[3]; unsigned int pixel32; int y0, u, y1, v; for (in = 0; in < width * height * 2; in += 4) { pixel_16 = yuv[in + 3] << 24 | yuv[in + 2] << 16 | yuv[in + 1] << 8 | yuv[in + 0]; y0 = (pixel_16 & 0x000000ff); u = (pixel_16 & 0x0000ff00) >> 8; y1 = (pixel_16 & 0x00ff0000) >> 16; v = (pixel_16 & 0xff000000) >> 24; pixel32 = convert_yuv_to_rgb_pixel(y0, u, v); pixel_24[0] = (unsigned char)(pixel32 & 0x000000ff); pixel_24[1] = (unsigned char)((pixel32 & 0x0000ff00) >> 8); pixel_24[2] = (unsigned char)((pixel32 & 0x00ff0000) >> 16); rgb[out++] = pixel_24[0]; rgb[out++] = pixel_24[1]; rgb[out++] = pixel_24[2]; pixel32 = convert_yuv_to_rgb_pixel(y1, u, v); pixel_24[0] = (unsigned char)(pixel32 & 0x000000ff); pixel_24[1] = (unsigned char)((pixel32 & 0x0000ff00) >> 8); pixel_24[2] = (unsigned char)((pixel32 & 0x00ff0000) >> 16); rgb[out++] = pixel_24[0]; rgb[out++] = pixel_24[1]; rgb[out++] = pixel_24[2]; } return 0; } #endif } // namespace camera } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/camera/usb_cam.h
/********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2014, Robert Bosch LLC. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Robert Bosch nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * *********************************************************************/ #pragma once #include <asm/types.h> /* for videodev2.h */ #include <malloc.h> #include <sys/ioctl.h> #include <sys/mman.h> #ifndef __aarch64__ #include <immintrin.h> #include <x86intrin.h> #endif extern "C" { #include <libavcodec/avcodec.h> #include <libavutil/mem.h> #include <libswscale/swscale.h> #include <linux/videodev2.h> } #include <libavcodec/version.h> #if LIBAVCODEC_VERSION_MAJOR < 55 #define AV_CODEC_ID_MJPEG CODEC_ID_MJPEG #endif #include <memory> #include <sstream> #include <string> #include "cyber/cyber.h" #include "modules/drivers/camera/proto/config.pb.h" namespace apollo { namespace drivers { namespace camera { using apollo::drivers::camera::config::Config; using apollo::drivers::camera::config::IO_METHOD_MMAP; using apollo::drivers::camera::config::IO_METHOD_READ; using apollo::drivers::camera::config::IO_METHOD_UNKNOWN; using apollo::drivers::camera::config::IO_METHOD_USERPTR; using apollo::drivers::camera::config::RGB; using apollo::drivers::camera::config::YUYV; // camera raw image struct struct CameraImage { int width; int height; int bytes_per_pixel; int image_size; int is_new; int tv_sec; int tv_usec; char* image; ~CameraImage() { if (image != nullptr) { free(reinterpret_cast<void*>(image)); image = nullptr; } } }; typedef std::shared_ptr<CameraImage> CameraImagePtr; struct buffer { void* start; size_t length; }; class UsbCam { public: UsbCam(); virtual ~UsbCam(); virtual bool init(const std::shared_ptr<Config>& camera_config); // user use this function to get camera frame data virtual bool poll(const CameraImagePtr& raw_image); bool is_capturing(); bool wait_for_device(void); private: int xioctl(int fd, int request, void* arg); bool init_device(void); bool uninit_device(void); void set_device_config(); // enables/disable auto focus void set_auto_focus(int value); // set video device parameters void set_v4l_parameter(const std::string& param, int value); void set_v4l_parameter(const std::string& param, const std::string& value); int init_mjpeg_decoder(int image_width, int image_height); void mjpeg2rgb(char* mjepg_buffer, int len, char* rgb_buffer, int pixels); #ifdef __aarch64__ int convert_yuv_to_rgb_pixel(int y, int u, int v); int convert_yuv_to_rgb_buffer(unsigned char* yuv, unsigned char* rgb, unsigned int width, unsigned int height); #endif bool init_read(unsigned int buffer_size); bool init_mmap(void); bool init_userp(unsigned int buffer_size); bool set_adv_trigger(void); bool close_device(void); bool open_device(void); bool read_frame(CameraImagePtr raw_image); bool process_image(void* src, int len, CameraImagePtr dest); bool start_capturing(void); bool stop_capturing(void); void reconnect(); void reset_device(); std::shared_ptr<Config> config_; int pixel_format_; int fd_; buffer* buffers_; unsigned int n_buffers_; bool is_capturing_; uint64_t image_seq_; AVFrame* avframe_camera_; AVFrame* avframe_rgb_; AVCodec* avcodec_; AVDictionary* avoptions_; AVCodecContext* avcodec_context_; int avframe_camera_size_; int avframe_rgb_size_; struct SwsContext* video_sws_; float frame_warning_interval_ = 0.0; float device_wait_sec_ = 0.0; uint64_t last_nsec_ = 0; float frame_drop_interval_ = 0.0; }; } // namespace camera } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/camera
apollo_public_repos/apollo/modules/drivers/camera/proto/BUILD
## Auto generated by `proto_build_generator.py` load("@rules_proto//proto:defs.bzl", "proto_library") load("@rules_cc//cc:defs.bzl", "cc_proto_library") load("//tools:python_rules.bzl", "py_proto_library") package(default_visibility = ["//visibility:public"]) cc_proto_library( name = "config_cc_proto", deps = [ ":config_proto", ], ) proto_library( name = "config_proto", srcs = ["config.proto"], ) py_proto_library( name = "config_py_pb2", deps = [ ":config_proto", ], )
0
apollo_public_repos/apollo/modules/drivers/camera
apollo_public_repos/apollo/modules/drivers/camera/proto/config.proto
syntax = "proto2"; package apollo.drivers.camera.config; enum IOMethod { IO_METHOD_UNKNOWN = 0; IO_METHOD_READ = 1; IO_METHOD_MMAP = 2; IO_METHOD_USERPTR = 3; } enum OutputType { YUYV = 0; RGB = 1; } message Config { optional string camera_dev = 1; optional string frame_id = 2; // v4l pixel format optional string pixel_format = 3 [default = "yuyv"]; // mmap, userptr, read optional IOMethod io_method = 4; optional uint32 width = 5; optional uint32 height = 6; optional uint32 frame_rate = 7; optional bool monochrome = 8 [default = false]; optional int32 brightness = 9 [default = -1]; optional int32 contrast = 10 [default = -1]; optional int32 saturation = 11 [default = -1]; optional int32 sharpness = 12 [default = -1]; optional int32 gain = 13 [default = -1]; optional bool auto_focus = 14 [default = false]; optional int32 focus = 15 [default = -1]; optional bool auto_exposure = 16 [default = true]; optional int32 exposure = 17 [default = 100]; optional bool auto_white_balance = 18 [default = true]; optional int32 white_balance = 19 [default = 4000]; optional uint32 bytes_per_pixel = 20 [default = 3]; optional uint32 trigger_internal = 21 [default = 0]; optional uint32 trigger_fps = 22 [default = 30]; optional string channel_name = 23; // wait time when camera select timeout optional uint32 device_wait_ms = 24 [default = 2000]; // camera select spin time optional uint32 spin_rate = 25 [default = 200]; optional OutputType output_type = 26; message CompressConfig { optional string output_channel = 1; optional uint32 image_pool_size = 2 [default = 20]; } optional CompressConfig compress_conf = 27; optional bool hardware_trigger = 28 [default = true]; }
0
apollo_public_repos/apollo/modules/drivers/camera
apollo_public_repos/apollo/modules/drivers/camera/launch/camera_and_video.launch
<cyber> <module> <name>camera</name> <dag_conf>/apollo/modules/drivers/camera/dag/camera.dag</dag_conf> <process_name>usb_cam</process_name> </module> <module> <name>video</name> <dag_conf>/apollo/modules/drivers/video/dag/video.dag</dag_conf> <process_name>h265_video</process_name> </module> </cyber>
0
apollo_public_repos/apollo/modules/drivers/camera
apollo_public_repos/apollo/modules/drivers/camera/launch/camera.launch
<cyber> <module> <name>camera</name> <dag_conf>/apollo/modules/drivers/camera/dag/camera.dag</dag_conf> <process_name>usb_cam</process_name> </module> </cyber>
0
apollo_public_repos/apollo/modules/drivers/camera
apollo_public_repos/apollo/modules/drivers/camera/dag/camera_no_compress.dag
# Define all coms in DAG streaming. module_config { module_library : "/apollo/bazel-bin/modules/drivers/camera/libcamera_component.so" components { class_name : "CameraComponent" config { name : "camera_front_6mm" config_file_path : "/apollo/modules/drivers/camera/conf/camera_front_6mm.pb.txt" } } components { class_name : "CameraComponent" config { name : "camera_front_12mm" config_file_path : "/apollo/modules/drivers/camera/conf/camera_front_12mm.pb.txt" } } components { class_name : "CameraComponent" config { name : "camera_front_fisheye" config_file_path : "/apollo/modules/drivers/camera/conf/camera_front_fisheye.pb.txt" } } # components { # class_name : "CameraComponent" # config { # name : "camera_left_front" # config_file_path : "/apollo/modules/drivers/camera/conf/camera_left_front.pb.txt" # } # } # components { # class_name : "CameraComponent" # config { # name : "camera_left_rear" # config_file_path : "/apollo/modules/drivers/camera/conf/camera_left_rear.pb.txt" # } # } components { class_name : "CameraComponent" config { name : "camera_left_fisheye" config_file_path : "/apollo/modules/drivers/camera/conf/camera_left_fisheye.pb.txt" } } # components { # class_name : "CameraComponent" # config { # name : "camera_right_front" # config_file_path : "/apollo/modules/drivers/camera/conf/camera_right_front.pb.txt" # } # } # components { # class_name : "CameraComponent" # config { # name : "camera_right_rear" # config_file_path : "/apollo/modules/drivers/camera/conf/camera_right_rear.pb.txt" # } # } components { class_name : "CameraComponent" config { name : "camera_right_fisheye" config_file_path : "/apollo/modules/drivers/camera/conf/camera_right_fisheye.pb.txt" } } components { class_name : "CameraComponent" config { name : "camera_rear_6mm" config_file_path : "/apollo/modules/drivers/camera/conf/camera_rear_6mm.pb.txt" } } }
0
apollo_public_repos/apollo/modules/drivers/camera
apollo_public_repos/apollo/modules/drivers/camera/dag/camera.dag
# Define all coms in DAG streaming. module_config { module_library : "/apollo/bazel-bin/modules/drivers/camera/libcamera_component.so" components { class_name : "CameraComponent" config { name : "camera_front_6mm" config_file_path : "/apollo/modules/drivers/camera/conf/camera_front_6mm.pb.txt" } } components { class_name : "CompressComponent" config { name : "camera_front_6mm_compress" config_file_path : "/apollo/modules/drivers/camera/conf/camera_front_6mm.pb.txt" readers { channel: "/apollo/sensor/camera/front_6mm/image" pending_queue_size: 10 } } } components { class_name : "CameraComponent" config { name : "camera_front_12mm" config_file_path : "/apollo/modules/drivers/camera/conf/camera_front_12mm.pb.txt" } } components { class_name : "CompressComponent" config { name : "camera_front_12mm_compress" config_file_path : "/apollo/modules/drivers/camera/conf/camera_front_12mm.pb.txt" readers { channel: "/apollo/sensor/camera/front_12mm/image" pending_queue_size: 10 } } } components { class_name : "CameraComponent" config { name : "camera_left_fisheye" config_file_path : "/apollo/modules/drivers/camera/conf/camera_left_fisheye.pb.txt" } } components { class_name : "CompressComponent" config { name : "camera_left_fisheye_compress" config_file_path : "/apollo/modules/drivers/camera/conf/camera_left_fisheye.pb.txt" readers { channel: "/apollo/sensor/camera/left_fisheye/image" pending_queue_size: 10 } } } components { class_name : "CameraComponent" config { name : "camera_right_fisheye" config_file_path : "/apollo/modules/drivers/camera/conf/camera_right_fisheye.pb.txt" } } components { class_name : "CompressComponent" config { name : "camera_right_fisheye_compress" config_file_path : "/apollo/modules/drivers/camera/conf/camera_right_fisheye.pb.txt" readers { channel: "/apollo/sensor/camera/right_fisheye/image" pending_queue_size: 10 } } } components { class_name : "CameraComponent" config { name : "camera_rear_6mm" config_file_path : "/apollo/modules/drivers/camera/conf/camera_rear_6mm.pb.txt" } } components { class_name : "CompressComponent" config { name : "camera_rear_6mm_compress" config_file_path : "/apollo/modules/drivers/camera/conf/camera_rear_6mm.pb.txt" readers { channel: "/apollo/sensor/camera/rear_6mm/image" pending_queue_size: 10 } } } }
0
apollo_public_repos/apollo/modules/drivers/camera
apollo_public_repos/apollo/modules/drivers/camera/conf/camera_short_conf.pb.txt
camera_dev: "/dev/camera/obstacle" frame_id: "camera_short" pixel_format: "yuyv" io_method: IO_METHOD_MMAP width: 1920 height: 1080 frame_rate: 20 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 2 trigger_internal: 0 trigger_fps: 20 channel_name: "/apollo/sensor/camera/traffic/image_short" device_wait_ms: 2000 spin_rate: 200 output_type: RGB compress_conf { output_channel: "/apollo/sensor/camera/traffic/image_short/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/camera
apollo_public_repos/apollo/modules/drivers/camera/conf/camera_front_conf.pb.txt
camera_dev: "/dev/camera/lanemark" frame_id: "camera_lanemark" pixel_format: "yuyv" io_method: IO_METHOD_MMAP width: 1920 height: 1080 frame_rate: 20 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 2 trigger_internal: 0 trigger_fps: 20 channel_name: "/apollo/sensor/camera/obstacle/front_6mm" device_wait_ms: 2000 spin_rate: 200 output_type: RGB compress_conf { output_channel: "/apollo/sensor/camera/obstacle/front_6mm/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/camera
apollo_public_repos/apollo/modules/drivers/camera/conf/camera_right_rear.pb.txt
camera_dev: "/dev/camera/right_rear" frame_id: "camera_right_rear" pixel_format: "yuyv" io_method: IO_METHOD_MMAP width: 1920 height: 1080 frame_rate: 20 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 2 trigger_internal: 0 trigger_fps: 20 channel_name: "/apollo/sensor/camera/right_rear/image" device_wait_ms: 2000 spin_rate: 200 output_type: RGB compress_conf { output_channel: "/apollo/sensor/camera/right_rear/image/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/camera
apollo_public_repos/apollo/modules/drivers/camera/conf/camera_long_conf.pb.txt
camera_dev: "/dev/camera/trafficlights" frame_id: "camera_long" pixel_format: "yuyv" io_method: IO_METHOD_MMAP width: 1920 height: 1080 frame_rate: 20 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 2 trigger_internal: 0 trigger_fps: 20 channel_name: "/apollo/sensor/camera/traffic/image_long" device_wait_ms: 2000 spin_rate: 200 output_type: RGB compress_conf { output_channel: "/apollo/sensor/camera/traffic/image_long/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/camera
apollo_public_repos/apollo/modules/drivers/camera/conf/camera_right_fisheye.pb.txt
camera_dev: "/dev/camera/right_fisheye" frame_id: "camera_right_fisheye" pixel_format: "yuyv" io_method: IO_METHOD_MMAP width: 1920 height: 1080 frame_rate: 20 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 2 trigger_internal: 0 trigger_fps: 20 channel_name: "/apollo/sensor/camera/right_fisheye/image" device_wait_ms: 2000 spin_rate: 200 output_type: RGB compress_conf { output_channel: "/apollo/sensor/camera/right_fisheye/image/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/camera
apollo_public_repos/apollo/modules/drivers/camera/conf/camera_rear_6mm.pb.txt
camera_dev: "/dev/camera/rear_6mm" frame_id: "camera_rear_6mm" pixel_format: "yuyv" io_method: IO_METHOD_MMAP width: 1920 height: 1080 frame_rate: 20 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 2 trigger_internal: 0 trigger_fps: 20 channel_name: "/apollo/sensor/camera/rear_6mm/image" device_wait_ms: 2000 spin_rate: 200 output_type: RGB compress_conf { output_channel: "/apollo/sensor/camera/rear_6mm/image/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/camera
apollo_public_repos/apollo/modules/drivers/camera/conf/camera_left_front.pb.txt
camera_dev: "/dev/camera/left_front" frame_id: "camera_left_front" pixel_format: "yuyv" io_method: IO_METHOD_MMAP width: 1920 height: 1080 frame_rate: 20 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 2 trigger_internal: 0 trigger_fps: 20 channel_name: "/apollo/sensor/camera/left_front/image" device_wait_ms: 2000 spin_rate: 200 output_type: RGB compress_conf { output_channel: "/apollo/sensor/camera/left_front/image/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/camera
apollo_public_repos/apollo/modules/drivers/camera/conf/camera_left_fisheye.pb.txt
camera_dev: "/dev/camera/left_fisheye" frame_id: "camera_left_fisheye" pixel_format: "yuyv" io_method: IO_METHOD_MMAP width: 1920 height: 1080 frame_rate: 20 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 2 trigger_internal: 0 trigger_fps: 20 channel_name: "/apollo/sensor/camera/left_fisheye/image" device_wait_ms: 2000 spin_rate: 200 output_type: RGB compress_conf { output_channel: "/apollo/sensor/camera/left_fisheye/image/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/camera
apollo_public_repos/apollo/modules/drivers/camera/conf/camera_right_front.pb.txt
camera_dev: "/dev/camera/right_front" frame_id: "camera_right_front" pixel_format: "yuyv" io_method: IO_METHOD_MMAP width: 1920 height: 1080 frame_rate: 20 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 2 trigger_internal: 0 trigger_fps: 20 channel_name: "/apollo/sensor/camera/right_front/image" device_wait_ms: 2000 spin_rate: 200 output_type: RGB compress_conf { output_channel: "/apollo/sensor/camera/right_front/image/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/camera
apollo_public_repos/apollo/modules/drivers/camera/conf/camera_front_6mm.pb.txt
camera_dev: "/dev/camera/front_6mm" frame_id: "camera_front_6mm" pixel_format: "yuyv" io_method: IO_METHOD_MMAP width: 1920 height: 1080 frame_rate: 20 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 2 trigger_internal: 0 trigger_fps: 20 channel_name: "/apollo/sensor/camera/front_6mm/image" device_wait_ms: 2000 spin_rate: 200 output_type: RGB compress_conf { output_channel: "/apollo/sensor/camera/front_6mm/image/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/camera
apollo_public_repos/apollo/modules/drivers/camera/conf/camera_front_fisheye.pb.txt
camera_dev: "/dev/camera/front_fisheye" frame_id: "camera_front_fisheye" pixel_format: "yuyv" io_method: IO_METHOD_MMAP width: 1920 height: 1080 frame_rate: 20 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 2 trigger_internal: 0 trigger_fps: 20 channel_name: "/apollo/sensor/camera/front_fisheye/image" device_wait_ms: 2000 spin_rate: 200 output_type: RGB compress_conf { output_channel: "/apollo/sensor/camera/front_fisheye/image/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/camera
apollo_public_repos/apollo/modules/drivers/camera/conf/camera_left_rear.pb.txt
camera_dev: "/dev/camera/left_rear" frame_id: "camera_left_rear" pixel_format: "yuyv" io_method: IO_METHOD_MMAP width: 1920 height: 1080 frame_rate: 20 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 2 trigger_internal: 0 trigger_fps: 20 channel_name: "/apollo/sensor/camera/left_rear/image" device_wait_ms: 2000 spin_rate: 200 output_type: RGB compress_conf { output_channel: "/apollo/sensor/camera/left_rear/image/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers/camera
apollo_public_repos/apollo/modules/drivers/camera/conf/camera_front_12mm.pb.txt
camera_dev: "/dev/camera/front_12mm" frame_id: "camera_front_12mm" pixel_format: "yuyv" io_method: IO_METHOD_MMAP width: 1920 height: 1080 frame_rate: 20 monochrome: false brightness: -1 contrast: -1 saturation: -1 sharpness: -1 gain: -1 auto_focus: false focus: -1 auto_exposure: true exposure: 100 auto_white_balance: true white_balance: 4000 bytes_per_pixel: 2 trigger_internal: 0 trigger_fps: 20 channel_name: "/apollo/sensor/camera/front_12mm/image" device_wait_ms: 2000 spin_rate: 200 output_type: RGB compress_conf { output_channel: "/apollo/sensor/camera/front_12mm/image/compressed" image_pool_size: 100 }
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/lidar/lidar_driver_component.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. *****************************************************************************/ #include "modules/drivers/lidar/lidar_driver_component.h" #include "modules/drivers/lidar/proto/lidar_parameter.pb.h" namespace apollo { namespace drivers { namespace lidar { LidarDriverComponent::LidarDriverComponent() {} bool LidarDriverComponent::Init() { if (!GetProtoConfig(&conf_)) { AERROR << "load config error, file:" << config_file_path_; return false; } node_ = apollo::cyber::CreateNode("drivers_lidar"); AINFO << "conf:" << conf_.DebugString(); LidarDriverFactory::Instance()->RegisterLidarClients(); driver_ = LidarDriverFactory::Instance()->CreateLidarDriver(node_, conf_); if (driver_ == nullptr || !driver_->Init()) { AERROR << "driver init error"; return false; } return true; } } // namespace lidar } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/lidar/lidar_driver_component.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. *****************************************************************************/ #pragma once #include <memory> #include "modules/drivers/lidar/proto/config.pb.h" #include "cyber/cyber.h" #include "modules/drivers/lidar/common/driver_factory/lidar_driver_factory.h" namespace apollo { namespace drivers { namespace lidar { class LidarDriverComponent : public ::apollo::cyber::Component<> { public: LidarDriverComponent(); ~LidarDriverComponent() {} bool Init() override; private: std::shared_ptr<LidarDriverFactory> lidar_factory_; apollo::drivers::lidar::config conf_; std::shared_ptr<::apollo::cyber::Node> node_; std::unique_ptr<LidarDriver> driver_; }; CYBER_REGISTER_COMPONENT(LidarDriverComponent) } // namespace lidar } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers
apollo_public_repos/apollo/modules/drivers/lidar/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") load("//tools/install:install.bzl", "install") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) install( name = "install", data_dest = "drivers/addition_data/lidar", library_dest = "drivers/lib/lidar", data = [ ":runtime_data", ], targets = [ "liblidar_driver_component.so", ], deps = [ "//modules/drivers/lidar/hesai:install", "//modules/drivers/lidar/robosense:install", "//modules/drivers/lidar/velodyne:install", "//modules/drivers/lidar/lslidar:install", ] ) filegroup( name = "runtime_data", srcs = glob([ "conf/*.txt", "conf/*.conf", "dag/*.dag", "launch/*.launch", ]), ) cc_library( name = "lidar_driver_component_lib", srcs = ["lidar_driver_component.cc"], hdrs = ["lidar_driver_component.h"], alwayslink = True, deps = [ "//cyber", "//modules/drivers/lidar/common/driver_factory:lidar_driver_factory", "//modules/drivers/lidar/proto:config_cc_proto", ], ) cc_binary( name = "liblidar_driver_component.so", linkshared = True, linkstatic = True, deps = [":lidar_driver_component_lib"], ) cpplint()
0
apollo_public_repos/apollo/modules/drivers/lidar
apollo_public_repos/apollo/modules/drivers/lidar/robosense/CHANGELOG.md
# Changelog ## v1.0.0 - 2020-07-28 ### Added - LiDAR Driver on Apollo platform - Add RS16, RS32, RS128, RSBP support ## 2022-11-09 ### change to a new version robosense driver by neolix - support rs16 rs-helios-16
0
apollo_public_repos/apollo/modules/drivers/lidar
apollo_public_repos/apollo/modules/drivers/lidar/robosense/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") load("//tools/install:install.bzl", "install") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) install( name = "install", data = [ ":runtime_data", ], data_dest = "drivers/addition_data/lidar/robosense", library_dest = "drivers/lib/lidar/robosense", targets = [ "libsuteng_driver_component.so", ], ) filegroup( name = "runtime_data", srcs = glob([ "conf/*.txt", "conf/*.conf", "dag/*.dag", "launch/*.launch", "params/**", ]), ) cc_binary( name = "libsuteng_driver_component.so", linkshared = True, linkstatic = True, deps = [":driver"], ) cc_library( name = "driver", srcs = glob( ["**/*.cpp"], ), hdrs = glob( ["**/*.h"], ), copts = ['-DMODULE_NAME=\\"suteng\\"'], deps = [ "//cyber", "//modules/common/util", "//modules/common_msgs/sensor_msgs:pointcloud_cc_proto", "//modules/drivers/lidar/robosense/proto:sensor_suteng_cc_proto", "@com_github_jbeder_yaml_cpp//:yaml-cpp", "@eigen", "@local_config_pcl//:pcl", ], alwayslink = True, ) cpplint()
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/proto/sensor_suteng.proto
syntax = "proto2"; package apollo.drivers.suteng; import "modules/common_msgs/basic_msgs/header.proto"; enum Model { UNKOWN = 0; HDL64E_S3S = 1; HDL64E_S3D = 2; HDL64E_S2 = 3; HDL32E = 4; VLP16 = 5; HELIOS_16P = 6; } enum Mode { STRONGEST = 1; LAST = 2; DUAL = 3; } message SutengPacket { optional uint64 stamp = 1; required bytes data = 2; } message SutengScan { optional apollo.common.Header header = 1; required Model model = 2; // Suteng device model required Mode mode = 3; // Suteng work mode repeated SutengPacket firing_pkts = 4; // for HDL32 and VLP16 repeated SutengPacket positioning_pkts = 5; // Suteng device serial number, corresponds to a specific calibration file optional string sn = 6; required uint64 basetime = 7 [default = 0]; optional float temperature = 8; }
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/proto/lidars_filter_config.proto
syntax = "proto2"; package apollo.drivers.suteng; // Vehicle parameters shared among several modules. // By default, all are measured with the SI units (meters, meters per second, // etc.). message Lidar { // Car center point is car reference point, i.e., center of rear axle. required string frame_id = 1; required int32 grading = 2; repeated string point = 3; } message LidarsFilter { repeated Lidar lidar = 1; }
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/proto/sensor_suteng_conf.proto
syntax = "proto2"; package apollo.drivers.suteng; import "modules/drivers/lidar/robosense/proto/sensor_suteng.proto"; message SutengConfig { required string frame_id = 1; required Model model = 2; required Mode mode = 3; optional string pcap_file = 4; optional int32 npackets = 5; required float rpm = 6; required bool use_gps_time = 7 [default = true]; required int32 time_zone = 8 [default = 8]; required uint32 firing_data_port = 9; optional uint32 positioning_data_port = 10; required float max_range = 11; required float min_range = 12; optional float max_angle = 13; optional float min_angle = 14; optional float view_direction = 15; optional float view_width = 16; required string calibration_file = 17; required bool organized = 18 [default = false]; optional string target_frame_id = 19; optional bool main_frame = 20 [default = false]; optional string vehicle_config_path = 21; optional string accurate_vehicle_config_path = 22; optional string lidars_filter_config_path = 23; optional string lidar_extrinsic_file_path = 24; required string scan_channel = 25; required string pc_channel = 26; optional string fusion_channel = 27; optional string compensator_channel = 28; }
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/proto/BUILD
load("@rules_proto//proto:defs.bzl", "proto_library") load("@rules_cc//cc:defs.bzl", "cc_proto_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_proto_library( name = "sensor_suteng_cc_proto", deps = [ ":sensor_suteng_conf_proto_lib", ], ) proto_library( name = "sensor_suteng_conf_proto_lib", srcs = [ "lidars_filter_config.proto", "sensor_suteng_conf.proto", ], deps = [ ":sensor_suteng_proto_lib", ], ) proto_library( name = "sensor_suteng_proto_lib", srcs = [ "sensor_suteng.proto", ], deps = [ "//modules/common_msgs/basic_msgs:header_proto", ], ) cpplint()
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/driver/driver_factory.h
/****************************************************************************** * Copyright 2021 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. *****************************************************************************/ #pragma once #include "modules/drivers/lidar/robosense/driver/driver.h" #include "modules/drivers/lidar/robosense/driver/driver16p.h" namespace apollo { namespace drivers { namespace robosense { class RobosenseDriverFactory { public: static RobosenseDriver* create_driver( const apollo::drivers::suteng::SutengConfig& robo_config); }; } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/driver/driver.h
/****************************************************************************** * Copyright 2021 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. *****************************************************************************/ #pragma once #include <memory> #include <string> #include "modules/drivers/lidar/robosense/proto/sensor_suteng.pb.h" #include "modules/drivers/lidar/robosense/proto/sensor_suteng_conf.pb.h" #include "modules/drivers/lidar/robosense/lib/data_type.h" #include "modules/drivers/lidar/robosense/lib/pcap_input.h" #include "modules/drivers/lidar/robosense/lib/socket_input.h" #include "modules/drivers/lidar/robosense/lib/socket_input_16p.h" namespace apollo { namespace drivers { namespace robosense { class RobosenseDriver { public: RobosenseDriver(); virtual ~RobosenseDriver() {} virtual bool poll( const std::shared_ptr<apollo::drivers::suteng::SutengScan>& scan) { return true; } virtual void init() = 0; uint64_t start_time() { return start_time_; } protected: apollo::drivers::suteng::SutengConfig config_; std::shared_ptr<Input> input_; bool flags = false; uint64_t basetime_; uint32_t last_gps_time_; uint64_t start_time_; int poll_standard( const std::shared_ptr<apollo::drivers::suteng::SutengScan>& scan); int poll_sync_count( const std::shared_ptr<apollo::drivers::suteng::SutengScan>& scan, bool main_frame); uint64_t last_count_; bool set_base_time(); void set_base_time_from_nmea_time(const NMEATimePtr& nmea_time, uint64_t* basetime, bool use_gps_time = false); void update_gps_top_hour(unsigned int current_time); bool cute_angle(apollo::drivers::suteng::SutengPacket* packet); }; class Robosense16Driver : public RobosenseDriver { public: explicit Robosense16Driver( const apollo::drivers::suteng::SutengConfig& robo_config); ~Robosense16Driver(); void init(); bool poll(const std::shared_ptr<apollo::drivers::suteng::SutengScan>& scan); void poll_positioning_packet(); private: std::shared_ptr<Input> positioning_input_; std::thread positioning_thread_; std::atomic<bool> running_ = {true}; }; } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/driver/driver16.cpp
/****************************************************************************** * Copyright 2021 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 <time.h> #include <unistd.h> #include <cmath> #include <memory> #include <string> #include <thread> #include "modules/drivers/lidar/robosense/driver/driver.h" namespace apollo { namespace drivers { namespace robosense { Robosense16Driver::Robosense16Driver( const apollo::drivers::suteng::SutengConfig& robo_config) : RobosenseDriver() { config_ = robo_config; } Robosense16Driver::~Robosense16Driver() { running_.store(false); if (positioning_thread_.joinable()) { positioning_thread_.join(); } } void Robosense16Driver::init() { running_.store(true); double packet_rate = 750; // 840.0; //每秒packet的数目 packet frequency (Hz) // robosense-754 beike v6k-781.25 v6c-833.33 double frequency = (config_.rpm() / 60.0); // 每秒的圈数 expected Hz rate // default number of packets for each scan is a single revolution // (fractions rounded up) config_.set_npackets( ceil(packet_rate / frequency)); // 每frame,即转一圈packet的数目 AINFO << "Time Synchronized is using time of pakcet"; AINFO << "_config.npackets() == " << config_.npackets(); if (config_.has_pcap_file()) { AINFO << "_config.pcap_file(): " << config_.pcap_file(); input_.reset( new robosense::PcapInput(packet_rate, config_.pcap_file(), false)); input_->init(); AINFO << "_config.pcap_file(): " << config_.pcap_file(); positioning_input_.reset(new robosense::PcapInput( packet_rate, config_.accurate_vehicle_config_path(), false)); positioning_input_->init(); AINFO << "driver16-inited----"; } else { input_.reset(new robosense::SocketInput()); input_->init(config_.firing_data_port()); positioning_input_.reset(new robosense::SocketInput()); positioning_input_->init(config_.positioning_data_port()); } positioning_thread_ = std::thread(&Robosense16Driver::poll_positioning_packet, this); } /** poll the device * * @returns true unless end of file reached */ bool Robosense16Driver::poll( const std::shared_ptr<apollo::drivers::suteng::SutengScan>& scan) { int poll_result = SOCKET_TIMEOUT; // Synchronizing all laser radars if (config_.main_frame()) { poll_result = poll_sync_count(scan, true); } else { poll_result = poll_sync_count(scan, false); } if (poll_result == PCAP_FILE_END) { return false; // read the end of pcap file, return false stop poll; } if (poll_result == SOCKET_TIMEOUT || poll_result == RECIEVE_FAIL) { return false; // poll again } if (scan->firing_pkts_size() == 0) { AINFO << "Get a empty scan from port: " << config_.firing_data_port(); return false; } scan->set_model(config_.model()); scan->set_mode(config_.mode()); scan->mutable_header()->set_frame_id(config_.frame_id()); scan->mutable_header()->set_lidar_timestamp( apollo::cyber::Time().Now().ToNanosecond()); scan->set_basetime(basetime_); AINFO << "time: " << apollo::cyber::Time().Now().ToNanosecond(); return true; } /** poll the device * * @returns true unless end of file reached */ void Robosense16Driver::poll_positioning_packet(void) { while (!apollo::cyber::IsShutdown() && running_.load()) { NMEATimePtr nmea_time(new NMEATime); if (!config_.use_gps_time()) { basetime_ = 1; // temp time_t t = time(NULL); struct tm ptm; struct tm* current_time = localtime_r(&t, &ptm); nmea_time->year = current_time->tm_year - 100; nmea_time->mon = current_time->tm_mon + 1; nmea_time->day = current_time->tm_mday; nmea_time->hour = current_time->tm_hour; nmea_time->min = current_time->tm_min; nmea_time->sec = current_time->tm_sec; } else { while (true && running_.load()) { if (positioning_input_ == nullptr) { AERROR << " positioning_input_ uninited."; return; } int rc = positioning_input_->get_positioning_data_packtet(nmea_time); AINFO << "gprmc data rc: " << rc << "---rc is normal when it is 0"; tm pkt_time; memset(&pkt_time, 0, sizeof(pkt_time)); pkt_time.tm_year = nmea_time->year + 100; pkt_time.tm_mon = nmea_time->mon - 1; pkt_time.tm_mday = nmea_time->day; pkt_time.tm_hour = nmea_time->hour + 8; pkt_time.tm_min = nmea_time->min; pkt_time.tm_sec = 0; uint64_t timestamp_sec = static_cast<uint64_t>(mktime(&pkt_time)) * 1e9; uint64_t timestamp_nsec = static_cast<uint64_t>(nmea_time->sec * 1e6 + nmea_time->msec * 1e3 + nmea_time->usec) * 1e3 + timestamp_sec; // ns AINFO << "first POS-GPS-timestamp: [" << timestamp_nsec << "]"; basetime_ = timestamp_nsec; start_time_ = apollo::cyber::Time().Now().ToNanosecond(); AINFO << "first start_time_:[" << start_time_ << "]"; if (rc == 0) { break; // got a full packet } } } if (basetime_) break; // temp } } } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/driver/driver.cpp
/****************************************************************************** * Copyright 2021 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 "modules/drivers/lidar/robosense/driver/driver.h" #include <atomic> #include <cmath> #include <ctime> #include <memory> #include <string> namespace apollo { namespace drivers { namespace robosense { RobosenseDriver::RobosenseDriver() : basetime_(0), last_gps_time_(0), last_count_(0) {} void RobosenseDriver::set_base_time_from_nmea_time(const NMEATimePtr& nmea_time, uint64_t* basetime, bool gps_time) { tm time; memset(&time, 0, sizeof(time)); time.tm_year = nmea_time->year + (2000 - 1900); time.tm_mon = nmea_time->mon - 1; time.tm_mday = nmea_time->day; time.tm_hour = nmea_time->hour; //+ config_.time_zone(); time.tm_min = 0; time.tm_sec = 0; // set last gps time using gps socket packet last_gps_time_ = (nmea_time->min * 60 + nmea_time->sec) * 1e6; AINFO << "Set base unix time : " << time.tm_year << "-" << time.tm_mon << "-" << time.tm_mday << " " << time.tm_hour << ":" << time.tm_min << ":" << time.tm_sec; uint64_t unix_base = 0; if (!gps_time) { AINFO << "local time--------------------------"; unix_base = static_cast<uint64_t>(mktime(&time)); } else { AINFO << "gps time---------------------------"; unix_base = static_cast<uint64_t>(timegm(&time)); } *basetime = unix_base; //* static_cast<uint64_t>(1e6); } bool RobosenseDriver::set_base_time() { NMEATimePtr nmea_time(new NMEATime); if (config_.use_gps_time()) { while (true) { int rc = input_->get_positioning_data_packtet(nmea_time); if (rc == 0) { break; // got a full packet } if (rc < 0) { return false; // end of file reached } } } else { time_t t = time(NULL); struct tm ptm; struct tm* current_time = localtime_r(&t, &ptm); nmea_time->year = current_time->tm_year - 100; nmea_time->mon = current_time->tm_mon + 1; nmea_time->day = current_time->tm_mday; nmea_time->hour = current_time->tm_hour; nmea_time->min = current_time->tm_min; nmea_time->sec = current_time->tm_sec; } set_base_time_from_nmea_time(nmea_time, &basetime_); input_->init(config_.firing_data_port()); return true; } int RobosenseDriver::poll_standard( const std::shared_ptr<apollo::drivers::suteng::SutengScan>& scan) { // Since the suteng delivers data at a very high rate, keep // reading and publishing scans as fast as possible. for (int32_t i = 0; i < config_.npackets(); ++i) { while (true) { apollo::drivers::suteng::SutengPacket* packet; // keep reading until full packet received packet = scan->add_firing_pkts(); int rc = input_->get_firing_data_packet(packet, i, start_time_); if (rc == 0) { break; // got a full packet? } if (rc < 0) { return rc; } } } return 0; } int RobosenseDriver::poll_sync_count( const std::shared_ptr<apollo::drivers::suteng::SutengScan>& scan, bool main_frame) { static std::atomic_ullong sync_counter(0); int time_zone = config_.time_zone(); // apollo::drivers::suteng::SutengPacket* tmp_packet; if (main_frame) { for (int32_t i = 0; i < config_.npackets(); ++i) { while (true) { apollo::drivers::suteng::SutengPacket* packet; // keep reading until full packet received packet = scan->add_firing_pkts(); int rc = input_->get_firing_data_packet(packet, time_zone, start_time_); // tmp_packet = packet; if (rc == 0) { break; // got a full packet? } if (rc < 0) { return rc; } } } sync_counter++; } else { int pk_i = 0; while (scan->firing_pkts_size() < config_.npackets()) { while (true) { apollo::drivers::suteng::SutengPacket* packet; // keep reading until full packet received packet = scan->add_firing_pkts(); int rc = input_->get_firing_data_packet(packet, time_zone, start_time_); pk_i++; if (rc == 0) { break; } if (rc < 0) { return rc; } } } last_count_ = sync_counter; } return 0; } static int ANGLE_HEAD = -36001; // note: cannot be set to -1, or stack smashing static int last_azimuth = ANGLE_HEAD; bool RobosenseDriver::cute_angle( apollo::drivers::suteng::SutengPacket* packet) { int azimuth = 256 * packet->data().c_str()[44] + packet->data().c_str()[45]; if (azimuth < last_azimuth) { last_azimuth -= 36000; } // Check if currently passing cut angle if (last_azimuth != ANGLE_HEAD && last_azimuth < 1 && azimuth >= 1) { last_azimuth = azimuth; return false; // Cut angle passed, one full revolution collected } last_azimuth = azimuth; return true; } void RobosenseDriver::update_gps_top_hour(uint32_t current_time) { if (!flags) { AINFO << "init current_time:" << current_time << ", last_gps_time:" << last_gps_time_; flags = true; } if (last_gps_time_ == 0) { last_gps_time_ = current_time; return; } if (last_gps_time_ > current_time) { if (std::fabs(last_gps_time_ - current_time) > 3599000000) { basetime_ += 3600; AINFO << "update_gps_top_hour. current:" << current_time << ", last time:" << last_gps_time_; } } last_gps_time_ = current_time; } } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/driver/driver16p.h
/****************************************************************************** * Copyright 2021 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. *****************************************************************************/ #pragma once #include <time.h> #include <unistd.h> #include <cmath> #include <memory> #include <string> #include <thread> #include "modules/drivers/lidar/robosense/proto/sensor_suteng.pb.h" #include "modules/drivers/lidar/robosense/proto/sensor_suteng_conf.pb.h" #include "modules/drivers/lidar/robosense/driver/driver.h" #include "modules/drivers/lidar/robosense/lib/data_type.h" #include "modules/drivers/lidar/robosense/lib/socket_input_16p.h" namespace apollo { namespace drivers { namespace robosense { class Robosense16PDriver : public RobosenseDriver { public: explicit Robosense16PDriver( const apollo::drivers::suteng::SutengConfig& robo_config); ~Robosense16PDriver(); void init(); bool poll(const std::shared_ptr<apollo::drivers::suteng::SutengScan>& scan); void poll_positioning_packet(); int poll_msop_sync_count( const std::shared_ptr<apollo::drivers::suteng::SutengScan>& scan); private: std::shared_ptr<SocketInput16P> positioning_input_; std::shared_ptr<SocketInput16P> input_16p_; std::thread positioning_thread_; std::atomic<bool> running_ = {true}; apollo::drivers::suteng::SutengPacket positioning_pkts_; // 1hz }; } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/driver/driver_factory.cpp
/****************************************************************************** * Copyright 2021 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 "modules/drivers/lidar/robosense/driver/driver_factory.h" namespace apollo { namespace drivers { namespace robosense { RobosenseDriver* RobosenseDriverFactory::create_driver( const apollo::drivers::suteng::SutengConfig& roboconfig_) { if (roboconfig_.model() == apollo::drivers::suteng::Model::VLP16) { return new Robosense16Driver(roboconfig_); } else if (roboconfig_.model() == apollo::drivers::suteng::Model::HELIOS_16P) { AINFO << "RobosenseDriverFactory HELIOS_16P 1"; return new Robosense16PDriver(roboconfig_); } else { AERROR << "Invalid lidar model, must be VLP16 or HELIOS_16P"; return nullptr; } } } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/driver/driver16p.cpp
/****************************************************************************** * Copyright 2021 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 "modules/drivers/lidar/robosense/driver/driver16p.h" namespace apollo { namespace drivers { namespace robosense { Robosense16PDriver::Robosense16PDriver( const apollo::drivers::suteng::SutengConfig& robo_config) : RobosenseDriver() { AINFO << "Robosense16PDriver HELIOS_16P 0"; config_ = robo_config; } Robosense16PDriver::~Robosense16PDriver() { running_.store(false); if (positioning_thread_.joinable()) { positioning_thread_.join(); } } void Robosense16PDriver::init() { running_.store(true); double packet_rate = 750; // 840.0; //每秒packet的数目 packet frequency (Hz) // robosense-754 beike v6k-781.25 v6c-833.33 double frequency = (config_.rpm() / 60.0); // 每秒的圈数 expected Hz rate AINFO << "Robosense16PDriver HELIOS_16P 1"; // default number of packets for each scan is a single revolution // (fractions rounded up) config_.set_npackets( ceil(packet_rate / frequency)); // 每frame,即转一圈packet的数目 AINFO << "Time Synchronized is using time of pakcet"; AINFO << "_config.npackets() == " << config_.npackets(); if (config_.has_pcap_file()) { AWARN << "Helios 16P does not support pcap_file. Using Socket instead."; } input_16p_.reset(new robosense::SocketInput16P()); input_16p_->init(config_.firing_data_port()); positioning_input_.reset(new robosense::SocketInput16P()); positioning_input_->init(config_.positioning_data_port()); positioning_thread_ = std::thread(&Robosense16PDriver::poll_positioning_packet, this); } /** poll the device * * @returns true unless end of file reached */ bool Robosense16PDriver::poll( const std::shared_ptr<apollo::drivers::suteng::SutengScan>& scan) { int poll_result = SOCKET_TIMEOUT; auto t0 = apollo::cyber::Time().Now().ToNanosecond(); // Synchronizing all laser radars poll_result = poll_msop_sync_count(scan); AINFO << "poll time: " << apollo::cyber::Time().Now().ToNanosecond() << " cost: " << (apollo::cyber::Time().Now().ToNanosecond() - t0) * 1e-6 << "ms"; if (poll_result == PCAP_FILE_END) { return false; // read the end of pcap file, return false stop poll; } if (poll_result == SOCKET_TIMEOUT || poll_result == RECIEVE_FAIL) { return false; // poll again } if (scan->firing_pkts_size() == 0) { AINFO << "Get an empty scan from port: " << config_.firing_data_port(); return false; } scan->set_model(config_.model()); scan->set_mode(config_.mode()); scan->mutable_header()->set_frame_id(config_.frame_id()); scan->mutable_header()->set_lidar_timestamp(basetime_); if (positioning_pkts_.IsInitialized()) { auto pkt = scan->add_positioning_pkts(); pkt->CopyFrom(positioning_pkts_); } scan->set_basetime(basetime_); return true; } int Robosense16PDriver::poll_msop_sync_count( const std::shared_ptr<apollo::drivers::suteng::SutengScan>& scan) { static std::atomic_ullong sync_counter(0); if (config_.main_frame()) { for (int32_t i = 0; i < config_.npackets(); ++i) { while (true) { apollo::drivers::suteng::SutengPacket* packet; // keep reading until full packet received packet = scan->add_firing_pkts(); int rc = input_16p_->get_firing_data_packet(packet, config_.use_gps_time()); // tmp_packet = packet; if (rc == 0) { break; // got a full packet? } if (rc < 0) { return rc; } } } sync_counter++; } else { int pk_i = 0; while (scan->firing_pkts_size() < config_.npackets()) { while (true) { apollo::drivers::suteng::SutengPacket* packet; // keep reading until full packet received packet = scan->add_firing_pkts(); int rc = input_16p_->get_firing_data_packet(packet, config_.use_gps_time()); pk_i++; if (rc == 0) { break; } if (rc < 0) { return rc; } } } last_count_ = sync_counter; } return 0; } /** poll the device * * @returns true unless end of file reached */ void Robosense16PDriver::poll_positioning_packet(void) { while (!apollo::cyber::IsShutdown() && running_.load()) { if (positioning_input_ == nullptr) { AERROR << " positioning_input_ uninited."; return; } int rc = positioning_input_->get_positioning_data_packet( &positioning_pkts_, config_.use_gps_time()); AINFO << "Difop data rc: " << rc << "---rc is normal when it is 0"; } } } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/launch/lidar_robosense_three.launch
<cyber> <desc>cyber driver robosense</desc> <version>1.0.0</version> <module> <name>driver_lidar_robosense</name> <dag_conf>/apollo/modules/drivers/lidar/robosense/dag/dag_driver_robo.dag</dag_conf> <process_name>dag_driver_robo_three</process_name> <version>1.0.0</version> </module> </cyber>
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/launch/lidar_robosense_one.launch
<!--this file list the modules which will be loaded dynamicly and their process name to be running in --> <cyber> <module> <name>lidar_suteng16</name> <dag_conf>/apollo/modules/drivers/lidar/robosense/dag/dag_driver_robo_one.dag</dag_conf> <process_name>cyber_suteng</process_name> <version>1.0.0</version> </module> </cyber>
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/dag/dag_driver_robo_one.dag
# Define all coms in DAG streaming. module_config { module_library : "/apollo/bazel-bin/modules/drivers/lidar/robosense/libsuteng_driver_component.so" ################################################## # drivers # ################################################## components { class_name : "CompRoboDriver" config { name : "robo_back_driver" config_file_path : "/apollo/modules/drivers/lidar/robosense/conf/lidar16_back.conf" } } ################################################## # convert # ################################################## components { class_name : "CompRoboConvert" config { name : "robo_back_convert" config_file_path : "/apollo/modules/drivers/lidar/robosense/conf/lidar16_back.conf" readers { channel: "/apollo/sensor/lidar16/back/Scan" } } } } ################################################## # compensation # ################################################## module_config { module_library : "/apollo/bazel-bin/modules/drivers/lidar/velodyne/compensator/libvelodyne_compensator_component.so" components { class_name : "CompensatorComponent" config { name : "robosense16_fusion_compensator" config_file_path : "/apollo/modules/drivers/lidar/robosense/conf/back_compensator.pb.txt" readers {channel: "/apollo/sensor/lidar16/back/PointCloud2"} } } }
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/dag/dag_driver_robo.dag
# Define all coms in DAG streaming. module_config { module_library : "/apollo/bazel-bin/modules/drivers/lidar/robosense/libsuteng_driver_component.so" ################################################## # drivers # ################################################## components { class_name : "CompRoboDriver" config { name : "robo_left_driver" config_file_path : "/apollo/modules/drivers/lidar/conf/lidar16_left.conf" } } components { class_name : "CompRoboDriver" config { name : "robo_right_driver" config_file_path : "/apollo/modules/drivers/lidar/conf/lidar16_right.conf" } } components { class_name : "CompRoboDriver" config { name : "robo_back_driver" config_file_path : "/apollo/modules/drivers/lidar/conf/lidar16_back.conf" } } ################################################## # convert # ################################################## components { class_name : "CompRoboConvert" config { name : "robo_left_convert" config_file_path : "/apollo/modules/drivers/lidar/conf/lidar16_left.conf" readers { #channel: "/sensor/lidar16/left/SutengScan" channel: "/apollo/sensor/lidar16/left/Scan" } } } components { class_name : "CompRoboConvert" config { name : "robo_right_convert" config_file_path : "/apollo/modules/drivers/lidar/conf/lidar16_right.conf" readers { #channel: "/sensor/suteng16/right/SutengScan" channel: "/apollo/sensor/lidar16/right/Scan" } } } components { class_name : "CompRoboConvert" config { name : "robo_back_convert" config_file_path : "/apollo/modules/drivers/lidar/conf/lidar16_back.conf" readers { #channel: "/sensor/suteng16/back/SutengScan" channel: "/apollo/sensor/lidar16/right/Scan" } } } } ################################################## # fusion # ################################################## module_config { module_library : "/apollo/bazel-bin/modules/drivers/lidar/robosense/fusion/librobosense_fusion_component.so" components { class_name : "PriSecFusionComponent" config { name : "robosense_fusion" config_file_path : "/apollo/modules/drivers/lidar/conf/robo_fusion_conf.pb.txt" readers {channel: "/apollo/sensor/lidar16/back/PointCloud2"} } } } ################################################## # compensation # ################################################## module_config { module_library : "/apollo/bazel-bin/modules/drivers/lidar/robosense/compensator/librobosense_compensator_component.so" components { class_name : "CompensatorComponent" config { name : "robosense16_fusion_compensator" config_file_path : "/apollo/modules/drivers/lidar/conf/lidar_robo_fusion_compensator.pb.txt" readers {channel: "/apollo/sensor/lidar16/fusion/PointCloud2"} } } }
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/dag/driver.dag
# Define all coms in DAG streaming. module_config { module_library : "/apollo/bazel-bin/modules/drivers/lidar/robosense/libsuteng_driver_component.so" ################################################## # drivers # ################################################## components { class_name : "CompRoboDriver" config { name : "robo_back_driver" config_file_path : "/apollo/modules/drivers/lidar/robosense/conf/lidar16_back.conf" } } }
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/dag/compensator.dag
# Define all coms in DAG streaming. ################################################## # compensation # ################################################## module_config { module_library : "/apollo/bazel-bin/modules/drivers/lidar/robosense/compensator/librobosense_compensator_component.so" components { class_name : "CompensatorComponent" config { name : "robosense16_fusion_compensator" config_file_path : "/apollo/modules/drivers/lidar/robosense/conf/back_compensator.pb.txt" readers {channel: "/apollo/sensor/lidar16/back/PointCloud2"} } } }
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/dag/convert.dag
# Define all coms in DAG streaming. module_config { module_library : "/apollo/bazel-bin/modules/drivers/lidar/robosense/libsuteng_driver_component.so" ################################################## # convert # ################################################## components { class_name : "CompRoboConvert" config { name : "robo_back_convert" config_file_path : "/apollo/modules/drivers/lidar/robosense/conf/lidar16_back.conf" readers { channel: "/apollo/sensor/lidar16/back/Scan" } } } }
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/component/component.cpp
/****************************************************************************** * Copyright 2021 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 "modules/drivers/lidar/robosense/component/component_convert.h" #include "modules/drivers/lidar/robosense/component/component_driver.h"
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/component/component_driver.h
/****************************************************************************** * Copyright 2021 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. *****************************************************************************/ #pragma once #include <memory> #include <string> #include <thread> #include "modules/drivers/lidar/robosense/proto/sensor_suteng.pb.h" #include "cyber/cyber.h" #include "modules/drivers/lidar/robosense/driver/driver.h" #include "modules/drivers/lidar/robosense/driver/driver_factory.h" namespace apollo { namespace drivers { namespace robosense { using apollo::cyber::Component; class CompRoboDriver : public Component<> { public: ~CompRoboDriver() { if (device_thread_->joinable()) { device_thread_->join(); } } bool Init() { // read config file apollo::drivers::suteng::SutengConfig config; if (!apollo::cyber::common::GetProtoFromFile(config_file_path_, &config)) { AERROR << "Failed to load config file"; return false; } AINFO << "config:" << config.DebugString(); // set default main frame if (!config.has_main_frame() && config.frame_id() == "robosense16_back") { config.set_main_frame(true); } RobosenseDriver *driver = robosense::RobosenseDriverFactory::create_driver(config); if (driver == nullptr) { return false; } writer_ = node_->CreateWriter<apollo::drivers::suteng::SutengScan>( config.scan_channel()); driver_.reset(driver); driver_->init(); // spawn device poll thread runing_ = true; device_thread_ = std::shared_ptr<std::thread>( new std::thread(std::bind(&CompRoboDriver::device_poll, this))); AINFO << "CompRoboDriver Init SUCC" << ", frame_id:" << config.frame_id(); return true; } private: void device_poll() { while (!apollo::cyber::IsShutdown()) { std::shared_ptr<apollo::drivers::suteng::SutengScan> scan( new apollo::drivers::suteng::SutengScan); if (driver_->poll(scan)) { writer_->Write(scan); } else { AWARN << "device poll failed"; } } AERROR << "CompRobosenseDriver thread exit"; runing_ = false; } // variable std::shared_ptr<RobosenseDriver> driver_; volatile bool runing_; ///< device thread is running uint32_t seq_ = 0; std::shared_ptr<std::thread> device_thread_; std::shared_ptr<apollo::cyber::Writer<apollo::drivers::suteng::SutengScan>> writer_; }; CYBER_REGISTER_COMPONENT(CompRoboDriver); } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/component/component_convert.h
/****************************************************************************** * Copyright 2021 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. *****************************************************************************/ #pragma once #include <deque> #include <memory> #include <string> #include <thread> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include "modules/common_msgs/sensor_msgs/pointcloud.pb.h" #include "modules/drivers/lidar/robosense/proto/sensor_suteng.pb.h" #include "cyber/cyber.h" #include "modules/drivers/lidar/robosense/parser/convert.h" namespace apollo { namespace drivers { namespace robosense { using apollo::cyber::Component; class CompRoboConvert : public Component<apollo::drivers::suteng::SutengScan> { public: bool Init() { // read config file apollo::drivers::suteng::SutengConfig config; if (!apollo::cyber::common::GetProtoFromFile(config_file_path_, &config)) { AERROR << "Failed to load config file"; return false; } AINFO << "config:" << config.DebugString(); conv_.reset(new Convert(config)); if (!conv_->Init()) { return false; } writer_ = node_->CreateWriter<apollo::drivers::PointCloud>(config.pc_channel()); uint32_t point_size = 28800; // 32256; AINFO << "pc fixed size:" << point_size; point_cloud_deque_.resize(size_); for (uint i = 0; i < size_; ++i) { point_cloud_deque_[i] = std::make_shared<apollo::drivers::PointCloud>(); if (point_cloud_deque_[i] == nullptr) { AERROR << " fail to make shared"; return false; } point_cloud_deque_[i]->mutable_point()->Reserve(point_size); } AINFO << "CompRoboConvert Init SUCC" << ", frame_id:" << config.frame_id(); return true; } bool Proc(const std::shared_ptr<apollo::drivers::suteng::SutengScan>& scan) { uint64_t start = apollo::cyber::Time().Now().ToNanosecond(); if (index_ >= size_) { index_ = 0; } auto point_cloud_send = point_cloud_deque_.at(index_++); if (point_cloud_send == nullptr) { AINFO << "null point cloud"; return false; } // just clear header now, we will reset all other value in pb. point_cloud_send->mutable_header()->Clear(); point_cloud_send->Clear(); conv_->convert_robosense_to_pointcloud(scan, point_cloud_send); if (point_cloud_send == nullptr || point_cloud_send->point_size() == 0) { AINFO << "discard null point cloud"; return false; } uint64_t diff = apollo::cyber::Time().Now().ToNanosecond() - start; point_cloud_send->mutable_header()->set_sequence_num(seq_); writer_->Write(point_cloud_send); if (seq_ % 10 == 0) { AINFO << " total:" << seq_ + 1 << "-RS-cost:" << diff * 1e-9 << "ms -meta:" << point_cloud_send->header().lidar_timestamp(); } seq_++; return true; } private: std::unique_ptr<Convert> conv_ = nullptr; std::deque<std::shared_ptr<apollo::drivers::PointCloud>> point_cloud_deque_; uint64_t index_ = 0; uint64_t seq_ = 0; uint64_t size_ = 8; std::shared_ptr<apollo::cyber::Writer<apollo::drivers::PointCloud>> writer_; }; CYBER_REGISTER_COMPONENT(CompRoboConvert); } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/parser/robosense16p_parser.cpp
/****************************************************************************** * Copyright 2021 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 "modules/drivers/lidar/robosense/parser/robosense16p_parser.h" #include <fstream> #include <memory> #include <string> #include <pcl/common/time.h> #include "cyber/cyber.h" namespace apollo { namespace drivers { namespace robosense { Robosense16PParser::Robosense16PParser( const apollo::drivers::suteng::SutengConfig& config) : RobosenseParser(config) {} void Robosense16PParser::setup() { RobosenseParser::setup(); init_params(); } void Robosense16PParser::init_params() {} bool Robosense16PParser::pkt_start = true; uint64_t Robosense16PParser::base_stamp = 0; void Robosense16PParser::generate_pointcloud( const std::shared_ptr<apollo::drivers::suteng::SutengScan const>& scan_msg, const std::shared_ptr<apollo::drivers::PointCloud>& out_msg) { out_msg->mutable_header()->set_frame_id(scan_msg->header().frame_id()); out_msg->mutable_header()->set_lidar_timestamp( scan_msg->header().lidar_timestamp()); out_msg->mutable_header()->set_timestamp_sec( apollo::cyber::Time().Now().ToSecond()); out_msg->set_height(1); point_index_ = 0; uint32_t nan_pts = 0; for (int i = 0; i < scan_msg->positioning_pkts_size(); ++i) { unpack_params(scan_msg->positioning_pkts(i)); } for (int i = 0; i < scan_msg->firing_pkts_size(); ++i) { // 75pkts unpack_robosense(scan_msg->firing_pkts(i), out_msg, &nan_pts); last_time_stamp_ = out_msg->header().timestamp_sec(); } if (out_msg->point_size() == 0) { // we discard this pointcloud if empty AERROR << " All points is NAN!Please check suteng:" << config_.model(); } else { uint64_t timestamp = out_msg->point(point_index_ - 1).timestamp(); double d_time = apollo::cyber::Time(timestamp).ToSecond(); out_msg->set_height(point_index_ / SCANS_PER_FIRING); out_msg->set_width(SCANS_PER_FIRING); out_msg->set_is_dense(false); out_msg->set_measurement_time(d_time); out_msg->mutable_header()->set_lidar_timestamp(d_time * 1e9); out_msg->mutable_header()->set_timestamp_sec( apollo::cyber::Time().Now().ToSecond()); } } float Robosense16PParser::parse_angle(angle_16p_t angle_pkt) { float angle; int32_t v; if (angle_pkt.sign == 0xFF) { AERROR << "Get err in angle sign"; return 0.0f; } v = ntohs(angle_pkt.value); if (angle_pkt.sign != 0) v = -v; angle = static_cast<float>(v * DEGREE_TO_RADIAN); return angle; } void Robosense16PParser::unpack_params( const apollo::drivers::suteng::SutengPacket& pkt) { if (last_difop_time_ < pkt.stamp()) { last_difop_time_ = pkt.stamp(); vertical_angles_16p_t* verti_angles = reinterpret_cast<vertical_angles_16p_t*>( const_cast<char*>(&pkt.data().c_str()[468])); horizontal_angles_16p_t* hori_angles = reinterpret_cast<horizontal_angles_16p_t*>( const_cast<char*>(&pkt.data().c_str()[564])); for (int i = 0; i < SCANS_PER_FIRING; i++) { SUTENG_VERT_16P_[i] = parse_angle(verti_angles->angles[i]); cor_hori_angles[i] = parse_angle(hori_angles->angles[i]); } } } void Robosense16PParser::unpack_robosense( const apollo::drivers::suteng::SutengPacket& pkt, const std::shared_ptr<apollo::drivers::PointCloud>& cloud, uint32_t* nan_pts) { float azimuth = 0.f; // 0.01degree float intensity = 0.f; float distance = 0.f; float azimuth_diff = 0.f; float azimuth_corrected_f = 0.f; int azimuth_corrected = 0; uint64_t pkt_stamp = pkt.stamp(); const raw_packet_16p_t* raw = (const raw_packet_16p_t*)&pkt.data().c_str()[42]; for (int block = 0; block < BLOCKS_PER_PACKET; ++block) { if (UPPER_BANK != raw->blocks[block].header) { AINFO << "skipping Suteng_liar DIFOP packet!" << raw->blocks[block].header; break; } azimuth = static_cast<float>(ntohs(raw->blocks[block].rotation)); if (block < (BLOCKS_PER_PACKET - 1)) { int azi1, azi2; azi1 = ntohs(raw->blocks[block + 1].rotation); azi2 = ntohs(raw->blocks[block].rotation); azimuth_diff = static_cast<float>((36000 + azi1 - azi2) % 36000); if (azimuth_diff <= 0.0 || azimuth_diff > 75.0) { continue; } } else { // the last two blocks in packet int azi1, azi2; azi1 = ntohs(raw->blocks[block].rotation); azi2 = ntohs(raw->blocks[block - 1].rotation); azimuth_diff = static_cast<float>((36000 + azi1 - azi2) % 36000); if (azimuth_diff <= 0.0 || azimuth_diff > 75.0) { continue; } } for (int firing = 0; firing < FIRINGS_PER_BLOCK; firing++) { for (int dsr = 0; dsr < SCANS_PER_FIRING; dsr++) { int idx = firing * SCANS_PER_FIRING + dsr; azimuth_corrected_f = azimuth + azimuth_diff * (TIME_OFFSET_16P[idx][block] - TIME_OFFSET_16P[0][block]) / TIME_OFFSET_16P[0][1]; azimuth_corrected = (static_cast<int>(round(azimuth_corrected_f))) % 36000; // convert to integral distance = ntohs(raw->blocks[block].channel_data[idx].distance) * DISTANCE_RESOLUTION_16P; // time of each point // block 0-11 firing 0-1 dsr 0-15 uint64_t time_pt = TIME_OFFSET_16P[idx][block]; uint64_t timestamp = pkt_stamp + time_pt * 1e3; if (distance == 0 || distance < config_.min_range() || distance > config_.max_range()) { if (config_.organized()) { apollo::drivers::PointXYZIT* point = cloud->add_point(); point->set_x(nan); point->set_y(nan); point->set_z(nan); point->set_timestamp(timestamp); point->set_intensity(0); ++point_index_; ++nan_pts; } continue; } apollo::drivers::PointXYZIT* point = cloud->add_point(); point->set_timestamp(timestamp); intensity = raw->blocks[block].channel_data[idx].reflectivity; point->set_intensity(intensity); // angle float arg_hori = static_cast<float>(azimuth_corrected * DEGREE_TO_RADIAN); float arg_hori_cor = arg_hori + cor_hori_angles[dsr]; float arg_vert = SUTENG_VERT_16P_[dsr]; float y = static_cast<float>(-distance * cos(arg_vert) * sin(arg_hori_cor) - RX_16P * sin(arg_hori)); float x = static_cast<float>(distance * cos(arg_vert) * cos(arg_hori_cor) + RX_16P * cos(arg_hori)); float z = static_cast<float>(distance * sin(arg_vert)); if (filter_set_.size() > 0) { std::string key = std::to_string(static_cast<float>(x * 100 / filter_grading_)) + "+" + std::to_string(static_cast<float>(y * 100 / filter_grading_)); if (filter_set_.find(key) != filter_set_.end()) { x = NAN; y = NAN; z = NAN; ++nan_pts; } } point->set_x(x); point->set_y(y); point->set_z(z); point->set_intensity(intensity); ++point_index_; } } } } } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/parser/convert.cpp
/****************************************************************************** * Copyright 2021 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 "modules/drivers/lidar/robosense/parser/convert.h" #include <memory> #include <pcl/common/time.h> #include "cyber/cyber.h" namespace apollo { namespace drivers { namespace robosense { /** @brief Constructor. */ Convert::Convert(const apollo::drivers::suteng::SutengConfig& robo_config) { config_ = robo_config; config_.set_view_direction(0.0); config_.set_view_width(2.0 * M_PI); } bool Convert::Init() { parser_ = RobosenseParserFactory::create_parser(config_); if (parser_ == nullptr) { AERROR << " can not create velodyen parser"; return false; } parser_->setup(); return true; } Convert::~Convert() { if (parser_ != nullptr) { delete parser_; } } uint32_t Convert::GetPointSize() { return parser_->GetPointSize(); } /** @brief Callback for raw scan messages. */ void Convert::convert_robosense_to_pointcloud( const std::shared_ptr<apollo::drivers::suteng::SutengScan const>& scan_msg, const std::shared_ptr<apollo::drivers::PointCloud>& point_cloud) { parser_->generate_pointcloud(scan_msg, point_cloud); if (point_cloud == nullptr || point_cloud->point_size() == 0) { AERROR << " point cloud has no point"; return; } } } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/parser/robosense_status.cpp
/****************************************************************************** * Copyright 2021 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 "modules/drivers/lidar/robosense/parser/robosense_status.h" #include <memory> #include <utility> namespace apollo { namespace drivers { namespace robosense { /** @brief Constructor. */ RobosenseStatus::RobosenseStatus() {} void RobosenseStatus::get_status( const std::shared_ptr<apollo::drivers::suteng::SutengScan const> &scan) { status_.clear(); // temp hard code for byte position for (auto &packet : scan->firing_pkts()) { uint8_t status_type = *(reinterpret_cast<uint8_t *>( const_cast<char *>(packet.data().data() + STATUS_TYPE_INDEX))); uint8_t status_value = *(reinterpret_cast<uint8_t *>( const_cast<char *>(packet.data().data() + STATUS_VALUE_INDEX))); status_.emplace_back(std::make_pair(status_type, status_value)); } check_warningbit(); check_motor_speed(); } void RobosenseStatus::check_warningbit() { for (auto &status : status_) { if (status.first == STATUS_WARNING) { warning_bits_ = reinterpret_cast<WarningBits *>(&status.second); ADEBUG << "gps:" << warning_bits_->gps_signal << "clean:" << warning_bits_->lens_ontamination << "hot:" << warning_bits_->unit_hot << "cold:" << warning_bits_->unit_cold; if (warning_bits_->gps_signal == 0) { AINFO << "suteng no gps signal"; } if (warning_bits_->lens_ontamination == 1) { AINFO << "suteng need clean"; } if (warning_bits_->unit_hot == 1) { AINFO << "suteng unit is too hot:>58"; } if (warning_bits_->unit_cold == 1) { AINFO << "suteng unit is too cold:<5"; } break; } } } void RobosenseStatus::check_motor_speed() { int length = status_.size(); for (int i = 0; i < length - 1; ++i) { if (status_[i].first == STATUS_SPEED_LOW && status_[i + 1].first == STATUS_SPEED_HIGH) { motor_speed_.speed_low = status_[i].second; motor_speed_.speed_high = status_[i + 1].second; ADEBUG << "speed:" << motor_speed_.speed; if (motor_speed_.speed < SPEED_TOL) { AINFO << "suteng unit speed is slow:" << motor_speed_.speed << "<" << SPEED_TOL; } break; } } } } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/parser/robosense16_parser.cpp
/****************************************************************************** * Copyright 2021 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 <fstream> #include <memory> #include <string> #include <pcl/common/time.h> #include "cyber/cyber.h" #include "modules/drivers/lidar/robosense/parser/robosense_parser.h" namespace apollo { namespace drivers { namespace robosense { Robosense16Parser::Robosense16Parser( const apollo::drivers::suteng::SutengConfig& config) : RobosenseParser(config), previous_packet_stamp_(0), gps_base_usec_(0) { need_two_pt_correction_ = false; } void Robosense16Parser::setup() { RobosenseParser::setup(); init_orderindex(); init_setup(); } void Robosense16Parser::init_setup() { pic.col = 0; pic.distance.resize(RS16_DATA_NUMBER_PER_SCAN); pic.intensity.resize(RS16_DATA_NUMBER_PER_SCAN); pic.azimuthforeachP.resize(RS16_DATA_NUMBER_PER_SCAN); pic.timestamp.resize(RS16_DATA_NUMBER_PER_SCAN); } void Robosense16Parser::init_orderindex() { for (uint32_t i = 0; i < VLP16_POINT_SIZE; ++i) { order_map_[i] = getOrderIndex(i); } } bool Robosense16Parser::pkt_start = true; uint64_t Robosense16Parser::base_stamp = 0; void Robosense16Parser::generate_pointcloud( const std::shared_ptr<apollo::drivers::suteng::SutengScan const>& scan_msg, const std::shared_ptr<apollo::drivers::PointCloud>& out_msg) { out_msg->mutable_header()->set_frame_id(scan_msg->header().frame_id()); out_msg->mutable_header()->set_lidar_timestamp( apollo::cyber::Time().Now().ToNanosecond()); out_msg->mutable_header()->set_timestamp_sec( apollo::cyber::Time().Now().ToSecond()); out_msg->set_height(1); gps_base_usec_ = scan_msg->basetime(); // * 1000000UL; point_index_ = 0; uint32_t nan_pts = 0; for (int i = 0; i < scan_msg->firing_pkts_size(); ++i) { // 84pkts 0-83 unpack_robosense(scan_msg->firing_pkts(i), out_msg, &nan_pts); last_time_stamp_ = out_msg->header().timestamp_sec(); } if (out_msg->point_size() == 0) { // we discard this pointcloud if empty AERROR << " All points is NAN!Please check suteng:" << config_.model(); } else { uint64_t timestamp = out_msg->point(point_index_ - 1).timestamp(); double d_time = apollo::cyber::Time(timestamp).ToSecond(); out_msg->set_height(point_index_ / RS16_SCANS_PER_FIRING); out_msg->set_width(RS16_SCANS_PER_FIRING); out_msg->set_is_dense(false); out_msg->set_measurement_time(d_time); out_msg->mutable_header()->set_lidar_timestamp(d_time * 1e9); out_msg->mutable_header()->set_timestamp_sec( apollo::cyber::Time().Now().ToSecond()); } } uint64_t Robosense16Parser::get_timestamp(double base_time, float time_offset, uint16_t block_id) { (void)block_id; double t = base_time - time_offset; // 时秒 base_time 0-1h us微妙 time_offset 0-1278.72us uint64_t timestamp = Robosense16Parser::get_gps_stamp( t, &previous_packet_stamp_, &gps_base_usec_); // gps_base_usec_ gps基准时间 精度s return timestamp; } void Robosense16Parser::unpack_robosense( const apollo::drivers::suteng::SutengPacket& pkt, const std::shared_ptr<apollo::drivers::PointCloud>& cloud, uint32_t* nan_pts) { float azimuth = 0.f; // 0.01degree float intensity = 0.f; float azimuth_diff = 0.f; float azimuth_corrected_f = 0.f; int azimuth_corrected = 0; uint64_t pkt_stamp = 0; const raw_packet_t* raw = (const raw_packet_t*)&pkt.data().c_str()[42]; if (pkt_start) { pkt_start = false; base_stamp = gps_base_usec_; AINFO << "base_stamp timestamp: [" << base_stamp << "], which is same as first POS-GPS-timestamp"; } pkt_stamp = pkt.stamp() + static_cast<uint64_t>(1e9); for (int block = 0; block < BLOCKS_PER_PACKET; ++block) { if (UPPER_BANK != raw->blocks[block].header) { AINFO << "skipping Suteng_liar DIFOP packet!"; break; } if (temp_packet_num < 20000 && temp_packet_num > 0) { temp_packet_num++; } else { temper = compute_temperature(pkt.data().c_str()[38], pkt.data().c_str()[39]); temp_packet_num = 1; } azimuth = static_cast<float>(256 * raw->blocks[block].rotation_1 + raw->blocks[block].rotation_2); if (block < (BLOCKS_PER_PACKET - 1)) { int azi1, azi2; azi1 = 256 * raw->blocks[block + 1].rotation_1 + raw->blocks[block + 1].rotation_2; azi2 = 256 * raw->blocks[block].rotation_1 + raw->blocks[block].rotation_2; azimuth_diff = static_cast<float>((36000 + azi1 - azi2) % 36000); if (azimuth_diff <= 0.0 || azimuth_diff > 75.0) { continue; } } else { // packet的最后两个blocks= int azi1, azi2; azi1 = 256 * raw->blocks[block].rotation_1 + raw->blocks[block].rotation_2; azi2 = 256 * raw->blocks[block - 1].rotation_1 + raw->blocks[block - 1].rotation_2; azimuth_diff = static_cast<float>((36000 + azi1 - azi2) % 36000); if (azimuth_diff <= 0.0 || azimuth_diff > 75.0) { continue; } } for (int firing = 0, k = 0; firing < RS16_FIRINGS_PER_BLOCK; firing++) { for (int dsr = 0; dsr < RS16_SCANS_PER_FIRING; dsr++, k += RAW_SCAN_SIZE) { // the azimuth of current point azimuth_corrected_f = azimuth + (azimuth_diff * ((dsr * RS16_DSR_TOFFSET) + (firing * RS16_FIRING_TOFFSET)) / RS16_BLOCK_TDURATION); azimuth_corrected = (static_cast<int>(round(azimuth_corrected_f))) % 36000; // convert to integral // value... //use union two_bytes raw_dist; raw_dist.bytes[1] = raw->blocks[block].data[k]; raw_dist.bytes[0] = raw->blocks[block].data[k + 1]; float distance = raw_dist.uint; // read intensity intensity = raw->blocks[block].data[k + 2]; float distance2 = distance; distance2 = distance2 * DISTANCE_RESOLUTION; // * 6.4/5.4; //use // time of each point // block 0-11 firing 0-1 dsr 0-15 uint64_t time_pt = (block * 2 + firing) * 50 + dsr * 3; // us uint64_t timestamp = pkt_stamp + time_pt * 1e3; if (block == BLOCKS_PER_PACKET - 1 && firing == RS16_FIRINGS_PER_BLOCK - 1 && dsr == RS16_SCANS_PER_FIRING - 1) { cloud->mutable_header()->set_lidar_timestamp(timestamp); cloud->set_measurement_time(static_cast<double>((timestamp) / 1e9)); } if (raw_dist.uint == 0 || distance2 < config_.min_range() || distance2 > config_.max_range()) { if (config_.organized()) { apollo::drivers::PointXYZIT* point = cloud->add_point(); point->set_x(nan); point->set_y(nan); point->set_z(nan); point->set_timestamp(timestamp); point->set_intensity(0); ++point_index_; ++nan_pts; } continue; } apollo::drivers::PointXYZIT* point = cloud->add_point(); point->set_timestamp(timestamp); point->set_intensity(intensity); // angle float arg_hori = static_cast<float>(azimuth_corrected / 18000.f * M_PI); float arg_vert = SUTENG_VERT[dsr]; float y = static_cast<float>(-distance2 * cos(arg_vert) * sin(arg_hori)); float x = static_cast<float>(distance2 * cos(arg_vert) * cos(arg_hori)); float z = static_cast<float>(distance2 * sin(arg_vert)); if (filter_set_.size() > 0) { std::string key = std::to_string(static_cast<float>(x * 100 / filter_grading_)) + "+" + std::to_string(static_cast<float>(y * 100 / filter_grading_)); if (filter_set_.find(key) != filter_set_.end()) { x = NAN; y = NAN; z = NAN; ++nan_pts; } } point->set_x(x); point->set_y(y); point->set_z(z); point->set_intensity(intensity); ++point_index_; } } } } uint32_t Robosense16Parser::GetPointSize() { return VLP16_POINT_SIZE; } uint32_t Robosense16Parser::getOrderIndex(uint32_t index) { uint32_t width = 16; uint32_t height_index = index / width; uint32_t width_index = index % width; uint32_t order_index = height_index * width + robosense::REORDER_16[width_index]; return order_index; } void Robosense16Parser::order( const std::shared_ptr<apollo::drivers::PointCloud>& cloud) { int width = 16; cloud->set_width(width); int height = cloud->point_size() / cloud->width(); cloud->set_height(height); } } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/parser/robosense16p_parser.h
/****************************************************************************** * Copyright 2021 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. *****************************************************************************/ #pragma once #include <errno.h> #include <stdint.h> #include <cmath> #include <map> #include <memory> #include <set> #include <string> #include "boost/format.hpp" #include "modules/common_msgs/sensor_msgs/pointcloud.pb.h" #include "modules/drivers/lidar/robosense/proto/lidars_filter_config.pb.h" #include "modules/drivers/lidar/robosense/proto/sensor_suteng.pb.h" #include "modules/drivers/lidar/robosense/proto/sensor_suteng_conf.pb.h" #include "modules/drivers/lidar/robosense/lib/calibration.h" #include "modules/drivers/lidar/robosense/lib/const_variables.h" #include "modules/drivers/lidar/robosense/lib/data_type.h" #include "modules/drivers/lidar/robosense/parser/robosense_parser.h" namespace apollo { namespace drivers { namespace robosense { class Robosense16PParser : public RobosenseParser { public: explicit Robosense16PParser( const apollo::drivers::suteng::SutengConfig& config); ~Robosense16PParser() {} void generate_pointcloud( const std::shared_ptr<apollo::drivers::suteng::SutengScan const>& scan_msg, const std::shared_ptr<apollo::drivers::PointCloud>& out_msg); void order(const std::shared_ptr<apollo::drivers::PointCloud>& cloud) { int width = 16; cloud->set_width(width); int height = cloud->point_size() / cloud->width(); cloud->set_height(height); } uint32_t GetPointSize() override { return POINT_SIZE; }; void setup() override; private: #pragma pack(push, 1) static constexpr uint32_t POINT_SIZE = 28800; static constexpr float DISTANCE_RESOLUTION_16P = 0.0025f; /**< meters */ // 16p static constexpr int SCANS_PER_FIRING = 16; static constexpr int FIRINGS_PER_BLOCK = 2; static constexpr float DEGREE_TO_RADIAN = M_PI / 18000.f; // 16P resolution: 0.01 degree float cor_hori_angles[SCANS_PER_FIRING]; float cor_vert_angles[SCANS_PER_FIRING]; uint64_t last_difop_time_ = 0; // lens center static constexpr float RX_16P = 0.03498f; static constexpr float RY_16P = -0.015f; static constexpr float RZ_16P = 0.0f; typedef struct channel_data_16p { uint16_t distance; uint8_t reflectivity; } channel_data_16p_t; typedef struct raw_block_16p { uint16_t header; // UPPER_BANK or LOWER_BANK uint16_t rotation; channel_data_16p_t channel_data[SCANS_PER_BLOCK]; } raw_block_16p_t; typedef struct raw_msop_packet_16p { raw_block_16p_t blocks[BLOCKS_PER_PACKET]; uint8_t unused[4]; uint16_t flag; } raw_packet_16p_t; typedef struct utc_time_16p { uint8_t sec[6]; uint8_t us[4]; } utc_time_16p_t; // offset: 303 typedef struct angle_16p { uint8_t sign; // 0x00: +, 0x01:-, 0xff: err uint16_t value; // big endian, resolution: 0.01 } angle_16p_t; typedef struct vertical_angles_16p { angle_16p_t angles[16]; } vertical_angles_16p_t; // offset: 468 typedef struct horizontal_angles_16p { angle_16p_t angles[16]; } horizontal_angles_16p_t; // offset: 564 #pragma pack(pop) uint64_t get_timestamp(double base_time, float time_offset, uint16_t laser_block_id) { return 0; } void unpack_params(const apollo::drivers::suteng::SutengPacket& pkt); float parse_angle(angle_16p_t angle_pkt); void unpack_robosense( const apollo::drivers::suteng::SutengPacket& pkt, const std::shared_ptr<apollo::drivers::PointCloud>& cloud, uint32_t* index); void init_params(); static bool pkt_start; static uint64_t base_stamp; float SUTENG_VERT_16P_[16] = { 0.22689280275926285, 0.2617993877991494, 0.15707963267948966, 0.19198621771937624, 0.08726646259971647, 0.12217304763960307, 0.017453292519943295, 0.05235987755982989, -0.05235987755982989, -0.017453292519943295, -0.12217304763960307, -0.08726646259971647, -0.19198621771937624, -0.15707963267948966, -0.2617993877991494, -0.22689280275926285}; // unit: us const float TIME_OFFSET_16P[32][12] = { {0.00, 111.11, 222.22, 333.33, 444.44, 555.56, 666.67, 777.78, 888.89, 1000.00, 1111.11, 1222.23}, {3.15, 114.26, 225.37, 336.48, 447.59, 558.70, 669.81, 780.92, 892.03, 1003.14, 1114.25, 1225.36}, {6.30, 117.41, 228.52, 339.63, 450.74, 561.85, 672.96, 784.07, 895.18, 1006.29, 1117.40, 1228.51}, {9.45, 120.56, 231.67, 342.78, 453.89, 565.00, 676.11, 787.22, 898.33, 1009.44, 1120.55, 1231.66}, {13.26, 124.38, 235.49, 346.60, 457.71, 568.82, 679.94, 791.05, 902.16, 1013.27, 1124.38, 1235.49}, {17.08, 128.19, 239.30, 350.41, 461.52, 572.64, 683.75, 794.86, 905.97, 1017.08, 1128.19, 1239.31}, {20.56, 131.67, 242.78, 353.90, 465.01, 576.12, 687.23, 798.34, 909.46, 1020.57, 1131.68, 1242.79}, {23.71, 134.82, 245.93, 357.05, 468.16, 579.27, 690.38, 801.49, 912.61, 1023.72, 1134.83, 1245.94}, {26.53, 137.64, 248.75, 359.86, 470.97, 582.08, 693.19, 804.30, 915.41, 1026.52, 1137.63, 1248.74}, {27.77, 138.88, 249.99, 361.10, 472.21, 583.32, 694.43, 805.54, 916.65, 1027.76, 1138.87, 1249.98}, {31.49, 142.60, 253.72, 364.83, 475.94, 587.05, 698.16, 809.28, 920.39, 1031.50, 1142.61, 1253.72}, {32.73, 143.85, 254.96, 366.07, 477.18, 588.29, 699.41, 810.52, 921.63, 1032.74, 1143.85, 1254.96}, {36.46, 147.57, 258.68, 369.79, 480.90, 592.01, 703.12, 814.23, 925.34, 1036.45, 1147.56, 1258.67}, {38.94, 150.05, 261.16, 372.27, 483.39, 594.50, 705.61, 816.72, 927.83, 1038.95, 1150.07, 1261.18}, {41.42, 152.54, 263.65, 374.76, 485.87, 596.98, 708.10, 819.21, 930.32, 1041.43, 1152.54, 1263.65}, {43.91, 155.02, 266.13, 377.24, 488.35, 599.46, 710.57, 821.68, 932.79, 1043.90, 1155.01, 1266.12}, {55.56, 166.67, 277.78, 388.89, 500.00, 611.11, 722.22, 833.33, 944.44, 1055.55, 1166.66, 1277.77}, {58.70, 169.82, 280.93, 392.04, 503.15, 614.26, 725.38, 836.49, 947.60, 1058.71, 1169.82, 1280.93}, {61.85, 172.97, 284.08, 395.19, 506.30, 617.41, 728.53, 839.64, 950.75, 1061.86, 1172.97, 1284.08}, {65.00, 176.11, 287.23, 398.34, 509.45, 620.56, 731.67, 842.79, 953.90, 1065.01, 1176.12, 1287.23}, {68.82, 179.93, 291.04, 402.15, 513.26, 624.38, 735.49, 846.60, 957.71, 1068.82, 1179.93, 1291.05}, {72.64, 183.75, 294.86, 405.97, 517.08, 628.19, 739.30, 850.41, 961.52, 1072.63, 1183.74, 1294.85}, {76.12, 187.23, 298.34, 409.45, 520.56, 631.67, 742.78, 853.89, 965.00, 1076.11, 1187.22, 1298.33}, {79.27, 190.38, 301.49, 412.60, 523.71, 634.82, 745.93, 857.04, 968.15, 1079.26, 1190.37, 1301.48}, {82.08, 193.19, 304.31, 415.42, 526.53, 637.64, 748.75, 859.87, 970.98, 1082.09, 1193.20, 1304.31}, {83.32, 194.44, 305.55, 416.66, 527.77, 638.88, 750.00, 861.11, 972.22, 1083.33, 1194.44, 1305.55}, {87.05, 198.16, 309.27, 420.38, 531.49, 642.60, 753.71, 864.82, 975.93, 1087.04, 1198.15, 1309.26}, {88.29, 199.40, 310.51, 421.62, 532.73, 643.85, 754.96, 866.07, 977.18, 1088.29, 1199.40, 1310.52}, {92.01, 203.13, 314.24, 425.35, 536.46, 647.57, 758.69, 869.80, 980.91, 1092.02, 1203.13, 1314.24}, {94.50, 205.61, 316.72, 427.83, 538.94, 650.05, 761.16, 872.27, 983.38, 1094.49, 1205.60, 1316.71}, {96.98, 208.09, 319.20, 430.31, 541.42, 652.54, 763.65, 874.76, 985.87, 1096.98, 1208.09, 1319.21}, {99.46, 210.57, 321.68, 432.80, 543.91, 655.02, 766.13, 877.24, 988.36, 1099.47, 1210.58, 1321.69}}; }; } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/parser/robosense_parser.h
/****************************************************************************** * Copyright 2021 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. *****************************************************************************/ #pragma once #include <errno.h> #include <stdint.h> #include <map> #include <memory> #include <set> #include <string> #include "boost/format.hpp" #include "modules/common_msgs/sensor_msgs/pointcloud.pb.h" #include "modules/drivers/lidar/robosense/proto/lidars_filter_config.pb.h" #include "modules/drivers/lidar/robosense/proto/sensor_suteng.pb.h" #include "modules/drivers/lidar/robosense/proto/sensor_suteng_conf.pb.h" #include "modules/drivers/lidar/robosense/lib/calibration.h" #include "modules/drivers/lidar/robosense/lib/const_variables.h" #include "modules/drivers/lidar/robosense/lib/data_type.h" namespace apollo { namespace drivers { namespace robosense { /** \brief suteng data conversion class */ class RobosenseParser { public: RobosenseParser() {} explicit RobosenseParser(const apollo::drivers::suteng::SutengConfig& config); virtual ~RobosenseParser() {} /** \brief Set up for data processing. * * Perform initializations needed before data processing can * begin: * * - read device-specific angles calibration * * @param private_nh private node handle for ROS parameters * @returns 0 if successful; * errno value for failure */ virtual void generate_pointcloud( const std::shared_ptr<apollo::drivers::suteng::SutengScan const>& scan_msg, const std::shared_ptr<apollo::drivers::PointCloud>& out_msg) = 0; virtual void setup(); virtual uint32_t GetPointSize() = 0; // order point cloud fod IDL by suteng model virtual void order( const std::shared_ptr<apollo::drivers::PointCloud>& cloud) = 0; const Calibration& get_calibration() { return calibration_; } double get_last_timestamp() { return last_time_stamp_; } // suteng float CalibIntensity(float intensity, int cal_idx, int distance, float temper); float PixelToDistance(int pixel_value, int passage_way, float temper); protected: // suteng int TEMPERATURE_RANGE = 40; // rs16 rs32-50 int TEMPERATURE_MIN = 31; int EstimateTemperature(float temper); float compute_temperature(unsigned char bit1, unsigned char bit2); const float (*_inner_time)[12][32]; /** * \brief Calibration file */ Calibration calibration_; float sin_rot_table_[ROTATION_MAX_UNITS]; float cos_rot_table_[ROTATION_MAX_UNITS]; apollo::drivers::suteng::SutengConfig config_; std::set<std::string> filter_set_; int filter_grading_; // Last suteng packet time stamp. (Full time) double last_time_stamp_; bool need_two_pt_correction_; uint32_t point_index_ = 0; Mode mode_; apollo::drivers::PointXYZIT get_nan_point(uint64_t timestamp); void init_angle_params(double view_direction, double view_width); /** * \brief Compute coords with the data in block * * @param tmp A two bytes union store the value of laser distance infomation * @param index The index of block */ bool is_scan_valid(int rotation, float distance); /** * \brief Unpack suteng packet * */ // virtual void unpack(const apollo::drivers::suteng::SutengPacket& pkt, // std::shared_ptr<apollo::drivers::PointCloud>& pc) = // 0; uint64_t get_gps_stamp(double current_stamp, double* previous_stamp, uint64_t* gps_base_usec); virtual uint64_t get_timestamp(double base_time, float time_offset, uint16_t laser_block_id) = 0; void timestamp_check(double timestamp); void init_sin_cos_rot_table(float* sin_rot_table, float* cos_rot_table, uint16_t rotation, float rotation_resolution); }; // class RobosenseParser class Robosense16Parser : public RobosenseParser { public: explicit Robosense16Parser( const apollo::drivers::suteng::SutengConfig& config); ~Robosense16Parser() {} void generate_pointcloud( const std::shared_ptr<apollo::drivers::suteng::SutengScan const>& scan_msg, const std::shared_ptr<apollo::drivers::PointCloud>& out_msg); void order(const std::shared_ptr<apollo::drivers::PointCloud>& cloud); uint32_t GetPointSize() override; void setup() override; void init_setup(); private: uint64_t get_timestamp(double base_time, float time_offset, uint16_t laser_block_id); void unpack_robosense( const apollo::drivers::suteng::SutengPacket& pkt, const std::shared_ptr<apollo::drivers::PointCloud>& cloud, uint32_t* index); // Previous suteng packet time stamp. (offset to the top hour) double previous_packet_stamp_; uint64_t gps_base_usec_; // full time std::map<uint32_t, uint32_t> order_map_; uint32_t getOrderIndex(uint32_t index); void init_orderindex(); RslidarPic pic; // sutegn int temp_packet_num = 0; float temper = 31.f; static bool pkt_start; static uint64_t base_stamp; uint64_t first_pkt_stamp; uint64_t final_pkt_stamp; uint64_t last_pkt_stamp = 0; }; // class Robosense32Parser class RobosenseParserFactory { public: static RobosenseParser* create_parser( const apollo::drivers::suteng::SutengConfig& config); }; } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/parser/convert.h
/****************************************************************************** * Copyright 2021 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. *****************************************************************************/ #pragma once #include <memory> #include "modules/common_msgs/sensor_msgs/pointcloud.pb.h" #include "modules/drivers/lidar/robosense/proto/sensor_suteng.pb.h" #include "modules/drivers/lidar/robosense/parser/robosense_parser.h" namespace apollo { namespace drivers { namespace robosense { // convert suteng data to pointcloud and republish class Convert { public: explicit Convert(const apollo::drivers::suteng::SutengConfig& robo_config); ~Convert(); void convert_robosense_to_pointcloud( const std::shared_ptr<apollo::drivers::suteng::SutengScan const>& scan_msg, const std::shared_ptr<apollo::drivers::PointCloud>& point_cloud); bool Init(); uint32_t GetPointSize(); private: RobosenseParser* parser_; apollo::drivers::suteng::SutengConfig config_; }; } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/parser/robosense_status.h
/****************************************************************************** * Copyright 2021 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. *****************************************************************************/ #pragma once #include <cmath> #include <memory> #include <string> #include <utility> #include <vector> #include "modules/common_msgs/sensor_msgs/pointcloud.pb.h" #include "modules/drivers/lidar/robosense/proto/sensor_suteng.pb.h" #include "modules/drivers/lidar/robosense/proto/sensor_suteng_conf.pb.h" #include "cyber/cyber.h" namespace apollo { namespace drivers { namespace robosense { constexpr double RADIANS_TO_DEGREES = 180.0 / M_PI; constexpr double DEGRESS_TO_RADIANS = M_PI / 180.0; const uint8_t STATUS_WARNING = 87; const uint8_t STATUS_SPEED_LOW = 254; const uint8_t STATUS_SPEED_HIGH = 255; // 600*95% const uint32_t SPEED_TOL = 570; const uint32_t STATUS_TYPE_INDEX = 1204; const uint32_t STATUS_VALUE_INDEX = 1205; // 64e s3 warning struct alignas(8) WarningBits { uint8_t lens_ontamination : 1; // 1: need clean, 0: not uint8_t unit_hot : 1; // 1:>58C 0: not uint8_t unit_cold : 1; // 1:<5C 0: not uint8_t reserved : 2; uint8_t pps_signal : 1; // 1: present, 0: not uint8_t gps_signal : 1; // 1: present, 0: not uint8_t not_used : 1; // 1: present, 0: not }; // 64e S3 speed union alignas(8) MotorSpeed { struct alignas(8) { uint8_t speed_low; uint8_t speed_high; }; uint16_t speed; }; // get suteng status from packet by suteng Manual class RobosenseStatus { public: RobosenseStatus(); ~RobosenseStatus() {} void get_status( const std::shared_ptr<apollo::drivers::suteng::SutengScan const>& scan); private: void check_warningbit(); void check_motor_speed(); std::string topic_packets_; std::string model_; std::vector<std::pair<uint8_t, uint8_t>> status_; // queue size for ros node pub int queue_size_; WarningBits* warning_bits_; MotorSpeed motor_speed_; }; } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/parser/robosense_parser.cpp
/****************************************************************************** * Copyright 2021 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 "modules/drivers/lidar/robosense/parser/robosense_parser.h" #include <algorithm> #include <fstream> #include <pcl/common/time.h> #include "cyber/cyber.h" #include "modules/drivers/lidar/robosense/parser/robosense16p_parser.h" namespace apollo { namespace drivers { namespace robosense { uint64_t RobosenseParser::get_gps_stamp(double current_packet_stamp, double* previous_packet_stamp, uint64_t* gps_base_usec) { if (std::abs(*previous_packet_stamp - current_packet_stamp) > 3599000000) { // 微妙 us *gps_base_usec += static_cast<uint64_t>(3600 * 1e6); // + 1小时 单位微妙 AINFO << "gps_base+1---current_stamp:" << current_packet_stamp << "previous_stamp:" << previous_packet_stamp; } if (current_packet_stamp >= *previous_packet_stamp) { // AINFO<<"curr - pre:"<<(current_packet_stamp - // previous_packet_stamp)*1e-3; if (*previous_packet_stamp != 0 && current_packet_stamp - *previous_packet_stamp > 100000) { AERROR << "Current stamp:" << std::fixed << current_packet_stamp << " ahead previous stamp:" << previous_packet_stamp << " over 100ms. GPS time stamp incorrect!"; } } *previous_packet_stamp = current_packet_stamp; uint64_t gps_stamp = *gps_base_usec + static_cast<uint64_t>(current_packet_stamp + 1000000); // us gps_stamp = gps_stamp * 1000; return gps_stamp; } apollo::drivers::PointXYZIT RobosenseParser::get_nan_point(uint64_t timestamp) { apollo::drivers::PointXYZIT nan_point; nan_point.set_timestamp(timestamp); nan_point.set_x(nan); nan_point.set_y(nan); nan_point.set_z(nan); nan_point.set_intensity(0); return nan_point; } RobosenseParser::RobosenseParser( const apollo::drivers::suteng::SutengConfig& config) : config_(config), last_time_stamp_(0), mode_(STRONGEST) {} void RobosenseParser::init_angle_params(double view_direction, double view_width) { // converting angle parameters into the suteng reference (rad) double tmp_min_angle = view_direction + view_width / 2; double tmp_max_angle = view_direction - view_width / 2; // computing positive modulo to keep theses angles into [0;2*M_PI] tmp_min_angle = fmod(fmod(tmp_min_angle, 2 * M_PI) + 2 * M_PI, 2 * M_PI); tmp_max_angle = fmod(fmod(tmp_max_angle, 2 * M_PI) + 2 * M_PI, 2 * M_PI); // converting into the hardware suteng ref (negative yaml and degrees) // adding 0.5 perfomrs a centered double to int conversion config_.set_min_angle(100 * (2 * M_PI - tmp_min_angle) * 180 / M_PI + 0.5); config_.set_max_angle(100 * (2 * M_PI - tmp_max_angle) * 180 / M_PI + 0.5); if (config_.min_angle() == config_.max_angle()) { // avoid returning empty cloud if min_angle = max_angle config_.set_min_angle(0); config_.set_max_angle(36000); } } /** Set up for on-line operation. */ void RobosenseParser::setup() { calibration_.read(config_.calibration_file()); if (!calibration_.initialized_) { AERROR << " Unable to open calibration file: " << config_.calibration_file(); } // setup angle parameters. init_angle_params(config_.view_direction(), config_.view_width()); init_sin_cos_rot_table(sin_rot_table_, cos_rot_table_, ROTATION_MAX_UNITS, ROTATION_RESOLUTION); // get lidars_filter_config and put them into filter_set_ if (!config_.lidars_filter_config_path().empty()) { // read config file apollo::drivers::suteng::LidarsFilter lidarsFilter; if (!apollo::cyber::common::GetProtoFromFile( config_.lidars_filter_config_path(), &lidarsFilter)) { AERROR << "Failed to load config file"; return; } AINFO << "lidarsFilter Config:" << lidarsFilter.DebugString(); for (int i = 0; i < lidarsFilter.lidar_size(); i++) { if (lidarsFilter.lidar(i).frame_id() == config_.frame_id()) { apollo::drivers::suteng::Lidar lidar(lidarsFilter.lidar(i)); filter_grading_ = lidar.grading(); for (int j = 0; j < lidar.point_size(); j++) { filter_set_.insert(lidar.point(j)); } break; } } } } bool RobosenseParser::is_scan_valid(int rotation, float range) { // check range first if (range < config_.min_range() || range > config_.max_range()) { return false; } (void)rotation; return true; } void RobosenseParser::timestamp_check(double timestamp) { (void)timestamp; } void RobosenseParser::init_sin_cos_rot_table(float* sin_rot_table, float* cos_rot_table, uint16_t rotation, float rotation_resolution) { for (uint16_t rot_index = 0; rot_index < rotation; ++rot_index) { float rotation = rotation_resolution * rot_index * M_PI / 180.0; cos_rot_table[rot_index] = cosf(rotation); sin_rot_table[rot_index] = sinf(rotation); } } RobosenseParser* RobosenseParserFactory::create_parser( const apollo::drivers::suteng::SutengConfig& config) { if (config.model() == apollo::drivers::suteng::VLP16) { return new Robosense16Parser(config); } else if (config.model() == apollo::drivers::suteng::Model::HELIOS_16P) { return new Robosense16PParser(config); } else { AERROR << " invalid model, must be VLP16 or HELIOS_16P"; return nullptr; } } int RobosenseParser::EstimateTemperature(float temperature) { int temp = static_cast<int>(floor(temperature + 0.5)); if (temp < TEMPERATURE_MIN) { temp = TEMPERATURE_MIN; } else if (temp > TEMPERATURE_MIN + TEMPERATURE_RANGE) { temp = TEMPERATURE_MIN + TEMPERATURE_RANGE; } return temp; } float RobosenseParser::CalibIntensity(float intensity, int calIdx, // 1-16 int distance, float temper) { int alg_dist; int sdist; int uplimit_dist; float real_pwr; float ref_pwr; float temp_inten; float distance_f; float end_of_section1; int temp = EstimateTemperature(temper); real_pwr = std::max( static_cast<float>( intensity / (1 + static_cast<float>(temp - TEMPERATURE_MIN) / 24.0f)), 1.0f); if (static_cast<int>(real_pwr < 126)) { real_pwr = real_pwr * 4.0f; } else { if (static_cast<int>(real_pwr >= 126) && static_cast<int>(real_pwr < 226)) { real_pwr = (real_pwr - 125.0f) * 16.0f + 500.0f; } else { real_pwr = (real_pwr - 225.0f) * 256.0f + 2100.0f; } } int indexTemper = EstimateTemperature(temper) - TEMPERATURE_MIN; uplimit_dist = CHANNEL_NUM[calIdx][indexTemper] + 20000; // limit sdist sdist = (distance > CHANNEL_NUM[calIdx][indexTemper]) ? distance : CHANNEL_NUM[calIdx][indexTemper]; sdist = (sdist < uplimit_dist) ? sdist : uplimit_dist; // minus the static offset (this data is For the intensity cal useage only) alg_dist = sdist - CHANNEL_NUM[calIdx][indexTemper]; // calculate intensity ref curves float ref_pwr_temp = 0.0f; int order = 3; end_of_section1 = 500.0f; distance_f = static_cast<float>(alg_dist); if (distance_f <= end_of_section1) { ref_pwr_temp = INTENSITY_CAL[0][calIdx] * static_cast<float>(exp(INTENSITY_CAL[1][calIdx] - INTENSITY_CAL[2][calIdx] * distance_f / 100.0f)) + INTENSITY_CAL[3][calIdx]; } else { for (int i = 0; i < order; i++) { ref_pwr_temp += static_cast<float>(INTENSITY_CAL[i + 4][calIdx] * pow(distance_f / 100.0f, order - 1 - i)); } } ref_pwr = std::max(std::min(ref_pwr_temp, 500.0f), 4.0f); temp_inten = (51 * ref_pwr) / real_pwr; temp_inten = static_cast<int>(temp_inten > 255 ? 255.0f : temp_inten); return temp_inten; } float RobosenseParser::PixelToDistance(int pixelValue, int passageway, float temper) { temper = 31.0; float distance_value; int indexTemper = EstimateTemperature(temper) - TEMPERATURE_MIN; if (pixelValue <= CHANNEL_NUM[passageway][indexTemper]) { distance_value = 0.0; } else { distance_value = static_cast<float>(pixelValue - CHANNEL_NUM[passageway][indexTemper]); } return distance_value; } float RobosenseParser::compute_temperature(unsigned char bit1, unsigned char bit2) { float temp; float bitneg = bit2 & 128; // 10000000 float highbit = bit2 & 127; // 01111111 float lowbit = bit1 >> 3; if (bitneg == 128) { temp = -1 * (highbit * 32 + lowbit) * 0.0625f; } else { temp = (highbit * 32 + lowbit) * 0.0625f; } return temp; } } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/params/robo_left_novatel_extrinsics.yaml
header: seq: 0 stamp: secs: 1598864144 nsecs: 0 frame_id: novatel transform: rotation: x: -0.00286894868765535 y: 0.004124527761619362 z: 0.9328082862516019 w: 0.3603378994988631 translation: z: 0.466768741607666 x: -0.5066532492637634 y: 1.299999952316284 child_frame_id: robosense16_left
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/params/robo_right_novatel_extrinsics.yaml
header: seq: 0 stamp: secs: 1598864145 nsecs: 0 frame_id: novatel transform: rotation: x: -0.002318980714959567 y: 0.01161046879743896 z: 0.3507677852187285 w: 0.9363876260209965 translation: z: 0.4873774349689484 x: 0.538250744342804 y: 1.299999952316284 child_frame_id: robosense16_right
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/params/robo_back_novatel_extrinsics.yaml
header: seq: 0 stamp: secs: 1598864145 nsecs: 0 frame_id: novatel transform: rotation: x: 0.008841838625589146 y: 0.004176859328882889 z: 0.7080300924249699 w: 0.7061145910068848 translation: z: 1.494589567184448 x: 0.0007851437549106777 y: -0.07000000029802322 child_frame_id: robosense16_back
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/lib/pcap_input.cpp
/****************************************************************************** * Copyright 2021 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 "modules/drivers/lidar/robosense/lib/pcap_input.h" #include <arpa/inet.h> #include <errno.h> #include <fcntl.h> #include <poll.h> #include <sys/file.h> #include <sys/socket.h> #include <time.h> #include <unistd.h> #include <string> #include "cyber/cyber.h" namespace apollo { namespace drivers { namespace robosense { PcapInput::PcapInput(double packet_rate, const std::string& filename, bool read_once, bool read_fast, double repeat_delay) : Input(), packet_rate_(packet_rate) { filename_ = filename; fp_ = NULL; pcap_ = NULL; empty_ = true; read_once_ = read_once; read_fast_ = read_fast; repeat_delay_ = repeat_delay; } void PcapInput::init() { if (pcap_ != NULL) { return; } if (read_once_) { AINFO << "Read input file only once."; } if (read_fast_) { AINFO << "Read input file as quickly as possible."; } if (repeat_delay_ > 0.0) { AINFO << "Delay %.3f seconds before repeating input file." << repeat_delay_; } if ((pcap_ = pcap_open_offline(filename_.c_str(), errbuf_)) == NULL) { AERROR << " Error opening suteng socket dump file."; } } /** destructor */ PcapInput::~PcapInput(void) { pcap_close(pcap_); } // static uint64_t last_pkt_stamp = 0; /** @brief Get one suteng packet. */ int PcapInput::get_firing_data_packet( apollo::drivers::suteng::SutengPacket* pkt, int time_zone, uint64_t start_time_) { struct pcap_pkthdr* header; const u_char* pkt_data; while (true) { int res = 0; if (pcap_ == nullptr) { return -1; } if ((res = pcap_next_ex(pcap_, &header, &pkt_data)) >= 0) { if (header->len != FIRING_DATA_PACKET_SIZE + ETHERNET_HEADER_SIZE) { continue; } // Keep the reader from blowing through the file. if (read_fast_ == false) { sleep(0.3); } usleep(1000); pkt->set_data(pkt_data + ETHERNET_HEADER_SIZE, FIRING_DATA_PACKET_SIZE); tm pkt_time; memset(&pkt_time, 0, sizeof(pkt_time)); pkt_time.tm_year = static_cast<int>(pkt->data().c_str()[20] + 100); pkt_time.tm_mon = static_cast<int>(pkt->data().c_str()[21] - 1); pkt_time.tm_mday = static_cast<int>(pkt->data().c_str()[22]); pkt_time.tm_hour = static_cast<int>(pkt->data().c_str()[23] + time_zone); pkt_time.tm_min = static_cast<int>(pkt->data().c_str()[24]); pkt_time.tm_sec = static_cast<int>(pkt->data().c_str()[25]); uint64_t timestamp_sec = static_cast<uint64_t>((mktime(&pkt_time)) * 1e9); uint64_t timestamp_nsec = static_cast<uint64_t>( (1000 * (256 * pkt->data().c_str()[26] + pkt->data().c_str()[27]) + (256 * pkt->data().c_str()[28] + pkt->data().c_str()[29])) * 1e3 + timestamp_sec); // ns pkt->set_stamp(timestamp_nsec); if (!flags) { AINFO << "pcap robo first PPS-GPS-timestamp: [" << timestamp_nsec << "]"; flags = true; } empty_ = false; return 0; // success } if (empty_) { // no data in file? AINFO << "Error %d reading suteng packet: %s" << res << pcap_geterr(pcap_); return -1; } if (read_once_) { AINFO << "end of file reached -- done reading."; return PCAP_FILE_END; } if (repeat_delay_ > 0.0) { AINFO << "end of file reached -- delaying %.3f seconds." << repeat_delay_; usleep(static_cast<int>(repeat_delay_ * 1000000.0)); } pcap_close(pcap_); pcap_ = pcap_open_offline(filename_.c_str(), errbuf_); empty_ = true; // maybe the file disappeared? } // loop back and try again } int PcapInput::get_positioning_data_packtet(const NMEATimePtr& nmea_time) { struct pcap_pkthdr* header; const u_char* pkt_data; while (true) { int res = 0; if (pcap_ == nullptr) { return -1; } if ((res = pcap_next_ex(pcap_, &header, &pkt_data)) >= 0) { if (header->len != POSITIONING_DATA_PACKET_SIZE + ETHERNET_HEADER_SIZE) { continue; } uint8_t bytes[POSITIONING_DATA_PACKET_SIZE]; memcpy(bytes, pkt_data + ETHERNET_HEADER_SIZE, POSITIONING_DATA_PACKET_SIZE); // read successful, exract nmea time if (exract_nmea_time_from_packet(nmea_time, bytes + 303)) { empty_ = false; return 0; // success } else { empty_ = false; return -1; } } if (empty_) { // no data in file? AINFO << "Error %d reading suteng packet: %s" << res << pcap_geterr(pcap_); return -1; } if (read_once_) { AINFO << "end of file reached -- done reading."; return PCAP_FILE_END; } if (repeat_delay_ > 0.0) { AINFO << "end of file reached -- delaying %.3f seconds." << repeat_delay_; usleep(static_cast<int>(repeat_delay_ * 1000000.0)); } // I can't figure out how to rewind the file, because it // starts with some kind of header. So, close the file // and reopen it with pcap. pcap_close(pcap_); pcap_ = pcap_open_offline(filename_.c_str(), errbuf_); empty_ = true; // maybe the file disappeared? } // loop back and try again } } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/lib/input.h
/****************************************************************************** * Copyright 2021 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. *****************************************************************************/ #pragma once #include <unistd.h> #include <cstdio> #include <pcap.h> #include "modules/drivers/lidar/robosense/proto/sensor_suteng.pb.h" #include "cyber/cyber.h" #include "modules/drivers/lidar/robosense/lib/data_type.h" namespace apollo { namespace drivers { namespace robosense { static const int POLL_TIMEOUT = 1000; // one second (in msec) static const size_t FIRING_DATA_PACKET_SIZE = 1248; static const size_t POSITIONING_DATA_PACKET_SIZE = 1248; // beike-256 robosense-512; static const size_t ETHERNET_HEADER_SIZE = 42; static const int PCAP_FILE_END = -1; static const int SOCKET_TIMEOUT = -2; static const int RECIEVE_FAIL = -3; /** @brief Pure virtual suteng input base class */ class Input { public: Input() {} virtual ~Input() {} /** @brief Read one suteng packet. * * @param pkt points to SutengPacket message * * @returns 0 if successful, * -1 if end of file * > 0 if incomplete packet (is this possible?) */ virtual int get_firing_data_packet(apollo::drivers::suteng::SutengPacket* pkt, int time_zone, uint64_t start_time_) = 0; virtual int get_positioning_data_packtet(const NMEATimePtr& nmea_time) = 0; virtual void init() {} virtual void init(uint32_t port) { (void)port; } bool flags = false; protected: // static uint64_t last_pkt_stamp; bool exract_nmea_time_from_packet(const NMEATimePtr& nmea_time, const uint8_t* bytes); }; } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/lib/pcap_input.h
/****************************************************************************** * Copyright 2021 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. *****************************************************************************/ #pragma once #include <unistd.h> #include <cstdio> #include <string> #include <pcap.h> #include "modules/drivers/lidar/robosense/lib/data_type.h" #include "modules/drivers/lidar/robosense/lib/input.h" namespace apollo { namespace drivers { namespace robosense { class PcapInput : public Input { public: PcapInput(double packet_rate, const std::string& filename, bool read_once = false, bool read_fast = false, double repeat_delay = 0.0); virtual ~PcapInput(); void init(); int get_firing_data_packet(apollo::drivers::suteng::SutengPacket* pkt, int pkt_index_, uint64_t start_time_); int get_positioning_data_packtet(const NMEATimePtr& nmea_time); private: std::string filename_; FILE* fp_; pcap* pcap_; char errbuf_[PCAP_ERRBUF_SIZE]; bool empty_; bool read_once_; bool read_fast_; double repeat_delay_; double packet_rate_; }; } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/lib/input.cpp
/****************************************************************************** * Copyright 2021 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 "modules/drivers/lidar/robosense/lib/input.h" #include "cyber/cyber.h" namespace apollo { namespace drivers { namespace robosense { // uint64_t Input::last_pkt_stamp = 0; bool Input::exract_nmea_time_from_packet(const NMEATimePtr& nmea_time, const uint8_t* bytes) { unsigned int field_index = 0; nmea_time->year = static_cast<uint16_t>(bytes[field_index]); nmea_time->mon = static_cast<uint16_t>(bytes[field_index + 1] & 0x0F); nmea_time->day = static_cast<uint16_t>(bytes[field_index + 2] & 0x1F); nmea_time->hour = static_cast<uint16_t>(bytes[field_index + 3] & 0x1F); nmea_time->min = static_cast<uint16_t>(bytes[field_index + 4] & 0x3F); nmea_time->sec = static_cast<uint16_t>(bytes[field_index + 5] & 0x3F); nmea_time->msec = static_cast<uint16_t>( bytes[field_index + 7] + (256 * (bytes[field_index + 6]) & 0x3F)); nmea_time->usec = static_cast<uint16_t>( bytes[field_index + 9] + (256 * (bytes[field_index + 8]) & 0x3F)); if (nmea_time->year < 0 || nmea_time->year > 99 || nmea_time->mon > 12 || nmea_time->mon < 1 || nmea_time->day > 31 || nmea_time->day < 1 || nmea_time->hour > 23 || nmea_time->hour < 0 || nmea_time->min > 59 || nmea_time->min < 0 || nmea_time->sec > 59 || nmea_time->sec < 0) { AINFO << "Invalid GPS time: " << nmea_time->year << "-" << nmea_time->mon << "-" << nmea_time->day << " " << nmea_time->hour << ":" << nmea_time->min << ":" << nmea_time->sec << ", make sure have connected to GPS device"; return false; } return true; } } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/lib/socket_input_16p.h
/****************************************************************************** * Copyright 2021 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. *****************************************************************************/ #pragma once #include <unistd.h> #include <cstdio> #include <pcap.h> #include "modules/drivers/lidar/robosense/lib/data_type.h" #include "modules/drivers/lidar/robosense/lib/input.h" namespace apollo { namespace drivers { namespace robosense { /** @brief Live suteng input from socket. */ class SocketInput16P : public Input { public: SocketInput16P(); virtual ~SocketInput16P(); void init(uint32_t port); int get_firing_data_packet(apollo::drivers::suteng::SutengPacket* pkt, bool use_gps_time); int get_positioning_data_packet(apollo::drivers::suteng::SutengPacket* pkt, bool use_gps_time); bool exract_utc_time_from_packet(const uint8_t* bytes, uint64_t* utc_time_ns); int get_firing_data_packet(apollo::drivers::suteng::SutengPacket* pkt, int time_zone, uint64_t start_time_) { return 0; } int get_positioning_data_packtet(const NMEATimePtr& nmea_time) { return 0; } private: int sockfd_; int port_; bool input_available(int timeout); }; } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/lib/calibration.cpp
/****************************************************************************** * Copyright 2021 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 "modules/drivers/lidar/robosense/lib/calibration.h" #include <cmath> #include <fstream> #include <iostream> #include <limits> #include <map> #include <string> #include <utility> #include <yaml-cpp/yaml.h> namespace apollo { namespace drivers { namespace robosense { const char NUM_LASERS[] = "num_lasers"; const char LASERS[] = "lasers"; const char LASER_ID[] = "laser_id"; const char ROT_CORRECTION[] = "rot_correction"; const char VERT_CORRECTION[] = "vert_correction"; const char DIST_CORRECTION[] = "dist_correction"; const char TWO_PT_CORRECTION_AVAILABLE[] = "two_pt_correction_available"; const char DIST_CORRECTION_X[] = "dist_correction_x"; const char DIST_CORRECTION_Y[] = "dist_correction_y"; const char VERT_OFFSET_CORRECTION[] = "vert_offset_correction"; const char HORIZ_OFFSET_CORRECTION[] = "horiz_offset_correction"; const char MAX_INTENSITY[] = "max_intensity"; const char MIN_INTENSITY[] = "min_intensity"; const char FOCAL_DISTANCE[] = "focal_distance"; const char FOCAL_SLOPE[] = "focal_slope"; // The >> operator disappeared in yaml-cpp 0.5, so this function is // added to provide support for code written under the yaml-cpp 0.3 API. template <typename T> void operator>>(const YAML::Node& node, T& i) { i = node.as<T>(); } void operator>>(const YAML::Node& node, std::pair<int, LaserCorrection>& correction) { node[LASER_ID] >> correction.first; node[ROT_CORRECTION] >> correction.second.rot_correction; node[VERT_CORRECTION] >> correction.second.vert_correction; node[DIST_CORRECTION] >> correction.second.dist_correction; node[DIST_CORRECTION_X] >> correction.second.dist_correction_x; node[DIST_CORRECTION_Y] >> correction.second.dist_correction_y; node[VERT_OFFSET_CORRECTION] >> correction.second.vert_offset_correction; node[HORIZ_OFFSET_CORRECTION] >> correction.second.horiz_offset_correction; if (node[MAX_INTENSITY]) { node[MAX_INTENSITY] >> correction.second.max_intensity; } else { correction.second.max_intensity = 255; } if (node[MIN_INTENSITY]) { node[MIN_INTENSITY] >> correction.second.min_intensity; } else { correction.second.min_intensity = 0; } node[FOCAL_DISTANCE] >> correction.second.focal_distance; node[FOCAL_SLOPE] >> correction.second.focal_slope; // Calculate cached values correction.second.cos_rot_correction = cosf(correction.second.rot_correction); correction.second.sin_rot_correction = sinf(correction.second.rot_correction); correction.second.cos_vert_correction = cosf(correction.second.vert_correction); correction.second.sin_vert_correction = sinf(correction.second.vert_correction); correction.second.focal_offset = 256 * pow(1 - correction.second.focal_distance / 13100, 2); correction.second.laser_ring = 0; // clear initially (set later) } void operator>>(const YAML::Node& node, Calibration& calibration) { int num_lasers = 0; node[NUM_LASERS] >> num_lasers; const YAML::Node& lasers = node[LASERS]; calibration.laser_corrections_.clear(); calibration.num_lasers_ = num_lasers; for (int i = 0; i < num_lasers; i++) { std::pair<int, LaserCorrection> correction; lasers[i] >> correction; calibration.laser_corrections_.insert(correction); } // For each laser ring, find the next-smallest vertical angle. // // This implementation is simple, but not efficient. That is OK, // since it only runs while starting up. double next_angle = -std::numeric_limits<double>::infinity(); for (int ring = 0; ring < num_lasers; ++ring) { // find minimum remaining vertical offset correction double min_seen = std::numeric_limits<double>::infinity(); int next_index = num_lasers; for (int j = 0; j < num_lasers; ++j) { double angle = calibration.laser_corrections_[j].vert_correction; if (next_angle < angle && angle < min_seen) { min_seen = angle; next_index = j; } } if (next_index < num_lasers) { // anything found in this ring? // store this ring number with its corresponding laser number calibration.laser_corrections_[next_index].laser_ring = ring; next_angle = min_seen; } } } YAML::Emitter& operator<<(YAML::Emitter& out, const std::pair<int, LaserCorrection> correction) { out << YAML::BeginMap; out << YAML::Key << LASER_ID << YAML::Value << correction.first; out << YAML::Key << ROT_CORRECTION << YAML::Value << correction.second.rot_correction; out << YAML::Key << VERT_CORRECTION << YAML::Value << correction.second.vert_correction; out << YAML::Key << DIST_CORRECTION << YAML::Value << correction.second.dist_correction; out << YAML::Key << DIST_CORRECTION_X << YAML::Value << correction.second.dist_correction_x; out << YAML::Key << DIST_CORRECTION_Y << YAML::Value << correction.second.dist_correction_y; out << YAML::Key << VERT_OFFSET_CORRECTION << YAML::Value << correction.second.vert_offset_correction; out << YAML::Key << HORIZ_OFFSET_CORRECTION << YAML::Value << correction.second.horiz_offset_correction; out << YAML::Key << MAX_INTENSITY << YAML::Value << correction.second.max_intensity; out << YAML::Key << MIN_INTENSITY << YAML::Value << correction.second.min_intensity; out << YAML::Key << FOCAL_DISTANCE << YAML::Value << correction.second.focal_distance; out << YAML::Key << FOCAL_SLOPE << YAML::Value << correction.second.focal_slope; out << YAML::EndMap; return out; } YAML::Emitter& operator<<(YAML::Emitter& out, const Calibration& calibration) { out << YAML::BeginMap; out << YAML::Key << NUM_LASERS << YAML::Value << calibration.laser_corrections_.size(); out << YAML::Key << LASERS << YAML::Value << YAML::BeginSeq; for (std::map<int, LaserCorrection>::const_iterator it = calibration.laser_corrections_.begin(); it != calibration.laser_corrections_.end(); it++) { out << *it; } out << YAML::EndSeq; out << YAML::EndMap; return out; } void Calibration::read(const std::string& calibration_file) { std::ifstream fin(calibration_file.c_str()); if (!fin.is_open()) { initialized_ = false; return; } initialized_ = true; try { YAML::Node doc; fin.close(); doc = YAML::LoadFile(calibration_file); doc >> *this; } catch (YAML::Exception& e) { std::cerr << "YAML Exception: " << e.what() << std::endl; initialized_ = false; } fin.close(); } void Calibration::write(const std::string& calibration_file) { std::ofstream fout(calibration_file.c_str()); YAML::Emitter out; out << *this; fout << out.c_str(); fout.close(); } } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/lib/const_variables.h
/****************************************************************************** * Copyright 2021 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. *****************************************************************************/ #pragma once #include <iostream> namespace apollo { namespace drivers { namespace robosense { /** * @brief Order array for re-ordering point cloud. * Refer to suteng official manual */ const int REORDER_16[16] = {0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15}; // suteng begin const float SUTENG_VERT[16] = {-0.26208, -0.227375, -0.192101, -0.157558, -0.122632, -0.0880222, -0.0531994, -0.0176226, 0.261264, 0.226544, 0.192463, 0.157313, 0.12177, 0.087153, 0.0523267, 0.017373}; const float CHANNEL_NUM[16][41] = { {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}; // suteng calib_curves_str const float INTENSITY_CAL[7][32] = { {15.43, 14.85, 13.03, 14.75, 10.95, 13.35, 12.43, 10.81, 14.23, 14.31, 14.69, 13.06, 14.18, 13.35, 12.43, 14.38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {2.217, 1.968, 1.782, 1.948, 1.555, 1.816, 1.715, 1.541, 1.835, 1.855, 2.016, 1.775, 1.821, 1.815, 1.713, 1.862, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {1, 1.239, 1.233, 1.203, 1.94, 1.309, 1.592, 1.785, 1.201, 1.169, 1.08, 1.201, 1.28, 1.138, 1.661, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {12.38, 7.835, 6.22, 7.364, 13.3, 5.541, 6.86, 6.056, 15.99, 9.172, 13.08, 8.809, 12.37, 4.158, 6.732, 10.72, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0.06665, 0.06259, 0.08801, 0.05752, 0.1008, 0.08642, 0.1031, 0.09952, 0.08328, 0.05468, 0.06668, 0.04685, 0.06749, 0.0657, 0.1105, 0.05781, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {-0.1445, -0.007686, -1.449, -0.01055, -0.9033, -1.081, -1.25, -1.054, -0.2039, -0.08978, -0.1738, 0.04205, -0.06929, -0.8856, -1.732, -0.02382, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {10.23, 4.915, 13.86, 4.8, 12.89, 9.734, 11.69, 10.34, 14.94, 6.363, 10.6, 6.25, 9.584, 8.288, 14.93, 6.861, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}; // suteng end } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/lib/calibration.h
/****************************************************************************** * Copyright 2021 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. *****************************************************************************/ #pragma once #include <map> #include <memory> #include <string> namespace apollo { namespace drivers { namespace robosense { struct LaserCorrection { /** parameters in db.xml */ float rot_correction; float vert_correction; float dist_correction; float dist_correction_x; float dist_correction_y; float vert_offset_correction; float horiz_offset_correction; int max_intensity; int min_intensity; float focal_distance; float focal_slope; float focal_offset; float cos_rot_correction; ///< cached cosine of rot_correction float sin_rot_correction; ///< cached sine of rot_correction float cos_vert_correction; ///< cached cosine of vert_correction float sin_vert_correction; ///< cached sine of vert_correction int laser_ring; ///< ring number for this laser }; class Calibration { public: std::map<int, LaserCorrection> laser_corrections_; int num_lasers_; bool initialized_; public: Calibration() : initialized_(false) {} explicit Calibration(const std::string& calibration_file) { read(calibration_file); } void read(const std::string& calibration_file); void write(const std::string& calibration_file); }; } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/lib/socket_input.cpp
/****************************************************************************** * Copyright 2021 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 "modules/drivers/lidar/robosense/lib/socket_input.h" #include <arpa/inet.h> #include <errno.h> #include <fcntl.h> #include <poll.h> #include <sys/file.h> #include <sys/socket.h> #include <time.h> #include <unistd.h> namespace apollo { namespace drivers { namespace robosense { //////////////////////////////////////////////////////////////////////// // InputSocket class implementation //////////////////////////////////////////////////////////////////////// /** @brief constructor * * @param private_nh private node handle for driver * @param udp_port UDP port number to connect */ SocketInput::SocketInput() : Input(), sockfd_(-1), port_(0) {} /** @brief destructor */ SocketInput::~SocketInput(void) { (void)close(sockfd_); } void SocketInput::init(uint32_t port) { if (sockfd_ != -1) { (void)close(sockfd_); } // connect to suteng UDP port AINFO << "Opening UDP socket: port " << uint16_t(port); port_ = port; sockfd_ = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd_ == -1) { AERROR << " Init socket failed, UDP port is " << port; } sockaddr_in my_addr; // my address information memset(&my_addr, 0, sizeof(my_addr)); // initialize to zeros my_addr.sin_family = AF_INET; // host byte order my_addr.sin_port = htons(uint16_t(port)); // short, in network byte order my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill in my IP AINFO << "SocketInput::init " << my_addr.sin_addr.s_addr; const int opt = -1; int rtn = setsockopt(sockfd_, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt)); if (rtn < 0) { AINFO << "setsockopt failed !!!!!!!!!!"; return; } if (bind(sockfd_, reinterpret_cast<sockaddr *>(&my_addr), sizeof(sockaddr)) == -1) { AERROR << " Socket bind failed! Port " << port_; return; } if (fcntl(sockfd_, F_SETFL, O_NONBLOCK | FASYNC) < 0) { AERROR << " non-block! Port " << port_; return; } AINFO << "suteng socket fd is " << sockfd_ << ", port " << port_; } /** @brief Get one suteng packet. */ int SocketInput::get_firing_data_packet( apollo::drivers::suteng::SutengPacket *pkt, int time_zone, uint64_t start_time_) { while (true) { if (!input_available(POLL_TIMEOUT)) { AINFO << "SocketInput::get_firing_data_packet---SOCKET_TIMEOUT"; return SOCKET_TIMEOUT; } // Receive packets that should now be available from the // socket using a blocking read. uint8_t bytes[FIRING_DATA_PACKET_SIZE]; ssize_t nbytes = recvfrom(sockfd_, bytes, FIRING_DATA_PACKET_SIZE, 0, NULL, NULL); if (nbytes < 0) { if (errno != EWOULDBLOCK) { AERROR << " recvfail from port " << port_; return RECIEVE_FAIL; } } if ((size_t)nbytes == FIRING_DATA_PACKET_SIZE) { pkt->set_data(bytes, FIRING_DATA_PACKET_SIZE); tm pkt_time; memset(&pkt_time, 0, sizeof(pkt_time)); pkt_time.tm_year = static_cast<int>(bytes[20] + 100); pkt_time.tm_mon = static_cast<int>(bytes[21] - 1); pkt_time.tm_mday = static_cast<int>(bytes[22]); pkt_time.tm_hour = static_cast<int>(bytes[23] + time_zone); pkt_time.tm_min = static_cast<int>(bytes[24]); pkt_time.tm_sec = static_cast<int>(bytes[25]); uint64_t timestamp_sec = static_cast<uint64_t>((mktime(&pkt_time)) * 1e9); uint64_t timestamp_nsec = static_cast<uint64_t>(1000 * (256 * bytes[26] + bytes[27]) + (256 * bytes[28] + bytes[29])) * 1e3 + timestamp_sec; // ns pkt->set_stamp(timestamp_nsec); if (!flags) { AINFO << "robo first PPS-GPS-timestamp: [" << timestamp_nsec << "]"; flags = true; } break; } AERROR << " Incomplete suteng rising data packet read: " << nbytes << " bytes from port " << port_; } return 0; } int SocketInput::get_positioning_data_packtet(const NMEATimePtr &nmea_time) { while (true) { if (!input_available(POLL_TIMEOUT)) { return 1; } // Receive packets that should now be available from the // socket using a blocking read. // Last 234 bytes not use uint8_t bytes[POSITIONING_DATA_PACKET_SIZE]; ssize_t nbytes = recvfrom(sockfd_, bytes, POSITIONING_DATA_PACKET_SIZE, 0, NULL, NULL); if (nbytes < 0) { if (errno != EWOULDBLOCK) { AERROR << " recvfail from port " << port_; return 1; } } if ((size_t)nbytes == POSITIONING_DATA_PACKET_SIZE) { // read successful, exract nmea time if (exract_nmea_time_from_packet(nmea_time, bytes + 303)) { break; } else { return 1; } } AINFO << "incomplete suteng packet read: " << nbytes << " bytes from port " << port_; } return 0; } bool SocketInput::input_available(int timeout) { (void)timeout; struct pollfd fds[1]; fds[0].fd = sockfd_; fds[0].events = POLLIN; do { int retval = poll(fds, 1, POLL_TIMEOUT); if (retval < 0) { // poll() error? if (errno != EINTR) { AERROR << " suteng port " << port_ << "poll() error: " << strerror(errno); } return false; } if (retval == 0) { // poll() timeout? AERROR << " suteng port " << port_ << " poll() timeout"; return false; } if ((fds[0].revents & POLLERR) || (fds[0].revents & POLLHUP) || (fds[0].revents & POLLNVAL)) { // device error? AERROR << " suteng port " << port_ << "poll() reports suteng error"; return false; } } while ((fds[0].revents & POLLIN) == 0); return true; } } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/lib/data_type.h
/****************************************************************************** * Copyright 2021 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. *****************************************************************************/ #pragma once #include <stdint.h> #include <limits> #include <memory> #include <vector> namespace apollo { namespace drivers { namespace robosense { /** * Raw suteng packet constants and structures. */ // static uint64_t pkts_stamp_[84]={0}; static const int BLOCK_SIZE = 100; static const int RAW_SCAN_SIZE = 3; static const int SCANS_PER_BLOCK = 32; // 1block = 32 points static const int BLOCK_DATA_SIZE = (SCANS_PER_BLOCK * RAW_SCAN_SIZE); // size of a block static const float ROTATION_RESOLUTION = 0.01f; /**< degrees */ // static const uint16_t ROTATION_MAX_UNITS = 36000; [>*< hundredths of degrees // <] // because angle_rang is [0, 36000], so thie size is 36001 static const uint16_t ROTATION_MAX_UNITS = 36001; /**< hundredths of degrees */ /** According to Bruce Hall DISTANCE_MAX is 65.0, but we noticed * valid packets with readings up to 130.0. */ static const float DISTANCE_MAX = 130.0f; /**< meters */ static const float DISTANCE_RESOLUTION = 0.005f; /**< meters */ // rs16 static const float DISTANCE_MAX_UNITS = (DISTANCE_MAX / DISTANCE_RESOLUTION + 1.0); // laser_block_id static const uint16_t UPPER_BANK = 0xeeff; static const uint16_t LOWER_BANK = 0xddff; static const float ANGULAR_RESOLUTION = 0.00300919; /** Special Defines for VLP16 support **/ static const int VLP16_FIRINGS_PER_BLOCK = 2; static const int VLP16_SCANS_PER_FIRING = 16; static const float VLP16_BLOCK_TDURATION = 110.592f; static const float VLP16_DSR_TOFFSET = 2.304f; static const float VLP16_FIRING_TOFFSET = 55.296f; static const int PACKET_SIZE = 1248; static const int BLOCKS_PER_PACKET = 12; static const int PACKET_STATUS_SIZE = 4; static const int SCANS_PER_PACKET = (SCANS_PER_BLOCK * BLOCKS_PER_PACKET); // 1 packet的point 个数 static constexpr uint32_t VLP16_SCAN_SIZE = 80; // ceil 754/10 一圈的packet的数目 static constexpr uint32_t VLP16_POINT_SIZE = 28800; // 32256;//VLP16_SCAN_SIZE * SCANS_PER_PACKET; //转一圈点的个数 static constexpr uint32_t HDL64S3D_SCAN_SIZE = 579; // ceil 5789/10 static constexpr uint32_t HDL64S3D_POINT_SIZE = HDL64S3D_SCAN_SIZE * SCANS_PER_PACKET; /** \brief Raw suteng data block. * * Each block contains data from either the upper or lower laser * bank. The device returns three times as many upper bank blocks. * * use stdint.h types, so things work with both 64 and 32-bit machines */ struct RawBlock { uint16_t laser_block_id; ///< UPPER_BANK or LOWER_BANK uint16_t rotation; ///< 0-35999, divide by 100 to get degrees uint8_t data[BLOCK_DATA_SIZE]; // 32*3 }; /** used for unpacking the first two data bytes in a block * * They are packed into the actual data stream misaligned. I doubt * this works on big endian machines. */ union RawDistance { uint16_t raw_distance; uint8_t bytes[2]; }; enum StatusType { HOURS = 72, MINUTES = 77, SECONDS = 83, DATE = 68, MONTH = 78, YEAR = 89, GPS_STATUS = 71 }; /** \brief Raw suteng packet. * * revolution is described in the device manual as incrementing * (mod 65536) for each physical turn of the device. Our device * seems to alternate between two different values every third * packet. One value increases, the other decreases. * * status has either a temperature encoding or the microcode level */ struct RawPacket { RawBlock blocks[BLOCKS_PER_PACKET]; unsigned int gps_timestamp; unsigned char status_type; unsigned char status_value; }; enum Mode { STRONGEST, LAST, DUAL }; static const float nan = std::numeric_limits<float>::signaling_NaN(); /** \brief Raw suteng packet. * * revolution is described in the device manual as incrementing * (mod 65536) for each physical turn of the device. Our device * seems to alternate between two different values every third * packet. One value increases, the other decreases. * * status has either a temperature encoding or the microcode level */ // suteng1 struct RslidarPic { uint32_t col; std::vector<float> distance; std::vector<float> intensity; std::vector<float> azimuthforeachP; std::vector<uint64_t> timestamp; }; // Special Defines for RS16 support static const int RS16_FIRINGS_PER_BLOCK = 2; static const int RS16_SCANS_PER_FIRING = 16; static const float RS16_BLOCK_TDURATION = 100.0f; // [µs] static const float RS16_DSR_TOFFSET = 3.0f; // [µs] static const float RS16_FIRING_TOFFSET = 50.0f; // [µs] static const int RS16_DATA_NUMBER_PER_SCAN = 40000; // Set 40000 to be large enough typedef struct raw_block { uint16_t header; // UPPER_BANK or LOWER_BANK uint8_t rotation_1; uint8_t rotation_2; // combine r1 and r2 together to get 0-35999 // divide by 100 to get degrees uint8_t data[BLOCK_DATA_SIZE]; // 96 } raw_block_t; typedef struct raw_packet { raw_block_t blocks[BLOCKS_PER_PACKET]; uint8_t unused[4]; uint16_t flag; } raw_packet_t; union two_bytes { uint16_t uint; uint8_t bytes[2]; }; // suteng2 union UPacket { struct { RawBlock blocks[BLOCKS_PER_PACKET]; unsigned int gps_timestamp; unsigned char status_type; unsigned char status_value; }; uint8_t data[PACKET_SIZE]; }; typedef std::shared_ptr<UPacket> UPacketPtr; struct NMEATime { uint16_t year; uint16_t mon; uint16_t day; uint16_t hour; uint16_t min; uint16_t sec; uint16_t msec; uint16_t usec; }; typedef std::shared_ptr<NMEATime> NMEATimePtr; } // namespace robosense } // namespace drivers } // namespace apollo
0
apollo_public_repos/apollo/modules/drivers/lidar/robosense
apollo_public_repos/apollo/modules/drivers/lidar/robosense/lib/socket_input_16p.cpp
/****************************************************************************** * Copyright 2021 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 "modules/drivers/lidar/robosense/lib/socket_input_16p.h" #include <arpa/inet.h> #include <errno.h> #include <fcntl.h> #include <poll.h> #include <sys/file.h> #include <sys/socket.h> #include <time.h> #include <unistd.h> namespace apollo { namespace drivers { namespace robosense { //////////////////////////////////////////////////////////////////////// // InputSocket class implementation //////////////////////////////////////////////////////////////////////// /** @brief constructor * * @param private_nh private node handle for driver * @param udp_port UDP port number to connect */ SocketInput16P::SocketInput16P() : Input(), sockfd_(-1), port_(0) {} /** @brief destructor */ SocketInput16P::~SocketInput16P(void) { (void)close(sockfd_); } void SocketInput16P::init(uint32_t port) { if (sockfd_ != -1) { (void)close(sockfd_); } // connect to suteng UDP port AINFO << "Opening UDP socket: port " << uint16_t(port); port_ = port; sockfd_ = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd_ == -1) { AERROR << " Init socket failed, UDP port is " << port; } sockaddr_in my_addr; // my address information memset(&my_addr, 0, sizeof(my_addr)); // initialize to zeros my_addr.sin_family = AF_INET; // host byte order my_addr.sin_port = htons(uint16_t(port)); // short, in network byte order my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill in my IP AINFO << "SocketInput16P::init " << my_addr.sin_addr.s_addr; const int opt = -1; int rtn = setsockopt(sockfd_, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt)); if (rtn < 0) { AINFO << "setsockopt failed !!!!!!!!!!"; return; } if (bind(sockfd_, reinterpret_cast<sockaddr*>(&my_addr), sizeof(sockaddr)) == -1) { AERROR << " Socket bind failed! Port " << port_; return; } if (fcntl(sockfd_, F_SETFL, O_NONBLOCK | FASYNC) < 0) { AERROR << " non-block! Port " << port_; return; } AINFO << "suteng socket fd is " << sockfd_ << ", port " << port_; } /** @brief Get one suteng packet. */ int SocketInput16P::get_firing_data_packet( apollo::drivers::suteng::SutengPacket* pkt, bool use_gps_time) { while (true) { if (!input_available(POLL_TIMEOUT)) { AINFO << "SocketInput16P::get_firing_data_packet---SOCKET_TIMEOUT"; return SOCKET_TIMEOUT; } // Receive packets that should now be available from the // socket using a blocking read. uint8_t bytes[FIRING_DATA_PACKET_SIZE]; ssize_t nbytes = recvfrom(sockfd_, bytes, FIRING_DATA_PACKET_SIZE, 0, NULL, NULL); if (nbytes < 0) { if (errno != EWOULDBLOCK) { AERROR << " recvfail from port " << port_; return RECIEVE_FAIL; } } if ((size_t)nbytes == FIRING_DATA_PACKET_SIZE) { pkt->set_data(bytes, FIRING_DATA_PACKET_SIZE); if (!use_gps_time) { pkt->set_stamp(apollo::cyber::Time().Now().ToNanosecond()); if (!flags) { AINFO << "robo msop first Cyber-timestamp: [" << pkt->stamp() << "]"; flags = true; } } else { uint64_t timestamp_nsec = 0; exract_utc_time_from_packet(bytes + 20, &timestamp_nsec); pkt->set_stamp(timestamp_nsec); if (!flags) { AINFO << "robo msop first PPS-GPS-timestamp: [" << timestamp_nsec << "]"; flags = true; } } break; } AERROR << " Incomplete suteng rising data packet read: " << nbytes << " bytes from port " << port_; } return 0; } bool SocketInput16P::exract_utc_time_from_packet(const uint8_t* bytes, uint64_t* utc_time_ns) { unsigned int field_index = 0; time_t tmp_utc_time_sec = 0; uint64_t tmp_utc_time_usec = 0; for (field_index = 0; field_index < 6; field_index++) { tmp_utc_time_sec <<= 8; tmp_utc_time_sec += static_cast<time_t>(bytes[field_index]); } for (field_index = 6; field_index < 10; field_index++) { tmp_utc_time_usec <<= 8; tmp_utc_time_usec += static_cast<uint64_t>(bytes[field_index]); } *utc_time_ns = static_cast<uint64_t>(tmp_utc_time_usec) * 1e3 + static_cast<uint64_t>((tmp_utc_time_sec)*1e9); // ns // AINFO << "Get UTC time [" << *utc_time_ns // << "]ns from pkt, sec: " << tmp_utc_time_sec // << " usec:" << tmp_utc_time_usec; return true; } int SocketInput16P::get_positioning_data_packet( apollo::drivers::suteng::SutengPacket* pkt, bool use_gps_time) { while (true) { if (!input_available(POLL_TIMEOUT * 5)) { return 1; } // Receive packets that should now be available from the // socket using a blocking read. uint8_t bytes[POSITIONING_DATA_PACKET_SIZE]; ssize_t nbytes = recvfrom(sockfd_, bytes, POSITIONING_DATA_PACKET_SIZE, 0, NULL, NULL); if (nbytes < 0) { if (errno != EWOULDBLOCK) { AERROR << " recvfail from port " << port_; return 1; } } if ((size_t)nbytes == POSITIONING_DATA_PACKET_SIZE) { // read successful, exract UTC time pkt->set_data(bytes, POSITIONING_DATA_PACKET_SIZE); if (!use_gps_time) { pkt->set_stamp(apollo::cyber::Time().Now().ToNanosecond()); if (!flags) { AINFO << "robo difop first Cyber-timestamp: [" << pkt->stamp() << "]"; flags = true; } } else { uint64_t timestamp_nsec = 0; exract_utc_time_from_packet(bytes + 303, &timestamp_nsec); if (!flags) { AINFO << "robo difop first PPS-GPS-timestamp: [" << timestamp_nsec << "] at Cyber-timestamp: [" << apollo::cyber::Time().Now().ToNanosecond() << "]"; flags = true; } pkt->set_stamp(timestamp_nsec); } break; } AINFO << "incomplete suteng packet read: " << nbytes << " bytes from port " << port_; } return 0; } bool SocketInput16P::input_available(int timeout) { struct pollfd fds[1]; fds[0].fd = sockfd_; fds[0].events = POLLIN; do { int retval = poll(fds, 1, timeout); if (retval < 0) { // poll() error? if (errno != EINTR) { AERROR << " suteng port " << port_ << "poll() error: " << strerror(errno); } return false; } if (retval == 0) { // poll() timeout? AERROR << " suteng port " << port_ << " poll() timeout"; return false; } if ((fds[0].revents & POLLERR) || (fds[0].revents & POLLHUP) || (fds[0].revents & POLLNVAL)) { // device error? AERROR << " suteng port " << port_ << "poll() reports suteng error"; return false; } } while ((fds[0].revents & POLLIN) == 0); return true; } } // namespace robosense } // namespace drivers } // namespace apollo
0