repo_id
stringlengths 19
138
| file_path
stringlengths 32
200
| content
stringlengths 1
12.9M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
apollo_public_repos/apollo-contrib/obu
|
apollo_public_repos/apollo-contrib/obu/security/ca_cert.pem
|
-----BEGIN PRIVATE KEY-----
3AyeQyCL7B/VBy0wQTbgjXDAqm7pJI4HQLmXVrllFHI=
-----END PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIGvgAECoQKAAKINgAEBgQhCYWlkdUNvAKNEoEKAQJK/23oXAB1z5IlKjyE+ScV+
Bv+C+SAKZIJsnKzjmPASlRq8XLIAN38+/eBWQ1nNKhbeJgHJa9fk9HJ1pT3DlAKk
BoAEHhh+AKVJgEcwRQIhAKUywIhFUTQGkYQijGugHLyIrWSu2NFAWYEdEDv4vIKl
AiA4eOrwas7+mlRA0+LhPiF5SHUsGsijVuu6tVI1KdtRdQ==
-----END CERTIFICATE-----
-----BEGIN SIGNATURE DIGEST-----
c82e38275369ce6c
-----END SIGNATURE DIGEST-----
| 0
|
apollo_public_repos/apollo-contrib/obu/network
|
apollo_public_repos/apollo-contrib/obu/network/uu/message_set_common.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**uu_message_set
* @file
*
* @brief message set common utils, now just for BSM.
*/
#ifndef MESSAGE_SET_COMMON_H_
#define MESSAGE_SET_COMMON_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stddef.h>
#include "MessageFrame.h"
#define IS_NULL(arg) ((arg) == NULL)
#define ALLOC_OBJ(type, size, ptr) do { \
ptr = (type *)calloc(1, size); \
} while(0)
// error code
#define CV2X_SUCCESS (0)
#define ERR_CV2X_CALLOC (6)
#define ERR_INPUT_NULL (1000)
#define ERR_CV2X_BSM_UPER_ENCODE (5006)
// define of the message config
typedef struct Position3DConfig {
uint8_t elevation;
} Position3DConfig_t;
typedef struct PositionConfidenceSetConfig {
uint8_t elevation;
} PositionConfidenceSetConfig_t;
typedef struct BrakeSystemStatusConfig {
uint8_t brakePadel;
uint8_t wheelBrakes;
uint8_t traction;
uint8_t abs;
uint8_t scs;
uint8_t brakeBoost;
uint8_t auxBrakes;
} BrakeSystemStatusConfig_t;
typedef struct VehicleSizeConfig {
uint8_t height;
} VehicleSizeConfig_t;
typedef struct BsmConfig {
uint8_t plateNo_size; // size
Position3DConfig_t posCfg;
PositionConfidenceSetConfig_t accuracyCfg;
uint8_t angle;
uint8_t motionCfd;
// TODO
// MotionConfidenceSetConfig_t motionCfdCfg;
BrakeSystemStatusConfig_t brakesCfg;
VehicleSizeConfig_t sizeCfg;
uint8_t safetyExt;
// TODO
// VehicleSafetyExtensionsConfig_t safetyExtCfg;
uint8_t token;
} BsmConfig_t;
typedef enum GBCreateOption {
GB_CREAT_ALL = 0,
GB_CREAT_CONTENTS_ONLY = 1
} GBCreateOption_t;
typedef enum GBFreeOption {
GB_FREE_ALL = 0,
GB_FREE_CONTENTS_ONLY = 1
} GBFreeOption_t;
#ifdef __cplusplus
}
#endif
#endif /* MESSAGE_SET_COMMON_H_ */
| 0
|
apollo_public_repos/apollo-contrib/obu/network
|
apollo_public_repos/apollo-contrib/obu/network/uu/gb_bsm.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file gb_bsm.h
*
* @brief BasicSafetyMessage in GB, MotionConfidenceSet and
* VehicleSafetyExtensions excluded.
*/
#pragma once
#ifndef GB_BSM_H_
#define GB_BSM_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "message_set_common.h"
// used to fill the bsm message, now the parameter is all needed
typedef struct BsmParam {
int32_t msgCnt;
uint8_t id[8];
int32_t milli_second;
int32_t pos_lon;
int32_t pos_lat;
int32_t accuracy_pos;
int32_t transmission;
int32_t speed;
int32_t heading;
int32_t acc_lon;
int32_t acc_lat;
int32_t acc_ver;
int32_t acc_yaw;
int32_t size_width;
int32_t size_length;
int32_t vehicle_class;
uint8_t token[4];
} BsmParam_t;
/**
* @brief Create BSM frame.
* @param ppBsm: second rank pointer to the BasicSafetyMessage structure
* pBsmCfg: pointer to the BsmConfig structure
* createOption: create option
* @return 0 if success
*/
int GbBSMCreate(BasicSafetyMessage_t **ppBsm, const BsmConfig_t *pBsmCfg,
GBCreateOption_t createOption);
/**
* @brief Fill BSM frame.
* @param ppBsm: second rank pointer to the BasicSafetyMessage structure
* pBsmCfg: pointer to the BsmConfig structure
* pBsmPara: pointer to the BsmParam structure
* @return 0 if success
*/
int GbBSMFill(BasicSafetyMessage_t **ppBsm, const BsmConfig_t *pBsmCfg,
const BsmParam_t *pBsmPara);
/**
* @brief Encode BSM frame.
* @param pBsm: pointer to the BasicSafetyMessage structure
* ppBuf: second rank pointer to the buffer
* bufSize: size of the buffer
* pCodeSize: pointer to size of the code encoded
* @return 0 if success
*/
int GbBSMEncode(BasicSafetyMessage_t *pBsm, uint8_t **ppBuf, const int bufSize,
int *pCodeSize);
/**
* @brief Free BSM frame.
* @param pBsm: pointer to the BasicSafetyMessage structure
* freeOption: free option
* @return 0 if success
*/
int GbBSMFree(BasicSafetyMessage_t *ppBsm, const GBFreeOption_t freeOption);
#ifdef __cplusplus
}
#endif
#endif // GB_BSM_H_
| 0
|
apollo_public_repos/apollo-contrib/obu/network
|
apollo_public_repos/apollo-contrib/obu/network/pc5/cv2x_app.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file cv2x_app.h
* @brief define network layer interface for application layer
*/
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define MAC_ADDR_LEN (6)
#define DSM_HDR_EXTS_LEN_MAX (256) // 256
// C-V2X system interface start-----------------------
typedef enum _eMsgType_ {
MSG_TYPE_BSM = 0,
MSG_TYPE_RSI,
MSG_TYPE_RSM,
MSG_TYPE_MAP,
MSG_TYPE_SPAT,
MSG_TYPE_SSM,
MSG_TYPE_MAX
} eMsgType;
typedef struct _tDSMRxParm_ {
uint8_t dsmpVer;
uint32_t appId;
char peerMac[MAC_ADDR_LEN];
uint8_t priority;
} __attribute__((packed)) tDSMRxParm;
typedef struct _tDSMTxParm_ {
uint32_t appId; // aid
uint8_t protTp; // eProtTp value
uint8_t priority; //
char peerMac[MAC_ADDR_LEN]; //
char dsmHdrExts[DSM_HDR_EXTS_LEN_MAX]; // must 0
} __attribute__((packed)) tDSMTxParm;
/**
*
* @brief: C-V2X network app system interface read function with blocking.
*
*
*/
int32_t v2x_system_read(char* const rxBuf, const int32_t bufLen,
tDSMRxParm* const rxDSMParm);
/**
*
* @brief: C-V2X network app system interface write function.
*
*
*/
int32_t v2x_system_write(char* const txBuf, const int32_t txLen,
tDSMTxParm* const txDSMParm);
/**
*
* @brief: C-V2X network app system interface init.
*
*
*/
extern int32_t v2x_system_init(void);
/**
*
* @brief: C-V2X network app system interface exit.
*
*
*/
extern int32_t v2x_system_exit(void);
/**
*
* @brief: Get the maximum transmission unit which is supported by network * layer.
*
*/
extern int32_t get_mtu(void);
/**
*
* @brief: Get the message type via appid paremeter.
*
*/
extern eMsgType get_msg_type(const uint32_t aicAid);
#ifdef __cplusplus
}
#endif
| 0
|
apollo_public_repos/apollo-contrib/obu
|
apollo_public_repos/apollo-contrib/obu/utils/os_thread.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file os_thread.cc
* @brief implement thread class
*/
#include <errno.h>
#include <cstring>
#include "glog/logging.h"
#include <iostream>
#include "os_thread.h"
namespace v2x {
OsThread::OsThread(const char* pName, int prio, int stacksize, bool joinable)
: name_(pName),
prio_(prio),
stack_size_(stacksize),
joinable_(joinable),
thread_id_(0) {}
OsThread::~OsThread() {
if (thread_id_) {
int rc = pthread_cancel(thread_id_);
if (0 != rc) {
LOG(ERROR) << "OsThread: Failed to terminate thread " << rc;
}
thread_id_ = 0;
}
}
void OsThread::Start() {
if (thread_id_) {
// The thread is already started
return;
}
int rc = 0;
pthread_attr_t attr;
pthread_attr_init(&attr);
if (joinable_) {
rc = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
if (0 != rc) {
LOG(ERROR) << "OsThread: set joinable attribute failed (" << rc << ")";
}
} else {
rc = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
if (0 != rc) {
LOG(ERROR) << "OsThread: set detached attribute failed (" << rc << ")";
}
}
rc = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
if (0 != rc) {
LOG(ERROR) << "OsThread: set inherit schedule failed (" << rc << ")";
}
rc = pthread_attr_setschedpolicy(&attr, SCHED_RR);
if (0 != rc) {
LOG(ERROR) << "OsThread: set schedule policy failed (" << rc << ")";
}
sched_param param;
memset(¶m, 0, sizeof(param));
param.sched_priority = prio_;
rc = pthread_attr_setschedparam(&attr, ¶m);
if (0 != rc) {
LOG(ERROR) << "OsThread: set priority failed (" << rc << ")";
}
rc = pthread_attr_setstacksize(&attr, stack_size_);
if (0 != rc) {
LOG(ERROR) << "OsThread: set stack size failed (" << rc << ")";
}
rc = pthread_create(&thread_id_, &attr, OsThread::ThreadProc, this);
if (0 != rc) {
LOG(ERROR) << "OsThread: spawn the os thread failed (" << rc << ")";
}
}
const char* OsThread::GetName() const {
return name_.c_str();
}
void* OsThread::ThreadProc(void* arg) {
OsThread* pthread = (OsThread*)arg;
try {
pthread->Run();
} catch (...) {
LOG(ERROR) << "OsThread"
"Exception is thrown in OsThread::Run !!! "
<< std::endl;
}
if (!pthread->joinable_) {
pthread->thread_id_ = 0;
delete pthread;
}
pthread_exit(0);
return nullptr;
}
int OsThread::Join(int waitMs) {
int rc = 0;
if (os_wait_forever == waitMs) {
rc = pthread_join(thread_id_, NULL);
} else {
struct timespec ts;
if (-1 == clock_gettime(CLOCK_REALTIME, &ts)) {
LOG(ERROR) << "get time failed";
return 0;
}
ts.tv_nsec += waitMs * 1000;
rc = pthread_timedjoin_np(thread_id_, NULL, &ts);
}
if (0 != rc) {
LOG(ERROR) << "Error in joining thread " << name_ << " (" << thread_id_
<< ") Error=" << rc;
}
return 1;
}
} // namespace v2x
| 0
|
apollo_public_repos/apollo-contrib/obu
|
apollo_public_repos/apollo-contrib/obu/utils/os_thread.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file os_thread.h
* @brief define thread class
*/
#pragma once
#include <pthread.h>
#include <string>
namespace v2x {
const int os_wait_forever = -1;
const int os_no_wait = 0;
enum Priority {
OS_THREAD_PRIORITY_IDLE = 10,
OS_THREAD_PRIORITY_LOWEST = 30,
OS_THREAD_PRIORITY_BELOW_NORMAL = 70,
OS_THREAD_PRIORITY_NORMAL = 90,
OS_THREAD_PRIORITY_ABOVE_NORMAL = 92,
OS_THREAD_PRIORITY_HIGHEST = 95,
OS_THREAD_PRIORITY_TIME_CRITICAL = 99,
};
enum {
OS_THREAD_DEFAULT_STACK_SIZE = 512 * 1024, // 512k
};
class OsThread {
public:
/**
* Create a thread.
*/
OsThread(const char* pName, int prio = OS_THREAD_PRIORITY_NORMAL,
int stacksize = OS_THREAD_DEFAULT_STACK_SIZE, bool joinable = false);
virtual ~OsThread() noexcept;
/**
* It will execute the Run method within this thread context.
*/
void Start();
/**
* Wait for the thread to exit.
*
* @param timeout The timeout value in ms. Default zero means forever
*/
int Join(int timeout = os_wait_forever);
/**
* Get the thread name
*/
const char* GetName() const;
protected:
/**
* The run method should be implemented by derived class.
*
* When this finishes, the thread itself will be destroyed
* if it is not joinable.
*/
virtual void Run() = 0;
private:
OsThread(const OsThread&);
OsThread& operator=(const OsThread&);
static void* ThreadProc(void* arg);
std::string name_;
int prio_;
int stack_size_;
bool joinable_;
pthread_t thread_id_;
};
} // namespace v2x
| 0
|
apollo_public_repos/apollo-contrib/obu
|
apollo_public_repos/apollo-contrib/obu/utils/CMakeLists.txt
|
cmake_minimum_required(VERSION 2.8)
#add_subdirectory(coordinate_transition)
#aux_source_directory(. DIRSRCS)
add_library(utils os_thread.cc coordinate_transition/coordinate_transition.cc)
| 0
|
apollo_public_repos/apollo-contrib/obu
|
apollo_public_repos/apollo-contrib/obu/utils/singleton.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file singleton.h
* @brief define singleton class
*/
#pragma once
#include <mutex>
namespace v2x {
template <typename Singleton>
class SingletonService {
public:
// Instance() returns the singleton object .
static Singleton* Instance(void);
// InstallInstance() install the singleton object.
static void InstallInstance(Singleton* pinstance);
// UninstallInstance() uninstall the singleton object.
static Singleton* UninstallInstance();
// Check if the instance is installed or not
static bool IsInstalled(void);
private:
static Singleton* instance_;
static std::mutex mutex_;
};
template <typename Singleton>
Singleton* SingletonService<Singleton>::instance_ = NULL;
template <typename Singleton>
std::mutex SingletonService<Singleton>::mutex_;
template <typename Singleton>
inline Singleton* SingletonService<Singleton>::Instance(void) {
if (instance_ != NULL) {
return instance_;
}
return nullptr;
}
template <typename Singleton>
inline void SingletonService<Singleton>::InstallInstance(
Singleton* pinstance) {
std::lock_guard<std::mutex> guard(mutex_);
instance_ = pinstance;
}
template <typename Singleton>
inline Singleton* SingletonService<Singleton>::UninstallInstance() {
std::lock_guard<std::mutex> guard(mutex_);
Singleton* pinstance = instance_;
instance_ = nullptr;
return pinstance;
}
template <typename Singleton>
inline bool SingletonService<Singleton>::IsInstalled(void) {
return (instance_ != nullptr);
}
} // namespace v2x
| 0
|
apollo_public_repos/apollo-contrib/obu
|
apollo_public_repos/apollo-contrib/obu/utils/apollo_ssm_decoder.h
|
#pragma once
#ifdef APOLLO_API
# undef APOLLO_API
#endif
#define APOLLO_API __attribute__((visibility("default")))
#include <string>
namespace apollo {
namespace v2x {
namespace obu {
namespace conv {
/**
* Decode a SSM data to serialized proto data
*
* @param buf SSM data buffer
* @param buflen SSM buffer length
* @param res serialized proto data
* @return true if success and res changed
* false if failed
*/
APOLLO_API bool DecodeSSM(const void *buf, size_t buflen, std::string *res);
} // namespace conv
} // namespace obu
} // namespace v2x
} // namespace apollo
| 0
|
apollo_public_repos/apollo-contrib/obu
|
apollo_public_repos/apollo-contrib/obu/utils/macro.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.
=========================================================================*/
#ifndef APP_COMMON_MACRO_H
#define APP_COMMON_MACRO_H
#include <iomanip>
#include <iostream>
#define DISALLOW_COPY_AND_ASSIGN(classname) \
private: \
classname(const classname &); \
classname &operator=(const classname &);
#define DISALLOW_IMPLICIT_CONSTRUCTORS(classname) \
private: \
classname(); \
DISALLOW_COPY_AND_ASSIGN(classname);
#define DECLARE_SINGLETON(classname) \
public: \
static classname *instance() { \
static classname instance; \
return &instance; \
} \
DISALLOW_IMPLICIT_CONSTRUCTORS(classname) \
private:
#endif // APP_COMMON_MACRO_H
| 0
|
apollo_public_repos/apollo-contrib/obu
|
apollo_public_repos/apollo-contrib/obu/utils/cmn_queue.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 <condition_variable>
#include <mutex>
#include <queue>
#include <thread>
namespace v2x {
template <typename DataType>
class CmnQueue {
public:
CmnQueue() : max_size_(1) {}
explicit CmnQueue(uint32_t size) {
max_size_ = size > 0 ? size : 1;
}
~CmnQueue() = default;
bool is_empty() const {
std::lock_guard<std::mutex> lk(queue_mutex_);
return ptr_queue_.empty();
}
void push(DataType data) {
// std::make_shared<>() may throw std::bad_alloc or any exception thrown by
// the constructor of DataType. If an exception is thrown, it has no effect.
try {
std::shared_ptr<DataType> data_ptr(
std::make_shared<DataType>(std::move(data)));
std::lock_guard<std::mutex> lk(queue_mutex_);
ptr_queue_.push(data_ptr);
while (ptr_queue_.size() > max_size_) {
ptr_queue_.pop();
}
queue_condition_.notify_one();
} catch (const std::bad_alloc& ba) {
std::cout << ba.what() << std::endl;
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
} catch (...) {
std::cout << "Exception is thrown in CmnQueue::push." << std::endl;
}
}
std::shared_ptr<DataType> pop() {
std::unique_lock<std::mutex> lk(queue_mutex_);
queue_condition_.wait(lk, [this] { return !ptr_queue_.empty(); });
std::shared_ptr<DataType> ret_ptr = ptr_queue_.front();
ptr_queue_.pop();
return ret_ptr;
}
std::shared_ptr<DataType> try_pop() {
std::lock_guard<std::mutex> lk(queue_mutex_);
if (ptr_queue_.empty()) {
return std::shared_ptr<DataType>(nullptr);
}
std::shared_ptr<DataType> ret_ptr = ptr_queue_.front();
ptr_queue_.pop();
return ret_ptr;
}
std::shared_ptr<DataType> read() const {
std::unique_lock<std::mutex> lk(queue_mutex_);
queue_condition_.wait(lk, [this] { return !ptr_queue_.empty(); });
return ptr_queue_.front();
}
std::shared_ptr<DataType> try_read() const {
std::lock_guard<std::mutex> lk(queue_mutex_);
if (ptr_queue_.empty()) {
return std::shared_ptr<DataType>(nullptr);
}
return ptr_queue_.front();
}
private:
uint64_t max_size_;
mutable std::mutex queue_mutex_;
std::queue<std::shared_ptr<DataType>> ptr_queue_;
std::condition_variable queue_condition_;
};
} // namespace v2x
| 0
|
apollo_public_repos/apollo-contrib/obu/utils
|
apollo_public_repos/apollo-contrib/obu/utils/coordinate_transition/coordinate_transition.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file coordinate_transition.cc
* @brief The coordinate transition program for the v2x module
*/
#include "coordinate_transition.h"
// namespace apollo {
namespace v2x {
CoordinateTransition::CoordinateTransition()
: zone_(FLAGS_zone), southhemi_(FLAGS_southernhemi_flag) {}
void CoordinateTransition::Init() {}
void CoordinateTransition::LatLonToUTMXY(const double lat, const double lon,
double& utm_x, double& utm_y) {
MathLanLonToXY(DegToRad(lat), DegToRad(lon), UTMCentralMeridian(lon), utm_x,
utm_y);
// Adjust easting and northing for UTM system
utm_x = utm_x * kUTMScaleFactor + kUTMXCompensation;
utm_y = utm_y * kUTMScaleFactor;
if (utm_y < 0.0) {
utm_y += kUTMYCompensation;
}
}
void CoordinateTransition::UTMXYToLatLon(double utm_x, double utm_y,
double& lat, double& lon) {
utm_x -= kUTMXCompensation;
utm_x /= kUTMScaleFactor;
// If in southern hemisphere, adjust y accordingly
if (southhemi_) {
utm_y -= kUTMYCompensation;
}
utm_y /= kUTMScaleFactor;
double cmeridian = DegToRad(zone_ * 6.0 - 183.0);
double lat_radian = 0.0;
double lon_radian = 0.0;
MathXYToLanLon(utm_x, utm_y, cmeridian, lat_radian, lon_radian);
lat = RadToDeg(lat_radian);
lon = RadToDeg(lon_radian);
}
void CoordinateTransition::ThetaToHeading(const double theta_radian,
double velocity_x, double velocity_y,
double& heading) {
// Stationary state
if (fabs(velocity_x) < 0.01) {
velocity_x = 0.0;
}
if (fabs(velocity_y) < 0.01) {
velocity_y = 0.0;
}
double heading_radian = 0.0;
if (fabs(velocity_x) < 0.01 && fabs(velocity_y) < 0.01) {
heading_radian = 0.0;
} else if (fabs(velocity_x) < 0.01 && velocity_y > 0.0) {
heading_radian = 0.0;
} else if (fabs(velocity_x) < 0.01 && velocity_y < 0.0) {
heading_radian = kPI;
} else if (fabs(velocity_y) < 0.01 && velocity_x > 0.0) {
heading_radian = kPI / 2;
} else if (fabs(velocity_y) < 0.01 && velocity_x < 0.0) {
heading_radian = (3 * kPI) / 2;
} else if (velocity_x > 0.0 && velocity_y > 0.0) {
heading_radian = kPI / 2 - theta_radian;
} else if (velocity_x > 0.0 && velocity_y < 0.0) {
heading_radian = kPI / 2 - theta_radian;
} else if (velocity_x < 0.0 && velocity_y < 0.0) {
heading_radian = kPI / 2 - theta_radian;
} else if (velocity_x < 0.0 && velocity_y > 0.0) {
heading_radian = (5 * kPI) / 2 - theta_radian;
}
heading = RadToDeg(heading_radian);
}
void CoordinateTransition::MathLanLonToXY(const double lat_radian,
const double lon_radian,
const double central_meridian_radian,
double& x, double& y) {
// Precalculate ep2
double ep2 = (pow(kEmA, 2.0) - pow(kEmB, 2.0)) / pow(kEmB, 2.0);
// Precalculate nu2
double nu2 = ep2 * pow(cos(lat_radian), 2.0);
// Precalculate N
double n = pow(kEmA, 2.0) / (kEmB * sqrt(1 + nu2));
// Precalculate t
double t = tan(lat_radian);
double t2 = pow(t, 2.0);
double t4 = pow(t, 4.0);
double t6 = pow(t, 6.0);
// Precalculate l
double l = lon_radian - central_meridian_radian;
// Precalculate coefficients for l**n in the equations below so a normal human
// being can read the expressions for easting and northing -- l**1 and l**2
// have coefficients of 1.0
double l3coef = 1.0 - t2 + nu2;
double l4coef = 5.0 - t2 + 9 * nu2 + 4.0 * (nu2 * nu2);
double l5coef = 5.0 - 18.0 * t2 + t4 + 14.0 * nu2 - 58.0 * t2 * nu2;
double l6coef = 61.0 - 58.0 * t2 + t4 + 270.0 * nu2 - 330.0 * t2 * nu2;
double l7coef = 61.0 - 479.0 * t2 + 179.0 * t4 - t6;
double l8coef = 1385.0 - 3111.0 * t2 + 543.0 * t4 - t6;
// Calculate easting (x)
x = n * cos(lat_radian) * l +
(n / 6.0 * pow(cos(lat_radian), 3.0) * l3coef * pow(l, 3.0)) +
(n / 120.0 * pow(cos(lat_radian), 5.0) * l5coef * pow(l, 5.0)) +
(n / 5040.0 * pow(cos(lat_radian), 7.0) * l7coef * pow(l, 7.0));
// Calculate northing (y)
y = ArcLengthOfMeridian(lat_radian) +
(t / 2.0 * n * pow(cos(lat_radian), 2.0) * pow(l, 2.0)) +
(t / 24.0 * n * pow(cos(lat_radian), 4.0) * l4coef * pow(l, 4.0)) +
(t / 720.0 * n * pow(cos(lat_radian), 6.0) * l6coef * pow(l, 6.0)) +
(t / 40320.0 * n * pow(cos(lat_radian), 8.0) * l8coef * pow(l, 8.0));
}
void CoordinateTransition::MathXYToLanLon(const double x, const double y,
const double central_meridian_radian,
double& lat_radian,
double& lon_radian) {
// Get the value of phif, the footpoint latitude
double phif = FootpointLatitude(y);
// Precalculate ep2
double ep2 = (pow(kEmA, 2.0) - pow(kEmB, 2.0)) / pow(kEmB, 2.0);
// Precalculate cos (phif)
double cf = cos(phif);
// Precalculate nuf2
double nuf2 = ep2 * pow(cf, 2.0);
// Precalculate Nf and initialize nf_pow
double nf = pow(kEmA, 2.0) / (kEmB * sqrt(1 + nuf2));
double nf_pow = nf;
// Precalculate tf
double tf = tan(phif);
double tf2 = tf * tf;
double tf4 = tf2 * tf2;
// Precalculate fractional coefficients for x**n in the equations below to
// simplify the expressions for latitude and longitude
double x1frac = 1.0 / (nf_pow * cf);
nf_pow *= nf; /* now equals Nf**2) */
double x2frac = tf / (2.0 * nf_pow);
nf_pow *= nf; /* now equals Nf**3) */
double x3frac = 1.0 / (6.0 * nf_pow * cf);
nf_pow *= nf; /* now equals Nf**4) */
double x4frac = tf / (24.0 * nf_pow);
nf_pow *= nf; /* now equals Nf**5) */
double x5frac = 1.0 / (120.0 * nf_pow * cf);
nf_pow *= nf; /* now equals Nf**6) */
double x6frac = tf / (720.0 * nf_pow);
nf_pow *= nf; /* now equals Nf**7) */
double x7frac = 1.0 / (5040.0 * nf_pow * cf);
nf_pow *= nf; /* now equals Nf**8) */
double x8frac = tf / (40320.0 * nf_pow);
// Precalculate polynomial coefficients for x**n. -- x**1 does not have a
// polynomial coefficient
double x2poly = -1.0 - nuf2;
double x3poly = -1.0 - 2 * tf2 - nuf2;
double x4poly = 5.0 + 3.0 * tf2 + 6.0 * nuf2 - 6.0 * tf2 * nuf2 -
3.0 * (nuf2 * nuf2) - 9.0 * tf2 * (nuf2 * nuf2);
double x5poly = 5.0 + 28.0 * tf2 + 24.0 * tf4 + 6.0 * nuf2 + 8.0 * tf2 * nuf2;
double x6poly =
-61.0 - 90.0 * tf2 - 45.0 * tf4 - 107.0 * nuf2 + 162.0 * tf2 * nuf2;
double x7poly = -61.0 - 662.0 * tf2 - 1320.0 * tf4 - 720.0 * (tf4 * tf2);
double x8poly = 1385.0 + 3633.0 * tf2 + 4095.0 * tf4 + 1575 * (tf4 * tf2);
// Calculate latitude
lat_radian = phif + x2frac * x2poly * (x * x) +
x4frac * x4poly * pow(x, 4.0) + x6frac * x6poly * pow(x, 6.0) +
x8frac * x8poly * pow(x, 8.0);
// Calculate longitude
lon_radian = central_meridian_radian + x1frac * x +
x3frac * x3poly * pow(x, 3.0) + x5frac * x5poly * pow(x, 5.0) +
x7frac * x7poly * pow(x, 7.0);
}
double CoordinateTransition::FootpointLatitude(const double y) {
double result = 0.0;
// Precalculate n (Eq. 10.18)
double n = (kEmA - kEmB) / (kEmA + kEmB);
// Precalculate alpha_ (Eq. 10.22)
// (Same as alpha in Eq. 10.17)
double alpha_ =
((kEmA + kEmB) / 2.0) * (1 + (pow(n, 2.0) / 4) + (pow(n, 4.0) / 64));
// Precalculate y_ (Eq. 10.23)
double y_ = y / alpha_;
// Precalculate beta_ (Eq. 10.22)
double beta_ = (3.0 * n / 2.0) + (-27.0 * pow(n, 3.0) / 32.0) +
(269.0 * pow(n, 5.0) / 512.0);
// Precalculate gamma_ (Eq. 10.22)
double gamma_ = (21.0 * pow(n, 2.0) / 16.0) + (-55.0 * pow(n, 4.0) / 32.0);
// Precalculate delta_ (Eq. 10.22)
double delta_ = (151.0 * pow(n, 3.0) / 96.0) + (-417.0 * pow(n, 5.0) / 128.0);
// Precalculate epsilon_ (Eq. 10.22)
double epsilon_ = (1097.0 * pow(n, 4.0) / 512.0);
// Now calculate the sum of the series (Eq. 10.21)
result = y_ + (beta_ * sin(2.0 * y_)) + (gamma_ * sin(4.0 * y_)) +
(delta_ * sin(6.0 * y_)) + (epsilon_ * sin(8.0 * y_));
return result;
}
double CoordinateTransition::ArcLengthOfMeridian(const double lat_radian) {
double result = 0.0;
// Precalculate n
double n = (kEmA - kEmB) / (kEmA + kEmB);
// Precalculate alpha
double alpha = ((kEmA + kEmB) / 2.0) *
(1.0 + (pow(n, 2.0) / 4.0) + (pow(n, 4.0) / 64.0));
// Precalculate beta
double beta = (-3.0 * n / 2.0) + (9.0 * pow(n, 3.0) / 16.0) +
(-3.0 * pow(n, 5.0) / 32.0);
// Precalculate gamma
double gamma = (15.0 * pow(n, 2.0) / 16.0) + (-15.0 * pow(n, 4.0) / 32.0);
// Precalculate delta
double delta = (-35.0 * pow(n, 3.0) / 48.0) + (105.0 * pow(n, 5.0) / 256.0);
// Precalculate epsilon
double epsilon = (315.0 * pow(n, 4.0) / 512.0);
// Now calculate the sum of the series and return
result = alpha *
(lat_radian + (beta * sin(2.0 * lat_radian)) +
(gamma * sin(4.0 * lat_radian)) + (delta * sin(6.0 * lat_radian)) +
(epsilon * sin(8.0 * lat_radian)));
return result;
}
double CoordinateTransition::UTMCentralMeridian(const double lon) {
double zone = 0.0;
if (lon < 0.0) {
zone = static_cast<int>((180 + lon) / 6.0) + 1;
} else {
zone = static_cast<int>(lon / 6) + 31;
}
return DegToRad(-183.0 + (zone * 6.0));
}
} // namespace v2x
//} // namespace apollo
| 0
|
apollo_public_repos/apollo-contrib/obu/utils
|
apollo_public_repos/apollo-contrib/obu/utils/coordinate_transition/coordinate_transition.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file coordinate_transition.h
* @brief The coordinate transition program for the v2x module
*/
#ifndef V2X_APP_POLICIES_COORDINATE_TRANSITION_COORDINATE_TRANSITION_H
#define V2X_APP_POLICIES_COORDINATE_TRANSITION_COORDINATE_TRANSITION_H
#include <math.h>
#include <iostream>
#include "v2x_gflags.h"
// namespace apollo {
namespace v2x {
class CoordinateTransition {
public:
explicit CoordinateTransition();
~CoordinateTransition() {}
// Function that init
void Init();
// Function that convert LatitudeLongitude pair to x and y coordinates
// in the Universal Transverse Mercator projection
void LatLonToUTMXY(const double lat, const double lon, double& utm_x,
double& utm_y);
// Function that convert XY coordinates in the Universal Transverse Mercator
// projection to LatitudeLongitude pair
void UTMXYToLatLon(double utm_x, double utm_y, double& lat, double& lon);
// Function that convert Theta to Heading, velocity_x and velocity_y(m/s)
void ThetaToHeading(const double theta_radian, double velocity_x,
double velocity_y, double& heading);
// Function that convert Deg to Rad
double DegToRad(const double deg) {
return (deg / 180.0 * kPI);
}
// Function that Rad Theta to Deg
double RadToDeg(const double rad) {
return (rad / kPI * 180.0);
}
const double kPI = 3.14159265358979323846;
const double kEmA = 6378137.0;
const double kEmB = 6356752.3142451;
const double kUTMScaleFactor = 0.9996;
const double kUTMXCompensation = 500000.0;
const double kUTMYCompensation = 10000000.0;
private:
// Function that mathematical formula to achieve LatLon to XY
void MathLanLonToXY(const double lat_radian, const double lon_radian,
const double central_meridian_radian, double& x,
double& y);
// Function that mathematical formula to achieve XY to LatLon
void MathXYToLanLon(const double x, const double y,
const double central_meridian_radian, double& lat_radian,
double& lon_radian);
// Function that computes the footpoint latitude for use
// in converting transverse Mercator coordinates to ellipsoidal coordinates
double FootpointLatitude(const double y);
// Function that computes the ellipsoidal distance from the equator to
// a point at a given latitude
double ArcLengthOfMeridian(const double lat_radian);
// Function that computes CentralMeridian
double UTMCentralMeridian(const double lon);
int zone_;
bool southhemi_;
};
} // namespace v2x
//} // namespace apollo
#endif // V2X_APP_POLICIES_COORDINATE_TRANSITION_COORDINATE_TRANSITION_H
| 0
|
apollo_public_repos/apollo-contrib/obu
|
apollo_public_repos/apollo-contrib/obu/conf/v2x.flag
|
--obu_ip_addr=192.168.10.6
--ipc_ip_addr=192.168.10.6
# security feature enable flag
--security_flag=false
--root_ca=
--self_ca=
# authentication parameters for uu interface mode
--auth_url=http://192.168.1.1:8000/v2x-auth/v1/auth
--uu_server_addr=192.168.1.1
--uu_socket_port=10000
--uu_device_id=00000000000000
--uu_device_mac=00000000000000
--uu_message_interval_in_ms=1000
--uu_debug=true
# coordination convert
--zone=50
--southernhemi_flag=false
--debug_flag=true
| 0
|
apollo_public_repos/apollo-contrib
|
apollo_public_repos/apollo-contrib/pandora/build_and_install.sh
|
#!/usr/bin/env bash
###############################################################################
# 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.
###############################################################################
ROS_PATH=/home/tmp/ros
source ${ROS_PATH}/setup.bash
cd /tmp
catkin_make_isolated --install \
--source /apollo/modules/drivers/pandora/pandora_driver \
--install-space ${ROS_PATH} -DCMAKE_BUILD_TYPE=Release \
--cmake-args --no-warn-unused-cli
catkin_make_isolated --install \
--source /apollo/modules/drivers/pandora/pandora_pointcloud \
--install-space ${ROS_PATH} -DCMAKE_BUILD_TYPE=Release \
--cmake-args --no-warn-unused-cli
echo "Build pandora driver successfully."
| 0
|
apollo_public_repos/apollo-contrib
|
apollo_public_repos/apollo-contrib/pandora/README.md
|
## Pandora
Pandora driver, including:
1. data packet processing --> /apollo/sensor/pandora/hesai40/PointCloud2
2. compensation --> /apollo/sensor/pandora/hesai40/compensator/PointCloud2
Compensation relies on `tf` to query the coordination transform, so gnss_driver
is required to run the pandora driver.
### Topics
* /apollo/sensor/pandora/hesai40/PointCloud2 --> sensor_msgs/PointCloud2
* /apollo/sensor/pandora/hesai40/compensator/PointCloud2 --> sensor_msgs/PointCloud2
### Coordination
* world
* novatel
* hesai40
### Build Pandora
```bash
# in dev docker
bash /apollo/modules/drivers/pandora/build_and_install.sh
```
The output will overwrite the pandora driver in `/home/tmp/ros/`.
### Configure Pandora Driver
First, specify the parameters of the car, modify them in launch file.
> Notice: Only for hesai40
**Intrinsic parameter file**
Intrinsic parameter file resides in lidar device, pandora driver will try to
read from device :
**Other configs**
```xml
<arg name="pandora_ip" default="192.168.20.51"/>
<arg name="lidar_recv_port" default="2368"/>
<arg name="gps_recv_port" default="10110"/>
<arg name="start_angle" default="135"/>
<arg name="pandora_camera_port" default="9870"/>
<arg name="enable_camera" default="true"/>
<arg name="timezone" default="8"/>
<arg name="frame_id" default="hesai40"/>
```
### Start Pandora Driver
**Please change the parameters in the launch file for cars when you start**
```bash
bash /apollo/scripts/pandora.sh
# or
roslaunch pandora_driver pandora_driver.launch
roslaunch pandora_pointcloud compensator_node.launch
```
### FAQ
1. 'no message of /apollo/sensor/pandora/hesai40/PointCloud2 topic'
The network between the host and pandora is having problem. Please use
`sudo tcpdump -i eth0 udp port 2368` to check if pandora packets are received.
2. 'cannot find transform ...'
`Compensaton` relies on `tf`, please double check if `gnss_driver` has been
started, and also use `rostopic echo /tf` to check if there are any message
in the tf.
| 0
|
apollo_public_repos/apollo-contrib
|
apollo_public_repos/apollo-contrib/pandora/BUILD
|
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
# Run build_and_install.sh to install Pandora driver. Here we just include the
# files into lint check.
filegroup(
name = "pandora",
srcs = glob([
"**/*.cc",
"**/*.h",
]),
)
cpplint()
| 0
|
apollo_public_repos/apollo-contrib/pandora
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/CMakeLists.txt
|
cmake_minimum_required(VERSION 2.8.3)
project(pandora_driver)
find_package(catkin REQUIRED)
catkin_package(
CATKIN_DEPENDS)
find_package(catkin REQUIRED COMPONENTS
cv_bridge
image_transport
pcl_ros
roscpp
roslib
sensor_msgs
)
find_package( Boost REQUIRED )
find_package( PCL REQUIRED COMPONENTS common )
find_package( OpenCV REQUIRED )
catkin_package()
set (CMAKE_CXX_FLAGS "-fPIC -std=c++11")
add_subdirectory(src/Pandar40P)
include_directories(
.
include
src/Pandar40P/include
${Boost_INCLUDE_DIRS}
${PCL_INCLUDE_DIRS}
${OpenCV_INCLUDE_DIRS}
${catkin_INCLUDE_DIRS}
)
add_library( ${PROJECT_NAME} SHARED
src/pandora.cc
src/pandora_client.c
src/pandora_camera.cc
src/util.c
src/tcp_command_client.c
)
target_link_libraries(${PROJECT_NAME}
Pandar40P
${catkin_LIBRARIES}
${Boost_LIBRARIES}
${PCL_IO_LIBRARIES}
${OpenCV_LIBS}
yaml-cpp
jpeg
)
if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR})
add_executable(pandora_node
src/main.cc
)
target_link_libraries(pandora_node
Pandar40P
${PROJECT_NAME}
${Boost_LIBRARIES}
${PCL_IO_LIBRARIES}
${OpenCV_LIBS}
yaml-cpp
jpeg
)
add_executable(pandora_test
test/test.cc
)
target_link_libraries(pandora_test
Pandar40P
${PROJECT_NAME}
${Boost_LIBRARIES}
${PCL_IO_LIBRARIES}
${OpenCV_LIBS}
yaml-cpp
jpeg
)
endif(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR})
install(DIRECTORY include/
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION})
install(DIRECTORY launch/
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/launch)
install(TARGETS ${PROJECT_NAME}
DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION})
install(TARGETS pandora_node
RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION})
install(TARGETS pandora_test
RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION})
| 0
|
apollo_public_repos/apollo-contrib/pandora
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/package.xml
|
<?xml version="1.0"?>
<package>
<name>pandora_driver</name>
<version>0.0.0</version>
<description>The pandora_driver package</description>
<!-- One maintainer tag required, multiple allowed, one person per tag -->
<!-- Example: -->
<!-- <maintainer email="jane.doe@example.com">Jane Doe</maintainer> -->
<maintainer email="wangpeng16@baidu.com">yy</maintainer>
<!-- One license tag required, multiple allowed, one license per tag -->
<!-- Commonly used license strings: -->
<!-- BSD, MIT, Boost Software License, GPLv2, GPLv3, LGPLv2.1, LGPLv3 -->
<license>TODO</license>
<!-- Url tags are optional, but multiple are allowed, one per tag -->
<!-- Optional attribute type can be: website, bugtracker, or repository -->
<!-- Example: -->
<!-- <url type="website">http://wiki.ros.org/pandora_camera</url> -->
<!-- Author tags are optional, multiple are allowed, one per tag -->
<!-- Authors do not have to be maintainers, but could be -->
<!-- Example: -->
<!-- <author email="jane.doe@example.com">Jane Doe</author> -->
<!-- The *_depend tags are used to specify dependencies -->
<!-- Dependencies can be catkin packages or system dependencies -->
<!-- Examples: -->
<!-- Use build_depend for packages you need at compile time: -->
<!-- <build_depend>message_generation</build_depend> -->
<!-- Use buildtool_depend for build tool packages: -->
<!-- <buildtool_depend>catkin</buildtool_depend> -->
<!-- Use run_depend for packages you need at runtime: -->
<!-- <run_depend>message_runtime</run_depend> -->
<!-- Use test_depend for packages you need only for testing: -->
<!-- <test_depend>gtest</test_depend> -->
<buildtool_depend>catkin</buildtool_depend>
<build_depend>roscpp</build_depend>
<build_depend>sensor_msgs</build_depend>
<run_depend>message_runtime</run_depend>
<run_depend>cv_bridge</run_depend>
<run_depend>image_transport</run_depend>
<run_depend>std_msgs</run_depend>
<!-- The export tag contains other, unspecified, tags -->
<export>
<!-- Other tools can request additional information be placed here -->
</export>
</package>
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/test/test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "pandora/pandora.h"
using apollo::drivers::hesai::Pandora;
FILE* lidarTimestampFile = fopen("lidar-timestamp.txt", "w");
double pandoraToSysTimeGap = 0;
int gpsTimestamp = 0;
void gpsCallback(int timestamp) {
struct timeval ts;
gettimeofday(&ts, NULL);
gpsTimestamp = timestamp;
double tv_sec = static_cast<double>(ts.tv_sec);
double tv_usec = static_cast<double>(ts.tv_usec);
double t = static_cast<double>(timestamp);
pandoraToSysTimeGap = tv_sec + (tv_usec / 1000000.0) - timestamp;
printf("gps: %d, gap: %f\n", timestamp, pandoraToSysTimeGap);
}
void lidarCallback(boost::shared_ptr<PPointCloud> cld, double timestamp) {
struct timeval ts;
gettimeofday(&ts, NULL);
printf("lidar: %lf with frame id : %s \n", timestamp,
cld->header.frame_id.c_str());
// fprintf(lidarTimestampFile, "%d, %f,%f\n", gpsTimestamp, timestamp,
// ts.tv_sec + (double)ts.tv_usec / 1000000 - pandoraToSysTimeGap -
// timestamp);
}
void cameraCallback(boost::shared_ptr<cv::Mat> matp, double timestamp,
int picid, bool distortion) {
printf("callback %d %d timestamp %lf \n", picid, distortion, timestamp);
}
int main(int argc, char** argv) {
Pandora pandora(std::string("192.168.20.51"), 2368, 10110, lidarCallback,
gpsCallback, 13500, 9870, cameraCallback, 1, 0,
std::string("hesai40"));
pandora.Start();
while (true) {
sleep(100);
}
}
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/launch/pandora_driver_apollo.launch
|
<launch>
<arg name="pandora_ip" default="192.168.20.51"/>
<arg name="lidar_recv_port" default="2368"/>
<arg name="gps_recv_port" default="10110"/>
<arg name="start_angle" default="135"/>
<arg name="pandora_camera_port" default="9870"/>
<arg name="enable_camera" default="false"/>
<arg name="timezone" default="8"/>
<arg name="frame_id" default="velodyne64"/>
<arg name="lidar_topic" default="/apollo/sensor/velodyne64/PointCloud2"/>
<arg name="camera0_topic" default="/apollo/sensor/pandora/camera/front_color"/>
<arg name="camera1_topic" default="/apollo/sensor/pandora/camera/front_gray"/>
<arg name="camera2_topic" default="/apollo/sensor/pandora/camera/right_gray"/>
<arg name="camera3_topic" default="/apollo/sensor/pandora/camera/back_gray"/>
<arg name="camera4_topic" default="/apollo/sensor/pandora/camera/left_gray"/>
<node pkg="pandora_driver" name="pandora_driver" type="pandora_node" output="screen" >
<param name="pandora_ip" type="string" value="$(arg pandora_ip)"/>
<param name="lidar_recv_port" type="int" value="$(arg lidar_recv_port)"/>
<param name="gps_recv_port" type="int" value="$(arg gps_recv_port)"/>
<param name="start_angle" type="double" value="$(arg start_angle)"/>
<param name="pandora_camera_port" type="int" value="$(arg pandora_camera_port)"/>
<param name="enable_camera" type="boolean" value="$(arg enable_camera)"/>
<param name="timezone" type="int" value="$(arg timezone)"/>
<param name="frame_id" type="string" value="$(arg frame_id)"/>
<param name="lidar_topic" type="string" value="$(arg lidar_topic)"/>
<param name="camera0_topic" type="string" value="$(arg camera0_topic)"/>
<param name="camera1_topic" type="string" value="$(arg camera1_topic)"/>
<param name="camera2_topic" type="string" value="$(arg camera2_topic)"/>
<param name="camera3_topic" type="string" value="$(arg camera3_topic)"/>
<param name="camera4_topic" type="string" value="$(arg camera4_topic)"/>
</node>
</launch>
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/launch/pandora_driver.launch
|
<launch>
<arg name="pandora_ip" default="192.168.20.51"/>
<arg name="lidar_recv_port" default="2368"/>
<arg name="gps_recv_port" default="10110"/>
<arg name="start_angle" default="135"/>
<arg name="pandora_camera_port" default="9870"/>
<arg name="enable_camera" default="true"/>
<arg name="timezone" default="8"/>
<arg name="frame_id" default="hesai40"/>
<arg name="lidar_topic" default="/apollo/sensor/pandora/hesai40/PointCloud2"/>
<arg name="camera0_topic" default="/apollo/sensor/pandora/camera/front_color"/>
<arg name="camera1_topic" default="/apollo/sensor/pandora/camera/front_gray"/>
<arg name="camera2_topic" default="/apollo/sensor/pandora/camera/right_gray"/>
<arg name="camera3_topic" default="/apollo/sensor/pandora/camera/back_gray"/>
<arg name="camera4_topic" default="/apollo/sensor/pandora/camera/left_gray"/>
<node pkg="pandora_driver" name="pandora_driver" type="pandora_node" output="screen" >
<param name="pandora_ip" type="string" value="$(arg pandora_ip)"/>
<param name="lidar_recv_port" type="int" value="$(arg lidar_recv_port)"/>
<param name="gps_recv_port" type="int" value="$(arg gps_recv_port)"/>
<param name="start_angle" type="double" value="$(arg start_angle)"/>
<param name="pandora_camera_port" type="int" value="$(arg pandora_camera_port)"/>
<param name="enable_camera" type="boolean" value="$(arg enable_camera)"/>
<param name="timezone" type="int" value="$(arg timezone)"/>
<param name="frame_id" type="string" value="$(arg frame_id)"/>
<param name="lidar_topic" type="string" value="$(arg lidar_topic)"/>
<param name="camera0_topic" type="string" value="$(arg camera0_topic)"/>
<param name="camera1_topic" type="string" value="$(arg camera1_topic)"/>
<param name="camera2_topic" type="string" value="$(arg camera2_topic)"/>
<param name="camera3_topic" type="string" value="$(arg camera3_topic)"/>
<param name="camera4_topic" type="string" value="$(arg camera4_topic)"/>
</node>
</launch>
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/include
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/include/pandora/pandora.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef INCLUDE_PANDORA_PANDORA_H_
#define INCLUDE_PANDORA_PANDORA_H_
#include <boost/function.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui_c.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pthread.h>
#include <semaphore.h>
#include <string>
#include <vector>
#include "pandar40p/pandar40p.h"
#include "pandar40p/point_types.h"
namespace apollo {
namespace drivers {
namespace hesai {
class Pandora_Internal;
class CameraCalibration {
public:
// intrinsic
cv::Mat cameraK;
cv::Mat cameraD;
// extrinsic
std::vector<double> cameraT; // w x y z
std::vector<double> cameraR; // x y z
};
class Pandora {
public:
/**
* @brief Constructor
* @param device_ip The ip of the device
* lidar_port The port number of lidar data
* gps_port The port number of gps data
* pcl_callback The callback of PCL data structure
* gps_callback The callback of GPS structure
* start_angle The start angle of every point cloud
* should be <real angle> * 100.
* pandoraCameraPort The port of camera data
* cameraCallback the call back for camera data
*/
Pandora(const std::string &device_ip, const uint16_t lidar_port,
const uint16_t gps_port,
boost::function<void(boost::shared_ptr<PPointCloud>, double)>
pcl_callback,
boost::function<void(double)> gps_callback, uint16_t start_angle,
const uint16_t pandoraCameraPort,
boost::function<void(boost::shared_ptr<cv::Mat> matp,
double timestamp, int picid, bool distortion)>
cameraCallback,
bool enable_camera = true, int tz = 0,
std::string frame_id = std::string("hesai40"));
/**
* @brief destructor
*/
~Pandora();
/**
* @brief load the lidar correction file
* @param contents The correction contents of lidar correction
*/
int LoadLidarCorrectionFile(const std::string &contents);
/**
* @brief Reset Lidar's start angle.
* @param angle The start angle
*/
void ResetLidarStartAngle(uint16_t start_angle);
/**
* @brief Upload the camera calibration contents to Pandora Device.
* @param calibs calibration contents , include camera intrinsics and
* extrinsics.
*/
int UploadCameraCalibration(const CameraCalibration calibs[5]);
/**
* @brief Get Camera's Calibration, include camera intrinsics and extrinsics.
* @param calibs calibration contents , include camera intrinsics and
* extrinsics.
*/
int GetCameraCalibration(CameraCalibration calibs[5]);
/**
* @brief Reset camera calibration as factory-set.
*/
int ResetCameraClibration();
/**
* @brief Run SDK.
*/
int Start();
/**
* @brief Stop SDK.
*/
void Stop();
private:
Pandora_Internal *internal_;
};
} // namespace hesai
} // namespace drivers
} // namespace apollo
#endif // INCLUDE_PANDORA_PANDORA_H_
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/main.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <ros/ros.h>
#include <arpa/inet.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl_conversions/pcl_conversions.h>
#include "pandora/pandora.h"
using apollo::drivers::hesai::Pandora;
class PandoraHesaiClient {
public:
PandoraHesaiClient(ros::NodeHandle node, ros::NodeHandle nh) {
// default configure
std::string pandoraIP = std::string("192.168.20.51");
int lidarRecvPort = 2368;
int gpsRecvPort = 10110;
int startAngle = 135;
int pandoraCameraPort = 9870;
std::string lidarTopic = "/apollo/sensor/pandora/hesai40/PointCloud2";
std::string cameraTopics[5];
cameraTopics[0] = std::string("/apollo/sensor/pandora/camera/front_color");
cameraTopics[1] = std::string("/apollo/sensor/pandora/camera/front_gray");
cameraTopics[2] = std::string("/apollo/sensor/pandora/camera/right_gray");
cameraTopics[3] = std::string("/apollo/sensor/pandora/camera/back_gray");
cameraTopics[4] = std::string("/apollo/sensor/pandora/camera/left_gray");
bool enableCamera = true;
int timezone = 8;
std::string frameId = std::string("hesai40");
// parse nodehandle param
bool ret = parseParameter(nh, &pandoraIP, &lidarRecvPort,
&gpsRecvPort, &startAngle, &pandoraCameraPort,
&lidarTopic, cameraTopics, &enableCamera, &timezone, &frameId);
if (!ret) {
ROS_INFO("Parse parameters failed, please check parameters above.");
return;
}
// advertise
lidarPublisher = node.advertise<sensor_msgs::PointCloud2>(lidarTopic, 10);
if (enableCamera) {
image_transport::ImageTransport it(nh);
for (int i = 0; i < 5; i++) {
imgPublishers[i] = it.advertise(cameraTopics[i], 1);
}
}
psdk = new Pandora(pandoraIP, lidarRecvPort, gpsRecvPort,
boost::bind(&PandoraHesaiClient::lidarCallback, this, _1, _2),
NULL, startAngle * 100, pandoraCameraPort,
boost::bind(&PandoraHesaiClient::cameraCallback,
this, _1, _2, _3, _4),
enableCamera, timezone, frameId);
psdk->Start();
}
bool parseParameter(ros::NodeHandle nh, std::string* pandoraIP,
int* lidarRecvPort, int* gpsRecvPort, int* startAngle,
int* pandoraCameraPort, std::string* lidarTopic,
std::string cameraTopics[], bool* enableCamera,
int* timezone, std::string* frameId) {
if (nh.hasParam("pandora_ip")) {
nh.getParam("pandora_ip", *pandoraIP);
}
if (nh.hasParam("lidar_recv_port")) {
nh.getParam("lidar_recv_port", *lidarRecvPort);
}
if (nh.hasParam("gps_recv_port")) {
nh.getParam("gps_recv_port", *gpsRecvPort);
}
if (nh.hasParam("start_angle")) {
nh.getParam("start_angle", *startAngle);
}
if (nh.hasParam("pandora_camera_port")) {
nh.getParam("pandora_camera_port", *pandoraCameraPort);
}
if (nh.hasParam("lidar_topic")) {
nh.getParam("lidar_topic", *lidarTopic);
}
if (nh.hasParam("camera0_topic")) {
nh.getParam("camera0_topic", cameraTopics[0]);
}
if (nh.hasParam("camera1_topic")) {
nh.getParam("camera1_topic", cameraTopics[1]);
}
if (nh.hasParam("camera2_topic")) {
nh.getParam("camera2_topic", cameraTopics[2]);
}
if (nh.hasParam("camera3_topic")) {
nh.getParam("camera3_topic", cameraTopics[3]);
}
if (nh.hasParam("camera4_topic")) {
nh.getParam("camera4_topic", cameraTopics[4]);
}
if (nh.hasParam("enable_camera")) {
nh.getParam("enable_camera", *enableCamera);
}
if (nh.hasParam("timezone")) {
nh.getParam("timezone", *timezone);
}
if (nh.hasParam("frame_id")) {
nh.getParam("frame_id", *frameId);
}
std::cout << "Configs: pandoraIP: " << *pandoraIP << ", lidarRecvPort: "
<< *lidarRecvPort << ", gpsRecvPort: " << *gpsRecvPort
<< ", startAngle: " << *startAngle << ", pandoraCameraPort: "
<< *pandoraCameraPort << ", lidarTopic: " << *lidarTopic
<< ", enableCamera: " << *enableCamera << ", frameId: "
<< *frameId << std::endl;
for (int i = 0; i < 5; i++) {
std::cout << "cameraTopic" << i << ": " << cameraTopics[i] << std::endl;
}
// check
struct sockaddr_in sa;
return checkPort(*lidarRecvPort) && checkPort(*gpsRecvPort)
&& checkPort(*pandoraCameraPort) && (*startAngle >= 0)
&& (*startAngle < 360)
&& (1 == inet_pton(AF_INET, pandoraIP->c_str(), &(sa.sin_addr)));
}
bool checkPort(int port) {
return (port > 0) && (port < 65535);
}
void cameraCallback(boost::shared_ptr<cv::Mat> matp, double timestamp,
int pic_id, bool distortion) {
sensor_msgs::ImagePtr imgMsg;
if (pic_id > 4 || pic_id < 0) {
ROS_INFO("picid wrong in getImageToPub");
return;
}
imgMsg = cv_bridge::CvImage(std_msgs::Header(), "rgb8", *matp).toImageMsg();
imgMsg->header.stamp = ros::Time(timestamp);
imgPublishers[pic_id].publish(imgMsg);
}
void lidarCallback(boost::shared_ptr<PPointCloud> cld, double timestamp) {
pcl_conversions::toPCL(ros::Time(timestamp), cld->header.stamp);
sensor_msgs::PointCloud2 output;
pcl::toROSMsg(*cld, output);
lidarPublisher.publish(output);
}
~PandoraHesaiClient() {
if (NULL != psdk) {
delete(psdk);
}
}
private:
ros::Publisher lidarPublisher;
image_transport::Publisher imgPublishers[5];
Pandora *psdk;
};
int main(int argc, char **argv) {
ros::init(argc, argv, "pandora_ros");
ros::NodeHandle nh("~");
ros::NodeHandle node;
PandoraHesaiClient pandoraClient(node, nh);
ros::spin();
return 0;
}
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/util.c
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <pthread.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <syslog.h>
#include <unistd.h>
#include "src/util.h"
#define DEFAULT_TIMEOUT 10 /*seconds, waiting for read/write*/
int sys_readn(int fd, void* vptr, int n) {
// printf("start sys_readn: %d....\n", n);
int nleft, nread;
char* ptr;
ptr = vptr;
nleft = n;
while (nleft > 0) {
// printf("start read\n");
if ((nread = read(fd, ptr, nleft)) < 0) {
if (errno == EINTR)
nread = 0;
else
return -1;
} else if (nread == 0) {
break;
}
// printf("end read, read: %d\n", nread);
nleft -= nread;
ptr += nread;
}
// printf("stop sys_readn....\n");
return n - nleft;
}
int sys_writen(int fd, const void* vptr, int n) {
int nleft;
int nwritten;
const char* ptr;
ptr = vptr;
nleft = n;
while (nleft > 0) {
if ((nwritten = write(fd, ptr, nleft)) <= 0) {
if (nwritten < 0 && errno == EINTR)
nwritten = 0; /* and call write() again */
else
return (-1); /* error */
}
nleft -= nwritten;
ptr += nwritten;
}
return n;
}
int tcp_open(const char* ipaddr, int port) {
int sockfd;
struct sockaddr_in servaddr;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) return -1;
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
if (inet_pton(AF_INET, ipaddr, &servaddr.sin_addr) <= 0) {
close(sockfd);
return -1;
}
if (connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1) {
close(sockfd);
return -1;
}
return sockfd;
}
/**
*Description:check the socket state
*
* @param
* fd: socket
* timeout:the time out of select
* wait_for:socket state(r,w,conn)
*
* @return 1 if everything was ok, 0 otherwise
*/
int select_fd(int fd, int timeout, int wait_for) {
fd_set fdset;
fd_set *rd = NULL, *wr = NULL;
struct timeval tmo;
int result;
FD_ZERO(&fdset);
FD_SET(fd, &fdset);
if (wait_for == WAIT_FOR_READ) {
rd = &fdset;
}
if (wait_for == WAIT_FOR_WRITE) {
wr = &fdset;
}
if (wait_for == WAIT_FOR_CONN) {
rd = &fdset;
wr = &fdset;
}
tmo.tv_sec = timeout;
tmo.tv_usec = 0;
do {
result = select(fd + 1, rd, wr, NULL, &tmo);
} while (result < 0 && errno == EINTR);
return result;
}
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/pandora.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 "pandora/pandora.h"
#include "src/pandora_camera.h"
#include "src/pandora_client.h"
#include "src/tcp_command_client.h"
#include "yaml-cpp/yaml.h"
namespace apollo {
namespace drivers {
namespace hesai {
#define PANDORA_TCP_COMMAND_PORT (9347)
class Pandora_Internal {
public:
Pandora_Internal(
const std::string &device_ip,
const uint16_t lidar_port, const uint16_t gps_port,
boost::function<void(boost::shared_ptr<PPointCloud>, double)>
pcl_callback,
boost::function<void(double)> gps_callback, uint16_t start_angle,
const uint16_t pandoraCameraPort,
boost::function<void(boost::shared_ptr<cv::Mat> matp, double timestamp,
int picid, bool distortion)>
cameraCallback,
bool enable_camera, int tz, std::string frame_id);
~Pandora_Internal();
int LoadLidarCorrectionFile(const std::string &correction_content);
void ResetLidarStartAngle(uint16_t start_angle);
int UploadCameraCalibrationFile(const CameraCalibration calibs[5]);
int GetCameraCalibration(CameraCalibration calibs[5]);
int ResetCameraClibration();
void GetCalibrationFromDevice();
int ParseCameraCalibration(const std::string &contents,
CameraCalibration calibs[5]);
int GenerateCameraCalibration(const CameraCalibration calibs[5],
std::string *contents);
int Start();
void Stop();
private:
Pandar40P *pandar40p_;
PandoraCamera *pandora_camera_;
void *tcp_command_client_;
boost::thread *get_calibration_thr_;
bool enable_get_calibration_thr_;
bool got_lidar_calibration_;
bool got_camera_calibration_;
CameraCalibration camera_calibs_[5];
bool enable_camera_;
};
Pandora_Internal::Pandora_Internal(
const std::string &device_ip,
const uint16_t lidar_port, const uint16_t gps_port,
boost::function<void(boost::shared_ptr<PPointCloud>, double)> pcl_callback,
boost::function<void(double)> gps_callback, uint16_t start_angle,
const uint16_t pandoraCameraPort,
boost::function<void(boost::shared_ptr<cv::Mat> matp, double timestamp,
int picid, bool distortion)>
cameraCallback,
bool enable_camera, int tz, std::string frame_id) {
enable_camera_ = enable_camera;
pandora_camera_ = NULL;
pandar40p_ = NULL;
pandar40p_ = new Pandar40P(device_ip, lidar_port, gps_port, pcl_callback,
gps_callback, start_angle, tz, frame_id);
if (enable_camera_) {
pandora_camera_ = new PandoraCamera(device_ip, pandoraCameraPort,
cameraCallback, NULL, tz);
}
tcp_command_client_ =
TcpCommandClientNew(device_ip.c_str(), PANDORA_TCP_COMMAND_PORT);
if (!tcp_command_client_) {
std::cout << "Init TCP Command Client Failed" << std::endl;
}
get_calibration_thr_ = NULL;
enable_get_calibration_thr_ = false;
got_lidar_calibration_ = false;
got_camera_calibration_ = false;
}
Pandora_Internal::~Pandora_Internal() {
Stop();
if (pandar40p_) {
delete pandar40p_;
}
if (pandora_camera_) {
delete pandora_camera_;
}
}
/**
* @brief load the correction file
* @param file The path of correction file
*/
int Pandora_Internal::LoadLidarCorrectionFile(const std::string &correction_content) { // NOLINT
return pandar40p_->LoadCorrectionFile(correction_content);
}
/**
* @brief load the correction file
* @param angle The start angle
*/
void Pandora_Internal::ResetLidarStartAngle(uint16_t start_angle) {
if (!pandar40p_) return;
pandar40p_->ResetStartAngle(start_angle);
}
int Pandora_Internal::Start() {
Stop();
if (pandora_camera_) {
pandora_camera_->Start();
}
if (pandar40p_) {
pandar40p_->Start();
}
enable_get_calibration_thr_ = true;
get_calibration_thr_ = new boost::thread(
boost::bind(&Pandora_Internal::GetCalibrationFromDevice, this));
}
void Pandora_Internal::Stop() {
if (pandar40p_) pandar40p_->Stop();
if (pandora_camera_) pandora_camera_->Stop();
enable_get_calibration_thr_ = false;
if (get_calibration_thr_) {
get_calibration_thr_->join();
}
}
int Pandora_Internal::UploadCameraCalibrationFile(
const CameraCalibration calibs[5]) {
std::string contents;
int ret = 0;
ret = GenerateCameraCalibration(calibs, &contents);
if (ret != 0) {
std::cout << "Generate Camera Calibration Failed" << std::endl;
return ret;
}
return TcpCommandSetCalibration(tcp_command_client_, contents.c_str(),
contents.size());
}
int Pandora_Internal::GetCameraCalibration(CameraCalibration calibs[5]) {
if (!got_camera_calibration_) {
return -1;
}
for (int i = 0; i < 5; ++i) {
/* assign */
calibs[i].cameraK = camera_calibs_[i].cameraK;
calibs[i].cameraD = camera_calibs_[i].cameraD;
calibs[i].cameraT = camera_calibs_[i].cameraT;
calibs[i].cameraR = camera_calibs_[i].cameraR;
}
}
int Pandora_Internal::ResetCameraClibration() {
if (!tcp_command_client_) {
std::cout << "Pandora Tcp Command Client is NULL" << std::endl;
return -1;
}
return TcpCommandResetCalibration(tcp_command_client_);
}
void Pandora_Internal::GetCalibrationFromDevice() {
if (!tcp_command_client_) {
return;
}
int32_t ret = 0;
while (enable_get_calibration_thr_ && !got_lidar_calibration_ &&
!got_camera_calibration_) {
if (!got_lidar_calibration_) {
// get lidar calibration.
char *buffer;
uint32_t len;
ret = TcpCommandGetLidarCalibration(tcp_command_client_, &buffer, &len);
if (ret == 0 && buffer) {
// success;
got_lidar_calibration_ = true;
if (pandar40p_) {
ret = pandar40p_->LoadCorrectionFile(std::string(buffer));
if (ret != 0) {
std::cout << "Parse Lidar Correction Error" << std::endl;
got_lidar_calibration_ = false;
} else {
std::cout << "Parse Lidar Correction Success!!!" << std::endl;
}
}
free(buffer);
}
}
// If got lidar's calibration , and camera is disabled
// stop to get camera's calibration
if (!enable_camera_ && got_lidar_calibration_) break;
if (!got_camera_calibration_) {
// get camera calibration.
char *buffer;
uint32_t len;
ret = TcpCommandGetCalibration(tcp_command_client_, &buffer, &len);
if (ret == 0 && buffer) {
// success;
ret = ParseCameraCalibration(std::string(buffer), camera_calibs_);
if (ret == 0) {
got_camera_calibration_ = true;
std::cout << "Parse Camera Calibration Success!!!" << std::endl;
} else {
std::cout << "Parse Camera Calibration Error" << std::endl;
free(buffer);
continue;
}
std::vector<cv::Mat> cameras_k;
std::vector<cv::Mat> cameras_d;
for (int i = 0; i < 5; ++i) {
cameras_k.push_back(camera_calibs_[i].cameraK);
cameras_d.push_back(camera_calibs_[i].cameraD);
}
if (pandora_camera_) {
pandora_camera_->loadIntrinsics(cameras_k, cameras_d);
}
free(buffer);
std::cout << "TcpCommandGetCalibration Success" << std::endl;
}
}
sleep(1);
}
}
int Pandora_Internal::ParseCameraCalibration(const std::string &contents,
CameraCalibration calibs[5]) {
std::cout << "Parse Camera Calibration..." << std::endl;
if (contents.empty()) {
std::cout << "string is empty" << std::endl;
return -1;
}
YAML::Node yn = YAML::Load(contents);
std::string cameraId;
for (int id = 0; id < 5; ++id) {
// cameraId = std::to_string(i);
cameraId = boost::lexical_cast<std::string>(id);
cv::Mat intrinsicK, intrinsicD;
// get intrinsicK
if (yn[cameraId]["K"].IsDefined()) {
intrinsicK = cv::Mat::zeros(3, 3, CV_64FC1);
for (int i = 0; i < yn[cameraId]["K"].size(); ++i) {
intrinsicK.at<double>(i) = yn[cameraId]["K"][i].as<double>();
}
calibs[id].cameraK = intrinsicK;
} else {
printf("invalid intrinsicFile content\n");
return -1;
}
// GET intrinsicD
if (yn[cameraId]["D"].IsDefined()) {
// std::cout<<"type: " << yn[cameraId]["D"].Type()<<std::endl;
intrinsicD = cv::Mat::zeros(yn[cameraId]["D"].size(), 1, CV_64FC1);
for (int i = 0; i < yn[cameraId]["D"].size(); ++i) {
intrinsicD.at<double>(i) = yn[cameraId]["D"][i].as<double>();
}
calibs[id].cameraD = intrinsicD;
} else {
printf("invalid intrinsicFile content\n");
return -1;
}
// get camera
if (yn[cameraId]["Extrinsic"]["rotation"]["x"].IsDefined() &&
yn[cameraId]["Extrinsic"]["rotation"]["y"].IsDefined() &&
yn[cameraId]["Extrinsic"]["rotation"]["z"].IsDefined() &&
yn[cameraId]["Extrinsic"]["rotation"]["w"].IsDefined()) {
calibs[id].cameraR.push_back(
yn[cameraId]["Extrinsic"]["rotation"]["w"].as<double>());
calibs[id].cameraR.push_back(
yn[cameraId]["Extrinsic"]["rotation"]["x"].as<double>());
calibs[id].cameraR.push_back(
yn[cameraId]["Extrinsic"]["rotation"]["y"].as<double>());
calibs[id].cameraR.push_back(
yn[cameraId]["Extrinsic"]["rotation"]["z"].as<double>());
} else {
printf("invalid intrinsicFile content\n");
return -1;
}
// get cameraR
if (yn[cameraId]["Extrinsic"]["translation"]["x"].IsDefined() &&
yn[cameraId]["Extrinsic"]["translation"]["y"].IsDefined() &&
yn[cameraId]["Extrinsic"]["translation"]["z"].IsDefined()) {
calibs[id].cameraT.push_back(
yn[cameraId]["Extrinsic"]["translation"]["x"].as<double>());
calibs[id].cameraT.push_back(
yn[cameraId]["Extrinsic"]["translation"]["y"].as<double>());
calibs[id].cameraT.push_back(
yn[cameraId]["Extrinsic"]["translation"]["z"].as<double>());
} else {
printf("invalid intrinsicFile content\n");
return -1;
}
}
return 0;
}
int Pandora_Internal::GenerateCameraCalibration(
const CameraCalibration calibs[5], std::string *contents) {
std::string cameraId;
YAML::Node node;
for (int id = 0; id < 5; ++id) {
YAML::Node nodeK, nodeD, nodeT, nodeR;
// nodeK.SetStyle(YAML::EmitterStyle::Flow);
// nodeD.SetStyle(YAML::EmitterStyle::Flow);
// nodeT.SetStyle(YAML::EmitterStyle::Flow);
// nodeR.SetStyle(YAML::EmitterStyle::Flow);
std::string id_str = boost::lexical_cast<std::string>(id);
int rowsK = calibs[id].cameraK.rows;
int colsK = calibs[id].cameraK.cols;
int rowsD = calibs[id].cameraD.rows;
int colsD = calibs[id].cameraD.cols;
for (int i = 0; i < rowsK * colsK; i++) {
nodeK[i] = calibs[id].cameraK.at<double>(i);
}
node[id_str]["K"] = nodeK;
for (int i = 0; i < rowsD * colsD; i++) {
nodeD[i] = calibs[id].cameraD.at<double>(i);
}
node[id_str]["D"] = nodeD;
for (int i = 0; i < calibs[id].cameraT.size(); i++) {
nodeT[i] = boost::lexical_cast<std::string>(calibs[id].cameraT[i]);
node[id_str]["Extrinsic"]["rotation"]["w"] = calibs[id].cameraR[0];
node[id_str]["Extrinsic"]["rotation"]["x"] = calibs[id].cameraR[1];
node[id_str]["Extrinsic"]["rotation"]["y"] = calibs[id].cameraR[2];
node[id_str]["Extrinsic"]["rotation"]["z"] = calibs[id].cameraR[3];
node[id_str]["Extrinsic"]["translation"]["x"] = calibs[id].cameraT[0];
node[id_str]["Extrinsic"]["translation"]["y"] = calibs[id].cameraT[1];
node[id_str]["Extrinsic"]["translation"]["z"] = calibs[id].cameraT[2];
}
}
*contents = YAML::Dump(node);
// std::cout<<node<<std::endl;
return 0;
}
/*****************************************************************************************
Pandora Part
*****************************************************************************************/
/**
* @brief Constructor
* @param device_ip The ip of the device
* lidar_port The port number of lidar data
* gps_port The port number of gps data
* pcl_callback The callback of PCL data structure
* gps_callback The callback of GPS structure
* start_angle The start angle of every point cloud
* pandoraCameraPort The port of camera data
* cameraCallback the call back for camera data
*/
Pandora::Pandora(
const std::string &device_ip,
const uint16_t lidar_port, const uint16_t gps_port,
boost::function<void(boost::shared_ptr<PPointCloud>, double)> pcl_callback,
boost::function<void(double)> gps_callback, uint16_t start_angle,
const uint16_t pandoraCameraPort,
boost::function<void(boost::shared_ptr<cv::Mat> matp, double timestamp,
int picid, bool distortion)>
cameraCallback,
bool enable_camera, int tz, std::string frame_id) {
internal_ = new Pandora_Internal(
device_ip, lidar_port, gps_port, pcl_callback, gps_callback, start_angle,
pandoraCameraPort, cameraCallback, enable_camera, tz, frame_id);
}
/**
* @brief destructor
*/
Pandora::~Pandora() { delete internal_; }
/**
* @brief load the lidar correction file
* @param contents The correction contents of lidar correction
*/
int Pandora::LoadLidarCorrectionFile(const std::string &correction_content) {
internal_->LoadLidarCorrectionFile(correction_content);
}
/**
* @brief Reset Lidar's start angle.
* @param angle The start angle
*/
void Pandora::ResetLidarStartAngle(uint16_t start_angle) {
internal_->ResetLidarStartAngle(start_angle);
}
/**
* @brief Upload the camera calibration contents to Pandora Device.
* @param calibs calibration contents , include camera intrinsics and
* extrinsics.
*/
int Pandora::UploadCameraCalibration(const CameraCalibration calibs[5]) {
internal_->UploadCameraCalibrationFile(calibs);
}
/**
* @brief Get Camera's Calibration, include camera intrinsics and extrinsics.
* @param calibs calibration contents , include camera intrinsics and
* extrinsics.
*/
int Pandora::GetCameraCalibration(CameraCalibration calibs[5]) {
internal_->GetCameraCalibration(calibs);
}
/**
* @brief Reset camera calibration as factory-set.
*/
int Pandora::ResetCameraClibration() { internal_->ResetCameraClibration(); }
/**
* @brief Run SDK.
*/
int Pandora::Start() { internal_->Start(); }
/**
* @brief Stop SDK.
*/
void Pandora::Stop() { internal_->Stop(); }
} // namespace hesai
} // namespace drivers
} // namespace apollo
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/pandora_client.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef SRC_PANDORA_CLIENT_H_
#define SRC_PANDORA_CLIENT_H_
#ifdef __cplusplus
extern "C" {
#endif
#define PANDORA_CAMERA_UNIT (5)
#define UTC_TIME
#ifdef UTC_TIME
typedef struct {
unsigned char UTC_Year;
unsigned char UTC_Month;
unsigned char UTC_Day;
unsigned char UTC_Hour;
unsigned char UTC_Minute;
unsigned char UTC_Second;
} UTC_Time_T;
#endif
typedef struct _PandoraPicHeader_s {
char SOP[2];
unsigned char pic_id;
unsigned char type;
unsigned int width;
unsigned int height;
unsigned timestamp;
unsigned len;
unsigned int totalLen;
unsigned int position;
#ifdef UTC_TIME
UTC_Time_T UTC_Time;
#endif
} PandoraPicHeader;
typedef struct _PandoraPic {
PandoraPicHeader header;
void* yuv;
} PandoraPic;
#ifdef UTC_TIME
#define PANDORA_CLIENT_HEADER_SIZE (34)
#else
#define PANDORA_CLIENT_HEADER_SIZE (28)
#endif
typedef int (*CallBack)(void* handle, int cmd, void* param, void* userp);
void* PandoraClientNew(const char* ip, int port, CallBack callback,
void* userp);
void PandoraClientDestroy(void* handle);
#ifdef __cplusplus
}
#endif
#endif // SRC_PANDORA_CLIENT_H_
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/pandora_camera.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef SRC_PANDORA_CAMERA_H_
#define SRC_PANDORA_CAMERA_H_
#include <boost/function.hpp>
#include <opencv2/opencv.hpp>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pthread.h>
#include <semaphore.h>
#include <list>
#include <string>
#include <vector>
#include "src/pandora_client.h"
namespace apollo {
namespace drivers {
namespace hesai {
#define CAMERA_NUM 5
#define IMAGE_WIDTH 1280
#define IMAGE_HEIGHT 720
class PandoraCamera {
public:
/**
* @brief Constructor
* @param device_ip The ip of the device
* lidar_port The port number of lidar data
* gps_port The port number of gps data
* pcl_callback The callback of PCL data structure
* gps_callback The callback of GPS structure
* type The device type
*/
PandoraCamera(
const std::string &device_ip, const uint16_t pandoraCameraPort,
boost::function<void(boost::shared_ptr<cv::Mat> matp, double timestamp,
int picid, bool distortion)>
camera_callback,
boost::function<void(bool connected)> connection_changed, int tz);
~PandoraCamera();
/**
* @brief load the correction file
* @param angle The start angle
*/
bool loadIntrinsics(const std::vector<cv::Mat> &cameras_k,
const std::vector<cv::Mat> &cameras_d);
int Start();
void Stop();
void pushPicture(PandoraPic *pic);
private:
void processPic();
int decompressJpeg(uint8_t *jpgBuffer, const uint32_t jpgSize, uint8_t **bmp,
uint32_t *bmpSize);
void yuv422ToCvmat(boost::shared_ptr<cv::Mat> dst, const void *pYUV422,
const int nWidth, const int nHeight, const int bitDepth);
void yuv422ToRgb24(const uint8_t *uyvy422, uint8_t *rgb24, const int width,
const int height);
void yuvToRgb(const int iY, const int iU, const int iV, int *iR, int *iG,
int *iB);
pthread_mutex_t pic_lock_;
sem_t pic_sem_;
boost::thread *process_pic_thread_;
bool continue_process_pic_;
bool need_remap_;
std::string ip_;
uint16_t camera_port_;
void *pandora_client_;
std::list<PandoraPic *> pic_list_;
std::vector<cv::Mat> mapx_;
std::vector<cv::Mat> mapy_;
boost::function<void(boost::shared_ptr<cv::Mat> matp, double timestamp,
int pic_id, bool distortion)>
camera_callback_;
boost::function<void(bool connected)> connection_changed_;
int tz_second_;
};
} // namespace hesai
} // namespace drivers
} // namespace apollo
#endif // SRC_PANDORA_CAMERA_H_
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/tcp_command_client.c
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "src/tcp_command_client.h"
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/sockios.h>
#include <net/if.h>
#include <netinet/in.h>
#include <pthread.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <syslog.h>
#include <unistd.h>
#include "src/util.h"
typedef struct TcpCommandClient_s {
pthread_mutex_t lock;
pthread_t tid;
int exit;
char ip[256];
unsigned short port;
int fd;
} TcpCommandClient;
#ifdef DEBUG
static void print_mem(char* mem, int len) {
int i = 0;
for (int i = 0; i < len; ++i) {
printf("%02x ", mem[i]);
}
printf("\n");
}
#else
static void print_mem(char* mem, int len) {}
#endif
static int tcpCommandHeaderParser(unsigned char* buffer, int len,
TcpCommandHeader* header) {
int index = 0;
header->cmd = buffer[index++];
header->ret_code = buffer[index++];
header->len =
((buffer[index] & 0xff) << 24) | ((buffer[index + 1] & 0xff) << 16) |
((buffer[index + 2] & 0xff) << 8) | ((buffer[index + 3] & 0xff) << 0);
return 0;
}
static int tcpCommandReadCommand(int connfd, TC_Command* cmd) {
int ret = 0;
if (!cmd) {
return -1;
}
memset(cmd, 0, sizeof(TC_Command));
unsigned char buffer[1500];
ret = sys_readn(connfd, buffer, 2);
if (ret <= 0 || buffer[0] != 0x47 || buffer[1] != 0x74) {
printf("Server Read failed\n");
return -1;
}
ret = sys_readn(connfd, buffer + 2, 6);
if (ret != 6) {
printf("Server Read failed\n");
return -1;
}
print_mem(buffer, 8);
tcpCommandHeaderParser(buffer + 2, 6, &cmd->header);
if (cmd->header.len > 0) {
cmd->data = malloc(cmd->header.len);
if (!cmd->data) {
printf("malloc data error\n");
return -1;
}
}
ret = sys_readn(connfd, cmd->data, cmd->header.len);
if (ret != cmd->header.len) {
free(cmd->data);
printf("Server Read failed\n");
return -1;
}
// cmd->ret_size = cmd->header.len;
print_mem(cmd->data, cmd->header.len);
return 0;
}
static int TcpCommand_buildHeader(char* buffer, TC_Command* cmd) {
if (!buffer) {
return -1;
}
int index = 0;
buffer[index++] = 0x47;
buffer[index++] = 0x74;
buffer[index++] = cmd->header.cmd;
buffer[index++] = cmd->header.ret_code; // color or mono
buffer[index++] = (cmd->header.len >> 24) & 0xff;
buffer[index++] = (cmd->header.len >> 16) & 0xff;
buffer[index++] = (cmd->header.len >> 8) & 0xff;
buffer[index++] = (cmd->header.len >> 0) & 0xff;
return index;
}
static PTC_ErrCode tcpCommandClient_SendCmd(TcpCommandClient* client,
TC_Command* cmd) {
if (!client || !cmd) {
printf("Bad Parameter\n");
return PTC_ERROR_BAD_PARAMETER;
}
if (cmd->header.len != 0 && cmd->data == NULL) {
printf("Bad Parameter : payload is null\n");
return PTC_ERROR_BAD_PARAMETER;
}
pthread_mutex_lock(&client->lock);
int fd = tcp_open(client->ip, client->port);
if (fd < 0) {
printf("Connect to Server Failed\n");
pthread_mutex_unlock(&client->lock);
return PTC_ERROR_CONNECT_SERVER_FAILED;
}
unsigned char buffer[128];
int size = TcpCommand_buildHeader(buffer, cmd);
print_mem(buffer, size);
int ret = write(fd, buffer, size);
if (ret != size) {
close(fd);
pthread_mutex_unlock(&client->lock);
printf("Write header error\n");
return PTC_ERROR_TRANSFER_FAILED;
}
if (cmd->header.len > 0 && cmd->data) {
print_mem(cmd->data, cmd->header.len);
ret = write(fd, cmd->data, cmd->header.len);
if (ret != cmd->header.len) {
printf("Write Payload error\n");
close(fd);
pthread_mutex_unlock(&client->lock);
return PTC_ERROR_TRANSFER_FAILED;
}
}
TC_Command feedBack;
ret = tcpCommandReadCommand(fd, &feedBack);
if (ret != 0) {
printf("Receive feed back failed!!!\n");
close(fd);
pthread_mutex_unlock(&client->lock);
return PTC_ERROR_TRANSFER_FAILED;
}
// printf("feed back : %d %d %d \n", feedBack.header.len ,
// cmd->header.ret_code,
// cmd->header.cmd);
cmd->ret_data = feedBack.data;
cmd->ret_size = feedBack.header.len;
cmd->header.ret_code = feedBack.header.ret_code;
close(fd);
pthread_mutex_unlock(&client->lock);
return PTC_ERROR_NO_ERROR;
}
void* TcpCommandClientNew(const char* ip, const unsigned short port) {
if (!ip) {
printf("Bad Parameter\n");
return NULL;
}
TcpCommandClient* client =
(TcpCommandClient*)malloc(sizeof(TcpCommandClient));
if (!client) {
printf("No Memory!!!\n");
return NULL;
}
memset(client, 0, sizeof(TcpCommandClient));
client->fd = -1;
strcpy(client->ip, ip);
client->port = port;
pthread_mutex_init(&client->lock, NULL);
printf("TCP Command Client Init Success!!!\n");
return (void*)client;
}
PTC_ErrCode TcpCommandSetCalibration(const void* handle, const char* buffer,
unsigned int len) {
if (!handle || !buffer || len <= 0) {
printf("Bad Parameter!!!\n");
return PTC_ERROR_BAD_PARAMETER;
}
TcpCommandClient* client = (TcpCommandClient*)handle;
TC_Command cmd;
memset(&cmd, 0, sizeof(TC_Command));
cmd.header.cmd = PTC_COMMAND_SET_CALIBRATION;
cmd.header.len = len;
cmd.data = strdup(buffer);
PTC_ErrCode errorCode = tcpCommandClient_SendCmd(client, &cmd);
if (errorCode != PTC_ERROR_NO_ERROR) {
printf("Set Calibration Failed\n");
free(cmd.data);
return errorCode;
}
free(cmd.data);
if (cmd.ret_data) {
// useless data;
free(cmd.ret_data);
}
return cmd.header.ret_code;
}
PTC_ErrCode TcpCommandGetCalibration(const void* handle, char** buffer,
unsigned int* len) {
if (!handle || !buffer || !len) {
printf("Bad Parameter!!!\n");
return PTC_ERROR_BAD_PARAMETER;
}
TcpCommandClient* client = (TcpCommandClient*)handle;
TC_Command cmd;
memset(&cmd, 0, sizeof(TC_Command));
cmd.header.cmd = PTC_COMMAND_GET_CALIBRATION;
cmd.header.len = 0;
cmd.data = NULL;
PTC_ErrCode errorCode = tcpCommandClient_SendCmd(client, &cmd);
if (errorCode != PTC_ERROR_NO_ERROR) {
printf("Set Calibration Failed\n");
return errorCode;
}
char* ret_str = (char*)malloc(cmd.ret_size + 1);
memcpy(ret_str, cmd.ret_data, cmd.ret_size);
ret_str[cmd.ret_size] = '\0';
free(cmd.ret_data);
*buffer = ret_str;
*len = cmd.ret_size + 1;
return cmd.header.ret_code;
}
PTC_ErrCode TcpCommandGetLidarCalibration(const void* handle, char** buffer,
unsigned int* len) {
if (!handle || !buffer || !len) {
printf("Bad Parameter!!!\n");
return PTC_ERROR_BAD_PARAMETER;
}
TcpCommandClient* client = (TcpCommandClient*)handle;
TC_Command cmd;
memset(&cmd, 0, sizeof(TC_Command));
cmd.header.cmd = PTC_COMMAND_GET_LIDAR_CALIBRATION;
cmd.header.len = 0;
cmd.data = NULL;
PTC_ErrCode errorCode = tcpCommandClient_SendCmd(client, &cmd);
if (errorCode != PTC_ERROR_NO_ERROR) {
printf("Set Calibration Failed\n");
return errorCode;
}
char* ret_str = (char*)malloc(cmd.ret_size + 1);
memcpy(ret_str, cmd.ret_data, cmd.ret_size);
ret_str[cmd.ret_size] = '\0';
free(cmd.ret_data);
*buffer = ret_str;
*len = cmd.ret_size + 1;
return cmd.header.ret_code;
}
PTC_ErrCode TcpCommandResetCalibration(const void* handle) {
if (!handle) {
printf("Bad Parameter!!!\n");
return PTC_ERROR_BAD_PARAMETER;
}
TcpCommandClient* client = (TcpCommandClient*)handle;
TC_Command cmd;
memset(&cmd, 0, sizeof(TC_Command));
cmd.header.cmd = PTC_COMMAND_RESET_CALIBRATION;
cmd.header.len = 0;
cmd.data = NULL;
PTC_ErrCode errorCode = tcpCommandClient_SendCmd(client, &cmd);
if (errorCode != PTC_ERROR_NO_ERROR) {
printf("Set Calibration Failed\n");
return errorCode;
}
if (cmd.ret_data) {
// useless data;
free(cmd.ret_data);
}
return cmd.header.ret_code;
}
void TcpCommandClientDestroy(const void* handle) {}
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/pandora_camera.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 <stdio.h>
#include <unistd.h>
#include <jpeglib.h>
#include <vector>
#include "src/pandora_camera.h"
#include "src/pandora_client.h"
namespace apollo {
namespace drivers {
namespace hesai {
cv::Size HesaiLidarSDK_IMAGE_SIZE(IMAGE_WIDTH, IMAGE_HEIGHT);
static int CameraClientCallback(void *handle, int cmd, void *param,
void *userp) {
PandoraPic *pic = static_cast<PandoraPic *>(param);
PandoraCamera *pSDK = static_cast<PandoraCamera *>(userp);
pSDK->pushPicture(pic);
return 0;
}
PandoraCamera::PandoraCamera(
const std::string &device_ip, const uint16_t pandoraCameraPort,
boost::function<void(boost::shared_ptr<cv::Mat> matp, double timestamp,
int picid, bool distortion)>
camera_callback,
boost::function<void(bool connected)> connectionChanged, int tz) {
ip_ = device_ip;
sem_init(&pic_sem_, 0, 0);
pthread_mutex_init(&pic_lock_, NULL);
process_pic_thread_ = NULL;
continue_process_pic_ = false;
need_remap_ = false;
camera_port_ = pandoraCameraPort;
pandora_client_ = NULL;
camera_callback_ = camera_callback;
connection_changed_ = connectionChanged;
tz_second_ = tz * 3600;
}
PandoraCamera::~PandoraCamera() {
Stop();
sem_destroy(&pic_sem_);
pthread_mutex_destroy(&pic_lock_);
}
int PandoraCamera::Start() {
continue_process_pic_ = true;
pandora_client_ =
PandoraClientNew(ip_.c_str(), camera_port_, CameraClientCallback,
static_cast<void *>(this));
if (!pandora_client_) {
continue_process_pic_ = false;
return -1;
}
process_pic_thread_ =
new boost::thread(boost::bind(&PandoraCamera::processPic, this));
if (!process_pic_thread_) {
continue_process_pic_ = false;
PandoraClientDestroy(pandora_client_);
return -1;
}
return 0;
}
void PandoraCamera::Stop() {
continue_process_pic_ = false;
if (pandora_client_) {
PandoraClientDestroy(pandora_client_);
}
pandora_client_ = NULL;
if (process_pic_thread_) {
process_pic_thread_->join();
delete process_pic_thread_;
}
process_pic_thread_ = NULL;
}
void PandoraCamera::pushPicture(PandoraPic *pic) {
pthread_mutex_lock(&pic_lock_);
pic_list_.push_back(pic);
pthread_mutex_unlock(&pic_lock_);
sem_post(&pic_sem_);
}
void PandoraCamera::processPic() {
while (continue_process_pic_) {
struct timespec ts;
if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
printf("processPic, get time error\n");
}
ts.tv_sec += 1;
if (sem_timedwait(&pic_sem_, &ts) == -1) {
continue;
}
pthread_mutex_lock(&pic_lock_);
PandoraPic *pic = pic_list_.front();
pic_list_.pop_front();
pthread_mutex_unlock(&pic_lock_);
if (pic == NULL) {
printf("pic is NULL\n");
return;
}
struct tm t;
t.tm_sec = pic->header.UTC_Time.UTC_Second;
t.tm_min = pic->header.UTC_Time.UTC_Minute;
t.tm_hour = pic->header.UTC_Time.UTC_Hour;
t.tm_mday = pic->header.UTC_Time.UTC_Day;
t.tm_mon = pic->header.UTC_Time.UTC_Month - 1;
t.tm_year = pic->header.UTC_Time.UTC_Year + 2000 - 1900;
t.tm_isdst = 0;
double timestamp = mktime(&t) + pic->header.timestamp / 1000000.0;
boost::shared_ptr<cv::Mat> cvMatPic(new cv::Mat());
switch (pic->header.pic_id) {
case 0:
yuv422ToCvmat(cvMatPic, pic->yuv, pic->header.width, pic->header.height,
8);
if (need_remap_)
remap(cvMatPic->clone(), *cvMatPic, mapx_[pic->header.pic_id],
mapy_[pic->header.pic_id], CV_INTER_LINEAR);
break;
case 1:
case 2:
case 3:
case 4:
uint8_t *bmp;
uint32_t bmpSize;
decompressJpeg(static_cast<uint8_t *>(pic->yuv), pic->header.len, &bmp,
&bmpSize);
*cvMatPic = cv::Mat(IMAGE_HEIGHT, IMAGE_WIDTH, CV_8UC3, bmp).clone();
if (need_remap_)
remap(cvMatPic->clone(), *cvMatPic, mapx_[pic->header.pic_id],
mapy_[pic->header.pic_id], CV_INTER_LINEAR);
free(bmp);
break;
default:
free(pic->yuv);
free(pic);
printf("wrong pic id\n");
return;
}
if (camera_callback_) {
// Add 2 seconds to correct the timestamp, Reason? No reason.
// liuxingwei@hesaitech.com
camera_callback_(cvMatPic, timestamp + 2 + tz_second_, pic->header.pic_id,
need_remap_);
}
free(pic->yuv);
pic->yuv = NULL;
free(pic);
pic = NULL;
}
}
bool PandoraCamera::loadIntrinsics(const std::vector<cv::Mat> &cameras_k,
const std::vector<cv::Mat> &cameras_d) {
for (int i = 0; i < CAMERA_NUM; i++) {
cv::Mat mapx = cv::Mat(HesaiLidarSDK_IMAGE_SIZE, CV_32FC1);
cv::Mat mapy = cv::Mat(HesaiLidarSDK_IMAGE_SIZE, CV_32FC1);
cv::Mat R = cv::Mat::eye(3, 3, CV_32F);
initUndistortRectifyMap(cameras_k[i], cameras_d[i], R, cameras_k[i],
HesaiLidarSDK_IMAGE_SIZE, CV_32FC1, mapx, mapy);
mapx_.push_back(mapx);
mapy_.push_back(mapy);
}
need_remap_ = true;
return true;
}
void PandoraCamera::yuvToRgb(const int iY, const int iU, const int iV, int *iR,
int *iG, int *iB) {
assert(&iR != NULL && &iG != NULL && &iB != NULL);
*iR = iY + 1.13983 * (iV - 128);
*iG = iY - 0.39465 * (iU - 128) - 0.58060 * (iV - 128);
*iB = iY + 2.03211 * (iU - 128);
*iR = *iR > 255 ? 255 : *iR;
*iR = *iR < 0 ? 0 : *iR;
*iG = *iG > 255 ? 255 : *iG;
*iG = *iG < 0 ? 0 : *iG;
*iB = *iB > 255 ? 255 : *iB;
*iB = *iB < 0 ? 0 : *iB;
}
void PandoraCamera::yuv422ToRgb24(const unsigned char *uyvy422,
unsigned char *rgb24, const int width,
const int height) {
int iR, iG, iB;
int iY0, iY1, iU, iV;
int i = 0;
int j = 0;
for (i = 0; i < width * height * 2; i += 4) {
iU = uyvy422[i + 0];
iY0 = uyvy422[i + 1];
iV = uyvy422[i + 2];
iY1 = uyvy422[i + 3];
yuvToRgb(iY0, iU, iV, &iR, &iG, &iB);
rgb24[j++] = iB;
rgb24[j++] = iG;
rgb24[j++] = iR;
yuvToRgb(iY1, iU, iV, &iR, &iG, &iB);
rgb24[j++] = iB;
rgb24[j++] = iG;
rgb24[j++] = iR;
}
}
void PandoraCamera::yuv422ToCvmat(boost::shared_ptr<cv::Mat> dst,
const void *pYUV422, const int nWidth,
const int nHeight, const int bitDepth) {
if (!pYUV422) {
return;
}
unsigned char *rgb24_buffer = new unsigned char[nWidth * nHeight * 3];
yuv422ToRgb24((unsigned char *)pYUV422, rgb24_buffer, nWidth, nHeight);
*dst = cv::Mat(nHeight, nWidth, CV_8UC3, rgb24_buffer).clone();
delete[] rgb24_buffer;
}
static void my_output_message(j_common_ptr ptr) { return; }
static void print_mem(unsigned char *mem, unsigned int size) {
int i = 0;
for (i = 0; i < size; i++) {
printf("%02x ", mem[i]);
}
printf("\n");
}
int PandoraCamera::decompressJpeg(uint8_t *jpgBuffer, const uint32_t jpgSize,
uint8_t **bmp, uint32_t *bmpSize) {
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
uint8_t *bmpBuffer;
int rowStride, width, height, pixelSize;
cinfo.err = jpeg_std_error(&jerr);
cinfo.err->output_message = my_output_message;
cinfo.err->error_exit = my_output_message;
jpeg_create_decompress(&cinfo);
jpeg_mem_src(&cinfo, jpgBuffer, jpgSize);
int rc = jpeg_read_header(&cinfo, TRUE);
if (rc != 1) {
return -1;
}
jpeg_start_decompress(&cinfo);
width = cinfo.output_width;
height = cinfo.output_height;
pixelSize = cinfo.output_components;
*bmpSize = width * height * pixelSize;
bmpBuffer = (unsigned char *)malloc(*bmpSize);
rowStride = width * pixelSize;
while (cinfo.output_scanline < cinfo.output_height) {
unsigned char *buffer_array[1];
buffer_array[0] = bmpBuffer + (cinfo.output_scanline) * rowStride;
jpeg_read_scanlines(&cinfo, buffer_array, 1);
}
*bmp = bmpBuffer;
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
return 0;
}
} // namespace hesai
} // namespace drivers
} // namespace apollo
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/pandora_client.c
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <pthread.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <syslog.h>
#include <unistd.h>
#include "src/pandora_client.h"
#include "src/util.h"
typedef struct _PandoraClient_s {
pthread_mutex_t cliSocketLock;
int cliSocket;
pthread_t receiveTask;
pthread_t heartBeatTask;
int exit;
char* ip;
int port;
CallBack callback;
void* userp;
unsigned int position[PANDORA_CAMERA_UNIT];
unsigned int startTimestamp[PANDORA_CAMERA_UNIT];
PandoraPic* pics[PANDORA_CAMERA_UNIT];
} PandoraClient;
void PandoraClientTask(void* handle);
void PandoraClientHeartBeatTask(void* handle);
void parseHeader(char* header, int len, PandoraPicHeader* picHeader) {
int index = 0;
picHeader->SOP[0] = header[index];
picHeader->SOP[1] = header[index + 1];
index += 2;
picHeader->pic_id = header[index];
picHeader->type = header[index + 1];
index += 2;
picHeader->width =
(header[index + 0] & 0xff) << 24 | (header[index + 1] & 0xff) << 16 |
(header[index + 2] & 0xff) << 8 | (header[index + 3] & 0xff) << 0;
index += 4;
picHeader->height =
(header[index + 0] & 0xff) << 24 | (header[index + 1] & 0xff) << 16 |
(header[index + 2] & 0xff) << 8 | (header[index + 3] & 0xff) << 0;
index += 4;
picHeader->timestamp =
(header[index + 0] & 0xff) << 24 | (header[index + 1] & 0xff) << 16 |
(header[index + 2] & 0xff) << 8 | (header[index + 3] & 0xff) << 0;
index += 4;
picHeader->len =
(header[index + 0] & 0xff) << 24 | (header[index + 1] & 0xff) << 16 |
(header[index + 2] & 0xff) << 8 | (header[index + 3] & 0xff) << 0;
index += 4;
picHeader->totalLen =
(header[index + 0] & 0xff) << 24 | (header[index + 1] & 0xff) << 16 |
(header[index + 2] & 0xff) << 8 | (header[index + 3] & 0xff) << 0;
index += 4;
picHeader->position =
(header[index + 0] & 0xff) << 24 | (header[index + 1] & 0xff) << 16 |
(header[index + 2] & 0xff) << 8 | (header[index + 3] & 0xff) << 0;
#ifdef UTC_TIME
index += 4;
picHeader->UTC_Time.UTC_Year = header[index++];
picHeader->UTC_Time.UTC_Month = header[index++];
picHeader->UTC_Time.UTC_Day = header[index++];
picHeader->UTC_Time.UTC_Hour = header[index++];
picHeader->UTC_Time.UTC_Minute = header[index++];
picHeader->UTC_Time.UTC_Second = header[index];
#endif
}
void* PandoraClientNew(const char* ip, int port, CallBack callback,
void* userp) {
if (!ip || !callback || !userp) {
printf("Bad Parameter\n");
return NULL;
}
int ret = 0;
PandoraClient* client = (PandoraClient*)malloc(sizeof(PandoraClient));
if (!client) {
printf("No Memory\n");
return NULL;
}
memset(client, 0, sizeof(PandoraClient));
client->callback = callback;
client->userp = userp;
client->cliSocket = -1;
client->ip = strdup(ip);
client->port = port;
pthread_mutex_init(&client->cliSocketLock, NULL);
ret = pthread_create(&client->receiveTask, NULL, (void*)PandoraClientTask,
(void*)client);
if (ret != 0) {
printf("Create Task Failed\n");
free(client);
return NULL;
}
ret = pthread_create(&client->heartBeatTask, NULL,
(void*)PandoraClientHeartBeatTask, (void*)client);
if (ret != 0) {
printf("Create heart beat Task Failed\n");
client->exit = 1;
pthread_join(client->receiveTask, NULL);
free(client);
return NULL;
}
return (void*)client;
}
void PandoraClientDestroy(void* handle) {
PandoraClient* client = (PandoraClient*)handle;
if (!client) {
printf("Bad Parameter\n");
return;
}
client->exit = 1;
pthread_join(client->heartBeatTask, NULL);
pthread_join(client->receiveTask, NULL);
close(client->cliSocket);
free(client);
}
void PandoraClientHeartBeatTask(void* handle) {
PandoraClient* client = (PandoraClient*)handle;
if (!client) {
printf("Bad Parameter\n");
return;
}
int ret = 0;
while (!client->exit) {
if (-1 == client->cliSocket) {
sleep(1);
continue;
}
ret = select_fd(client->cliSocket, 1, WAIT_FOR_WRITE);
if (ret > 0) {
ret = write(client->cliSocket, "HEARTBEAT", strlen("HEARTBEAT"));
if (ret < 0) {
printf("Write Error\n");
}
}
sleep(1);
}
}
void PandoraClientTask(void* handle) {
PandoraClient* client = (PandoraClient*)handle;
if (!client) {
printf("Bad Parameter\n");
return;
}
int connfd = client->cliSocket;
while (!client->exit) {
if (client->cliSocket == -1) {
printf("Camera: Connecting......\n");
connfd = tcp_open(client->ip, client->port);
if (connfd < 0) {
printf("Connect to server failed\n");
sleep(1);
continue;
}
pthread_mutex_lock(&client->cliSocketLock);
client->cliSocket = connfd;
pthread_mutex_unlock(&client->cliSocketLock);
printf("Camera: connect to server successfully!\n");
struct timeval tv;
tv.tv_sec = 5; /* 5 Secs Timeout */
tv.tv_usec = 0; // Not init'ing this can cause strange errors
setsockopt(client->cliSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv,
sizeof(struct timeval));
connfd = client->cliSocket;
}
int ret = 0;
// printf("start select_fd for read\n");
ret = select_fd(connfd, 1, WAIT_FOR_READ);
if (ret == 0) {
printf("select for read wrong\n");
pthread_mutex_lock(&client->cliSocketLock);
close(client->cliSocket);
client->cliSocket = -1;
pthread_mutex_unlock(&client->cliSocketLock);
sleep(5);
continue;
} else if (ret > 0) {
char header[64];
int n = sys_readn(connfd, header, 2);
if (n < 0) {
printf("read header wrong!\n");
pthread_mutex_lock(&client->cliSocketLock);
close(client->cliSocket);
client->cliSocket = -1;
pthread_mutex_unlock(&client->cliSocketLock);
continue;
}
if (header[0] != 0x47 || header[1] != 0x74) {
printf("InValid Header SOP\n");
printf("%02x %02x \n", header[0], header[1]);
exit(0);
continue;
}
n = sys_readn(connfd, header + 2, PANDORA_CLIENT_HEADER_SIZE - 2);
if (n <= 0) {
printf("read header2 wrong!\n");
pthread_mutex_lock(&client->cliSocketLock);
close(client->cliSocket);
client->cliSocket = -1;
pthread_mutex_unlock(&client->cliSocketLock);
continue;
}
PandoraPic* pic = (PandoraPic*)malloc(sizeof(PandoraPic));
if (!pic) {
printf("No Memory\n");
continue;
}
parseHeader(header, n + 2, &pic->header);
pic->yuv = malloc(pic->header.len);
if (!pic->yuv) {
printf("No Memory\n");
free(pic);
continue;
}
n = sys_readn(connfd, pic->yuv, pic->header.len);
if (n <= 0) {
printf("read pic_yuv wrong!\n");
pthread_mutex_lock(&client->cliSocketLock);
close(client->cliSocket);
client->cliSocket = -1;
pthread_mutex_unlock(&client->cliSocketLock);
continue;
}
if (n != pic->header.len) {
printf("picLength wrong\n");
free(pic->yuv);
free(pic);
continue;
}
// check frame id
if (pic->header.pic_id < 0 || pic->header.pic_id >= PANDORA_CAMERA_UNIT) {
free(pic->yuv);
free(pic);
continue;
}
// check the desired frame position packet.
if (pic->header.position != client->position[pic->header.pic_id]) {
client->position[pic->header.pic_id] = 0;
free(pic->yuv);
free(pic);
continue;
}
if (!client->pics[pic->header.pic_id]) {
client->pics[pic->header.pic_id] = malloc(sizeof(PandoraPic));
memcpy(client->pics[pic->header.pic_id], pic, sizeof(PandoraPic));
client->pics[pic->header.pic_id]->yuv = malloc(pic->header.totalLen);
}
memcpy(client->pics[pic->header.pic_id]->yuv +
client->position[pic->header.pic_id],
pic->yuv, pic->header.len);
if (client->position[pic->header.pic_id] == 0) {
client->startTimestamp[pic->header.pic_id] = pic->header.timestamp;
}
client->position[pic->header.pic_id] += pic->header.len;
if (client->position[pic->header.pic_id] == pic->header.totalLen) {
client->pics[pic->header.pic_id]->header.len = pic->header.totalLen;
client->pics[pic->header.pic_id]->header.timestamp =
pic->header.timestamp;
client->pics[pic->header.pic_id]->header.UTC_Time =
pic->header.UTC_Time;
// a whole frame
if (client->callback)
client->callback(client, 0, client->pics[pic->header.pic_id],
client->userp);
client->pics[pic->header.pic_id] = NULL;
client->position[pic->header.pic_id] = 0;
}
free(pic->yuv);
free(pic);
} else {
printf("Read Error\n");
pthread_mutex_lock(&client->cliSocketLock);
close(client->cliSocket);
client->cliSocket = -1;
pthread_mutex_unlock(&client->cliSocketLock);
continue;
}
}
}
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/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.
*****************************************************************************/
#ifndef SRC_UTIL_H_
#define SRC_UTIL_H_
#ifdef __cplusplus
extern "C" {
#endif
int sys_readn(int fd, void* vptr, int n);
int sys_writen(int fd, const void* vptr, int n);
int tcp_open(const char* ipaddr, int port);
int select_fd(int fd, int timeout, int wait_for);
enum { WAIT_FOR_READ, WAIT_FOR_WRITE, WAIT_FOR_CONN };
#ifdef __cplusplus
}
#endif
#endif // SRC_UTIL_H_
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/tcp_command_client.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef SRC_TCP_COMMAND_CLIENT_H_
#define SRC_TCP_COMMAND_CLIENT_H_
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
PTC_COMMAND_GET_CALIBRATION = 0,
PTC_COMMAND_SET_CALIBRATION,
PTC_COMMAND_HEARTBEAT,
PTC_COMMAND_RESET_CALIBRATION,
PTC_COMMAND_TEST,
PTC_COMMAND_GET_LIDAR_CALIBRATION,
} PTC_COMMAND;
typedef enum {
PTC_ERROR_NO_ERROR = 0,
PTC_ERROR_BAD_PARAMETER,
PTC_ERROR_CONNECT_SERVER_FAILED,
PTC_ERROR_TRANSFER_FAILED,
PTC_ERROR_NO_MEMORY,
} PTC_ErrCode;
typedef struct TcpCommandHeader_s {
unsigned char cmd;
unsigned char ret_code;
unsigned int len;
} TcpCommandHeader;
typedef struct TC_Command_s {
TcpCommandHeader header;
unsigned char* data;
unsigned char* ret_data;
unsigned int ret_size;
} TC_Command;
void* TcpCommandClientNew(const char* ip, const unsigned short port);
PTC_ErrCode TcpCommandSetCalibration(const void* handle, const char* buffer,
unsigned int len);
PTC_ErrCode TcpCommandGetCalibration(const void* handle, char** buffer,
unsigned int* len);
PTC_ErrCode TcpCommandGetLidarCalibration(const void* handle, char** buffer,
unsigned int* len);
PTC_ErrCode TcpCommandResetCalibration(const void* handle);
void TcpCommandClientDestroy(const void* handle);
#ifdef __cplusplus
}
#endif
#endif // SRC_TCP_COMMAND_CLIENT_H_
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/Pandar40P/CMakeLists.txt
|
cmake_minimum_required(VERSION 2.8)
project(Pandar40P)
find_package( Boost REQUIRED )
find_package(PCL REQUIRED COMPONENTS common)
set (CMAKE_CXX_FLAGS "-fPIC -std=c++11")
include_directories(
.
include
${Boost_INCLUDE_DIRS}
${PCL_INCLUDE_DIRS}
)
add_library( ${PROJECT_NAME}
src/input.cc
src/pandar40p_internal.cc
src/pandar40p.cc
)
target_link_libraries(${PROJECT_NAME}
${Boost_LIBRARIES}
${PCL_IO_LIBRARIES}
)
if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR})
add_executable(pandar40_test
test/test.cc
)
target_link_libraries(pandar40_test
${PROJECT_NAME}
${Boost_LIBRARIES}
${PCL_IO_LIBRARIES}
)
endif(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR})
install(TARGETS ${PROJECT_NAME}
DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION})
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/Pandar40P
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/Pandar40P/test/test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "pandar40p/pandar40p.h"
using apollo::drivers::hesai;
FILE* lidarTimestampFile = fopen("lidar-timestamp.txt", "w");
double pandoraToSysTimeGap = 0;
int gpsTimestamp = 0;
void gpsCallback(int timestamp) {
struct timeval ts;
gettimeofday(&ts, NULL);
gpsTimestamp = timestamp;
double sec = static_cast<double>(ts.tv_sec);
double usec = static_cast<double>(ts.tv_usec);
double t = static_cast<timestamp>(timestamp);
pandoraToSysTimeGap = tv_sec + (tv_usec / 1000000.0) - timestamp;
printf("gps: %d, gap: %f\n", timestamp, pandoraToSysTimeGap);
}
void lidarCallback(boost::shared_ptr<PPointCloud> cld, double timestamp) {
struct timeval ts;
gettimeofday(&ts, NULL);
printf("lidar: %lf\n", timestamp);
double usec = static_cast<double>(ts.tv_usec);
fprintf(lidarTimestampFile, "%d, %f,%f\n", gpsTimestamp, timestamp,
ts.tv_sec + tv_usec / 1000000 - pandoraToSysTimeGap - timestamp);
}
int main(int argc, char** argv) {
Pandar40P pandar40p(std::string("192.168.20.51"), 2368, 10110, lidarCallback,
gpsCallback, 0);
pandar40p.Start();
while (true) {
sleep(100);
}
}
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/Pandar40P/include
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/Pandar40P/include/pandar40p/point_types.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef INCLUDE_POINT_TYPES_H_
#define INCLUDE_POINT_TYPES_H_
#include <pcl/point_types.h>
namespace apollo {
namespace drivers {
namespace hesai {
struct PointXYZIT {
PCL_ADD_POINT4D
uint8_t intensity;
double timestamp;
uint16_t ring; ///< laser ring number
EIGEN_MAKE_ALIGNED_OPERATOR_NEW // make sure our new allocators are aligned
} EIGEN_ALIGN16;
} // namespace hesai
} // namespace drivers
} // namespace apollo
POINT_CLOUD_REGISTER_POINT_STRUCT(
apollo::drivers::hesai::PointXYZIT,
(float, x, x)(float, y, y)(float, z, z)(uint8_t, intensity, intensity)(
double, timestamp, timestamp)(uint16_t, ring, ring))
typedef apollo::drivers::hesai::PointXYZIT PPoint;
typedef pcl::PointCloud<PPoint> PPointCloud;
#endif // INCLUDE_POINT_TYPES_H_
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/Pandar40P/include
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/Pandar40P/include/pandar40p/pandar40p.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef INCLUDE_PANDAR40P_H_
#define INCLUDE_PANDAR40P_H_
#include <boost/function.hpp>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pthread.h>
#include <semaphore.h>
#include <string>
#include "pandar40p/point_types.h"
namespace apollo {
namespace drivers {
namespace hesai {
class Pandar40P_Internal;
class Pandar40P {
public:
/**
* @brief Constructor
* @param device_ip The ip of the device
* lidar_port The port number of lidar data
* gps_port The port number of gps data
* pcl_callback The callback of PCL data structure
* gps_callback The callback of GPS structure
* start_angle The start angle of every point cloud ,
* should be <real angle> * 100.
*/
Pandar40P(const std::string &device_ip,
uint16_t lidar_port, uint16_t gps_port,
boost::function<void(boost::shared_ptr<PPointCloud>, double)>
pcl_callback,
boost::function<void(double)> gps_callback, uint16_t start_angle,
int tz, std::string frame_id);
/**
* @brief destructor
*/
~Pandar40P();
/**
* @brief load the lidar correction file
* @param contents The correction contents of lidar correction
*/
int LoadCorrectionFile(const std::string &contents);
/**
* @brief Reset Lidar's start angle.
* @param angle The start angle
*/
void ResetStartAngle(uint16_t start_angle);
/**
* @brief Run SDK.
*/
int Start();
/**
* @brief Stop SDK.
*/
void Stop();
private:
Pandar40P_Internal *internal_;
};
} // namespace hesai
} // namespace drivers
} // namespace apollo
#endif // INCLUDE_PANDAR40P_H_
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/Pandar40P
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/Pandar40P/src/input.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef SRC_INPUT_H_
#define SRC_INPUT_H_
#include <netinet/in.h>
#include <pcap.h>
#include <stdio.h>
#include <unistd.h>
#include <string>
namespace apollo {
namespace drivers {
namespace hesai {
#define ETHERNET_MTU (1500)
typedef struct PandarPacket_s {
double stamp;
uint8_t data[ETHERNET_MTU];
uint32_t size;
} PandarPacket;
class Input {
public:
Input(uint16_t port, uint16_t gpsPort);
~Input();
Input(std::string filePath, int type); // not implemented
int getPacket(PandarPacket *pkt);
int getPacketFromPcap(PandarPacket *pkt); // not implemented
private:
int socketForLidar;
int socketForGPS;
int socketNumber;
};
} // namespace hesai
} // namespace drivers
} // namespace apollo
#endif // SRC_INPUT_H_
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/Pandar40P
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/Pandar40P/src/pandar40p_internal.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef SRC_PANDAR40P_INTERNAL_H_
#define SRC_PANDAR40P_INTERNAL_H_
#include <boost/function.hpp>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pthread.h>
#include <semaphore.h>
#include <list>
#include <string>
#include "pandar40p/point_types.h"
#include "src/input.h"
#define RATE_PER_PACKET (2)
#define PACKETS_PER_ROUND (360 / RATE_PER_PACKET)
#define SOB_ANGLE_SIZE (4)
#define RAW_MEASURE_SIZE (3)
#define LASER_COUNT (40)
#define BLOCKS_PER_PACKET (10)
#define BLOCK_SIZE (RAW_MEASURE_SIZE * LASER_COUNT + SOB_ANGLE_SIZE)
#define TIMESTAMP_SIZE (4)
#define FACTORY_INFO_SIZE (1)
#define ECHO_SIZE (1)
#define RESERVE_SIZE (8)
#define REVOLUTION_SIZE (2)
#define INFO_SIZE \
(TIMESTAMP_SIZE + FACTORY_INFO_SIZE + ECHO_SIZE + RESERVE_SIZE + \
REVOLUTION_SIZE)
#define UTC_TIME (6)
#define PACKET_SIZE (BLOCK_SIZE * BLOCKS_PER_PACKET + INFO_SIZE + UTC_TIME)
#define LASER_RETURN_TO_DISTANCE_RATE (0.004)
#define GPS_PACKET_SIZE (512)
#define GPS_PACKET_FLAG_SIZE (2)
#define GPS_PACKET_YEAR_SIZE (2)
#define GPS_PACKET_MONTH_SIZE (2)
#define GPS_PACKET_DAY_SIZE (2)
#define GPS_PACKET_HOUR_SIZE (2)
#define GPS_PACKET_MINUTE_SIZE (2)
#define GPS_PACKET_SECOND_SIZE (2)
#define GPS_ITEM_NUM (7)
#define HesaiLidarSDK_DEFAULT_LIDAR_RECV_PORT 8080
#define HesaiLidarSDK_DEFAULT_GPS_RECV_PORT 10110
struct Pandar40PUnit_s {
uint8_t intensity;
double distance;
};
typedef struct Pandar40PUnit_s Pandar40PUnit;
struct Pandar40PBlock_s {
uint16_t azimuth;
uint16_t sob;
Pandar40PUnit units[LASER_COUNT];
};
typedef struct Pandar40PBlock_s Pandar40PBlock;
struct Pandar40PPacket_s {
Pandar40PBlock blocks[BLOCKS_PER_PACKET];
struct tm t;
uint32_t usec;
int echo;
};
typedef struct Pandar40PPacket_s Pandar40PPacket;
struct PandarGPS_s {
uint16_t flag;
uint16_t year;
uint16_t month;
uint16_t day;
uint16_t second;
uint16_t minute;
uint16_t hour;
uint32_t fineTime;
};
typedef struct PandarGPS_s PandarGPS;
#define ROTATION_MAX_UNITS (36001)
namespace apollo {
namespace drivers {
namespace hesai {
class Pandar40P_Internal {
public:
/**
* @brief Constructor
* @param device_ip The ip of the device
* lidar_port The port number of lidar data
* gps_port The port number of gps data
* pcl_callback The callback of PCL data structure
* gps_callback The callback of GPS structure
* type The device type
*/
Pandar40P_Internal(
const std::string &device_ip, uint16_t lidar_port, uint16_t gps_port,
boost::function<void(boost::shared_ptr<PPointCloud>, double)>
pcl_callback,
boost::function<void(double)> gps_callback, uint16_t start_angle, int tz,
std::string frame_id);
/**
* @brief load the correction file
* @param correction The path of correction file
*/
int LoadCorrectionFile(const std::string &correction);
/**
* @brief reset the start angle.
* @param angle The start angle
*/
void ResetStartAngle(uint16_t start_angle);
~Pandar40P_Internal();
int Start();
void Stop();
private:
void RecvTask();
void ProcessGps(const PandarGPS &gpsMsg);
void ProcessLiarPacket();
void PushLiDARData(PandarPacket packet);
int ParseRawData(Pandar40PPacket *packet, const uint8_t *buf, const int len);
int ParseGPS(PandarGPS *packet, const uint8_t *recvbuf, const int size);
void CalcPointXYZIT(Pandar40PPacket *pkt, int blockid,
boost::shared_ptr<PPointCloud> cld);
pthread_mutex_t lidar_lock_;
sem_t lidar_sem_;
boost::thread *lidar_recv_thr_;
boost::thread *lidar_process_thr_;
bool enable_lidar_recv_thr_;
bool enable_lidar_process_thr_;
int start_angle_ = 0;
double timestamp_ = 0;
std::list<struct PandarPacket_s> lidar_packets_;
boost::shared_ptr<Input> input_;
boost::function<void(boost::shared_ptr<PPointCloud> cld, double timestamp)>
pcl_callback_;
boost::function<void(double timestamp)> gps_callback_;
float sin_lookup_table_[ROTATION_MAX_UNITS];
float cos_lookup_table_[ROTATION_MAX_UNITS];
float elev_angle_map_[LASER_COUNT];
float horizatal_azimuth_offset_map_[LASER_COUNT];
float blockOffset_[BLOCKS_PER_PACKET];
float laserOffset_[LASER_COUNT];
int tz_second_;
std::string frame_id_;
};
} // namespace hesai
} // namespace drivers
} // namespace apollo
#endif // SRC_PANDAR40P_INTERNAL_H_
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/Pandar40P
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/Pandar40P/src/pandar40p_internal.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 <algorithm>
#include <sstream>
#include "src/input.h"
#include "src/pandar40p_internal.h"
namespace apollo {
namespace drivers {
namespace hesai {
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
double degreeToRadian(double degree) { return degree * M_PI / 180; }
// elevation angle of each line for HS Line 40 Lidar, Line 1 - Line 40
static const float pandar40p_elev_angle_map[] = {
6.96, 5.976, 4.988, 3.996, 2.999, 2.001, 1.667, 1.333,
1.001, 0.667, 0.333, 0, -0.334, -0.667, -1.001, -1.334,
-1.667, -2.001, -2.331, -2.667, -3, -3.327, -3.663, -3.996,
-4.321, -4.657, -4.986, -5.311, -5.647, -5.974, -6.957, -7.934,
-8.908, -9.871, -10.826, -11.772, -12.705, -13.63, -14.543, -15.444};
// Line 40 Lidar azimuth Horizontal offset , Line 1 - Line 40
static const float pandar40p_horizatal_azimuth_offset_map[] = {
0.005, 0.006, 0.006, 0.006, -2.479, -2.479, 2.491, -4.953,
-2.479, 2.492, -4.953, -2.479, 2.492, -4.953, 0.007, 2.491,
-4.953, 0.006, 4.961, -2.479, 0.006, 4.96, -2.478, 0.006,
4.958, -2.478, 2.488, 4.956, -2.477, 2.487, 2.485, 2.483,
0.004, 0.004, 0.003, 0.003, -2.466, -2.463, -2.46, -2.457};
Pandar40P_Internal::Pandar40P_Internal(
const std::string &device_ip, uint16_t lidar_port, uint16_t gps_port,
boost::function<void(boost::shared_ptr<PPointCloud>, double)> pcl_callback,
boost::function<void(double)> gps_callback, uint16_t start_angle, int tz,
std::string frame_id) {
pthread_mutex_init(&lidar_lock_, NULL);
sem_init(&lidar_sem_, 0, 0);
lidar_recv_thr_ = NULL;
lidar_process_thr_ = NULL;
enable_lidar_recv_thr_ = false;
enable_lidar_process_thr_ = false;
start_angle_ = start_angle > 36000 ? 0 : start_angle;
for (uint16_t rotIndex = 0; rotIndex < ROTATION_MAX_UNITS; ++rotIndex) {
float rotation = degreeToRadian(0.01 * static_cast<double>(rotIndex));
cos_lookup_table_[rotIndex] = cosf(rotation);
sin_lookup_table_[rotIndex] = sinf(rotation);
}
input_.reset(new Input(lidar_port, gps_port));
pcl_callback_ = pcl_callback;
gps_callback_ = gps_callback;
// init the block time offset, us
blockOffset_[9] = 55.1f * 0.0 + 45.18f;
blockOffset_[8] = 55.1f * 1.0 + 45.18f;
blockOffset_[7] = 55.1f * 2.0 + 45.18f;
blockOffset_[6] = 55.1f * 3.0 + 45.18f;
blockOffset_[5] = 55.1f * 4.0 + 45.18f;
blockOffset_[4] = 55.1f * 5.0 + 45.18f;
blockOffset_[3] = 55.1f * 6.0 + 45.18f;
blockOffset_[2] = 55.1f * 7.0 + 45.18f;
blockOffset_[1] = 55.1f * 8.0 + 45.18f;
blockOffset_[0] = 55.1f * 9.0 + 45.18f;
// init the laser shot time offset, us
laserOffset_[3] = 0.93f * 1.0f;
laserOffset_[35] = 0.93f * 2.0f;
laserOffset_[39] = 0.93f * 3.0f;
laserOffset_[23] = 0.93f * 3.0f + 1.6f * 1.0f;
laserOffset_[16] = 0.93f * 3.0f + 1.6f * 2.0f;
laserOffset_[27] = 0.93f * 4.0f + 1.6f * 2.0f;
laserOffset_[11] = 0.93f * 4.0f + 1.6f * 3.0f;
laserOffset_[31] = 0.93f * 5.0f + 1.6f * 3.0f;
laserOffset_[28] = 0.93f * 6.0f + 1.6f * 3.0f;
laserOffset_[15] = 0.93f * 6.0f + 1.6f * 4.0f;
laserOffset_[2] = 0.93f * 7.0f + 1.6f * 4.0f;
laserOffset_[34] = 0.93f * 8.0f + 1.6f * 4.0f;
laserOffset_[38] = 0.93f * 9.0f + 1.6f * 4.0f;
laserOffset_[20] = 0.93f * 9.0f + 1.6f * 5.0f;
laserOffset_[13] = 0.93f * 9.0f + 1.6f * 6.0f;
laserOffset_[24] = 0.93f * 9.0f + 1.6f * 7.0f;
laserOffset_[8] = 0.93f * 9.0f + 1.6f * 8.0f;
laserOffset_[30] = 0.93f * 10.0f + 1.6f * 8.0f;
laserOffset_[25] = 0.93f * 11.0f + 1.6f * 8.0f;
laserOffset_[12] = 0.93f * 11.0f + 1.6f * 9.0f;
laserOffset_[1] = 0.93f * 12.0f + 1.6f * 9.0f;
laserOffset_[33] = 0.93f * 13.0f + 1.6f * 9.0f;
laserOffset_[37] = 0.93f * 14.0f + 1.6f * 9.0f;
laserOffset_[17] = 0.93f * 14.0f + 1.6f * 10.0f;
laserOffset_[10] = 0.93f * 14.0f + 1.6f * 11.0f;
laserOffset_[21] = 0.93f * 14.0f + 1.6f * 12.0f;
laserOffset_[5] = 0.93f * 14.0f + 1.6f * 13.0f;
laserOffset_[29] = 0.93f * 15.0f + 1.6f * 13.0f;
laserOffset_[22] = 0.93f * 15.0f + 1.6f * 14.0f;
laserOffset_[9] = 0.93f * 15.0f + 1.6f * 15.0f;
laserOffset_[0] = 0.93f * 16.0f + 1.6f * 15.0f;
laserOffset_[32] = 0.93f * 17.0f + 1.6f * 15.0f;
laserOffset_[36] = 0.93f * 18.0f + 1.6f * 15.0f;
laserOffset_[14] = 0.93f * 18.0f + 1.6f * 16.0f;
laserOffset_[7] = 0.93f * 18.0f + 1.6f * 17.0f;
laserOffset_[18] = 0.93f * 18.0f + 1.6f * 18.0f;
laserOffset_[4] = 0.93f * 19.0f + 1.6f * 18.0f;
laserOffset_[26] = 0.93f * 20.0f + 1.6f * 18.0f;
laserOffset_[19] = 0.93f * 20.0f + 1.6f * 19.0f;
laserOffset_[6] = 0.93f * 20.0f + 1.6f * 20.0f;
for (int i = 0; i < LASER_COUNT; ++i) {
/* for all the laser offset */
elev_angle_map_[i] = pandar40p_elev_angle_map[i];
horizatal_azimuth_offset_map_[i] =
pandar40p_horizatal_azimuth_offset_map[i];
}
frame_id_ = frame_id;
tz_second_ = tz * 3600;
}
Pandar40P_Internal::~Pandar40P_Internal() {
Stop();
sem_destroy(&lidar_sem_);
pthread_mutex_destroy(&lidar_lock_);
}
/**
* @brief load the correction file
* @param file The path of correction file
*/
int Pandar40P_Internal::LoadCorrectionFile(const std::string &correction_content) { // NOLINT
std::istringstream ifs(correction_content);
std::string line;
if (std::getline(ifs, line)) { // first line "Laser id,Elevation,Azimuth"
std::cout << "Parse Lidar Correction..." << std::endl;
}
double azimuthOffset[LASER_COUNT];
double elev_angle[LASER_COUNT];
int lineCounter = 0;
while (std::getline(ifs, line)) {
if (lineCounter++ >= LASER_COUNT) break;
int lineId = 0;
double elev, azimuth;
std::stringstream ss(line);
std::string subline;
std::getline(ss, subline, ',');
std::stringstream(subline) >> lineId;
std::getline(ss, subline, ',');
std::stringstream(subline) >> elev;
std::getline(ss, subline, ',');
std::stringstream(subline) >> azimuth;
if (lineId != lineCounter) {
return -1;
}
elev_angle[lineId - 1] = elev;
azimuthOffset[lineId - 1] = azimuth;
}
for (int i = 0; i < LASER_COUNT; ++i) {
/* for all the laser offset */
elev_angle_map_[i] = elev_angle[i];
horizatal_azimuth_offset_map_[i] = azimuthOffset[i];
}
return 0;
}
/**
* @brief reset the start angle
* @param angle The start angle
*/
void Pandar40P_Internal::ResetStartAngle(uint16_t start_angle) {
start_angle_ = start_angle;
}
int Pandar40P_Internal::Start() {
Stop();
enable_lidar_recv_thr_ = true;
enable_lidar_process_thr_ = true;
lidar_process_thr_ = new boost::thread(
boost::bind(&Pandar40P_Internal::ProcessLiarPacket, this));
lidar_recv_thr_ =
new boost::thread(boost::bind(&Pandar40P_Internal::RecvTask, this));
}
void Pandar40P_Internal::Stop() {
enable_lidar_recv_thr_ = false;
enable_lidar_process_thr_ = false;
if (lidar_process_thr_) {
lidar_process_thr_->join();
delete lidar_process_thr_;
lidar_process_thr_ = NULL;
}
if (lidar_recv_thr_) {
lidar_recv_thr_->join();
delete lidar_recv_thr_;
lidar_recv_thr_ = NULL;
}
return;
}
void Pandar40P_Internal::RecvTask() {
int ret = 0;
while (enable_lidar_recv_thr_) {
PandarPacket pkt;
int rc = input_->getPacket(&pkt);
if (rc == -1) {
continue;
}
if (pkt.size == GPS_PACKET_SIZE) {
PandarGPS gpsMsg;
ret = ParseGPS(&gpsMsg, pkt.data, pkt.size);
if (ret == 0) {
ProcessGps(gpsMsg);
}
continue;
}
PushLiDARData(pkt);
}
}
void Pandar40P_Internal::ProcessLiarPacket() {
struct timespec ts;
int ret = 0;
static int packetIndex = 0;
boost::shared_ptr<PPointCloud> outMsg(new PPointCloud());
while (enable_lidar_process_thr_) {
if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
std::cout << "get time error" << std::endl;
}
ts.tv_sec += 1;
if (sem_timedwait(&lidar_sem_, &ts) == -1) {
continue;
}
pthread_mutex_lock(&lidar_lock_);
PandarPacket packet = lidar_packets_.front();
lidar_packets_.pop_front();
pthread_mutex_unlock(&lidar_lock_);
if (packet.size == PACKET_SIZE) {
Pandar40PPacket pkt;
ret = ParseRawData(&pkt, packet.data, packet.size);
if (ret != 0) {
continue;
}
packetIndex++;
for (int i = 0; i < BLOCKS_PER_PACKET; ++i) {
/* ready a round ? */
uint16_t current_azimuth = pkt.blocks[i].azimuth;
int limit_degree = RATE_PER_PACKET * 100/2;
int gap = std::min(std::abs(current_azimuth - start_angle_),
36000 - std::abs(current_azimuth - start_angle_));
// at lease 150 packets, no more than 182
if ((packetIndex > PACKETS_PER_ROUND * 5/6 && gap <= limit_degree) ||
packetIndex > PACKETS_PER_ROUND + 1) {
// ok
if (pcl_callback_ && outMsg->points.size() > 0) {
// std::cout << std::fixed << std::setprecision(18)
// << "Size: " << packetIndex << ", current: " << current_azimuth
// << ", timestamp_: " << timestamp_ << std::endl;
pcl_callback_(outMsg, timestamp_);
outMsg.reset(new PPointCloud());
// reset
packetIndex = 0; timestamp_ = 0;
}
}
CalcPointXYZIT(&pkt, i, outMsg);
}
} else {
continue;
}
outMsg->header.frame_id = frame_id_;
outMsg->height = 1;
}
}
void Pandar40P_Internal::PushLiDARData(PandarPacket packet) {
pthread_mutex_lock(&lidar_lock_);
lidar_packets_.push_back(packet);
sem_post(&lidar_sem_);
pthread_mutex_unlock(&lidar_lock_);
}
void Pandar40P_Internal::ProcessGps(const PandarGPS &gpsMsg) {
struct tm t;
t.tm_sec = gpsMsg.second;
t.tm_min = gpsMsg.minute;
t.tm_hour = gpsMsg.hour;
t.tm_mday = gpsMsg.day;
// UTC's month start from 1, but mktime only accept month from 0.
t.tm_mon = gpsMsg.month - 1;
// UTC's year only include 0 - 99 year , which indicates 2000 to 2099.
// and mktime's year start from 1900 which is 0, so we need to add 100 years.
t.tm_year = gpsMsg.year + 100;
t.tm_isdst = 0;
if (gps_callback_) {
gps_callback_(static_cast<double>(mktime(&t) + tz_second_) + 1);
}
}
int Pandar40P_Internal::ParseRawData(Pandar40PPacket *packet,
const uint8_t *buf, const int len) {
if (len != PACKET_SIZE) {
std::cout << "packet size mismatch Pandar40P_Internal " << len << ","
<< PACKET_SIZE << std::endl;
return -1;
}
int index = 0;
// 10 BLOCKs
for (int i = 0; i < BLOCKS_PER_PACKET; i++) {
Pandar40PBlock &block = packet->blocks[i];
block.sob = (buf[index] & 0xff) | ((buf[index + 1] & 0xff) << 8);
block.azimuth = (buf[index + 2] & 0xff) | ((buf[index + 3] & 0xff) << 8);
index += SOB_ANGLE_SIZE;
// 40x units
for (int j = 0; j < LASER_COUNT; j++) {
Pandar40PUnit &unit = block.units[j];
uint32_t range = (buf[index] & 0xff) | ((buf[index + 1] & 0xff) << 8);
// distance is M.
unit.distance =
(static_cast<double>(range)) * LASER_RETURN_TO_DISTANCE_RATE;
unit.intensity = (buf[index + 2] & 0xff);
// TODO(Philip.Pi): Filtering wrong data for LiDAR.
if ((unit.distance == 0x010101 && unit.intensity == 0x0101) ||
unit.distance > (200 * 1000 / 2 /* 200m -> 2mm */)) {
unit.distance = 0;
unit.intensity = 0;
}
index += RAW_MEASURE_SIZE;
}
}
index += RESERVE_SIZE; // skip reserved bytes
index += REVOLUTION_SIZE;
packet->usec = (buf[index] & 0xff) | (buf[index + 1] & 0xff) << 8 |
((buf[index + 2] & 0xff) << 16) |
((buf[index + 3] & 0xff) << 24);
packet->usec %= 1000000;
index += TIMESTAMP_SIZE;
packet->echo = buf[index] & 0xff;
index += FACTORY_INFO_SIZE + ECHO_SIZE;
// parse the UTC Time.
// UTC's year only include 0 - 99 year , which indicate 2000 to 2099.
// and mktime's year start from 1900 which is 0, so we need to add 100 years.
packet->t.tm_year = (buf[index + 0] & 0xff) + 100;
// UTC's month start from 1, but mktime only accept month from 0.
packet->t.tm_mon = (buf[index + 1] & 0xff) - 1;
packet->t.tm_mday = buf[index + 2] & 0xff;
packet->t.tm_hour = buf[index + 3] & 0xff;
packet->t.tm_min = buf[index + 4] & 0xff;
packet->t.tm_sec = buf[index + 5] & 0xff;
packet->t.tm_isdst = 0;
return 0;
}
int Pandar40P_Internal::ParseGPS(PandarGPS *packet, const uint8_t *recvbuf,
const int size) {
if (size != GPS_PACKET_SIZE) {
return -1;
}
int index = 0;
packet->flag = (recvbuf[index] & 0xff) | ((recvbuf[index + 1] & 0xff) << 8);
index += GPS_PACKET_FLAG_SIZE;
packet->year =
(recvbuf[index] & 0xff - 0x30) + (recvbuf[index + 1] & 0xff - 0x30) * 10;
index += GPS_PACKET_YEAR_SIZE;
packet->month =
(recvbuf[index] & 0xff - 0x30) + (recvbuf[index + 1] & 0xff - 0x30) * 10;
index += GPS_PACKET_MONTH_SIZE;
packet->day =
(recvbuf[index] & 0xff - 0x30) + (recvbuf[index + 1] & 0xff - 0x30) * 10;
index += GPS_PACKET_DAY_SIZE;
packet->second =
(recvbuf[index] & 0xff - 0x30) + (recvbuf[index + 1] & 0xff - 0x30) * 10;
index += GPS_PACKET_SECOND_SIZE;
packet->minute =
(recvbuf[index] & 0xff - 0x30) + (recvbuf[index + 1] & 0xff - 0x30) * 10;
index += GPS_PACKET_MINUTE_SIZE;
packet->hour =
(recvbuf[index] & 0xff - 0x30) + (recvbuf[index + 1] & 0xff - 0x30) * 10;
index += GPS_PACKET_HOUR_SIZE;
packet->fineTime =
(recvbuf[index] & 0xff) | (recvbuf[index + 1] & 0xff) << 8 |
((recvbuf[index + 2] & 0xff) << 16) | ((recvbuf[index + 3] & 0xff) << 24);
#ifdef DEBUG
if (packet->year != 18) {
printf("error gps\n");
char str[128];
int fd = open("/var/tmp/error_gps.txt", O_RDWR | O_CREAT, 0666);
lseek(fd, 0, SEEK_END);
int i = 0;
for (i = 0; i < 512; i++) {
snprintf(str, "%02x ", recvbuf[i], 127);
write(fd, str, strlen(str));
}
write(fd, "\n", 1);
close(fd);
}
#endif
return 0;
}
void Pandar40P_Internal::CalcPointXYZIT(Pandar40PPacket *pkt, int blockid,
boost::shared_ptr<PPointCloud> cld) {
Pandar40PBlock *block = &pkt->blocks[blockid];
double unix_second =
static_cast<double>(mktime(&pkt->t) + 1 + tz_second_); // 1 second offset
for (int i = 0; i < LASER_COUNT; ++i) {
/* for all the units in a block */
Pandar40PUnit &unit = block->units[i];
PPoint point;
/* skip wrong points */
if (unit.distance <= 0.5 || unit.distance > 200.0) {
continue;
}
double xyDistance =
unit.distance * cosf(degreeToRadian(elev_angle_map_[i]));
point.x = static_cast<float>(
xyDistance *
sinf(degreeToRadian(horizatal_azimuth_offset_map_[i] +
(static_cast<double>(block->azimuth)) / 100.0)));
point.y = static_cast<float>(
xyDistance *
cosf(degreeToRadian(horizatal_azimuth_offset_map_[i] +
(static_cast<double>(block->azimuth)) / 100.0)));
point.z = static_cast<float>(unit.distance *
sinf(degreeToRadian(elev_angle_map_[i])));
// point.x = static_cast<float>(xyDistance *
// sin_lookup_table_[xylookup_id]);
// point.y = static_cast<float>(xyDistance *
// cos_lookup_table_[xylookup_id]);
// point.z = static_cast<float>(unit.distance *
// sin_lookup_table_[zlookup_id]);
point.intensity = unit.intensity;
point.timestamp =
unix_second + (static_cast<double>(pkt->usec)) / 1000000.0;
if (pkt->echo == 0x39) {
// dual return, block 0&1 (2&3 , 4*5 ...)'s timestamp is the same.
point.timestamp =
point.timestamp - (static_cast<double>(blockOffset_[blockid / 2] +
laserOffset_[i / 2]) /
1000000.0f);
} else {
point.timestamp =
point.timestamp -
(static_cast<double>(blockOffset_[blockid] + laserOffset_[i]) /
1000000.0f);
}
point.ring = i;
// get smallest timestamp
if ((timestamp_ > 0 && timestamp_ < point.timestamp)
|| timestamp_ <= 0) {
timestamp_ = point.timestamp;
}
cld->push_back(point);
}
}
} // namespace hesai
} // namespace drivers
} // namespace apollo
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/Pandar40P
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/Pandar40P/src/input.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 <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <string.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <iostream>
#include <sstream>
#include "src/input.h"
namespace apollo {
namespace drivers {
namespace hesai {
Input::Input(uint16_t port, uint16_t gpsPort) {
socketForGPS = -1;
socketForLidar = -1;
socketForLidar = socket(PF_INET, SOCK_DGRAM, 0);
if (socketForLidar == -1) {
perror("socket"); // TODO(Philip.Pi): perror errno.
return;
}
sockaddr_in myAddress; // my address information
memset(&myAddress, 0, sizeof(myAddress)); // initialize to zeros
myAddress.sin_family = AF_INET; // host byte order
myAddress.sin_port = htons(port); // port in network byte order
myAddress.sin_addr.s_addr = INADDR_ANY; // automatically fill in my IP
if (bind(socketForLidar, reinterpret_cast<sockaddr *>(&myAddress),
sizeof(sockaddr)) == -1) {
perror("bind"); // TODO(Philip.Pi): perror errno
return;
}
if (fcntl(socketForLidar, F_SETFL, O_NONBLOCK | FASYNC) < 0) {
perror("non-block");
return;
}
if (port == gpsPort) {
socketNumber = 1;
return;
}
// gps socket
socketForGPS = socket(PF_INET, SOCK_DGRAM, 0);
if (socketForGPS == -1) {
perror("socket"); // TODO(Philip.Pi): perror errno.
return;
}
sockaddr_in myAddressGPS; // my address information
memset(&myAddressGPS, 0, sizeof(myAddressGPS)); // initialize to zeros
myAddressGPS.sin_family = AF_INET; // host byte order
myAddressGPS.sin_port = htons(gpsPort); // port in network byte order
myAddressGPS.sin_addr.s_addr = INADDR_ANY; // automatically fill in my IP
if (bind(socketForGPS, reinterpret_cast<sockaddr *>(&myAddressGPS),
sizeof(sockaddr)) == -1) {
perror("bind"); // TODO(Philip.Pi): perror errno
return;
}
if (fcntl(socketForGPS, F_SETFL, O_NONBLOCK | FASYNC) < 0) {
perror("non-block");
return;
}
socketNumber = 2;
}
Input::~Input(void) {
if (socketForGPS > 0) close(socketForGPS);
if (socketForLidar > 0) (void)close(socketForLidar);
}
// return : 0 - lidar
// 1 - gps
// -1 - error
int Input::getPacket(PandarPacket *pkt) {
struct pollfd fds[socketNumber];
if (socketNumber == 2) {
fds[0].fd = socketForGPS;
fds[0].events = POLLIN;
fds[1].fd = socketForLidar;
fds[1].events = POLLIN;
} else if (socketNumber == 1) {
fds[0].fd = socketForLidar;
fds[0].events = POLLIN;
}
static const int POLL_TIMEOUT = 1000; // one second (in msec)
sockaddr_in senderAddress;
socklen_t senderAddressLen = sizeof(senderAddress);
int retval = poll(fds, socketNumber, POLL_TIMEOUT);
if (retval < 0) { // poll() error?
if (errno != EINTR) printf("poll() error: %s", strerror(errno));
return -1;
}
if (retval == 0) {
return -1;
}
if ((fds[0].revents & POLLERR) || (fds[0].revents & POLLHUP) ||
(fds[0].revents & POLLNVAL)) {
// device error?
perror("poll() reports Pandar error");
return -1;
}
senderAddressLen = sizeof(senderAddress);
ssize_t nbytes = 0;
for (int i = 0; i != socketNumber; ++i) {
if (fds[i].revents & POLLIN) {
nbytes = recvfrom(fds[i].fd, &pkt->data[0], ETHERNET_MTU, 0,
reinterpret_cast<sockaddr *>(&senderAddress),
&senderAddressLen);
break;
}
}
if (nbytes < 0) {
if (errno != EWOULDBLOCK) {
perror("recvfail");
return -1;
}
}
pkt->size = nbytes;
return 0;
}
} // namespace hesai
} // namespace drivers
} // namespace apollo
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/Pandar40P
|
apollo_public_repos/apollo-contrib/pandora/pandora_driver/src/Pandar40P/src/pandar40p.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 "pandar40p/pandar40p.h"
#include "src/pandar40p_internal.h"
namespace apollo {
namespace drivers {
namespace hesai {
/**
* @brief Constructor
* @param device_ip The ip of the device
* lidar_port The port number of lidar data
* gps_port The port number of gps data
* pcl_callback The callback of PCL data structure
* gps_callback The callback of GPS structure
* start_angle The start angle of every point cloud
*/
Pandar40P::Pandar40P(
const std::string &device_ip, uint16_t lidar_port, uint16_t gps_port,
boost::function<void(boost::shared_ptr<PPointCloud>, double)> pcl_callback,
boost::function<void(double)> gps_callback, uint16_t start_angle, int tz,
std::string frame_id) {
internal_ =
new Pandar40P_Internal(device_ip, lidar_port, gps_port, pcl_callback,
gps_callback, start_angle, tz, frame_id);
}
/**
* @brief destructor
*/
Pandar40P::~Pandar40P() { delete internal_; }
/**
* @brief load the lidar correction file
* @param contents The correction contents of lidar correction
*/
int Pandar40P::LoadCorrectionFile(const std::string &file) {
return internal_->LoadCorrectionFile(file);
}
/**
* @brief Reset Lidar's start angle.
* @param angle The start angle
*/
void Pandar40P::ResetStartAngle(uint16_t start_angle) {
internal_->ResetStartAngle(start_angle);
}
/**
* @brief Run SDK.
*/
int Pandar40P::Start() { return internal_->Start(); }
/**
* @brief Stop SDK.
*/
void Pandar40P::Stop() { internal_->Stop(); }
} // namespace hesai
} // namespace drivers
} // namespace apollo
| 0
|
apollo_public_repos/apollo-contrib/pandora
|
apollo_public_repos/apollo-contrib/pandora/pandora_pointcloud/CMakeLists.txt
|
cmake_minimum_required(VERSION 2.8.3)
project(pandora_pointcloud)
set(${PROJECT_NAME}_CATKIN_DEPS
angles
nodelet
pcl_ros
roscpp
roslib
sensor_msgs
eigen_conversions)
find_package(catkin REQUIRED COMPONENTS ${${PROJECT_NAME}_CATKIN_DEPS})
include_directories(include ${catkin_INCLUDE_DIRS})
find_package(Eigen3 REQUIRED)
include_directories(${EIGEN3_INCLUDE_DIR})
find_package(Boost REQUIRED)
find_package(PCL 1.7 REQUIRED)
include_directories(${PCL_INCLUDE_DIRS})
link_directories(${PCL_LIBRARY_DIRS})
add_definitions(${PCL_DEFINITIONS})
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -O2 -fopenmp")
catkin_package()
######################
# compensator #
######################
add_executable(compensator_node src/compensator_node.cc src/compensator.cc)
target_link_libraries(compensator_node
${catkin_LIBRARIES}
${PCL_LIBRARIES})
install(
TARGETS
compensator_node
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION})
install(DIRECTORY include/${PROJECT_NAME}/
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION})
install(DIRECTORY launch/
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/launch)
| 0
|
apollo_public_repos/apollo-contrib/pandora
|
apollo_public_repos/apollo-contrib/pandora/pandora_pointcloud/package.xml
|
<package>
<name>pandora_pointcloud</name>
<version>1.0.0</version>
<description>Point cloud conversions for Pandora 3D LIDARs.</description>
<maintainer email="info@apollo.auto">car-os</maintainer>
<license>Licensed under the Apache License, Version 2.0</license>
<buildtool_depend>catkin</buildtool_depend>
<build_depend>angles</build_depend>
<build_depend>pcl_conversions</build_depend>
<build_depend>pluginlib</build_depend>
<build_depend>roscpp</build_depend>
<build_depend>roslib</build_depend>
<build_depend>pcl_ros</build_depend>
<build_depend>sensor_msgs</build_depend>
<build_depend>yaml-cpp</build_depend>
<build_depend>eigen_conversions</build_depend>
<!-- these build dependencies are only needed for unit testing -->
<build_depend>roslaunch</build_depend>
<build_depend>rostest</build_depend>
<run_depend>angles</run_depend>
<run_depend>pluginlib</run_depend>
<run_depend>python-yaml</run_depend>
<run_depend>roscpp</run_depend>
<run_depend>roslib</run_depend>
<run_depend>pcl_ros</run_depend>
<run_depend>sensor_msgs</run_depend>
<run_depend>yaml-cpp</run_depend>
<run_depend>eigen_conversions</run_depend>
<export>
<nodelet plugin="${prefix}/nodelets.xml"/>
</export>
</package>
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_pointcloud
|
apollo_public_repos/apollo-contrib/pandora/pandora_pointcloud/launch/compensator_node_apollo.launch
|
<launch>
<arg name="topic_pointcloud" default="/apollo/sensor/velodyne64/PointCloud2"/>
<arg name="topic_compensated_pointcloud" default="/apollo/sensor/velodyne64/compensator/PointCloud2"/>
<arg name="child_frame_id" default="velodyne64"/>
<arg name="tf_query_timeout" default="0.1"/>
<node pkg="pandora_pointcloud" name="pandora_pointcloud" type="compensator_node" output="screen" >
<param name="topic_pointcloud" value="$(arg topic_pointcloud)"/>
<param name="topic_compensated_pointcloud" value="$(arg topic_compensated_pointcloud)"/>
<param name="child_frame_id" value="$(arg child_frame_id)"/>
<param name="tf_query_timeout" value="$(arg tf_query_timeout)"/>
</node>
</launch>
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_pointcloud
|
apollo_public_repos/apollo-contrib/pandora/pandora_pointcloud/launch/compensator_node.launch
|
<launch>
<arg name="topic_pointcloud" default="/apollo/sensor/pandora/hesai40/PointCloud2"/>
<arg name="topic_compensated_pointcloud" default="/apollo/sensor/pandora/hesai40/compensator/PointCloud2"/>
<arg name="child_frame_id" default="hesai40"/>
<arg name="tf_query_timeout" default="0.1"/>
<node pkg="pandora_pointcloud" name="pandora_pointcloud" type="compensator_node" output="screen" >
<param name="topic_pointcloud" value="$(arg topic_pointcloud)"/>
<param name="topic_compensated_pointcloud" value="$(arg topic_compensated_pointcloud)"/>
<param name="child_frame_id" value="$(arg child_frame_id)"/>
<param name="tf_query_timeout" value="$(arg tf_query_timeout)"/>
</node>
</launch>
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_pointcloud/include
|
apollo_public_repos/apollo-contrib/pandora/pandora_pointcloud/include/pandora_pointcloud/compensator.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.
*****************************************************************************/
#ifndef MODULES_DRIVERS_PANDORA_PANDORA_POINTCLOUD_COMPENSATOR_H_
#define MODULES_DRIVERS_PANDORA_PANDORA_POINTCLOUD_COMPENSATOR_H_
#include <eigen_conversions/eigen_msg.h>
#include <pcl/common/time.h>
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <std_msgs/String.h>
#include <tf2_ros/transform_listener.h>
#include <Eigen/Eigen>
#include <string>
namespace apollo {
namespace drivers {
namespace pandora {
class Compensator {
public:
Compensator(ros::NodeHandle node, ros::NodeHandle private_nh);
virtual ~Compensator() {}
private:
/**
* @brief get pointcloud2 msg, compensate it,publish pointcloud2 after
* compensator
*/
void pointcloud_callback(sensor_msgs::PointCloud2ConstPtr msg);
/**
* @brief get pose affine from tf2 by gps timestamp
* novatel-preprocess broadcast the tf2 transfrom.
*/
bool query_pose_affine_from_tf2(const double timestamp,
Eigen::Affine3d* pose);
/**
* @brief check if message is valid, check width, height, timesatmp.
* set timestamp_offset and point data type
*/
bool check_message(sensor_msgs::PointCloud2ConstPtr msg);
/**
* @brief motion compensation for point cloud
*/
template <typename Scalar>
void motion_compensation(sensor_msgs::PointCloud2::Ptr msg,
const double timestamp_min,
const double timestamp_max,
const Eigen::Affine3d& pose_min_time,
const Eigen::Affine3d& pose_max_time);
/**
* @brief get min timestamp and max timestamp from points in pointcloud2
*/
inline void get_timestamp_interval(
sensor_msgs::PointCloud2ConstPtr msg, double* timestamp_min,
double* timestamp_max);
/**
* @brief get point field size by sensor_msgs::datatype
*/
inline uint get_field_size(const int data_type);
// subsrcibe pandora pointcloud2 msg.
ros::Subscriber pointcloud_sub_;
// publish point cloud2 after motion compensation
ros::Publisher compensation_pub_;
// ros::Publisher metastatus_publisher_;
// tf2 buffer
tf2_ros::Buffer tf2_buffer_;
// tf2 transform listener to get transform by gps timestamp.
tf2_ros::TransformListener tf2_transform_listener_;
// transform child frame id(world -> child frame)
std::string child_frame_id_;
float tf_timeout_;
// variables for point fields value, we get point x,y,z by these offset
int x_offset_;
int y_offset_;
int z_offset_;
int timestamp_offset_;
uint timestamp_data_size_;
// topic names
std::string topic_compensated_pointcloud_;
std::string topic_pointcloud_;
// ros queue size for publisher and subscriber
int queue_size_;
};
} // namespace pandora
} // namespace drivers
} // namespace apollo
#endif // MODULES_DRIVERS_PANDORA_PANDORA_POINTCLOUD_COMPENSATOR_H_
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_pointcloud
|
apollo_public_repos/apollo-contrib/pandora/pandora_pointcloud/src/compensator.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 <limits>
#include <string>
#include "pandora_pointcloud/compensator.h"
#include "ros/this_node.h"
namespace apollo {
namespace drivers {
namespace pandora {
Compensator::Compensator(ros::NodeHandle node, ros::NodeHandle private_nh)
: tf2_transform_listener_(tf2_buffer_, node),
x_offset_(-1),
y_offset_(-1),
z_offset_(-1),
timestamp_offset_(-1),
timestamp_data_size_(0) {
private_nh.param("child_frame_id", child_frame_id_,
std::string("hesai40"));
private_nh.param(
"topic_compensated_pointcloud", topic_compensated_pointcloud_,
std::string("/apollo/sensor/pandora/hesai40/compensator/PointCloud2"));
private_nh.param("topic_pointcloud", topic_pointcloud_,
std::string("/apollo/sensor/pandora/hesai40/PointCloud2"));
private_nh.param("queue_size", queue_size_, 10);
private_nh.param("tf_query_timeout", tf_timeout_, 0.1f);
// advertise output point cloud (before subscribing to input data)
compensation_pub_ = node.advertise<sensor_msgs::PointCloud2>(
topic_compensated_pointcloud_, queue_size_);
pointcloud_sub_ =
node.subscribe(topic_pointcloud_, queue_size_,
&Compensator::pointcloud_callback,
reinterpret_cast<Compensator*>(this));
}
void Compensator::pointcloud_callback(
sensor_msgs::PointCloud2ConstPtr msg) {
if (!check_message(msg)) {
ROS_FATAL("MotionCompensation : Input point cloud data field is invalid");
return;
}
Eigen::Affine3d pose_min_time;
Eigen::Affine3d pose_max_time;
double timestamp_min = 0;
double timestamp_max = 0;
get_timestamp_interval(msg, ×tamp_min, ×tamp_max);
// compensate point cloud, remove nan point
if (query_pose_affine_from_tf2(timestamp_min, &pose_min_time) &&
query_pose_affine_from_tf2(timestamp_max, &pose_max_time)) {
// we change message after motion compensation
sensor_msgs::PointCloud2::Ptr q_msg(new sensor_msgs::PointCloud2());
*q_msg = *msg;
motion_compensation<float>(q_msg, timestamp_min, timestamp_max,
pose_min_time, pose_max_time);
q_msg->header.stamp.fromSec(timestamp_max);
compensation_pub_.publish(q_msg);
}
}
inline void Compensator::get_timestamp_interval(
sensor_msgs::PointCloud2ConstPtr msg, double* timestamp_min,
double* timestamp_max) {
*timestamp_max = 0.0;
*timestamp_min = std::numeric_limits<double>::max();
int total = msg->width * msg->height;
// get min time and max time
for (int i = 0; i < total; ++i) {
double timestamp = 0.0;
memcpy(×tamp, &msg->data[i * msg->point_step + timestamp_offset_],
timestamp_data_size_);
if (timestamp < *timestamp_min) {
*timestamp_min = timestamp;
}
if (timestamp > *timestamp_max) {
*timestamp_max = timestamp;
}
}
}
// TODO(a): if point type is always float, and timestamp is always double?
inline bool Compensator::check_message(
sensor_msgs::PointCloud2ConstPtr msg) {
// check msg width and height
if (msg->width == 0 || msg->height == 0) {
return false;
}
int x_data_type = 0;
int y_data_type = 0;
int z_data_type = 0;
// TODO(a): will use a new datastruct with interface to get offset,
// datatype,datasize...
for (size_t i = 0; i < msg->fields.size(); ++i) {
const sensor_msgs::PointField& f = msg->fields[i];
if (f.name == "x") {
x_offset_ = f.offset;
x_data_type = f.datatype;
if ((x_data_type != 7 && x_data_type != 8) || f.count != 1 ||
x_offset_ == -1) {
return false;
}
} else if (f.name == "y") {
y_offset_ = f.offset;
y_data_type = f.datatype;
if (f.count != 1 || y_offset_ == -1) {
return false;
}
} else if (f.name == "z") {
z_offset_ = f.offset;
z_data_type = f.datatype;
if (f.count != 1 || z_offset_ == -1) {
return false;
}
} else if (f.name == "timestamp") {
timestamp_offset_ = f.offset;
timestamp_data_size_ = f.count * get_field_size(f.datatype);
if (timestamp_offset_ == -1 || timestamp_data_size_ == -1) {
return false;
}
} else {
ROS_DEBUG_STREAM("get a unused field name:" << f.name);
}
}
// check offset if valid
if (x_offset_ == -1 || y_offset_ == -1 || z_offset_ == -1 ||
timestamp_offset_ == -1 || timestamp_data_size_ == -1) {
return false;
}
if (!(x_data_type == y_data_type && y_data_type == z_data_type)) {
return false;
}
return true;
}
bool Compensator::query_pose_affine_from_tf2(const double timestamp,
Eigen::Affine3d* pose) {
ros::Time query_time(timestamp);
std::string err_string;
if (!tf2_buffer_.canTransform("world", child_frame_id_, query_time,
ros::Duration(tf_timeout_), &err_string)) {
ROS_WARN_STREAM("Can not find transform. "
<< std::fixed << timestamp
<< " Error info: " << err_string);
return false;
}
geometry_msgs::TransformStamped stamped_transform;
try {
stamped_transform =
tf2_buffer_.lookupTransform("world", child_frame_id_, query_time);
} catch (tf2::TransformException& ex) {
ROS_ERROR_STREAM(ex.what());
return false;
}
tf::transformMsgToEigen(stamped_transform.transform, *pose);
// ROS_DEBUG_STREAM("pose matrix : " << pose);
return true;
}
/** \brief Obtains the size of a specific field data type in bytes
* \param[in] datatype the field data type
*/
inline uint Compensator::get_field_size(const int datatype) {
switch (datatype) {
case sensor_msgs::PointField::INT8:
case sensor_msgs::PointField::UINT8:
return 1;
case sensor_msgs::PointField::INT16:
case sensor_msgs::PointField::UINT16:
return 2;
case sensor_msgs::PointField::INT32:
case sensor_msgs::PointField::UINT32:
case sensor_msgs::PointField::FLOAT32:
return 4;
case sensor_msgs::PointField::FLOAT64:
return 8;
default:
ROS_ERROR_STREAM("can not get field size by datatype:" << datatype);
return 0;
}
}
template <typename Scalar>
void Compensator::motion_compensation(sensor_msgs::PointCloud2::Ptr msg,
const double timestamp_min,
const double timestamp_max,
const Eigen::Affine3d& pose_min_time,
const Eigen::Affine3d& pose_max_time) {
using std::abs;
using std::sin;
using std::acos;
Eigen::Vector3d translation =
pose_min_time.translation() - pose_max_time.translation();
Eigen::Quaterniond q_max(pose_max_time.linear());
Eigen::Quaterniond q_min(pose_min_time.linear());
Eigen::Quaterniond q1(q_max.conjugate() * q_min);
Eigen::Quaterniond q0(Eigen::Quaterniond::Identity());
q1.normalize();
translation = q_max.conjugate() * translation;
int total = msg->width * msg->height;
double d = q0.dot(q1);
double abs_d = abs(d);
double f = 1.0 / (timestamp_max - timestamp_min);
// Threshold for a "significant" rotation from min_time to max_time:
// The LiDAR range accuracy is ~2 cm. Over 70 meters range, it means an angle
// of 0.02 / 70 =
// 0.0003 rad. So, we consider a rotation "significant" only if the scalar
// part of quaternion is
// less than cos(0.0003 / 2) = 1 - 1e-8.
if (abs_d < 1.0 - 1.0e-8) {
double theta = acos(abs_d);
double sin_theta = sin(theta);
double c1_sign = (d > 0) ? 1 : -1;
for (int i = 0; i < total; ++i) {
size_t offset = i * msg->point_step;
Scalar* x_scalar =
reinterpret_cast<Scalar*>(&msg->data[offset + x_offset_]);
if (std::isnan(*x_scalar)) {
ROS_DEBUG_STREAM("nan point do not need motion compensation");
continue;
}
Scalar* y_scalar =
reinterpret_cast<Scalar*>(&msg->data[offset + y_offset_]);
Scalar* z_scalar =
reinterpret_cast<Scalar*>(&msg->data[offset + z_offset_]);
Eigen::Vector3d p(*x_scalar, *y_scalar, *z_scalar);
double tp = 0.0;
memcpy(&tp, &msg->data[i * msg->point_step + timestamp_offset_],
timestamp_data_size_);
double t = (timestamp_max - tp) * f;
Eigen::Translation3d ti(t * translation);
double c0 = sin((1 - t) * theta) / sin_theta;
double c1 = sin(t * theta) / sin_theta * c1_sign;
Eigen::Quaterniond qi(c0 * q0.coeffs() + c1 * q1.coeffs());
Eigen::Affine3d trans = ti * qi;
p = trans * p;
*x_scalar = p.x();
*y_scalar = p.y();
*z_scalar = p.z();
}
return;
}
// Not a "significant" rotation. Do translation only.
for (int i = 0; i < total; ++i) {
Scalar* x_scalar =
reinterpret_cast<Scalar*>(&msg->data[i * msg->point_step + x_offset_]);
if (std::isnan(*x_scalar)) {
ROS_DEBUG_STREAM("nan point do not need motion compensation");
continue;
}
Scalar* y_scalar =
reinterpret_cast<Scalar*>(&msg->data[i * msg->point_step + y_offset_]);
Scalar* z_scalar =
reinterpret_cast<Scalar*>(&msg->data[i * msg->point_step + z_offset_]);
Eigen::Vector3d p(*x_scalar, *y_scalar, *z_scalar);
double tp = 0.0;
memcpy(&tp, &msg->data[i * msg->point_step + timestamp_offset_],
timestamp_data_size_);
double t = (timestamp_max - tp) * f;
Eigen::Translation3d ti(t * translation);
p = ti * p;
*x_scalar = p.x();
*y_scalar = p.y();
*z_scalar = p.z();
}
}
} // namespace pandora
} // namespace drivers
} // namespace apollo
| 0
|
apollo_public_repos/apollo-contrib/pandora/pandora_pointcloud
|
apollo_public_repos/apollo-contrib/pandora/pandora_pointcloud/src/compensator_node.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 "pandora_pointcloud/compensator.h"
#include <ros/ros.h>
/** Main node entry point. */
int main(int argc, char **argv) {
ROS_INFO("Point cloud node init");
ros::init(argc, argv, "pandora_compensator_node");
ros::NodeHandle node;
ros::NodeHandle priv_nh("~");
apollo::drivers::pandora::Compensator compensator(node, priv_nh);
// handle callbacks until shut down
ros::spin();
return 0;
}
| 0
|
apollo_public_repos/apollo-contrib
|
apollo_public_repos/apollo-contrib/lslidar_apollo/README.md
|
# lslidar_c16
## version track
Author: Yutong
### Ver2.1 Yutong
- Remove unused code and format code
- Remove `C16` in namespace, file name, folder name in order to make this driver to adapt to other further lslidar models. This is not completed, put it in the TODO list
### Ver2.0 Yutong
- Add GPS timestamp to PointCloud2 message
There is timestamp field in PointCloud2/fields part
- Using apollo/drivers/ namespace to adapt to apollo interface
### ver1.1 Yutong
Using new message type to distinguish different channel data
topic name: scan_channel
topic type: LslidarC16Layer
details: LslidarC16Layer is consist of 16 sets data for different channel, each set of data is represented by Sensor_msgs/LaserScan rosmessage type
Usage: rostopic echo /scan_channel will output all 16 channels data
rostopic echo /scan_channel/scan_channel[*] (* can be from 0 to 15 represents channel num) --> output data will be sensor_msgs/LaserScan message type
Example: There is an example script to show you how to obtain each channel data, located at /lslidar_c16_decoder/scripts/Test_MultiChannel.py
You will need python package numpy and matplotlib.pyplot(optional) to fully run this script
### ver1.05 Yutong
Using rostopic to select the channel you wish to output
topic name: layer_num
topic type: std_msgs/Int8
details: send layer number to topic layer_num
Usage: rostopic pub /layer_num std_msgs/Int8 "data: 5" --> output channel 5 data to topic /scan, message type is sensor_msgs/LaserScan . data number can only from 0 to 15
## Description
The `lslidar_c16` package is a linux ROS driver for lslidar c16.
The package is tested on Ubuntu 14.04 with ROS indigo.
## Compling
This is a Catkin package. Make sure the package is on `ROS_PACKAGE_PATH` after cloning the package to your workspace. And the normal procedure for compiling a catkin package will work.
```
cd your_work_space
catkin_make
```
## Example Usage
### lslidar_c16_decoder
**Parameters**
`device_ip` (`string`, `default: 192.168.1.200`)
By default, the IP address of the device is 192.168.1.200.
`frame_id` (`string`, `default: laser`)
The frame ID entry for the sent messages.
**Published Topics**
`lslidar_packets` (`lslidar_c16_msgs/LslidarC16Packet`)
Each message corresponds to a lslidar packet sent by the device through the Ethernet.
### lslidar_c16_decoder
**Parameters**
`min_range` (`double`, `0.15`)
`max_range` (`double`, `150.0`)
Points outside this range will be removed.
`frequency` (`frequency`, `10.0`)
Note that the driver does not change the frequency of the sensor.
`publish_point_cloud` (`bool`, `true`)
If set to true, the decoder will additionally send out a local point cloud consisting of the points in each revolution.
**Published Topics**
`lslidar_sweep` (`lslidar_c16_msgs/LslidarC16Sweep`)
The message arranges the points within each sweep based on its scan index and azimuth.
`lslidar_point_cloud` (`sensor_msgs/PointCloud2`)
This is only published when the `publish_point_cloud` is set to `true` in the launch file.
**Node**
```
roslaunch lslidar_c16_decoder lslidar_c16.launch --screen
```
Note that this launch file launches both the driver and the decoder, which is the only launch file needed to be used.
## FAQ
## Bug Report
| 0
|
apollo_public_repos/apollo-contrib
|
apollo_public_repos/apollo-contrib/lslidar_apollo/ReadMe_Apollo.md
|
# lslidar_c16
## preparation
### IP address
The default IP address for lslidar_c16 is 192.168.1.200, port number is 2368.
The default IP address for PC client is 192.168.1.102, port number is 2368.
These parameters can be configured by using lslidar_c16 configuration software tool.
## ROS
lslidar_c16 driver runs as node, including:
1. data packet processing --> /lslidar_driver_node
2. point cloud generation --> /lslidar_decoder_node
3. compensation --> /lslidar_compensator_node
lslidar_c16 driver runs as nodelet, including:
1. data packet processing --> /lslidar_driver_nodelet
2. point cloud generation --> /lslidar_decoder_nodelet
3. compensation --> /lslidar_compensator_nodelet
Compensation relies on `tf` to query the coordination transform, so gnss_driver is required to run the lslidar nodelets.
### decoder nodelet
roslaunch lslidar_decoder lslidar_c16_apollo.launch
lslidar_decoder runs as nodelet without motion compensation. The lslidar_driver already includes in this launch file, so you don't need to run lslidar_driver alone
Default nodelet manager name is: lslidar_nodelet_manager
Output
frame_id: lslidar
rostopic: /apollo/sensor/lslidarC16/PointCloud2
rosmsg: sensor_msgs/PointCloud2
### compensator nodelet
roslaunch lslidar_compensator lslidar_compensator_nodelet.launch
lslidar_compensator runs as nodelet with motion compensation. The lslidar_driver and lslidar_decoder already includes in this launch file, so you don't need to run they alone
* But it need a GNSS driver to publish a TF between world_frame_id ("world") and chile_frame_id ("lslidar") *
Default nodelet manager name is: lslidar_nodelet_manager
Output
1. PointCloud from lidar without motion compensator
rostopic: /apollo/sensor/lslidar/PointCloud2
rosmsg: sensor_msgs/PointCloud2
2. PointCloud obtained from lidar with motion compensator
rostopic: /apollo/sensor/lslidar/compensator/PointCloud2
rosmsg: sensor_msgs/PointCloud2
### Topics
* /apollo/sensor/lslidar/LslidarPacket --> lslidar_msgs/LslidarPacket
* /apollo/sensor/lslidar/PointCloud2 --> sensor_msgs/PointCloud2
* /apollo/sensor/lslidar/compensator/PointCloud2 --> sensor_msgs/PointCloud2
### TF frame
* world
* lslidar
### Build Velodyne
```bash
# in dev docker
cd /apollo
bash apollo.sh build_lslidar
```
The output will overwrite the lslidar driver in `/home/tmp/ros/`.
### Start lslidar_c16 Driver
**Please change the parameters in the launch file when you start**
```bash
# with GNSS compensator
roslaunch lslidar_compensator lslidar_compensator_nodelet.launch
# or
# without GNSS compensator
roslaunch lslidar_decoder lslidar_c16_apollo.launch
```
### FAQ
1. 'lslidar port 2368 poll() timeout'
The network between the host and lslidar_c16 is having problem. Please use `sudo tcpdump -i eth0 udp port 2368` to check if lidar_c16 packets with 1206 length data are received.
2. 'cannot find transform ...'
`Compensaton` relies on `tf`, please double check if `gnss_driver` has been started, and also use `rostopic echo /tf` to check if there are any message in the tf.
| 0
|
apollo_public_repos/apollo-contrib
|
apollo_public_repos/apollo-contrib/lslidar_apollo/apollo.sh
|
#!/usr/bin/env bash
###############################################################################
# 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.
###############################################################################
#=================================================
# Utils
#=================================================
function source_apollo_base() {
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "${DIR}"
source "${DIR}/scripts/apollo_base.sh"
}
function apollo_check_system_config() {
# check docker environment
if [ ${MACHINE_ARCH} == "x86_64" ] && [ $(hostname) != "in_dev_docker" ] &&
[ $(hostname) != "in_release_docker" ]; then
echo -e "${RED}Must run $0 in dev docker or release docker${NO_COLOR}"
exit 0
fi
# check operating system
OP_SYSTEM=$(uname -s)
case $OP_SYSTEM in
"Linux")
echo "System check passed. Build continue ..."
# check system configuration
DEFAULT_MEM_SIZE="2.0"
MEM_SIZE=$(free | grep Mem | awk '{printf("%0.2f", $2 / 1024.0 / 1024.0)}')
if (( $(echo "$MEM_SIZE < $DEFAULT_MEM_SIZE" | bc -l) )); then
warning "System memory [${MEM_SIZE}G] is lower than minimum required memory size [2.0G]. Apollo build could fail."
fi
;;
"Darwin")
warning "Mac OS is not officially supported in the current version. Build could fail. We recommend using Ubuntu 14.04."
;;
*)
error "Unsupported system: ${OP_SYSTEM}."
error "Please use Linux, we recommend Ubuntu 14.04."
exit 1
;;
esac
}
function check_machine_arch() {
# the machine type, currently support x86_64, aarch64
MACHINE_ARCH=$(uname -m)
# Generate WORKSPACE file based on machine architecture
if [ "$MACHINE_ARCH" == 'x86_64' ]; then
sed "s/MACHINE_ARCH/x86_64/g" WORKSPACE.in > WORKSPACE
elif [ "$MACHINE_ARCH" == 'aarch64' ]; then
sed "s/MACHINE_ARCH/aarch64/g" WORKSPACE.in > WORKSPACE
else
fail "Unknown machine architecture $MACHINE_ARCH"
exit 1
fi
#setup vtk folder name for different systems.
VTK_VERSION=$(find /usr/include/ -type d -name "vtk-*" | tail -n1 | cut -d '-' -f 2)
sed -i "s/VTK_VERSION/${VTK_VERSION}/g" WORKSPACE
}
function check_esd_files() {
CAN_CARD="fake_can"
if [ -f ./third_party/can_card_library/esd_can/include/ntcan.h \
-a -f ./third_party/can_card_library/esd_can/lib/libntcan.so.4 \
-a -f ./third_party/can_card_library/esd_can/lib/libntcan.so.4.0.1 ]; then
USE_ESD_CAN=true
CAN_CARD="esd_can"
else
warning "ESD CAN library supplied by ESD Electronics does not exist. If you need ESD CAN, please refer to third_party/can_card_library/esd_can/README.md."
USE_ESD_CAN=false
fi
}
function generate_build_targets() {
if [ -z $NOT_BUILD_PERCEPTION ] ; then
BUILD_TARGETS=`bazel query //...`
else
info 'Skip building perception module!'
BUILD_TARGETS=`bazel query //... except //modules/perception/... except //modules/calibration/lidar_ex_checker/...`
fi
if [ $? -ne 0 ]; then
fail 'Build failed!'
fi
if ! $USE_ESD_CAN; then
BUILD_TARGETS=$(echo $BUILD_TARGETS |tr ' ' '\n' | grep -v "esd")
fi
#skip msf for non x86_64 platforms
if [ ${MACHINE_ARCH} != "x86_64" ]; then
BUILD_TARGETS=$(echo $BUILD_TARGETS |tr ' ' '\n' | grep -v "msf")
fi
}
#=================================================
# Build functions
#=================================================
function build() {
START_TIME=$(get_now)
info "Start building, please wait ..."
generate_build_targets
info "Building on $MACHINE_ARCH..."
MACHINE_ARCH=$(uname -m)
JOB_ARG=""
if [ "$MACHINE_ARCH" == 'aarch64' ]; then
JOB_ARG="--jobs=3"
fi
echo "$BUILD_TARGETS" | xargs bazel build $JOB_ARG $DEFINES -c $@
if [ $? -ne 0 ]; then
fail 'Build failed!'
fi
# Build python proto
build_py_proto
# Clear KV DB and update commit_id after compiling.
rm -fr data/kv_db
python modules/tools/common/kv_db.py put \
"apollo:data:commit_id" "$(git rev-parse HEAD)"
if [ -d /apollo-simulator ] && [ -e /apollo-simulator/build.sh ]; then
cd /apollo-simulator && bash build.sh build
if [ $? -ne 0 ]; then
fail 'Build failed!'
fi
fi
if [ $? -eq 0 ]; then
success 'Build passed!'
fi
}
function cibuild() {
START_TIME=$(get_now)
echo "Start building, please wait ..."
generate_build_targets
echo "Building on $MACHINE_ARCH..."
BUILD_TARGETS="
//modules/control
//modules/dreamview
//modules/localization
//modules/perception
//modules/planning
//modules/prediction
//modules/routing
"
bazel build $DEFINES $@ $BUILD_TARGETS
if [ $? -eq 0 ]; then
success 'Build passed!'
else
fail 'Build failed!'
fi
}
function apollo_build_dbg() {
build "dbg" $@
}
function apollo_build_opt() {
build "opt" $@
}
function build_py_proto() {
if [ -d "./py_proto" ];then
rm -rf py_proto
fi
mkdir py_proto
PROTOC='./bazel-out/host/bin/external/com_google_protobuf/protoc'
find modules/ -name "*.proto" \
| grep -v node_modules \
| grep -v modules/drivers/gnss \
| xargs ${PROTOC} --python_out=py_proto
find py_proto/* -type d -exec touch "{}/__init__.py" \;
}
function check() {
local check_start_time=$(get_now)
bash $0 build && bash $0 "test" && bash $0 lint
START_TIME=$check_start_time
if [ $? -eq 0 ]; then
success 'Check passed!'
return 0
else
fail 'Check failed!'
return 1
fi
}
function warn_proprietary_sw() {
echo -e "${RED}The release built contains proprietary software provided by other parties.${NO_COLOR}"
echo -e "${RED}Make sure you have obtained proper licensing agreement for redistribution${NO_COLOR}"
echo -e "${RED}if you intend to publish the release package built.${NO_COLOR}"
echo -e "${RED}Such licensing agreement is solely between you and the other parties,${NO_COLOR}"
echo -e "${RED}and is not covered by the license terms of the apollo project${NO_COLOR}"
echo -e "${RED}(see file license).${NO_COLOR}"
}
function release() {
RELEASE_DIR="${HOME}/.cache/apollo_release"
if [ -d "${RELEASE_DIR}" ]; then
rm -rf "${RELEASE_DIR}"
fi
APOLLO_RELEASE_DIR="${RELEASE_DIR}/apollo"
mkdir -p "${APOLLO_RELEASE_DIR}"
# Find binaries and convert from //path:target to path/target
BINARIES=$(bazel query "kind(cc_binary, //...)" | sed 's/^\/\///' | sed 's/:/\//')
# Copy binaries to release dir.
for BIN in ${BINARIES}; do
SRC_PATH="bazel-bin/${BIN}"
DST_PATH="${APOLLO_RELEASE_DIR}/${BIN}"
if [ -e "${SRC_PATH}" ]; then
mkdir -p "$(dirname "${DST_PATH}")"
cp "${SRC_PATH}" "${DST_PATH}"
fi
done
# modules data and conf
CONFS=$(find modules/ -name "conf")
DATAS=$(find modules/ -name "data")
OTHER=("modules/tools"
"modules/perception/model")
rm -rf test/*
for conf in $CONFS; do
mkdir -p $APOLLO_RELEASE_DIR/$conf
rsync -a $conf/* $APOLLO_RELEASE_DIR/$conf
done
for data in $DATAS; do
mkdir -p $APOLLO_RELEASE_DIR/$data
if [ $data != "modules/map/data" ]; then
rsync -a $data/* $APOLLO_RELEASE_DIR/$data
fi
done
# Other
for path in "${OTHER[@]}"; do
mkdir -p $APOLLO_RELEASE_DIR/$path
rsync -a $path/* $APOLLO_RELEASE_DIR/$path
done
# dreamview frontend
cp -a modules/dreamview/frontend $APOLLO_RELEASE_DIR/modules/dreamview
# remove all pyc file in modules/
find modules/ -name "*.pyc" | xargs -I {} rm {}
# scripts
cp -r scripts ${APOLLO_RELEASE_DIR}
# lib
LIB_DIR="${APOLLO_RELEASE_DIR}/lib"
mkdir "${LIB_DIR}"
if $USE_ESD_CAN; then
warn_proprietary_sw
for m in esd_can
do
cp third_party/can_card_library/$m/lib/* $LIB_DIR
done
fi
cp -r bazel-genfiles/external $LIB_DIR
cp -r py_proto/modules $LIB_DIR
cp /apollo/modules/perception/cuda_util/cmake_build/libcuda_util.so $LIB_DIR
# doc
cp -r docs "${APOLLO_RELEASE_DIR}"
cp LICENSE "${APOLLO_RELEASE_DIR}"
cp third_party/ACKNOWLEDGEMENT.txt "${APOLLO_RELEASE_DIR}"
# release info
META="${APOLLO_RELEASE_DIR}/meta.ini"
echo "git_commit: $(git rev-parse HEAD)" >> $META
echo "car_type: LINCOLN.MKZ" >> $META
echo "arch: ${MACHINE_ARCH}" >> $META
}
function gen_coverage() {
bazel clean
generate_build_targets
echo "$BUILD_TARGETS" | grep -v "cnn_segmentation_test" | xargs bazel test $DEFINES -c dbg --config=coverage $@
if [ $? -ne 0 ]; then
fail 'run test failed!'
fi
COV_DIR=data/cov
rm -rf $COV_DIR
files=$(find bazel-out/local-dbg/bin/modules/ -iname "*.gcda" -o -iname "*.gcno" | grep -v external)
for f in $files; do
target="$COV_DIR/objs/modules/${f##*modules}"
mkdir -p "$(dirname "$target")"
cp "$f" "$target"
done
files=$(find bazel-out/local-opt/bin/modules/ -iname "*.gcda" -o -iname "*.gcno" | grep -v external)
for f in $files; do
target="$COV_DIR/objs/modules/${f##*modules}"
mkdir -p "$(dirname "$target")"
cp "$f" "$target"
done
lcov --capture --directory "$COV_DIR/objs" --output-file "$COV_DIR/conv.info"
if [ $? -ne 0 ]; then
fail 'lcov failed!'
fi
lcov --remove "$COV_DIR/conv.info" \
"external/*" \
"/usr/*" \
"bazel-out/*" \
"*third_party/*" \
"tools/*" \
-o $COV_DIR/stripped_conv.info
genhtml $COV_DIR/stripped_conv.info --output-directory $COV_DIR/report
echo "Generated coverage report in $COV_DIR/report/index.html"
}
function run_test() {
START_TIME=$(get_now)
generate_build_targets
if [ "$USE_GPU" == "1" ]; then
echo -e "${RED}Need GPU to run the tests.${NO_COLOR}"
echo "$BUILD_TARGETS" | xargs bazel test $DEFINES --config=unit_test -c dbg --test_verbose_timeout_warnings $@
else
echo "$BUILD_TARGETS" | grep -v "cnn_segmentation_test" | grep -v "yolo_camera_detector_test" | xargs bazel test $DEFINES --config=unit_test -c dbg --test_verbose_timeout_warnings $@
fi
if [ $? -ne 0 ]; then
fail 'Test failed!'
return 1
fi
if [ -d /apollo-simulator ] && [ -e /apollo-simulator/build.sh ]; then
cd /apollo-simulator && bash build.sh test
if [ $? -ne 0 ]; then
fail 'Test failed!'
return 1
fi
fi
if [ $? -eq 0 ]; then
success 'Test passed!'
return 0
fi
}
function citest() {
START_TIME=$(get_now)
BUILD_TARGETS="
//modules/planning/integration_tests:garage_test
//modules/planning/integration_tests:sunnyvale_loop_test
//modules/control/integration_tests:simple_control_test
//modules/prediction/container/obstacles:obstacle_test
//modules/dreamview/backend/simulation_world:simulation_world_service_test
"
bazel test $DEFINES --config=unit_test --test_verbose_timeout_warnings $@ $BUILD_TARGETS
if [ $? -eq 0 ]; then
success 'Test passed!'
return 0
else
fail 'Test failed!'
return 1
fi
}
function run_cpp_lint() {
generate_build_targets
echo "$BUILD_TARGETS" | xargs bazel test --config=cpplint -c dbg
}
function run_bash_lint() {
FILES=$(find "${APOLLO_ROOT_DIR}" -type f -name "*.sh" | grep -v ros)
echo "${FILES}" | xargs shellcheck
}
function run_lint() {
START_TIME=$(get_now)
# Add cpplint rule to BUILD files that do not contain it.
for file in $(find modules -name BUILD | \
xargs grep -l -E 'cc_library|cc_test|cc_binary' | xargs grep -L 'cpplint()')
do
sed -i '1i\load("//tools:cpplint.bzl", "cpplint")\n' $file
sed -i -e '$a\\ncpplint()' $file
done
run_cpp_lint
if [ $? -eq 0 ]; then
success 'Lint passed!'
else
fail 'Lint failed!'
fi
}
function clean() {
bazel clean --async
}
function buildify() {
START_TIME=$(get_now)
local buildifier_url=https://github.com/bazelbuild/buildtools/releases/download/0.4.5/buildifier
wget $buildifier_url -O ~/.buildifier
chmod +x ~/.buildifier
find . -name '*BUILD' -type f -exec ~/.buildifier -showlog -mode=fix {} +
if [ $? -eq 0 ]; then
success 'Buildify worked!'
else
fail 'Buildify failed!'
fi
rm ~/.buildifier
}
function build_fe() {
cd modules/dreamview/frontend
yarn build
}
function gen_doc() {
rm -rf docs/doxygen
doxygen apollo.doxygen
}
function version() {
commit=$(git log -1 --pretty=%H)
date=$(git log -1 --pretty=%cd)
echo "Commit: ${commit}"
echo "Date: ${date}"
}
function build_gnss() {
CURRENT_PATH=$(pwd)
if [ -d "${ROS_ROOT}" ]; then
ROS_PATH="${ROS_ROOT}/../.."
else
warning "ROS not found. Run apollo.sh build first."
exit 1
fi
source "${ROS_PATH}/setup.bash"
protoc modules/common/proto/error_code.proto --cpp_out=./
protoc modules/common/proto/header.proto --cpp_out=./
protoc modules/common/proto/geometry.proto --cpp_out=./
protoc modules/localization/proto/imu.proto --cpp_out=./
protoc modules/localization/proto/gps.proto --cpp_out=./
protoc modules/localization/proto/pose.proto --cpp_out=./
protoc modules/drivers/gnss/proto/gnss.proto --cpp_out=./
protoc modules/drivers/gnss/proto/imu.proto --cpp_out=./
protoc modules/drivers/gnss/proto/ins.proto --cpp_out=./ --python_out=./
protoc modules/drivers/gnss/proto/config.proto --cpp_out=./
protoc modules/drivers/gnss/proto/gnss_status.proto --cpp_out=./ --python_out=./
protoc modules/drivers/gnss/proto/gpgga.proto --cpp_out=./
protoc modules/drivers/gnss/proto/gnss_raw_observation.proto --cpp_out=./ --python_out=./
protoc modules/drivers/gnss/proto/gnss_best_pose.proto --cpp_out=./ --python_out=./
cd modules
catkin_make_isolated --install --source drivers/gnss \
--install-space "${ROS_PATH}" -DCMAKE_BUILD_TYPE=Release \
--cmake-args --no-warn-unused-cli
find "${ROS_PATH}" -name "*.pyc" -print0 | xargs -0 rm -rf
cd -
rm -rf modules/common/proto/*.pb.cc
rm -rf modules/common/proto/*.pb.h
rm -rf modules/drivers/gnss/proto/*.pb.cc
rm -rf modules/drivers/gnss/proto/*.pb.h
rm -rf modules/drivers/gnss/proto/*_pb2.py
rm -rf modules/localization/proto/*.pb.cc
rm -rf modules/localization/proto/*.pb.h
rm -rf modules/.catkin_workspace
rm -rf modules/build_isolated/
rm -rf modules/devel_isolated/
}
function build_velodyne() {
CURRENT_PATH=$(pwd)
if [ -d "${ROS_ROOT}" ]; then
ROS_PATH="${ROS_ROOT}/../.."
else
warning "ROS not found. Run apollo.sh build first."
exit 1
fi
source "${ROS_PATH}/setup.bash"
cd modules
catkin_make_isolated --install --source drivers/velodyne \
--install-space "${ROS_PATH}" -DCMAKE_BUILD_TYPE=Release \
--cmake-args --no-warn-unused-cli
find "${ROS_PATH}" -name "*.pyc" -print0 | xargs -0 rm -rf
cd -
rm -rf modules/.catkin_workspace
rm -rf modules/build_isolated/
rm -rf modules/devel_isolated/
}
function build_lslidar() {
CURRENT_PATH=$(pwd)
if [ -d "${ROS_ROOT}" ]; then
ROS_PATH="${ROS_ROOT}/../.."
else
warning "ROS not found. Run apollo.sh build first."
exit 1
fi
source "${ROS_PATH}/setup.bash"
cd modules
catkin_make_isolated --install --source drivers/lslidar_apollo \
--install-space "${ROS_PATH}" -DCMAKE_BUILD_TYPE=Release \
--cmake-args --no-warn-unused-cli
find "${ROS_PATH}" -name "*.pyc" -print0 | xargs -0 rm -rf
cd -
rm -rf modules/.catkin_workspace
rm -rf modules/build_isolated/
rm -rf modules/devel_isolated/
}
function build_usbcam() {
CURRENT_PATH=$(pwd)
if [ -d "${ROS_ROOT}" ]; then
ROS_PATH="${ROS_ROOT}/../.."
else
warning "ROS not found. Run apollo.sh build first."
exit 1
fi
source "${ROS_PATH}/setup.bash"
cd modules
catkin_make_isolated --install --source drivers/usb_cam \
--install-space "${ROS_PATH}" -DCMAKE_BUILD_TYPE=Release \
--cmake-args --no-warn-unused-cli
find "${ROS_PATH}" -name "*.pyc" -print0 | xargs -0 rm -rf
cd -
rm -rf modules/.catkin_workspace
rm -rf modules/build_isolated/
rm -rf modules/devel_isolated/
}
function config() {
${APOLLO_ROOT_DIR}/scripts/configurator.sh
}
function print_usage() {
RED='\033[0;31m'
BLUE='\033[0;34m'
BOLD='\033[1m'
NONE='\033[0m'
echo -e "\n${RED}Usage${NONE}:
.${BOLD}/apollo.sh${NONE} [OPTION]"
echo -e "\n${RED}Options${NONE}:
${BLUE}build${NONE}: run build only
${BLUE}build_opt${NONE}: build optimized binary for the code
${BLUE}build_gpu${NONE}: run build only with Caffe GPU mode support
${BLUE}build_gnss${NONE}: build gnss driver
${BLUE}build_velodyne${NONE}: build velodyne driver
${BLUE}build_usbcam${NONE}: build usb camera driver
${BLUE}build_opt_gpu${NONE}: build optimized binary with Caffe GPU mode support
${BLUE}build_fe${NONE}: compile frontend javascript code, this requires all the node_modules to be installed already
${BLUE}build_no_perception [dbg|opt]${NONE}: run build build skip building perception module, useful when some perception dependencies are not satisfied, e.g., CUDA, CUDNN, LIDAR, etc.
${BLUE}build_prof${NONE}: build for gprof support.
${BLUE}buildify${NONE}: fix style of BUILD files
${BLUE}check${NONE}: run build/lint/test, please make sure it passes before checking in new code
${BLUE}clean${NONE}: run Bazel clean
${BLUE}config${NONE}: run configurator tool
${BLUE}coverage${NONE}: generate test coverage report
${BLUE}doc${NONE}: generate doxygen document
${BLUE}lint${NONE}: run code style check
${BLUE}usage${NONE}: print this menu
${BLUE}release${NONE}: build release version
${BLUE}test${NONE}: run all unit tests
${BLUE}version${NONE}: display current commit and date
"
}
function main() {
source_apollo_base
check_machine_arch
apollo_check_system_config
check_esd_files
DEFINES="--define ARCH=${MACHINE_ARCH} --define CAN_CARD=${CAN_CARD} --cxxopt=-DUSE_ESD_CAN=${USE_ESD_CAN}"
if [ ${MACHINE_ARCH} == "x86_64" ]; then
DEFINES="${DEFINES} --copt=-mavx2"
fi
local cmd=$1
shift
case $cmd in
check)
DEFINES="${DEFINES} --cxxopt=-DCPU_ONLY"
check $@
;;
build)
DEFINES="${DEFINES} --cxxopt=-DCPU_ONLY"
apollo_build_dbg $@
;;
build_prof)
DEFINES="${DEFINES} --config=cpu_prof --cxxopt=-DCPU_ONLY"
apollo_build_dbg $@
;;
build_no_perception)
DEFINES="${DEFINES} --cxxopt=-DCPU_ONLY"
NOT_BUILD_PERCEPTION=true
if [ "$1" == "opt" ]; then
shift
apollo_build_opt $@
elif [ "$1" == "dbg" ]; then
shift
apollo_build_dbg $@
fi
;;
cibuild)
DEFINES="${DEFINES} --cxxopt=-DCPU_ONLY"
cibuild $@
;;
build_opt)
DEFINES="${DEFINES} --cxxopt=-DCPU_ONLY"
apollo_build_opt $@
;;
build_gpu)
DEFINES="${DEFINES} --cxxopt=-DUSE_GPU"
apollo_build_dbg $@
;;
build_opt_gpu)
DEFINES="${DEFINES} --cxxopt=-DUSE_GPU"
apollo_build_opt $@
;;
build_fe)
build_fe
;;
buildify)
buildify
;;
build_gnss)
build_gnss
;;
build_py)
build_py_proto
;;
build_velodyne)
build_velodyne
;;
build_usbcam)
build_usbcam
;;
config)
config
;;
doc)
gen_doc
;;
lint)
run_lint
;;
test)
DEFINES="${DEFINES} --cxxopt=-DCPU_ONLY"
run_test $@
;;
citest)
DEFINES="${DEFINES} --cxxopt=-DCPU_ONLY"
citest $@
;;
test_gpu)
DEFINES="${DEFINES} --cxxopt=-DUSE_GPU"
USE_GPU="1"
run_test $@
;;
release)
release 1
;;
release_noproprietary)
release 0
;;
coverage)
gen_coverage $@
;;
clean)
clean
;;
version)
version
;;
usage)
print_usage
;;
*)
print_usage
;;
esac
}
main $@
| 0
|
apollo_public_repos/apollo-contrib
|
apollo_public_repos/apollo-contrib/lslidar_apollo/.travis.yml
|
sudo: required
dist: trusty
language: generic # Force travis to use its minimal image with default Python settings
compiler:
- gcc
notifications:
email:
recipients:
- shaohuashu@lslidar.com
before_install: # Use this to prepare the system to install prerequisites or dependencies
# Define some config vars
- export ROS_DISTRO=jade
- sudo sh -c 'echo "deb http://packages.ros.org/ros/ubuntu trusty main" > /etc/apt/sources.list.d/ros-latest.list'
- wget http://packages.ros.org/ros.key -O - | sudo apt-key add -
- sudo apt-get update -qq
install: # Use this to install any prerequisites or dependencies necessary to run your build
- sudo apt-get install -q -y python-rosdep
# Setup rosdep
- sudo rosdep init
- rosdep update
before_script: # Use this to prepare your build for testing e.g. copy database configurations, environment variables, etc.
- export CI_SOURCE_PATH=$(pwd)
- export REPOSITORY_NAME=${PWD##*/}
- echo "Testing branch $TRAVIS_BRANCH of $REPOSITORY_NAME"
# Create workspace
- mkdir -p ~/ros/catkin_ws/src
- cd ~/ros/catkin_ws/src
- ln -s $CI_SOURCE_PATH . # Link the repo we are testing to the new workspace
- rosdep install --from-paths . --ignore-src --rosdistro $ROS_DISTRO -y
- source /opt/ros/$ROS_DISTRO/setup.bash
- catkin_init_workspace
- cd ../
- export ROS_PARALLEL_JOBS='-j2 -l2' # Limit parallel jobs
script: # All commands must exit with code 0 on success. Anything else is considered failure.
- catkin_make -DCMAKE_BUILD_TYPE=Release
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_driver/nodelet_lslidar.xml
|
<library path="lib/liblslidar_driver_nodelet">
<class name="lslidar_driver/LslidarDriverNodelet"
type="apollo::drivers::lslidar_driver::LslidarDriverNodelet"
base_class_type="nodelet::Nodelet">
<description>
Publish one lslidar raw data packet each time.
</description>
</class>
</library>
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_driver/CMakeLists.txt
|
cmake_minimum_required(VERSION 2.8.3)
project(lslidar_driver)
add_definitions(-std=c++0x)
find_package(catkin REQUIRED COMPONENTS
roscpp
nodelet
lslidar_msgs
)
find_package(Boost REQUIRED)
catkin_package(
INCLUDE_DIRS include
CATKIN_DEPENDS
roscpp
nodelet
lslidar_msgs
DEPENDS
boost
)
include_directories(
include
${Boost_INCLUDE_DIR}
${catkin_INCLUDE_DIRS}
)
link_directories(
${catkin_LIBRARY_DIRS}
)
# Leishen c16 lidar driver
add_library(lslidar_driver
src/lslidar_driver.cc
)
target_link_libraries(lslidar_driver
${catkin_LIBRARIES}
)
add_dependencies(lslidar_driver
${${PROJECT_NAME}_EXPORTED_TARGETS}
${catkin_EXPORTED_TARGETS}
)
# Leishen c16 lidar nodelet
add_executable(lslidar_driver_node
src/lslidar_driver_node.cc
)
target_link_libraries(lslidar_driver_node
lslidar_driver
${catkin_LIBRARIES}
)
add_dependencies(lslidar_driver_node
${${PROJECT_NAME}_EXPORTED_TARGETS}
${catkin_EXPORTED_TARGETS}
)
# Leishen c16 lidar nodelet
add_library(lslidar_driver_nodelet
src/lslidar_driver_nodelet.cc
)
target_link_libraries(lslidar_driver_nodelet
lslidar_driver
${catkin_LIBRARIES}
)
add_dependencies(lslidar_driver_nodelet
${${PROJECT_NAME}_EXPORTED_TARGETS}
${catkin_EXPORTED_TARGETS}
)
# install options
install(
TARGETS
lslidar_driver
lslidar_driver_node
lslidar_driver_nodelet
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION})
install(DIRECTORY include/${PROJECT_NAME}/
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION})
install(FILES nodelet_lslidar.xml
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION})
install(DIRECTORY launch/
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/launch)
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_driver/package.xml
|
<package>
<name>lslidar_driver</name>
<version>2.0.0</version>
<description>
ROS device driver for Leishen C16 lidar.
</description>
<maintainer email="yutongyan@lslidar.com">yutongyan</maintainer>
<author>yutongyan</author>
<license>Licensed under the Apache License, Version 2.0 </license>
<buildtool_depend>catkin</buildtool_depend>
<build_depend>nodelet</build_depend>
<build_depend>roscpp</build_depend>
<build_depend>lslidar_msgs</build_depend>
<run_depend>nodelet</run_depend>
<run_depend>roscpp</run_depend>
<run_depend>lslidar_msgs</run_depend>
<export>
<nodelet plugin="${prefix}/nodelet_lslidar.xml"/>
</export>
</package>
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_driver
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_driver/launch/lslidar_c16_driver_nodelet.launch
|
<launch>
<!-- start nodelet manager and load driver nodelet -->
<node pkg="nodelet" type="nodelet"
name="lslidar_nodelet_manager"
args="manager" output="screen"/>
<node pkg="nodelet" type="nodelet"
name="lslidar_driver_nodelet"
args="load lslidar_driver/LslidarDriverNodelet
lslidar_nodelet_manager" >
<param name="frame_id" value="lslidar"/>
<param name="device_ip" value="192.168.1.200"/>
</node>
</launch>
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_driver/include
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_driver/include/lslidar_driver/lslidar_driver_nodelet.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. /
****************************************************************************/
#include <string>
#include <boost/thread.hpp>
#include <ros/ros.h>
#include <pluginlib/class_list_macros.h>
#include <nodelet/nodelet.h>
#include <lslidar_driver/lslidar_driver.h>
namespace apollo {
namespace drivers {
namespace lslidar_driver{
class LslidarDriverNodelet: public nodelet::Nodelet
{
public:
LslidarDriverNodelet();
~LslidarDriverNodelet();
private:
virtual void onInit(void);
virtual void devicePoll(void);
volatile bool running; ///< device thread is running
boost::shared_ptr<boost::thread> device_thread;
LslidarDriverPtr lslidar_driver; ///< driver implementation class
};
} // namespace lslidar_driver
} // namespace drivers
} // namespace apollo
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_driver/include
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_driver/include/lslidar_driver/lslidar_driver.h
|
/***************************************************************************
Copyright 2018 The Apollo Authors. All Rights Reserved /
/
Licensed under the Apache License, Version 2.0 (the "License"); /
you may not use this file except in compliance with the License. /
You may obtain a copy of the License at /
/
http://www.apache.org/licenses/LICENSE-2.0 /
/
Unless required by applicable law or agreed to in writing, software /
distributed under the License is distributed on an "AS IS" BASIS, /
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /
See the License for the specific language governing permissions and /
limitations under the License. /
****************************************************************************/
#ifndef LSLIDAR_DRIVER_H
#define LSLIDAR_DRIVER_H
#include <unistd.h>
#include <stdio.h>
#include <netinet/in.h>
#include <string>
#include <time.h>
#include <boost/shared_ptr.hpp>
#include <ros/ros.h>
#include <std_msgs/UInt64.h>
#include <lslidar_msgs/LslidarPacket.h>
namespace apollo {
namespace drivers {
namespace lslidar_driver {
//static uint16_t UDP_PORT_NUMBER = 8080;
static uint16_t PACKET_SIZE = 1206;
class LslidarDriver {
public:
LslidarDriver(ros::NodeHandle& n, ros::NodeHandle& pn);
~LslidarDriver();
bool initialize();
bool polling();
void initTimeStamp(void);
void getFPGA_GPSTimeStamp(lslidar_msgs::LslidarPacketPtr &packet);
typedef boost::shared_ptr<LslidarDriver> LslidarDriverPtr;
typedef boost::shared_ptr<const LslidarDriver> LslidarDriverConstPtr;
private:
bool loadParameters();
bool createRosIO();
bool openUDPPort();
int getPacket(lslidar_msgs::LslidarPacketPtr& msg);
// Ethernet related variables
std::string device_ip_string;
in_addr device_ip;
int UDP_PORT_NUMBER;
int socket_id;
// ROS related variables
ros::NodeHandle nh;
ros::NodeHandle pnh;
std::string frame_id;
ros::Publisher packet_pub;
uint64_t pointcloudTimeStamp;
unsigned char packetTimeStamp[10];
struct tm cur_time;
unsigned short int us;
unsigned short int ms;
ros::Time timeStamp;
};
typedef LslidarDriver::LslidarDriverPtr LslidarDriverPtr;
typedef LslidarDriver::LslidarDriverConstPtr LslidarDriverConstPtr;
} // namespace lslidar_driver
}
}
#endif // _LSLIDAR_DRIVER_H_
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_driver
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_driver/src/lslidar_driver_nodelet.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 <string>
#include <boost/thread.hpp>
#include <ros/ros.h>
#include <pluginlib/class_list_macros.h>
#include <nodelet/nodelet.h>
#include <lslidar_driver/lslidar_driver_nodelet.h>
namespace apollo {
namespace drivers {
namespace lslidar_driver{
LslidarDriverNodelet::LslidarDriverNodelet():
running(false) {
return;
}
LslidarDriverNodelet::~LslidarDriverNodelet() {
if (running) {
NODELET_INFO("shutting down driver thread");
running = false;
device_thread->join();
NODELET_INFO("driver thread stopped");
}
return;
}
void LslidarDriverNodelet::onInit()
{
// start the driver
lslidar_driver.reset(
new LslidarDriver(getNodeHandle(), getPrivateNodeHandle()));
if (!lslidar_driver->initialize()) {
ROS_ERROR("Cannot initialize lslidar driver...");
return;
}
// spawn device poll thread
running = true;
device_thread = boost::shared_ptr< boost::thread >
(new boost::thread(boost::bind(&LslidarDriverNodelet::devicePoll, this)));
}
/** @brief Device poll thread main loop. */
void LslidarDriverNodelet::devicePoll()
{
while(ros::ok()) {
// poll device until end of file
running = lslidar_driver->polling();
// ROS_INFO_THROTTLE(30, "polling data successfully");
if (!running)
break;
}
running = false;
}
} // namespace lslidar_driver
}
}
// Register this plugin with pluginlib. Names must match nodelet_lslidar.xml.
//
// parameters are: package, class name, class type, base class type
PLUGINLIB_DECLARE_CLASS(lslidar_driver, LslidarDriverNodelet,
apollo::drivers::lslidar_driver::LslidarDriverNodelet,
nodelet::Nodelet);
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_driver
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_driver/src/lslidar_driver.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 <string>
#include <cmath>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <poll.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/file.h>
#include <ros/ros.h>
#include <tf/transform_listener.h>
#include <lslidar_driver/lslidar_driver.h>
namespace apollo {
namespace drivers {
namespace lslidar_driver {
LslidarDriver::LslidarDriver(
ros::NodeHandle& n, ros::NodeHandle& pn):
nh(n),
pnh(pn),
socket_id(-1){
}
LslidarDriver::~LslidarDriver() {
(void) close(socket_id);
}
bool LslidarDriver::loadParameters() {
pnh.param("frame_id", frame_id, std::string("lslidar"));
pnh.param("device_ip", device_ip_string, std::string("192.168.1.222"));
pnh.param<int>("device_port", UDP_PORT_NUMBER, 2368);
inet_aton(device_ip_string.c_str(), &device_ip);
ROS_INFO_STREAM("Opening UDP socket: address " << device_ip_string);
ROS_INFO_STREAM("Opening UDP socket: port " << UDP_PORT_NUMBER);
return true;
}
bool LslidarDriver::createRosIO() {
// Output lidar_packet publisher
packet_pub = nh.advertise<lslidar_msgs::LslidarPacket>(
"lslidar_packet", 100);
return true;
}
bool LslidarDriver::openUDPPort() {
socket_id = socket(PF_INET, SOCK_DGRAM, 0);
if (socket_id == -1) {
perror("socket");
return false;
}
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(UDP_PORT_NUMBER); // short, in network byte order
ROS_INFO_STREAM("Opening UDP socket: port " << UDP_PORT_NUMBER);
my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill in my IP
if (bind(socket_id, (sockaddr *)&my_addr, sizeof(sockaddr)) == -1) {
perror("bind"); // TODO: ROS_ERROR errno
return false;
}
if (fcntl(socket_id, F_SETFL, O_NONBLOCK|FASYNC) < 0) {
perror("non-block");
return false;
}
return true;
}
bool LslidarDriver::initialize() {
this->initTimeStamp();
if (!loadParameters()) {
ROS_ERROR("Cannot load all required ROS parameters...");
return false;
}
if (!createRosIO()) {
ROS_ERROR("Cannot create all ROS IO...");
return false;
}
if (!openUDPPort()) {
ROS_ERROR("Cannot open UDP port...");
return false;
}
ROS_INFO("Initialised lslidar c16 without error");
return true;
}
int LslidarDriver::getPacket(
lslidar_msgs::LslidarPacketPtr& packet) {
double time1 = ros::Time::now().toSec();
struct pollfd fds[1];
fds[0].fd = socket_id;
fds[0].events = POLLIN;
static const int POLL_TIMEOUT = 2000; // one second (in msec)
sockaddr_in sender_address;
socklen_t sender_address_len = sizeof(sender_address);
while (true)
{
do {
// poll() until input available
int retval = poll(fds, 1, POLL_TIMEOUT);
if (retval < 0) // poll() error?
{
if (errno != EINTR)
ROS_ERROR("poll() error: %s", strerror(errno));
return 1;
}
if (retval == 0) // poll() timeout?
{
ROS_WARN("lslidar poll() timeout");
return 1;
}
if ((fds[0].revents & POLLERR)
|| (fds[0].revents & POLLHUP)
|| (fds[0].revents & POLLNVAL)) // device error?
{
ROS_ERROR("poll() reports lslidar error");
return 1;
}
} while ((fds[0].revents & POLLIN) == 0);
// Receive packets that should now be available from the
// socket using a blocking read.
ssize_t nbytes = recvfrom(socket_id, &packet->data[0], PACKET_SIZE, 0,
(sockaddr*) &sender_address, &sender_address_len);
if (nbytes < 0)
{
if (errno != EWOULDBLOCK)
{
perror("recvfail");
ROS_INFO("recvfail");
return 1;
}
}
else if ((size_t) nbytes == PACKET_SIZE)
{
// read successful,
// if packet is not from the lidar scanner we selected by IP,
// continue otherwise we are done
if( device_ip_string != "" && sender_address.sin_addr.s_addr != device_ip.s_addr )
continue;
else
break; //done
}
}
// get GPS and FPGA timestamp from packet
this->getFPGA_GPSTimeStamp(packet);
packet->stamp = this->timeStamp;
return 0;
}
bool LslidarDriver::polling()
{
// Allocate a new shared pointer for zero-copy sharing with other nodelets.
lslidar_msgs::LslidarPacketPtr packet(
new lslidar_msgs::LslidarPacket());
while (true)
{
// keep reading until full packet received
int rc = getPacket(packet);
if (rc == 0) break; // got a full packet?
if (rc < 0) return false; // end of file reached?
}
// publish message using time of last packet read
// ROS_DEBUG("Publishing a full lslidar scan.");
packet_pub.publish(*packet);
return true;
}
void LslidarDriver::initTimeStamp(void)
{
int i;
for(i = 0;i < 10;i ++)
{
this->packetTimeStamp[i] = 0;
}
this->pointcloudTimeStamp = 0;
this->timeStamp = ros::Time(0.0);
}
void LslidarDriver::getFPGA_GPSTimeStamp(lslidar_msgs::LslidarPacketPtr &packet)
{
unsigned char head2[] = {packet->data[0],packet->data[1],packet->data[2],packet->data[3]};
if(head2[0] == 0xA5 && head2[1] == 0xFF)
{
if(head2[2] == 0x00 && head2[3] == 0x5A)
{
this->packetTimeStamp[4] = packet->data[41];
this->packetTimeStamp[5] = packet->data[40];
this->packetTimeStamp[6] = packet->data[39];
this->packetTimeStamp[7] = packet->data[38];
this->packetTimeStamp[8] = packet->data[37];
this->packetTimeStamp[9] = packet->data[36];
}
}
else if(head2[0] == 0xFF && head2[1] == 0xEE)
{
uint64_t packet_timestamp;
packet_timestamp = (packet->data[1200] +
packet->data[1201] * pow(2, 8) +
packet->data[1202] * pow(2, 16) +
packet->data[1203] * pow(2, 24)) * 1e3;
cur_time.tm_sec = this->packetTimeStamp[4];
cur_time.tm_min = this->packetTimeStamp[5];
cur_time.tm_hour = this->packetTimeStamp[6];
cur_time.tm_mday = this->packetTimeStamp[7];
cur_time.tm_mon = this->packetTimeStamp[8]-1;
cur_time.tm_year = this->packetTimeStamp[9]+2000-1900;
this->pointcloudTimeStamp = static_cast<uint64_t>(timegm(&cur_time));
// timeStamp = ros::Time(this->pointcloudTimeStamp+total_us/10e5);
timeStamp = ros::Time(this->pointcloudTimeStamp, packet_timestamp);
ROS_DEBUG("ROS TS: %f, GPS: y:%d m:%d d:%d h:%d m:%d s:%d; FPGA: us:%lu",
timeStamp.toSec(),
cur_time.tm_year,cur_time.tm_mon,cur_time.tm_mday,cur_time.tm_hour,cur_time.tm_min,cur_time.tm_sec,
packet_timestamp);
}
}
} // namespace lslidar_driver
} // namespace drivers
} // namespace apollo
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_driver
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_driver/src/lslidar_driver_node.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 <ros/ros.h>
#include <lslidar_driver/lslidar_driver.h>
int main(int argc, char** argv)
{
ros::init(argc, argv, "lslidar_driver_node");
ros::NodeHandle node;
ros::NodeHandle private_nh("~");
// start the driver
apollo::drivers::lslidar_driver::LslidarDriver driver(node, private_nh);
if (!driver.initialize()) {
ROS_ERROR("Cannot initialize lslidar driver...");
return 0;
}
// loop until shut down or end of file
while(ros::ok() && driver.polling()) {
ros::spinOnce();
}
return 0;
}
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_compensator/CMakeLists.txt
|
cmake_minimum_required(VERSION 2.8.3)
project(lslidar_compensator)
add_definitions(-std=c++0x)
find_package(catkin REQUIRED COMPONENTS
angles
roscpp
pluginlib
sensor_msgs
pcl_ros
pcl_conversions
lslidar_msgs
nodelet
eigen_conversions
)
find_package(Eigen3 REQUIRED)
include_directories(${EIGEN3_INCLUDE_DIR})
find_package(Boost REQUIRED)
find_package(PCL 1.7 REQUIRED)
include_directories(${PCL_INCLUDE_DIRS})
link_directories(${PCL_LIBRARY_DIRS})
add_definitions(${PCL_DEFINITIONS})
catkin_package(
INCLUDE_DIRS include
CATKIN_DEPENDS
roscpp sensor_msgs pluginlib nodelet
pcl_ros pcl_conversions
lslidar_msgs
eigen_conversions
angles
DEPENDS
Boost
)
include_directories(
include
${Boost_INCLUDE_DIR}
${catkin_INCLUDE_DIRS}
)
link_directories(
${catkin_LIBRARY_DIRS}
)
# Lslidar C16 compensator node
add_executable(lslidar_compensator_node src/compensator_node.cpp src/compensator.cpp)
add_dependencies(lslidar_compensator_node
${${PROJECT_NAME}_EXPORTED_TARGETS}
${catkin_EXPORTED_TARGETS}
)
target_link_libraries(lslidar_compensator_node
${catkin_LIBRARIES}
${PCL_LIBRARIES})
add_library(lslidar_compensator_nodelet src/compensator_nodelet.cpp src/compensator.cpp)
target_link_libraries(lslidar_compensator_nodelet
${catkin_LIBRARIES}
${PCL_LIBRARIES})
add_dependencies(lslidar_compensator_nodelet
${${PROJECT_NAME}_EXPORTED_TARGETS}
${catkin_EXPORTED_TARGETS}
)
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_compensator/package.xml
|
<?xml version="1.0"?>
<package format="2">
<name>lslidar_compensator</name>
<version>2.0.0</version>
<description>
Point cloud conversions for Leishen C16 LIDARs.
</description>
<maintainer email="yutongyan@lslidar.com">yutongyan</maintainer>
<author>yutongyan</author>
<license>Licensed under the Apache License, Version 2.0 </license>
<buildtool_depend>catkin</buildtool_depend>
<depend>pluginlib</depend>
<depend>roscpp</depend>
<depend>sensor_msgs</depend>
<depend>nodelet</depend>
<depend>angles</depend>
<depend>eigen_conversions</depend>
<depend>pcl_ros</depend>
<depend>pcl_conversions</depend>
<depend>libpcl-all-dev</depend>
<depend>libpcl-all</depend>
<depend>lslidar_msgs</depend>
<export>
<nodelet plugin="${prefix}/nodelet_lslidar_compensator.xml"/>
</export>
</package>
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_compensator/nodelet_lslidar_compensator.xml
|
<library path="lib/liblslidar_compensator_nodelet">
<class name="lslidar_compensator/CompensatorNodelet"
type="apollo::drivers::lslidar_compensator::CompensatorNodelet"
base_class_type="nodelet::Nodelet">
<description>
Aggregates points from multiple packets, publishing LslidarC16Sweep msg defined
in lslidar_msgs.
</description>
</class>
</library>
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_compensator
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_compensator/launch/lslidar_compensator_nodelet.launch
|
<launch>
<arg name="child_frame_id" default="lslidar"/>
<arg name="world_frame_id" default="world"/>
<arg name="nodelet_manager_name" value="lslidar_nodelet_manager" />
<arg name="device_ip" value="192.168.1.200"/>
<arg name="firing_port" value="2368"/>
<arg name="topic_packet" default="/apollo/sensor/lslidar/LslidarPacket"/>
<arg name="topic_pointcloud" default="/apollo/sensor/lslidar/PointCloud2"/>
<arg name="topic_compensated_pointcloud" default="/apollo/sensor/lslidar/compensator/PointCloud2"/>
<!-- nodelet manager -->
<node pkg="nodelet" type="nodelet" name="$(arg nodelet_manager_name)" output="screen"
args="manager" />
<!-- nodelet driver for lslidar -->
<node pkg="nodelet" type="nodelet"
name="lslidar_driver_nodelet"
args="load lslidar_driver/LslidarDriverNodelet
$(arg nodelet_manager_name)" >
<param name="frame_id" value="lslidar"/>
<param name="device_ip" value="$(arg device_ip)"/>
<param name="device_port" value="$(arg firing_port)"/>
<remap from="lslidar_packet" to="$(arg topic_packet)"/>
</node>
<node pkg="nodelet" type="nodelet" name="lslidar_decoder_nodelet"
args="load lslidar_decoder/LslidarDecoderNodelet
$(arg nodelet_manager_name)"
output="screen">
<param name="child_frame_id" value="$(arg child_frame_id)"/>
<param name="min_range" value="0.3"/>
<param name="max_range" value="100.0"/>
<param name="frequency" value="10.0"/>
<param name="publish_point_cloud" value="true"/>
<param name="publish_channels" value="false"/>
<remap from="lslidar_packet" to="$(arg topic_packet)"/>
<remap from="lslidar_point_cloud" to="$(arg topic_pointcloud)"/>
</node>
<node pkg="nodelet" type="nodelet" name="lslidar_compensator_nodelet"
args="load lslidar_compensator/CompensatorNodelet $(arg nodelet_manager_name)" output="screen">
<param name="lslidar_point_cloud" value="$(arg topic_pointcloud)"/>
<param name="topic_compensated_pointcloud" value="$(arg topic_compensated_pointcloud)"/>
<param name="child_frame_id" value="$(arg child_frame_id)"/>
<param name="tf_query_timeout" value="0.2"/>
</node>
<!-- <node name="rviz" pkg="rviz" type="rviz" args="-d $(find lslidar_decoder)/launch/lslidar.rviz" output="screen"/>
-->
</launch>
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_compensator
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_compensator/launch/lslidar_c16_compensator.launch
|
<launch>
<arg name="topic_packet" default="/apollo/sensor/lslidar/LslidarPacket"/>
<arg name="topic_pointcloud" default="/apollo/sensor/lslidar/PointCloud2"/>
<arg name="topic_scan_unified" default="/apollo/sensor/lslidar/VelodyneScanUnified"/>
<arg name="topic_compensated_pointcloud" default="/apollo/sensor/lslidar/compensator/PointCloud2"/>
<arg name="child_frame_id" value="lslidar"/>
<node pkg="lslidar_driver" type="lslidar_driver_node" name="lslidar_driver_node" output="screen">
<param name="frame_id" value="$(arg child_frame_id)"/>
<param name="device_ip" value="192.168.1.200"/>
<param name="device_port" value="2368"/>
<remap from="lslidar_packet" to="$(arg topic_packet)"/>>
</node>
<node pkg="lslidar_decoder" type="lslidar_decoder_node" name="lslidar_decoder_node" output="screen">
<param name="child_frame_id" value="$(arg child_frame_id)"/>
<param name="point_num" value="2000"/>
<param name="channel_num" value="8"/>
<param name="angle_disable_min" value="0"/>
<param name="angle_disable_max" value="0"/>
<param name="min_range" value="0.15"/>
<param name="max_range" value="150.0"/>
<param name="frequency" value="10.0"/>
<param name="publish_point_cloud" value="true"/>
<param name="publish_channels" value="true"/>
<remap from="lslidar_packet" to="$(arg topic_packet)"/>
<remap from="lslidar_point_cloud" to="$(arg topic_pointcloud)"/>
</node>
<node pkg="lslidar_compensator" type="lslidar_compensator_node" name="lslidar_compensator_node"
output="screen">
<param name="lslidar_point_cloud" value="$(arg topic_pointcloud)"/>
<param name="topic_compensated_pointcloud" value="$(arg topic_compensated_pointcloud)"/>
<param name="child_frame_id" value="$(arg child_frame_id)"/>
<param name="tf_query_timeout" value="0.5"/>
</node>
<!--node name="rviz" pkg="rviz" type="rviz" args="-d $(find lslidar_decoder)/launch/lslidar.rviz" output="screen"/-->
</launch>
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_compensator/include
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_compensator/include/lslidar_compensator/compensator.h
|
/***************************************************************************
Copyright 2018 The Apollo Authors. All Rights Reserved /
/
Licensed under the Apache License, Version 2.0 (the "License"); /
you may not use this file except in compliance with the License. /
You may obtain a copy of the License at /
/
http://www.apache.org/licenses/LICENSE-2.0 /
/
Unless required by applicable law or agreed to in writing, software /
distributed under the License is distributed on an "AS IS" BASIS, /
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /
See the License for the specific language governing permissions and /
limitations under the License. /
****************************************************************************/
#ifndef MODULES_DRIVERS_LSLIDAR_POINTCLOUD_COMPENSATOR_H_
#define MODULES_DRIVERS_LSLIDAR_POINTCLOUD_COMPENSATOR_H_
#include <eigen_conversions/eigen_msg.h>
#include <pcl/common/time.h>
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <std_msgs/String.h>
#include <tf2_ros/transform_listener.h>
#include <Eigen/Eigen>
namespace apollo {
namespace drivers {
namespace lslidar_compensator{
class Compensator {
public:
Compensator(ros::NodeHandle node, ros::NodeHandle private_nh);
virtual ~Compensator() {}
private:
/**
* @brief get pointcloud2 msg, compensate it,publish pointcloud2 after
* compensator
*/
void pointcloud_callback(const sensor_msgs::PointCloud2ConstPtr& msg);
/**
* @brief get pose affine from tf2 by gps timestamp
* novatel-preprocess broadcast the tf2 transform.
*/
bool query_pose_affine_from_tf2(const double& timestamp,
Eigen::Affine3d& pose);
/**
* @brief check if message is valid, check width, height, timestamp.
* set timestamp_offset and point data type
*/
bool check_message(const sensor_msgs::PointCloud2ConstPtr& msg);
/**
* @brief motion compensation for point cloud
*/
template <typename Scalar>
void motion_compensation(sensor_msgs::PointCloud2::Ptr& msg,
const double timestamp_min,
const double timestamp_max,
const Eigen::Affine3d& pose_min_time,
const Eigen::Affine3d& pose_max_time);
/**
* @brief get min timestamp and max timestamp from points in pointcloud2
*/
inline void get_timestamp_interval(
const sensor_msgs::PointCloud2ConstPtr& msg, double& timestamp_min,
double& timestamp_max);
/**
* @brief get point field size by sensor_msgs::datatype
*/
inline uint get_field_size(const int data_type);
// subscribe velodyne pointcloud2 msg.
ros::Subscriber pointcloud_sub_;
// publish point cloud2 after motion compensation
ros::Publisher compensation_pub_;
// ros::Publisher metastatus_publisher_;
// tf2 buffer
tf2_ros::Buffer tf2_buffer_;
// tf2 transform listener to get transform by gps timestamp.
tf2_ros::TransformListener tf2_transform_listener_;
// transform child frame id(world -> child frame)
std::string child_frame_id_;
std::string world_frame_id_;
float tf_timeout_;
// variables for point fields value, we get point x,y,z by these offset
int x_offset_;
int y_offset_;
int z_offset_;
int timestamp_offset_;
uint timestamp_data_size_;
// topic names
std::string topic_compensated_pointcloud_;
std::string topic_pointcloud_;
// ros queue size for publisher and subscriber
int queue_size_;
};
} // namespace lslidar
}
}
#endif // MODULES_DRIVERS_LSLIDAR_POINTCLOUD_COMPENSATOR_H_
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_compensator
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_compensator/src/compensator.cpp
|
/***************************************************************************
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 "lslidar_compensator/compensator.h"
#include "ros/this_node.h"
namespace apollo {
namespace drivers {
namespace lslidar_compensator {
Compensator::Compensator(ros::NodeHandle node, ros::NodeHandle private_nh)
: tf2_transform_listener_(tf2_buffer_, node),
x_offset_(-1),
y_offset_(-1),
z_offset_(-1),
timestamp_offset_(-1),
timestamp_data_size_(0) {
private_nh.param("child_frame_id", child_frame_id_,
std::string("lslidar"));
private_nh.param("world_frame_id", world_frame_id_,
std::string("world"));
private_nh.param("topic_compensated_pointcloud",
topic_compensated_pointcloud_, std::string("/apollo/sensor/lslidar/compensator/PointCloud2"));
private_nh.param("lslidar_point_cloud", topic_pointcloud_, std::string("/apollo/sensor/lslidar/PointCloud2"));
private_nh.param("queue_size", queue_size_, 10);
private_nh.param("tf_query_timeout", tf_timeout_, float(0.1));
// advertise output point cloud (before subscribing to input data)
compensation_pub_ = node.advertise<sensor_msgs::PointCloud2>(
topic_compensated_pointcloud_, queue_size_);
pointcloud_sub_ =
node.subscribe(topic_pointcloud_, queue_size_,
&Compensator::pointcloud_callback, (Compensator*)this);
}
void Compensator::pointcloud_callback(
const sensor_msgs::PointCloud2ConstPtr& msg) {
if (!check_message(msg)) {
ROS_FATAL("MotionCompensation : Input point cloud data field is invalid");
return;
}
Eigen::Affine3d pose_min_time;
Eigen::Affine3d pose_max_time;
double timestamp_min = 0;
double timestamp_max = 0;
get_timestamp_interval(msg, timestamp_min, timestamp_max);
// compensate point cloud, remove nan point
if (query_pose_affine_from_tf2(timestamp_min, pose_min_time) &&
query_pose_affine_from_tf2(timestamp_max, pose_max_time)) {
// we change message after motion compensation
sensor_msgs::PointCloud2::Ptr q_msg(new sensor_msgs::PointCloud2());
*q_msg = *msg;
motion_compensation<float>(q_msg, timestamp_min, timestamp_max,
pose_min_time, pose_max_time);
q_msg->header.stamp.fromSec(timestamp_max);
compensation_pub_.publish(q_msg);
}
}
inline void Compensator::get_timestamp_interval(
const sensor_msgs::PointCloud2ConstPtr& msg, double& timestamp_min,
double& timestamp_max) {
timestamp_max = 0.0;
timestamp_min = std::numeric_limits<double>::max();
int total = msg->width * msg->height;
// get min time and max time
for (int i = 0; i < total; ++i) {
double timestamp = 0.0;
memcpy(×tamp, &msg->data[i * msg->point_step + timestamp_offset_],
timestamp_data_size_);
if (timestamp < timestamp_min) {
timestamp_min = timestamp;
}
if (timestamp > timestamp_max) {
timestamp_max = timestamp;
}
}
}
// TODO: if point type is always float, and timestamp is always double?
inline bool Compensator::check_message(
const sensor_msgs::PointCloud2ConstPtr& msg) {
// check msg width and height
if (msg->width == 0 || msg->height == 0) {
return false;
}
int x_data_type = 0;
int y_data_type = 0;
int z_data_type = 0;
// TODO: will use a new data structure with interface to get offset,
// datatype,datasize...
for (size_t i = 0; i < msg->fields.size(); ++i) {
const sensor_msgs::PointField& f = msg->fields[i];
if (f.name == "x") {
x_offset_ = f.offset;
x_data_type = f.datatype;
if ((x_data_type != 7 && x_data_type != 8) || f.count != 1 ||
x_offset_ == -1) {
return false;
}
} else if (f.name == "y") {
y_offset_ = f.offset;
y_data_type = f.datatype;
if (f.count != 1 || y_offset_ == -1) {
return false;
}
} else if (f.name == "z") {
z_offset_ = f.offset;
z_data_type = f.datatype;
if (f.count != 1 || z_offset_ == -1) {
return false;
}
} else if (f.name == "timestamp") {
timestamp_offset_ = f.offset;
timestamp_data_size_ = f.count * get_field_size(f.datatype);
if (timestamp_offset_ == -1 || timestamp_data_size_ == -1) {
return false;
}
} else {
ROS_DEBUG_STREAM("get a unused field name:" << f.name);
}
}
// check offset if valid
if (x_offset_ == -1 || y_offset_ == -1 || z_offset_ == -1 ||
timestamp_offset_ == -1 || timestamp_data_size_ == -1) {
return false;
}
if (!(x_data_type == y_data_type && y_data_type == z_data_type)) {
return false;
}
return true;
}
bool Compensator::query_pose_affine_from_tf2(const double& timestamp,
Eigen::Affine3d& pose) {
ros::Time query_time(timestamp);
std::string err_string;
if (!tf2_buffer_.canTransform(world_frame_id_, child_frame_id_, query_time,
ros::Duration(tf_timeout_), &err_string)) {
ROS_WARN_STREAM("Can not find transform. "
<< std::fixed << timestamp
<< " Error info: " << err_string);
return false;
}
geometry_msgs::TransformStamped stamped_transform;
try {
stamped_transform =
tf2_buffer_.lookupTransform(world_frame_id_, child_frame_id_, query_time);
} catch (tf2::TransformException& ex) {
ROS_ERROR_STREAM(ex.what());
return false;
}
tf::transformMsgToEigen(stamped_transform.transform, pose);
// ROS_DEBUG_STREAM("pose matrix : " << pose);
return true;
}
/** \brief Obtains the size of a specific field data type in bytes
* \param[in] datatype the field data type
*/
inline uint Compensator::get_field_size(const int datatype) {
switch (datatype) {
case sensor_msgs::PointField::INT8:
case sensor_msgs::PointField::UINT8:
return 1;
case sensor_msgs::PointField::INT16:
case sensor_msgs::PointField::UINT16:
return 2;
case sensor_msgs::PointField::INT32:
case sensor_msgs::PointField::UINT32:
case sensor_msgs::PointField::FLOAT32:
return 4;
case sensor_msgs::PointField::FLOAT64:
return 8;
default:
ROS_ERROR_STREAM("can not get field size by datatype:" << datatype);
return 0;
}
}
template <typename Scalar>
void Compensator::motion_compensation(sensor_msgs::PointCloud2::Ptr& msg,
const double timestamp_min,
const double timestamp_max,
const Eigen::Affine3d& pose_min_time,
const Eigen::Affine3d& pose_max_time) {
using std::abs;
using std::sin;
using std::acos;
Eigen::Vector3d translation =
pose_min_time.translation() - pose_max_time.translation();
Eigen::Quaterniond q_max(pose_max_time.linear());
Eigen::Quaterniond q_min(pose_min_time.linear());
Eigen::Quaterniond q1(q_max.conjugate() * q_min);
Eigen::Quaterniond q0(Eigen::Quaterniond::Identity());
q1.normalize();
translation = q_max.conjugate() * translation;
int total = msg->width * msg->height;
double d = q0.dot(q1);
double abs_d = abs(d);
double f = 1.0 / (timestamp_max - timestamp_min);
// Threshold for a "significant" rotation from min_time to max_time:
// The LiDAR range accuracy is ~2 cm. Over 70 meters range, it means an angle
// of 0.02 / 70 =
// 0.0003 rad. So, we consider a rotation "significant" only if the scalar
// part of quaternion is
// less than cos(0.0003 / 2) = 1 - 1e-8.
if (abs_d < 1.0 - 1.0e-8) {
double theta = acos(abs_d);
double sin_theta = sin(theta);
double c1_sign = (d > 0) ? 1 : -1;
for (int i = 0; i < total; ++i) {
size_t offset = i * msg->point_step;
Scalar* x_scalar =
reinterpret_cast<Scalar*>(&msg->data[offset + x_offset_]);
if (std::isnan(*x_scalar)) {
ROS_DEBUG_STREAM("nan point do not need motion compensation");
continue;
}
Scalar* y_scalar =
reinterpret_cast<Scalar*>(&msg->data[offset + y_offset_]);
Scalar* z_scalar =
reinterpret_cast<Scalar*>(&msg->data[offset + z_offset_]);
Eigen::Vector3d p(*x_scalar, *y_scalar, *z_scalar);
double tp = 0.0;
memcpy(&tp, &msg->data[i * msg->point_step + timestamp_offset_],
timestamp_data_size_);
double t = (timestamp_max - tp) * f;
Eigen::Translation3d ti(t * translation);
double c0 = sin((1 - t) * theta) / sin_theta;
double c1 = sin(t * theta) / sin_theta * c1_sign;
Eigen::Quaterniond qi(c0 * q0.coeffs() + c1 * q1.coeffs());
Eigen::Affine3d trans = ti * qi;
p = trans * p;
*x_scalar = p.x();
*y_scalar = p.y();
*z_scalar = p.z();
}
return;
}
// Not a "significant" rotation. Do translation only.
for (int i = 0; i < total; ++i) {
Scalar* x_scalar =
reinterpret_cast<Scalar*>(&msg->data[i * msg->point_step + x_offset_]);
if (std::isnan(*x_scalar)) {
ROS_DEBUG_STREAM("nan point do not need motion compensation");
continue;
}
Scalar* y_scalar =
reinterpret_cast<Scalar*>(&msg->data[i * msg->point_step + y_offset_]);
Scalar* z_scalar =
reinterpret_cast<Scalar*>(&msg->data[i * msg->point_step + z_offset_]);
Eigen::Vector3d p(*x_scalar, *y_scalar, *z_scalar);
double tp = 0.0;
memcpy(&tp, &msg->data[i * msg->point_step + timestamp_offset_],
timestamp_data_size_);
double t = (timestamp_max - tp) * f;
Eigen::Translation3d ti(t * translation);
p = ti * p;
*x_scalar = p.x();
*y_scalar = p.y();
*z_scalar = p.z();
}
}
} // namespace lslidar
} // namespace drivers
} // namespace apollo
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_compensator
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_compensator/src/compensator_node.cpp
|
/***************************************************************************
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 "lslidar_compensator/compensator.h"
#include <ros/ros.h>
/** Main node entry point. */
int main(int argc, char **argv) {
ROS_INFO("Point cloud node init");
ros::init(argc, argv, "compensator_node");
ros::NodeHandle node;
ros::NodeHandle priv_nh("~");
apollo::drivers::lslidar_compensator::Compensator compensator(node, priv_nh);
// handle callbacks until shut down
ros::spin();
return 0;
}
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_compensator
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_compensator/src/compensator_nodelet.cpp
|
/***************************************************************************
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 <lslidar_compensator/compensator.h>
#include <nodelet/nodelet.h>
#include <pluginlib/class_list_macros.h>
#include <ros/ros.h>
namespace apollo {
namespace drivers {
namespace lslidar_compensator {
class CompensatorNodelet : public nodelet::Nodelet {
public:
CompensatorNodelet() {}
~CompensatorNodelet() {}
private:
virtual void onInit();
boost::shared_ptr<Compensator> compensator_;
};
/** @brief Nodelet initialization. */
void CompensatorNodelet::onInit() {
ROS_INFO("Compensator nodelet init");
compensator_.reset(new Compensator(getNodeHandle(), getPrivateNodeHandle()));
}
} // end namespace lslidar_c16_decoder
}
}
PLUGINLIB_DECLARE_CLASS(lslidar_compensator, CompensatorNodelet,
apollo::drivers::lslidar_compensator::CompensatorNodelet,
nodelet::Nodelet);
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_msgs/CMakeLists.txt
|
cmake_minimum_required(VERSION 2.8.3)
project(lslidar_msgs)
find_package(catkin REQUIRED COMPONENTS
message_generation
std_msgs
sensor_msgs
)
add_message_files(
DIRECTORY msg
FILES
LslidarLayer.msg
LslidarPacket.msg
LslidarPoint.msg
LslidarScan.msg
LslidarSweep.msg
)
generate_messages(DEPENDENCIES std_msgs sensor_msgs)
catkin_package(
CATKIN_DEPENDS message_runtime std_msgs sensor_msgs
)
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_msgs/package.xml
|
<package>
<name>lslidar_msgs</name>
<version>2.0.0</version>
<description>
ROS message definitions for Leishen LIDARs.
</description>
<maintainer email="yutongyan@lslidar.com">yutongyan</maintainer>
<author>yutongyan</author>
<license>Licensed under the Apache License, Version 2.0 </license>
<buildtool_depend>catkin</buildtool_depend>
<build_depend>message_generation</build_depend>
<build_depend>sensor_msgs</build_depend>
<build_depend>std_msgs</build_depend>
<run_depend>message_runtime</run_depend>
<run_depend>sensor_msgs</run_depend>
<run_depend>std_msgs</run_depend>
</package>
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_msgs
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_msgs/msg/LslidarPacket.msg
|
# Raw Leishen LIDAR packet.
time stamp # packet timestamp
uint8[1206] data # packet contents
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_msgs
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_msgs/msg/LslidarScan.msg
|
# Altitude of all the points within this scan
float64 altitude
# The valid points in this scan sorted by azimuth
# from 0 to 359.99
LslidarPoint[] points
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_msgs
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_msgs/msg/LslidarPoint.msg
|
# Time when the point is captured
float32 time
# Converted distance in the sensor frame
float64 x
float64 y
float64 z
# Raw measurement from Leishen C16
float64 azimuth
float64 distance
float64 intensity
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_msgs
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_msgs/msg/LslidarLayer.msg
|
# Header header
# The 0th scan is at the bottom
sensor_msgs/LaserScan[16] scan_channel
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_msgs
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_msgs/msg/LslidarSweep.msg
|
Header header
# The 0th scan is at the bottom
LslidarScan[16] scans
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_decoder/CMakeLists.txt
|
cmake_minimum_required(VERSION 2.8.3)
project(lslidar_decoder)
add_definitions(-std=c++0x)
find_package(catkin REQUIRED COMPONENTS
roscpp
pluginlib
sensor_msgs
pcl_ros
pcl_conversions
lslidar_msgs
nodelet
)
find_package(Boost REQUIRED)
catkin_package(
INCLUDE_DIRS include
# LIBRARIES lslidar_c16_decoder
CATKIN_DEPENDS
roscpp sensor_msgs pluginlib nodelet
pcl_ros pcl_conversions
lslidar_msgs
DEPENDS
Boost
)
include_directories(
include
${Boost_INCLUDE_DIR}
${catkin_INCLUDE_DIRS}
)
link_directories(
${catkin_LIBRARY_DIRS}
)
# Lslidar C16 Decoder
add_library(lslidar_decoder
src/lslidar_decoder.cpp
)
target_link_libraries(lslidar_decoder
${catkin_LIBRARIES}
)
add_dependencies(lslidar_decoder
${${PROJECT_NAME}_EXPORTED_TARGETS}
${catkin_EXPORTED_TARGETS}
)
# Lslidar C16 Decoder node
add_executable(lslidar_decoder_node
src/lslidar_decoder_node.cpp
)
target_link_libraries(lslidar_decoder_node
lslidar_decoder
${catkin_LIBRARIES}
)
add_dependencies(lslidar_decoder_node
${${PROJECT_NAME}_EXPORTED_TARGETS}
${catkin_EXPORTED_TARGETS}
)
# Lslidar N301 Decoder nodelet
add_library(lslidar_decoder_nodelet
src/lslidar_decoder_nodelet.cpp
)
target_link_libraries(lslidar_decoder_nodelet
lslidar_decoder
${catkin_LIBRARIES}
)
add_dependencies(lslidar_decoder_nodelet
${${PROJECT_NAME}_EXPORTED_TARGETS}
${catkin_EXPORTED_TARGETS}
)
install(
TARGETS
lslidar_decoder
lslidar_decoder_node
lslidar_decoder_nodelet
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION})
install(DIRECTORY include/${PROJECT_NAME}/
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION})
install(FILES nodelet_lslidar_decoder.xml
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION})
install(DIRECTORY launch/
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/launch)
install(DIRECTORY scripts/
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/scripts)
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_decoder/package.xml
|
<?xml version="1.0"?>
<package format="2">
<name>lslidar_decoder</name>
<version>2.0.0</version>
<description>
Point cloud conversions for Leishen C16 LIDARs.
</description>
<maintainer email="yutongyan@lslidar.com">yutongyan</maintainer>
<author>yutongyan</author>
<license>Licensed under the Apache License, Version 2.0 </license>
<buildtool_depend>catkin</buildtool_depend>
<depend>pluginlib</depend>
<depend>roscpp</depend>
<depend>sensor_msgs</depend>
<depend>nodelet</depend>
<depend>pcl_ros</depend>
<depend>pcl_conversions</depend>
<depend>libpcl-all-dev</depend>
<depend>libpcl-all</depend>
<depend>lslidar_msgs</depend>
<export>
<nodelet plugin="${prefix}/nodelet_lslidar_decoder.xml"/>
</export>
</package>
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_decoder/nodelet_lslidar_decoder.xml
|
<library path="lib/liblslidar_decoder_nodelet">
<class name="lslidar_decoder/LslidarDecoderNodelet"
type="apollo::drivers::lslidar_decoder::LslidarDecoderNodelet"
base_class_type="nodelet::Nodelet">
<description>
Aggregates points from multiple packets, publishing LslidarSweep msg defined
in lslidar_msgs.
</description>
</class>
</library>
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_decoder
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_decoder/launch/lslidar_c16_apollo.launch
|
<launch>
<arg name="child_frame_id" default="lslidar"/>
<arg name="nodelet_manager_name" value="lslidar_nodelet_manager" />
<arg name="device_ip" value="192.168.1.200"/>
<arg name="firing_port" value="2368"/>
<arg name="topic_packet" default="/apollo/sensor/lslidar/LslidarPacket"/>
<arg name="topic_pointcloud" default="/apollo/sensor/lslidar/PointCloud2"/>
<!-- nodelet manager -->
<node pkg="nodelet" type="nodelet" name="$(arg nodelet_manager_name)" output="screen"
args="manager" />
<!-- nodelet driver for lslidar -->
<node pkg="nodelet" type="nodelet"
name="lslidar_driver_nodelet"
args="load lslidar_driver/LslidarDriverNodelet
$(arg nodelet_manager_name)" >
<param name="frame_id" value="lslidar"/>
<param name="device_ip" value="$(arg device_ip)"/>
<param name="device_port" value="$(arg firing_port)"/>
<remap from="lslidar_packet" to="$(arg topic_packet)"/>
</node>
<node pkg="nodelet" type="nodelet" name="lslidar_decoder_nodelet"
args="load lslidar_decoder/LslidarDecoderNodelet
$(arg nodelet_manager_name)"
output="screen">
<param name="child_frame_id" value="$(arg child_frame_id)"/>
<param name="min_range" value="0.3"/>
<param name="max_range" value="100.0"/>
<param name="frequency" value="10.0"/>
<param name="publish_point_cloud" value="true"/>
<param name="publish_channels" value="false"/>
<remap from="lslidar_packet" to="$(arg topic_packet)"/>
<remap from="lslidar_point_cloud" to="$(arg topic_pointcloud)"/>
</node>
<!-- <node name="rviz" pkg="rviz" type="rviz" args="-d $(find lslidar_decoder)/launch/lslidar.rviz" output="screen"/>
-->
</launch>
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_decoder
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_decoder/launch/lslidar_c16_decoder_nodelet.launch
|
<launch>
<arg name="fixed_frame_id" default="map"/>
<arg name="child_frame_id" default="lslidar"/>
<include file="$(find lslidar_driver)/launch/lslidar_c16_driver_nodelet.launch"/>
<node pkg="nodelet" type="nodelet" name="lslidar_decoder_nodelet"
args="load lslidar_decoder/LslidarDecoderNodelet
lslidar_nodelet_manager"
output="screen">
<param name="fixed_frame_id" value="$(arg fixed_frame_id)"/>
<param name="child_frame_id" value="$(arg child_frame_id)"/>
<param name="min_range" value="0.3"/>
<param name="max_range" value="100.0"/>
<param name="frequency" value="10.0"/>
<param name="publish_point_cloud" value="true"/>
</node>
<!-- <node name="rviz" pkg="rviz" type="rviz" args="-d $(find lslidar_decoder)/launch/lslidar.rviz" output="screen"/>
-->
</launch>
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_decoder
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_decoder/launch/lslidar_c16.launch
|
<launch>
<node pkg="lslidar_driver" type="lslidar_driver_node" name="lslidar_driver_node" output="screen">
<param name="frame_id" value="laser_link"/>
<param name="device_ip" value="192.168.1.200"/>
<param name="device_port" value="2368"/>
</node>
<node pkg="lslidar_decoder" type="lslidar_decoder_node" name="lslidar_decoder_node" output="screen">
<param name="child_frame_id" value="laser_link"/>
<param name="point_num" value="2000"/>
<param name="channel_num" value="8"/>
<param name="angle_disable_min" value="0"/>
<param name="angle_disable_max" value="0"/>
<param name="min_range" value="0.15"/>
<param name="max_range" value="150.0"/>
<param name="frequency" value="10.0"/>
<param name="publish_point_cloud" value="true"/>
<param name="publish_channels" value="true"/>
</node>
<!--node name="rviz" pkg="rviz" type="rviz" args="-d $(find lslidar_decoder)/launch/lslidar.rviz" output="screen"/-->
</launch>
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_decoder/include
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_decoder/include/lslidar_decoder/lslidar_decoder_nodelet.h
|
/***************************************************************************
Copyright 2018 The Apollo Authors. All Rights Reserved /
/
Licensed under the Apache License, Version 2.0 (the "License"); /
you may not use this file except in compliance with the License. /
You may obtain a copy of the License at /
/
http://www.apache.org/licenses/LICENSE-2.0 /
/
Unless required by applicable law or agreed to in writing, software /
distributed under the License is distributed on an "AS IS" BASIS, /
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /
See the License for the specific language governing permissions and /
limitations under the License. /
****************************************************************************/
#ifndef LSLIDAR_DECODER_NODELET_H
#define LSLIDAR_DECODER_NODELET_H
#include <ros/ros.h>
#include <pluginlib/class_list_macros.h>
#include <nodelet/nodelet.h>
#include <lslidar_decoder/lslidar_decoder.h>
namespace apollo {
namespace drivers {
namespace lslidar_decoder {
class LslidarDecoderNodelet: public nodelet::Nodelet {
public:
LslidarDecoderNodelet() {}
~LslidarDecoderNodelet() {}
private:
virtual void onInit();
LslidarDecoderPtr decoder;
};
} // end namespace lslidar_n301_decoder
}
}
#endif
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_decoder/include
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_decoder/include/lslidar_decoder/lslidar_decoder.h
|
/***************************************************************************
Copyright 2018 The Apollo Authors. All Rights Reserved /
/
Licensed under the Apache License, Version 2.0 (the "License"); /
you may not use this file except in compliance with the License. /
You may obtain a copy of the License at /
/
http://www.apache.org/licenses/LICENSE-2.0 /
/
Unless required by applicable law or agreed to in writing, software /
distributed under the License is distributed on an "AS IS" BASIS, /
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /
See the License for the specific language governing permissions and /
limitations under the License. /
****************************************************************************/
#ifndef LSLIDAR_DECODER_H
#define LSLIDAR_DECODER_H
#define DEG_TO_RAD 0.017453292
#define RAD_TO_DEG 57.29577951
#include <cmath>
#include <vector>
#include <string>
#include <boost/shared_ptr.hpp>
#include <ros/ros.h>
#include <std_msgs/UInt64.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/LaserScan.h>
#include <std_msgs/Int8.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl_ros/point_cloud.h>
#include <pcl/point_types.h>
#include <lslidar_msgs/LslidarPacket.h>
#include <lslidar_msgs/LslidarPoint.h>
#include <lslidar_msgs/LslidarScan.h>
#include <lslidar_msgs/LslidarSweep.h>
#include <lslidar_msgs/LslidarLayer.h>
namespace apollo {
namespace drivers {
namespace lslidar_decoder {
// Raw lslidar packet constants and structures.
static const int SIZE_BLOCK = 100;
static const int RAW_SCAN_SIZE = 3;
static const int SCANS_PER_BLOCK = 32;
static const int BLOCK_DATA_SIZE =
(SCANS_PER_BLOCK * RAW_SCAN_SIZE);
// According to Bruce Hall DISTANCE_MAX is 65.0, but we noticed
// valid packets with readings up to 130.0.
static const double DISTANCE_MAX = 130.0; /**< meters */
static const double DISTANCE_RESOLUTION = 0.01; /**< meters */
static const double DISTANCE_MAX_UNITS =
(DISTANCE_MAX / DISTANCE_RESOLUTION + 1.0);
/** @todo make this work for both big and little-endian machines */
static const uint16_t UPPER_BANK = 0xeeff;
static const uint16_t LOWER_BANK = 0xddff;
/** Special Defines for VLP16 support **/
static const int FIRINGS_PER_BLOCK = 2;
static const int SCANS_PER_FIRING = 16;
static const double BLOCK_TDURATION = 110.592; // [µs]
static const double DSR_TOFFSET = 2.304; // [µs]
static const double FIRING_TOFFSET = 55.296; // [µs]
static const int PACKET_SIZE = 1206;
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);
static const int FIRINGS_PER_PACKET =
FIRINGS_PER_BLOCK * BLOCKS_PER_PACKET;
// Pre-compute the sine and cosine for the altitude angles.
static const double SCAN_ALTITUDE[16] = {
-0.2617993877991494, 0.017453292519943295,
-0.22689280275926285, 0.05235987755982989,
-0.19198621771937624, 0.08726646259971647,
-0.15707963267948966, 0.12217304763960307,
-0.12217304763960307, 0.15707963267948966,
-0.08726646259971647, 0.19198621771937624,
-0.05235987755982989, 0.22689280275926285,
-0.017453292519943295, 0.2617993877991494
};
static const double COS_SCAN_ALTITUDE[16] = {
std::cos(SCAN_ALTITUDE[ 0]), std::cos(SCAN_ALTITUDE[ 1]),
std::cos(SCAN_ALTITUDE[ 2]), std::cos(SCAN_ALTITUDE[ 3]),
std::cos(SCAN_ALTITUDE[ 4]), std::cos(SCAN_ALTITUDE[ 5]),
std::cos(SCAN_ALTITUDE[ 6]), std::cos(SCAN_ALTITUDE[ 7]),
std::cos(SCAN_ALTITUDE[ 8]), std::cos(SCAN_ALTITUDE[ 9]),
std::cos(SCAN_ALTITUDE[10]), std::cos(SCAN_ALTITUDE[11]),
std::cos(SCAN_ALTITUDE[12]), std::cos(SCAN_ALTITUDE[13]),
std::cos(SCAN_ALTITUDE[14]), std::cos(SCAN_ALTITUDE[15]),
};
static const double SIN_SCAN_ALTITUDE[16] = {
std::sin(SCAN_ALTITUDE[ 0]), std::sin(SCAN_ALTITUDE[ 1]),
std::sin(SCAN_ALTITUDE[ 2]), std::sin(SCAN_ALTITUDE[ 3]),
std::sin(SCAN_ALTITUDE[ 4]), std::sin(SCAN_ALTITUDE[ 5]),
std::sin(SCAN_ALTITUDE[ 6]), std::sin(SCAN_ALTITUDE[ 7]),
std::sin(SCAN_ALTITUDE[ 8]), std::sin(SCAN_ALTITUDE[ 9]),
std::sin(SCAN_ALTITUDE[10]), std::sin(SCAN_ALTITUDE[11]),
std::sin(SCAN_ALTITUDE[12]), std::sin(SCAN_ALTITUDE[13]),
std::sin(SCAN_ALTITUDE[14]), std::sin(SCAN_ALTITUDE[15]),
};
struct point_struct{
double distance;
double intensity;
};
struct PointXYZIT {
PCL_ADD_POINT4D
uint8_t intensity;
double timestamp;
EIGEN_MAKE_ALIGNED_OPERATOR_NEW // make sure our new allocators are aligned
} EIGEN_ALIGN16;
// enforce SSE padding for correct memory alignment
class LslidarDecoder {
public:
LslidarDecoder(ros::NodeHandle& n, ros::NodeHandle& pn);
LslidarDecoder(const LslidarDecoder&) = delete;
LslidarDecoder operator=(const LslidarDecoder&) = delete;
~LslidarDecoder() {return;}
bool initialize();
typedef boost::shared_ptr<LslidarDecoder> LslidarDecoderPtr;
typedef boost::shared_ptr<const LslidarDecoder> LslidarDecoderConstPtr;
private:
union TwoBytes {
uint16_t distance;
uint8_t bytes[2];
};
struct RawBlock {
uint16_t header; ///< UPPER_BANK or LOWER_BANK
uint16_t rotation; ///< 0-35999, divide by 100 to get degrees
uint8_t data[BLOCK_DATA_SIZE];
};
struct RawPacket {
RawBlock blocks[BLOCKS_PER_PACKET];
uint32_t time_stamp;
uint8_t factory[2];
//uint16_t revolution;
//uint8_t status[PACKET_STATUS_SIZE];
};
struct Firing {
// Azimuth associated with the first shot within this firing.
double firing_azimuth;
double azimuth[SCANS_PER_FIRING];
double distance[SCANS_PER_FIRING];
double intensity[SCANS_PER_FIRING];
};
// Intialization sequence
bool loadParameters();
bool createRosIO();
// Callback function for a single lslidar packet.
bool checkPacketValidity(const RawPacket* packet);
void decodePacket(const RawPacket* packet);
void layerCallback(const std_msgs::Int8Ptr& msg);
void packetCallback(const lslidar_msgs::LslidarPacketConstPtr& msg);
// Publish data
void publishPointCloud();
void publishChannelScan();
// Publish scan Data
void publishScan();
// Check if a point is in the required range.
bool isPointInRange(const double& distance) {
return (distance >= min_range && distance <= max_range);
}
double rawAzimuthToDouble(const uint16_t& raw_azimuth) {
// According to the user manual,
// azimuth = raw_azimuth / 100.0;
return static_cast<double>(raw_azimuth) / 100.0 * DEG_TO_RAD;
}
// calc the means_point
point_struct getMeans(std::vector<point_struct> clusters);
// configuration degree base
int point_num;
double angle_base;
// Configuration parameters
double min_range;
double max_range;
double angle_disable_min;
double angle_disable_max;
double frequency;
bool publish_point_cloud;
bool publish_channels;
bool apollo_interface;
double cos_azimuth_table[6300];
double sin_azimuth_table[6300];
bool is_first_sweep;
double last_azimuth;
double sweep_start_time;
double packet_start_time;
double point_time;
int layer_num;
Firing firings[FIRINGS_PER_PACKET];
// ROS related parameters
ros::NodeHandle nh;
ros::NodeHandle pnh;
std::string fixed_frame_id;
std::string child_frame_id;
lslidar_msgs::LslidarSweepPtr sweep_data;
lslidar_msgs::LslidarLayerPtr multi_scan;
sensor_msgs::PointCloud2 point_cloud_data;
ros::Subscriber packet_sub;
ros::Subscriber layer_sub;
ros::Publisher sweep_pub;
ros::Publisher point_cloud_pub;
ros::Publisher scan_pub;
ros::Publisher channel_scan_pub;
};
typedef LslidarDecoder::LslidarDecoderPtr LslidarDecoderPtr;
typedef LslidarDecoder::LslidarDecoderConstPtr LslidarDecoderConstPtr;
typedef PointXYZIT VPoint;
typedef pcl::PointCloud<VPoint> VPointCloud;
} // end namespace lslidar_decoder
}
}
POINT_CLOUD_REGISTER_POINT_STRUCT(apollo::drivers::lslidar_decoder::PointXYZIT,
(float, x, x)(float, y, y)(float, z, z)(
uint8_t, intensity,
intensity)(double, timestamp, timestamp))
#endif
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_decoder
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_decoder/scripts/Test_MultiChannel.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time : 18-4-23 下午5:25
# @Author : Yutong
# @Email : 416178264@qq.com
# @Site :
# @File : Test_MultiChannel.py
# @Software: PyCharm
# @Desc :
'''
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. /
'''
import rospy
from lslidar_c16_msgs.msg import LslidarC16Layer
import os
import numpy as np
import matplotlib.pyplot as plt
Remote_IP = '192.168.0.138'
ROS_IP='http://'+Remote_IP+':11311'
os.environ['ROS_MASTER_URI']=ROS_IP #environ的键值必须是字符串
os.system('echo $ROS_MASTER_URI')
if __name__ == '__main__':
rospy.init_node("multi_channel")
msg = rospy.wait_for_message("scan_channel", LslidarC16Layer)
data_len = len(msg.scan_channel)
for i in range(data_len):
laser_msg = msg.scan_channel[i]
laser_distance = np.array(laser_msg.ranges)
counter = len(laser_distance)
laser_distance[laser_distance == np.inf] = 0.0
laser_angle = np.linspace(laser_msg.angle_min, laser_msg.angle_max, counter)
intensity = np.array(laser_msg.intensities)
x_laser = np.multiply(laser_distance, np.cos(laser_angle))
y_laser = np.multiply(laser_distance, np.sin(laser_angle))
plt.plot(x_laser, y_laser, 'b.')
plt.show()
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_decoder
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_decoder/src/lslidar_decoder.cpp
|
/***************************************************************************
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 <lslidar_decoder/lslidar_decoder.h>
#include <std_msgs/Int8.h>
using namespace std;
namespace apollo {
namespace drivers {
namespace lslidar_decoder {
LslidarDecoder::LslidarDecoder(
ros::NodeHandle& n, ros::NodeHandle& pn):
nh(n),
pnh(pn),
publish_point_cloud(true),
is_first_sweep(true),
last_azimuth(0.0),
sweep_start_time(0.0),
// layer_num(8),
packet_start_time(0.0),
sweep_data(new lslidar_msgs::LslidarSweep()),
multi_scan(new lslidar_msgs::LslidarLayer())
{
return;
}
bool LslidarDecoder::loadParameters() {
pnh.param<int>("point_num", point_num, 1000);
pnh.param<int>("channel_num", layer_num, 8);
pnh.param<double>("min_range", min_range, 0.5);
pnh.param<double>("max_range", max_range, 100.0);
pnh.param<double>("angle_disable_min", angle_disable_min,-1);
pnh.param<double>("angle_disable_max", angle_disable_max, -1);
pnh.param<double>("frequency", frequency, 20.0);
pnh.param<bool>("publish_point_cloud", publish_point_cloud, true);
pnh.param<bool>("publish_channels", publish_channels, true);
pnh.param<bool>("apollo_interface", apollo_interface, false);
pnh.param<string>("fixed_frame_id", fixed_frame_id, "map");
pnh.param<string>("child_frame_id", child_frame_id, "lslidar");
angle_base = M_PI*2 / point_num;
if (apollo_interface)
{
ROS_WARN("This is apollo interface mode");
}
return true;
}
bool LslidarDecoder::createRosIO() {
packet_sub = nh.subscribe<lslidar_msgs::LslidarPacket>(
"lslidar_packet", 100, &LslidarDecoder::packetCallback, this);
layer_sub = nh.subscribe(
"layer_num", 100, &LslidarDecoder::layerCallback, this);
sweep_pub = nh.advertise<lslidar_msgs::LslidarSweep>(
"lslidar_sweep", 10);
point_cloud_pub = nh.advertise<sensor_msgs::PointCloud2>(
"lslidar_point_cloud", 10);
scan_pub = nh.advertise<sensor_msgs::LaserScan>(
"scan", 100);
channel_scan_pub = nh.advertise<lslidar_msgs::LslidarLayer>(
"scan_channel", 100);
return true;
}
bool LslidarDecoder::initialize() {
if (!loadParameters()) {
ROS_ERROR("Cannot load all required parameters...");
return false;
}
if (!createRosIO()) {
ROS_ERROR("Cannot create ROS I/O...");
return false;
}
// Fill in the altitude for each scan.
for (size_t scan_idx = 0; scan_idx < 16; ++scan_idx) {
size_t remapped_scan_idx = scan_idx%2 == 0 ? scan_idx/2 : scan_idx/2+8;
sweep_data->scans[remapped_scan_idx].altitude = SCAN_ALTITUDE[scan_idx];
}
// Create the sin and cos table for different azimuth values.
for (size_t i = 0; i < 6300; ++i) {
double angle = static_cast<double>(i) / 1000.0;
cos_azimuth_table[i] = cos(angle);
sin_azimuth_table[i] = sin(angle);
}
return true;
}
bool LslidarDecoder::checkPacketValidity(const RawPacket* packet) {
for (size_t blk_idx = 0; blk_idx < BLOCKS_PER_PACKET; ++blk_idx) {
if (packet->blocks[blk_idx].header != UPPER_BANK) {
//ROS_WARN("Skip invalid LS-16 packet: block %lu header is %x",
//blk_idx, packet->blocks[blk_idx].header);
return false;
}
}
return true;
}
void LslidarDecoder::publishPointCloud() {
VPointCloud::Ptr point_cloud(new VPointCloud());
// pcl_conversions::toPCL(sweep_data->header).stamp;
point_cloud->header.frame_id = child_frame_id;
point_cloud->height = 1;
for (size_t i = 0; i < 16; ++i) {
const lslidar_msgs::LslidarScan& scan = sweep_data->scans[i];
// The first and last point in each scan is ignored, which
// seems to be corrupted based on the received data.
// TODO: The two end points should be removed directly
// in the scans.
// point_time unit is sec
double timestamp = point_time;
point_cloud->header.stamp = static_cast<uint64_t>(timestamp * 1e6);
if (scan.points.size() == 0) continue;
size_t j;
VPoint point;
for (j = 1; j < scan.points.size()-1; ++j) {
point.timestamp = timestamp - (scan.points.size()-1 - j)*0.05; // time interval for each point is 50ms
point.x = scan.points[j].x;
point.y = scan.points[j].y;
point.z = scan.points[j].z;
point.intensity = scan.points[j].intensity;
point_cloud->points.push_back(point);
++point_cloud->width;
}
}
point_cloud_pub.publish(point_cloud);
}
void LslidarDecoder::publishChannelScan()
{
multi_scan = lslidar_msgs::LslidarLayerPtr(
new lslidar_msgs::LslidarLayer());
// lslidar_msgs::LslidarLayer multi_scan(new lslidar_msgs::LslidarLayer);
sensor_msgs::LaserScan scan;
int layer_num_local = layer_num;
ROS_INFO_ONCE("default channel is %d", layer_num_local );
if(sweep_data->scans[layer_num_local].points.size() <= 1)
{
return;
}
for (uint16_t j=0; j<16; j++)
{
scan.header.frame_id = child_frame_id;
scan.header.stamp = sweep_data->header.stamp;
scan.angle_min = 0.0;
scan.angle_max = 2.0*M_PI;
scan.angle_increment = (scan.angle_max - scan.angle_min)/point_num;
// scan.time_increment = motor_speed_/1e8;
scan.range_min = min_range;
scan.range_max = max_range;
scan.ranges.reserve(point_num);
scan.ranges.assign(point_num, std::numeric_limits<float>::infinity());
scan.intensities.reserve(point_num);
scan.intensities.assign(point_num, std::numeric_limits<float>::infinity());
for(uint16_t i = 0; i < sweep_data->scans[j].points.size(); i++)
{
int point_idx = sweep_data->scans[j].points[i].azimuth / angle_base;
if (point_idx >= point_num)
point_idx = 0;
if (point_idx < 0)
point_idx = point_num - 1;
scan.ranges[point_num - 1-point_idx] = sweep_data->scans[j].points[i].distance;
scan.intensities[point_num - 1-point_idx] = sweep_data->scans[j].points[i].intensity;
}
for (int i = point_num - 1; i >= 0; i--)
{
if((i >= angle_disable_min*point_num/360) && (i < angle_disable_max*point_num/360))
{
scan.ranges[i] = std::numeric_limits<float>::infinity();
}
}
multi_scan->scan_channel[j] = scan;
if (j == layer_num_local)
{
scan_pub.publish(scan);
}
}
channel_scan_pub.publish(multi_scan);
}
void LslidarDecoder::publishScan()
{
sensor_msgs::LaserScan::Ptr scan(new sensor_msgs::LaserScan);
int layer_num_local = layer_num;
ROS_INFO_ONCE("default channel is %d", layer_num_local);
if(sweep_data->scans[layer_num_local].points.size() <= 1)
{
return;
}
scan->header.frame_id = child_frame_id;
scan->header.stamp = sweep_data->header.stamp;
scan->angle_min = 0.0;
scan->angle_max = 2.0*M_PI;
scan->angle_increment = (scan->angle_max - scan->angle_min)/point_num;
// scan->time_increment = motor_speed_/1e8;
scan->range_min = min_range;
scan->range_max = max_range;
scan->ranges.reserve(point_num);
scan->ranges.assign(point_num, std::numeric_limits<float>::infinity());
scan->intensities.reserve(point_num);
scan->intensities.assign(point_num, std::numeric_limits<float>::infinity());
for(uint16_t i = 0; i < sweep_data->scans[layer_num_local].points.size(); i++)
{
int point_idx = sweep_data->scans[layer_num_local].points[i].azimuth / angle_base;
if (point_idx >= point_num)
point_idx = 0;
if (point_idx < 0)
point_idx = point_num - 1;
scan->ranges[point_num - 1-point_idx] = sweep_data->scans[layer_num_local].points[i].distance;
scan->intensities[point_num - 1-point_idx] = sweep_data->scans[layer_num_local].points[i].intensity;
}
for (int i = point_num - 1; i >= 0; i--)
{
if((i >= angle_disable_min*point_num/360) && (i < angle_disable_max*point_num/360))
scan->ranges[i] = std::numeric_limits<float>::infinity();
}
scan_pub.publish(scan);
}
void LslidarDecoder::decodePacket(const RawPacket* packet) {
// Compute the azimuth angle for each firing.
for (size_t fir_idx = 0; fir_idx < FIRINGS_PER_PACKET; fir_idx+=2) {
size_t blk_idx = fir_idx / 2;
firings[fir_idx].firing_azimuth = rawAzimuthToDouble(
packet->blocks[blk_idx].rotation);
}
// Interpolate the azimuth values
for (size_t fir_idx = 1; fir_idx < FIRINGS_PER_PACKET; fir_idx+=2) {
size_t lfir_idx = fir_idx - 1;
size_t rfir_idx = fir_idx + 1;
double azimuth_diff;
if (fir_idx == FIRINGS_PER_PACKET - 1) {
lfir_idx = fir_idx - 3;
rfir_idx = fir_idx - 1;
}
azimuth_diff = firings[rfir_idx].firing_azimuth -
firings[lfir_idx].firing_azimuth;
azimuth_diff = azimuth_diff < 0 ? azimuth_diff + 2*M_PI : azimuth_diff;
firings[fir_idx].firing_azimuth =
firings[fir_idx-1].firing_azimuth + azimuth_diff/2.0;
firings[fir_idx].firing_azimuth =
firings[fir_idx].firing_azimuth > 2*M_PI ?
firings[fir_idx].firing_azimuth-2*M_PI : firings[fir_idx].firing_azimuth;
}
// Fill in the distance and intensity for each firing.
for (size_t blk_idx = 0; blk_idx < BLOCKS_PER_PACKET; ++blk_idx) {
const RawBlock& raw_block = packet->blocks[blk_idx];
for (size_t blk_fir_idx = 0; blk_fir_idx < FIRINGS_PER_BLOCK; ++blk_fir_idx){
size_t fir_idx = blk_idx*FIRINGS_PER_BLOCK + blk_fir_idx;
double azimuth_diff = 0.0;
if (fir_idx < FIRINGS_PER_PACKET - 1)
{
azimuth_diff = firings[fir_idx+1].firing_azimuth -
firings[fir_idx].firing_azimuth;
}
else
{
azimuth_diff = firings[fir_idx].firing_azimuth -
firings[fir_idx-1].firing_azimuth;
}
for (size_t scan_fir_idx = 0; scan_fir_idx < SCANS_PER_FIRING; ++scan_fir_idx){
size_t byte_idx = RAW_SCAN_SIZE * (
SCANS_PER_FIRING*blk_fir_idx + scan_fir_idx);
// Azimuth
firings[fir_idx].azimuth[scan_fir_idx] = firings[fir_idx].firing_azimuth +
(scan_fir_idx*DSR_TOFFSET/FIRING_TOFFSET) * azimuth_diff;
// Distance
TwoBytes raw_distance;
raw_distance.bytes[0] = raw_block.data[byte_idx];
raw_distance.bytes[1] = raw_block.data[byte_idx+1];
firings[fir_idx].distance[scan_fir_idx] = static_cast<double>(
raw_distance.distance) * DISTANCE_RESOLUTION;
// Intensity
firings[fir_idx].intensity[scan_fir_idx] = static_cast<double>(
raw_block.data[byte_idx+2]);
}
}
}
return;
}
void LslidarDecoder::layerCallback(const std_msgs::Int8Ptr& msg){
int num = msg->data;
if (num < 0)
{
num = 0;
ROS_WARN("layer num outside of the index, select layer 0 instead!");
}
else if (num > 15)
{
num = 15;
ROS_WARN("layer num outside of the index, select layer 15 instead!");
}
ROS_INFO("select layer num: %d", msg->data);
layer_num = num;
return;
}
void LslidarDecoder::packetCallback(
const lslidar_msgs::LslidarPacketConstPtr& msg) {
// ROS_WARN("packetCallBack");
// Convert the msg to the raw packet type.
const RawPacket* raw_packet = (const RawPacket*) (&(msg->data[0]));
// Check if the packet is valid
if (!checkPacketValidity(raw_packet))
{
return;
}
// Decode the packet
decodePacket(raw_packet);
point_time = msg->stamp.toSec();
// Find the start of a new revolution
// If there is one, new_sweep_start will be the index of the start firing,
// otherwise, new_sweep_start will be FIRINGS_PER_PACKET.
size_t new_sweep_start = 0;
do {
// if (firings[new_sweep_start].firing_azimuth < last_azimuth) break;
if (fabs(firings[new_sweep_start].firing_azimuth - last_azimuth) > M_PI)
{
break;
}
else {
last_azimuth = firings[new_sweep_start].firing_azimuth;
++new_sweep_start;
}
} while (new_sweep_start < FIRINGS_PER_PACKET);
// ROS_WARN("new_sweep_start %d", new_sweep_start);
// The first sweep may not be complete. So, the firings with
// the first sweep will be discarded. We will wait for the
// second sweep in order to find the 0 azimuth angle.
size_t start_fir_idx = 0;
size_t end_fir_idx = new_sweep_start;
if (is_first_sweep && new_sweep_start == FIRINGS_PER_PACKET)
{
// The first sweep has not ended yet.
return;
}
else
{
if (is_first_sweep) {
is_first_sweep = false;
start_fir_idx = new_sweep_start;
end_fir_idx = FIRINGS_PER_PACKET;
sweep_start_time = msg->stamp.toSec() +
FIRING_TOFFSET * (end_fir_idx-start_fir_idx) * 1e-6;
}
}
for (size_t fir_idx = start_fir_idx; fir_idx < end_fir_idx; ++fir_idx)
{
for (size_t scan_idx = 0; scan_idx < SCANS_PER_FIRING; ++scan_idx)
{
// Check if the point is valid.
if (!isPointInRange(firings[fir_idx].distance[scan_idx])) continue;
// Convert the point to xyz coordinate
size_t table_idx = floor(firings[fir_idx].azimuth[scan_idx]*1000.0+0.5);
//cout << table_idx << endl;
double cos_azimuth = cos_azimuth_table[table_idx];
double sin_azimuth = sin_azimuth_table[table_idx];
double x = firings[fir_idx].distance[scan_idx] *
COS_SCAN_ALTITUDE[scan_idx] * sin_azimuth;
double y = firings[fir_idx].distance[scan_idx] *
COS_SCAN_ALTITUDE[scan_idx] * cos_azimuth;
double z = firings[fir_idx].distance[scan_idx] *
SIN_SCAN_ALTITUDE[scan_idx];
double x_coord = y;
double y_coord = -x;
double z_coord = z;
// Compute the time of the point
double time = packet_start_time +
FIRING_TOFFSET*fir_idx + DSR_TOFFSET*scan_idx;
// Remap the index of the scan
int remapped_scan_idx = scan_idx%2 == 0 ? scan_idx/2 : scan_idx/2+8;
sweep_data->scans[remapped_scan_idx].points.push_back(
lslidar_msgs::LslidarPoint());
lslidar_msgs::LslidarPoint& new_point = // new_point refers to the last element of push_back
sweep_data->scans[remapped_scan_idx].points[
sweep_data->scans[remapped_scan_idx].points.size()-1];
// Pack the data into point msg
new_point.time = time;
new_point.x = x_coord;
new_point.y = y_coord;
new_point.z = z_coord;
new_point.azimuth = firings[fir_idx].azimuth[scan_idx];
new_point.distance = firings[fir_idx].distance[scan_idx];
new_point.intensity = firings[fir_idx].intensity[scan_idx];
}
}
packet_start_time += FIRING_TOFFSET * (end_fir_idx-start_fir_idx);
// A new sweep begins
if (end_fir_idx != FIRINGS_PER_PACKET)
{
// ROS_WARN("A new sweep begins");
// Publish the last revolution
sweep_data->header.frame_id = "sweep";
sweep_data->header.stamp = ros::Time(sweep_start_time);
sweep_pub.publish(sweep_data);
if (publish_point_cloud)
{
publishPointCloud();
}
if (publish_channels)
{
publishChannelScan();
}
else
{
publishScan();
}
sweep_data = lslidar_msgs::LslidarSweepPtr(
new lslidar_msgs::LslidarSweep());
// Prepare the next revolution
sweep_start_time = msg->stamp.toSec() +
FIRING_TOFFSET * (end_fir_idx-start_fir_idx) * 1e-6;
packet_start_time = 0.0;
last_azimuth = firings[FIRINGS_PER_PACKET-1].firing_azimuth;
start_fir_idx = end_fir_idx;
end_fir_idx = FIRINGS_PER_PACKET;
for (size_t fir_idx = start_fir_idx; fir_idx < end_fir_idx; ++fir_idx)
{
for (size_t scan_idx = 0; scan_idx < SCANS_PER_FIRING; ++scan_idx)
{
// Check if the point is valid.
if (!isPointInRange(firings[fir_idx].distance[scan_idx]))
{
continue;
}
// Convert the point to xyz coordinate
size_t table_idx = floor(firings[fir_idx].azimuth[scan_idx]*1000.0+0.5);
double cos_azimuth = cos_azimuth_table[table_idx];
double sin_azimuth = sin_azimuth_table[table_idx];
double x = firings[fir_idx].distance[scan_idx] *
COS_SCAN_ALTITUDE[scan_idx] * sin_azimuth;
double y = firings[fir_idx].distance[scan_idx] *
COS_SCAN_ALTITUDE[scan_idx] * cos_azimuth;
double z = firings[fir_idx].distance[scan_idx] *
SIN_SCAN_ALTITUDE[scan_idx];
double x_coord = y;
double y_coord = -x;
double z_coord = z;
// Compute the time of the point
double time = packet_start_time +
FIRING_TOFFSET*(fir_idx-start_fir_idx) + DSR_TOFFSET*scan_idx;
// Remap the index of the scan
int remapped_scan_idx = scan_idx%2 == 0 ? scan_idx/2 : scan_idx/2+8;
sweep_data->scans[remapped_scan_idx].points.push_back(
lslidar_msgs::LslidarPoint());
lslidar_msgs::LslidarPoint& new_point =
sweep_data->scans[remapped_scan_idx].points[
sweep_data->scans[remapped_scan_idx].points.size()-1];
// Pack the data into point msg
new_point.time = time;
new_point.x = x_coord;
new_point.y = y_coord;
new_point.z = z_coord;
new_point.azimuth = firings[fir_idx].azimuth[scan_idx];
new_point.distance = firings[fir_idx].distance[scan_idx];
new_point.intensity = firings[fir_idx].intensity[scan_idx];
}
}
packet_start_time += FIRING_TOFFSET * (end_fir_idx-start_fir_idx);
}
// ROS_WARN("pack end");
return;
}
} // end namespace lslidar_decoder
}
}
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_decoder
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_decoder/src/lslidar_decoder_nodelet.cpp
|
/***************************************************************************
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 <lslidar_decoder/lslidar_decoder_nodelet.h>
namespace apollo {
namespace drivers {
namespace lslidar_decoder {
void LslidarDecoderNodelet::onInit() {
decoder.reset(new LslidarDecoder(
getNodeHandle(), getPrivateNodeHandle()));
if(!decoder->initialize()) {
ROS_ERROR("Cannot initialize the lslidar puck decoder...");
return;
}
return;
}
} // end namespace lslidar_decoder
}
}
PLUGINLIB_DECLARE_CLASS(lslidar_decoder, LslidarNodelet,
apollo::drivers::lslidar_decoder::LslidarDecoderNodelet,
nodelet::Nodelet);
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_decoder
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_decoder/src/lslidar_decoder_node.cpp
|
/***************************************************************************
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 <ros/ros.h>
#include <lslidar_decoder/lslidar_decoder.h>
int main(int argc, char** argv) {
ros::init(argc, argv, "lslidar_decoder_node");
ros::NodeHandle nh;
ros::NodeHandle pnh("~");
apollo::drivers::lslidar_decoder::LslidarDecoderPtr decoder(
new apollo::drivers::lslidar_decoder::LslidarDecoder(nh, pnh));
if (!decoder->initialize()) {
ROS_INFO("Cannot initialize the decoder...");
return -1;
}
ros::spin();
return 0;
}
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_apollo/CMakeLists.txt
|
cmake_minimum_required(VERSION 2.8.3)
project(lslidar_apollo)
find_package(catkin REQUIRED)
catkin_metapackage()
| 0
|
apollo_public_repos/apollo-contrib/lslidar_apollo
|
apollo_public_repos/apollo-contrib/lslidar_apollo/lslidar_apollo/package.xml
|
<package>
<name>lslidar_apollo</name>
<version>2.0.0</version>
<description>
Basic ROS and Apollo support for the Leishen C16 LIDARs.
</description>
<maintainer email="yutongyan@lslidar.com">yutongyan</maintainer>
<author>yutongyan</author>
<license>Licensed under the Apache License, Version 2.0 </license>
<buildtool_depend>catkin</buildtool_depend>
<run_depend>lslidar_driver</run_depend>
<run_depend>lslidar_msgs</run_depend>
<run_depend>lslidar_decoder</run_depend>
<export>
<metapackage/>
</export>
</package>
| 0
|
apollo_public_repos
|
apollo_public_repos/application-demo/WORKSPACE
|
#######################################APOLLO#######################################
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "build_bazel_rules_apple",
sha256 = "0052d452af7742c8f3a4e0929763388a66403de363775db7e90adecb2ba4944b",
urls = [
"https://apollo-system.cdn.bcebos.com/archive/8.0/rules_apple.0.31.3.tar.gz",
"https://github.com/bazelbuild/rules_apple/releases/download/0.31.3/rules_apple.0.31.3.tar.gz",
],
)
http_archive(
name = "rules_foreign_cc",
sha256 = "6041f1374ff32ba711564374ad8e007aef77f71561a7ce784123b9b4b88614fc",
strip_prefix = "rules_foreign_cc-0.8.0",
urls = [
"https://apollo-system.bj.bcebos.com/archive/6.0/rules_foreign_cc-0.8.0.tar.gz",
"https://github.com/bazelbuild/rules_foreign_cc/archive/0.8.0.tar.gz",
],
)
load("@rules_foreign_cc//foreign_cc:repositories.bzl", "rules_foreign_cc_dependencies")
rules_foreign_cc_dependencies()
http_archive(
name = "rules_cc",
patches = ["//tools/package:rules_cc.patch"],
sha256 = "4dccbfd22c0def164c8f47458bd50e0c7148f3d92002cdb459c2a96a68498241",
urls = [
"https://apollo-system.cdn.bcebos.com/archive/8.0/rules_cc-0.0.1.tar.gz",
"https://github.com/bazelbuild/rules_cc/releases/download/0.0.1/rules_cc-0.0.1.tar.gz",
],
)
load("//dev/bazel:deps.bzl", "init_deps")
init_deps()
load("@bazel_skylib//:workspace.bzl", "bazel_skylib_workspace")
bazel_skylib_workspace()
load("@com_github_grpc_grpc//bazel:grpc_deps.bzl", "grpc_deps")
grpc_deps()
load("@com_github_grpc_grpc//bazel:grpc_extra_deps.bzl", "grpc_extra_deps")
grpc_extra_deps()
load("@rules_proto//proto:repositories.bzl", "rules_proto_dependencies", "rules_proto_toolchains")
rules_proto_dependencies()
rules_proto_toolchains()
#######################################APOLLO#######################################
| 0
|
apollo_public_repos/application-demo
|
apollo_public_repos/application-demo/example_components/cyberfile.xml
|
<package>
<name>example-components</name>
<version>1.0.0</version>
<description>
example component
</description>
<maintainer email="apollo-support">apollo-support@baidu.com</maintainer>
<type>module</type>
<src_path>//example_components</src_path>
<license>BSD</license>
<author>Apollo</author>
<depend type="binary" src_path="//cyber" repo_name="cyber">cyber-dev</depend>
<depend>bazel-extend-tools-dev</depend>
<depend lib_names="protobuf" repo_name="com_google_protobuf">3rd-protobuf-dev</depend>
<builder>bazel</builder>
</package>
| 0
|
apollo_public_repos/application-demo
|
apollo_public_repos/application-demo/example_components/example.launch
|
<cyber>
<module>
<name>example</name>
<dag_conf>/opt/apollo/neo/packages/example-components-dev/latest/dag/example.dag</dag_conf>
<process_name>example</process_name>
</module>
</cyber>
| 0
|
apollo_public_repos/application-demo
|
apollo_public_repos/application-demo/example_components/example.dag
|
# Define all coms in DAG streaming.
module_config {
module_library : "/opt/apollo/neo/packages/example-components-dev/latest/lib/libcomponent_examples.so"
timer_components {
class_name : "TimerCommonComponentSample"
config {
name : "CommonComponent"
interval : 10
}
}
components {
class_name : "CommonComponentSample"
config {
name : "example"
readers {
channel: "/apollo/channel_example/driver_test"
}
readers {
channel: "/apollo/channel_example/driver_test2"
}
}
}
}
| 0
|
apollo_public_repos/application-demo
|
apollo_public_repos/application-demo/example_components/BUILD
|
load("//tools/install:install.bzl", "install", "install_src_files")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "conf",
srcs = [
":example.dag",
":example.launch",
],
)
install(
name = "install",
data = [
"//example_components/proto:examples_cc_proto",
":cyberfile.xml"
],
data_dest = "example-components",
library_dest = "example-components/lib",
library_strip_prefix = ["src", "proto"],
targets = [
"//example_components/src:libcomponent_examples.so",
"//example_components/proto:examples_cc_proto"
],
deps = [
":pb_headers",
":dag",
":launch"
]
)
install(
name = "pb_headers",
data = [
"//example_components/proto:examples_cc_proto",
],
data_dest = "example-components/include",
)
install(
name = "dag",
data = [":example.dag"],
data_dest = "example-components/dag"
)
install(
name = "launch",
data = [":example.launch"],
data_dest = "example-components/launch"
)
install_src_files(
name = "headers",
src_dir = ["src"],
dest = "example-components/include",
filter = "*.h",
)
install_src_files(
name = "install_src",
src_dir = ["."],
dest = "example-components/src",
filter = "*",
deps = [
":headers"
]
)
| 0
|
apollo_public_repos/application-demo/example_components
|
apollo_public_repos/application-demo/example_components/proto/examples.proto
|
syntax = "proto2";
package example.proto;
message SamplesTest1 {
optional string class_name = 1;
optional string case_name = 2;
};
message Chatter {
optional uint64 timestamp = 1;
optional uint64 lidar_timestamp = 2;
optional uint64 seq = 3;
optional bytes content = 4;
};
message Driver {
optional string content = 1;
optional uint64 msg_id = 2;
optional uint64 timestamp = 3;
};
| 0
|
apollo_public_repos/application-demo/example_components
|
apollo_public_repos/application-demo/example_components/proto/BUILD
|
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")
load("//tools/install:install.bzl", "install", "install_files")
package(default_visibility = ["//visibility:public"])
cc_proto_library(
name = "examples_cc_proto",
deps = [
":examples_proto",
],
)
proto_library(
name = "examples_proto",
srcs = ["examples.proto"],
)
py_proto_library(
name = "examples_py_pb2",
deps = [
":examples_proto",
],
)
| 0
|
apollo_public_repos/application-demo/example_components
|
apollo_public_repos/application-demo/example_components/src/timer_common_component_example.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 "example_components/src/timer_common_component_example.h"
bool TimerCommonComponentSample::Init() {
using apollo::cyber::ComponentBase;
using example::proto::Driver;
AINFO << "Commontest component init";
driver_writer_ = ComponentBase::node_->CreateWriter<Driver>("/apollo/channel_example/driver_test");
second_driver_writer_ = ComponentBase::node_->CreateWriter<Driver>("/apollo/channel_example/driver_test2");
return true;
}
bool TimerCommonComponentSample::Proc() {
static int i = 0;
auto out_msg = std::make_shared<example::proto::Driver>();
out_msg->set_msg_id(i++);
driver_writer_->Write(out_msg);
second_driver_writer_->Write(out_msg);
AINFO << "timer_component_example: Write same drivermsg to mutliple channel->"
<< out_msg->ShortDebugString();
return true;
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.