space_location_test.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. /**
  2. * 激光定位接口,发布定位位姿
  3. *
  4. * @2020年5月22日 成都河狸智能科技有限责任公司.保留所有权利.
  5. *
  6. * 作者: lumin
  7. */
  8. #include <ros/ros.h>
  9. #include <ros/package.h>
  10. #include <sensor_msgs/PointCloud.h>
  11. #include <geometry_msgs/Point32.h>
  12. #include <geometry_msgs/Pose2D.h>
  13. #include <sensor_msgs/LaserScan.h>
  14. #include <nav_msgs/Odometry.h>
  15. #include <nav_msgs/MapMetaData.h>
  16. #include <nav_msgs/GetMap.h>
  17. #include <geometry_msgs/PoseStamped.h>
  18. #include <geometry_msgs/PoseWithCovarianceStamped.h>
  19. #include <tf/transform_broadcaster.h>
  20. #include <tf/transform_listener.h>
  21. #include <space_lib/space_lib.h>
  22. #include <std_msgs/Float32.h>
  23. #include <yaml-cpp/yaml.h>
  24. #include <key/key.h>
  25. #include <atomic>
  26. #include <thread>
  27. #include <mutex>
  28. #include <fstream>
  29. #include <sys/io.h>
  30. #include <opencv2/core/core.hpp>
  31. #include <opencv2/highgui/highgui.hpp>
  32. #include "base_msgs/global_position.h"
  33. #include <location_base/location_base.h>
  34. namespace {
  35. using namespace space_location::sensor;
  36. using namespace space_location;
  37. ros::NodeHandle* nh_;
  38. ros::Subscriber location_msgs_sub_;
  39. ros::Subscriber odom_data_sub_;
  40. ros::Publisher map_pose_pub_;
  41. ros::Publisher map_pub_;
  42. std::vector<ros::Subscriber> subs_;
  43. std::thread matchThread_;
  44. std::atomic<bool> is_calibration_;
  45. std::atomic<bool> is_located_;
  46. std::string odom_frame_id_ = "odom";
  47. std::string base_frame_id_ = "base_link";
  48. std::string global_frame_id_ = "map";
  49. ros::Duration transform_tolerance_;
  50. tf::Transform tf_transform_;
  51. std::unique_ptr<tf::TransformBroadcaster> trans_tfb_;
  52. std::unique_ptr<tf::TransformListener> tf_;
  53. float linear_search_; // 线性方向搜索
  54. float angular_search_; // 角度方向搜索
  55. float angular_perturbation_step_size_; // 角度搜索精度
  56. float init_linear_search_;
  57. float init_angular_search_;
  58. float init_angular_step_;
  59. float occupied_space_weight_; // 点云匹配权重
  60. float translation_weight_; // 里程计位移权重
  61. float rotation_weight_; // 旋转权重
  62. float self_stab_weight_; // 自稳定旋转权重
  63. std::map<std::string, Eigen::Matrix<float, 4, 4>> transforms_;
  64. std::mutex start_location_mutex_;
  65. Eigen::Vector3f init_location_pose_;
  66. #define START_LOCATION_LOCK() std::lock_guard<std::mutex> lockGuard(start_location_mutex_);
  67. #define MAP_IDX(sx, i, j) ((sx) * (j) + (i))
  68. template <typename T>
  69. static void operator>>(const YAML::Node &node, T &i)
  70. {
  71. i = node.as<T>();
  72. }
  73. struct PointCloudWeight {
  74. PointCloud point_cloud;
  75. std::vector<float> weights;
  76. ros::Time stamp;
  77. };
  78. static void __laserDataCallback(const sensor_msgs::LaserScanConstPtr& msg);
  79. static void __odomDataCallback(const nav_msgs::OdometryConstPtr& msg);
  80. static void __pubMapPose(const float& x, const float& y, const float& yaw);
  81. static void __tfMapToOdom(const float& x, const float& y, const float& yaw, ros::Time stamp);
  82. static void __mapPub(std::string map_file, std::string config_path);
  83. static bool __readLocationConfig()
  84. {
  85. std::string path = space::home() + "configure/location_config.json";
  86. Json::Value c = space::readConfig(path);
  87. Json::Value compair = c;
  88. space::jsonValueTo(c["linear_search"], linear_search_) ?
  89. false : (c["linear_search"] = linear_search_ = 0.5);
  90. space::jsonValueTo(c["angular_search"], angular_search_) ?
  91. false : (c["angular_search"] = angular_search_ = 0.67);
  92. space::jsonValueTo(c["angular_perturbation_step"], angular_perturbation_step_size_) ?
  93. false : (c["angular_perturbation_step"] = angular_perturbation_step_size_ = 0.017);
  94. space::jsonValueTo(c["init_linear_search"], init_linear_search_) ?
  95. false : (c["init_linear_search"] = init_linear_search_ = 5.0);
  96. space::jsonValueTo(c["init_angular_search"], init_angular_search_) ?
  97. false : (c["init_angular_search"] = init_angular_search_ = M_PI);
  98. space::jsonValueTo(c["init_angular_step"], init_angular_step_) ?
  99. false : (c["init_angular_step"] = init_angular_step_ = 0.108);
  100. space::jsonValueTo(c["occupied_space_weight"], occupied_space_weight_) ?
  101. false : (c["occupied_space_weight"] = occupied_space_weight_ = 1.0);
  102. space::jsonValueTo(c["translation_weight"], translation_weight_) ?
  103. false : (c["translation_weight"] = translation_weight_ = 2.0);
  104. space::jsonValueTo(c["rotation_weight"], rotation_weight_) ?
  105. false : (c["rotation_weight"] = rotation_weight_ = 3.0);
  106. space::jsonValueTo(c["self_stab_weight"], self_stab_weight_) ?
  107. false : (c["self_stab_weight"] = self_stab_weight_ = 1.0);
  108. if (compair != c) {
  109. space::writeConfig(path, c);
  110. }
  111. return true;
  112. }
  113. static Json::Value __readLaserConfig()
  114. {
  115. std::string path = space::home() + "configure/laser_config.json";
  116. Json::Value c = space::readConfig(path);
  117. Json::Value laser;
  118. space::jsonValueTo(c, laser);
  119. return laser;
  120. }
  121. static bool __CacluLaserToBaseLinkTransform()
  122. {
  123. transforms_.clear();
  124. Json::Value lasers = __readLaserConfig();
  125. for (int i = 0;i < lasers.size();i++) {
  126. float tf_x, tf_y, tf_z, tf_roll, tf_pitch, tf_yaw;
  127. std::string name;
  128. bool ok = space::jsonValueTo(lasers[i]["tf_x"], tf_x) &&
  129. space::jsonValueTo(lasers[i]["tf_y"], tf_y) &&
  130. space::jsonValueTo(lasers[i]["tf_z"], tf_z) &&
  131. space::jsonValueTo(lasers[i]["tf_roll"], tf_roll) &&
  132. space::jsonValueTo(lasers[i]["tf_pitch"], tf_pitch) &&
  133. space::jsonValueTo(lasers[i]["tf_yaw"], tf_yaw) &&
  134. space::jsonValueTo(lasers[i]["name"], name);
  135. if (ok) {
  136. Eigen::AngleAxisd rollAngle(Eigen::AngleAxisd(tf_roll, Eigen::Vector3d::UnitX()));
  137. Eigen::AngleAxisd pitchAngle(Eigen::AngleAxisd(tf_pitch, Eigen::Vector3d::UnitY()));
  138. Eigen::AngleAxisd yawAngle(Eigen::AngleAxisd(tf_yaw, Eigen::Vector3d::UnitZ()));
  139. Eigen::Matrix3f rotation_matrix;
  140. Eigen::Matrix<float, 4, 4> transform;
  141. rotation_matrix = (yawAngle * pitchAngle * rollAngle).cast<float>();
  142. transform.rightCols<1>() << tf_x, tf_y, tf_z, 1.0;
  143. transform.block<3, 3>(0, 0, 3, 3) = rotation_matrix;
  144. transform.bottomRows<1>() << 0, 0, 0, 1.0;
  145. transforms_.emplace(std::make_pair(name, transform));
  146. }
  147. }
  148. if (!transforms_.empty()) {
  149. return true;
  150. }
  151. return false;
  152. }
  153. static void __match(PointCloud point_cloud, std::vector<float> weights, ros::Time stamp)
  154. {
  155. if (!is_located_) {
  156. if (location_base::initLocation(
  157. point_cloud,
  158. init_location_pose_(0),
  159. init_location_pose_(1),
  160. init_location_pose_(2),
  161. init_linear_search_,
  162. init_angular_search_,
  163. init_angular_step_) == location_base::State::OK) {
  164. is_located_ = true;
  165. }
  166. }else {
  167. if (!is_calibration_) {
  168. location_base::Pose2D pose_2d;
  169. location_base::State state = location_base::scanMatchPrediction(point_cloud, weights, pose_2d);
  170. __pubMapPose(pose_2d.x, pose_2d.y, pose_2d.yaw);
  171. __tfMapToOdom(pose_2d.x, pose_2d.y, pose_2d.yaw, stamp);
  172. }else {
  173. double estimate[7];
  174. location_base::Pose2D pose_2d;
  175. location_base::State state = location_base::clibreation(point_cloud, weights, estimate, pose_2d);
  176. if (state == location_base::State::CLIBREATION_OK) {
  177. LOG(INFO)<<"estimate 0: "<<estimate[0];
  178. LOG(INFO)<<"estimate 1: "<<estimate[1];
  179. LOG(INFO)<<"estimate 2: "<<estimate[2];
  180. Eigen::Quaterniond quaternion(estimate[6], estimate[3], estimate[4], estimate[5]);
  181. LOG(INFO)<<"z: "<<quaternion.matrix().eulerAngles(2, 1, 0)(0);
  182. }else {
  183. // LOG(INFO)<<"state: "<<state;
  184. }
  185. }
  186. }
  187. }
  188. static void __initLocation(const base_msgs::global_position position)
  189. {
  190. START_LOCATION_LOCK()
  191. enum LOCMODE {
  192. QUIT = 0,
  193. FAST,
  194. EXACT,
  195. CALIBRATION
  196. };
  197. if (__readLocationConfig()) {
  198. location_base::setCeresWeight(
  199. occupied_space_weight_, translation_weight_, rotation_weight_, self_stab_weight_
  200. );
  201. location_base::setSearchParam(
  202. linear_search_, angular_search_, angular_perturbation_step_size_
  203. );
  204. }
  205. {
  206. init_location_pose_ = Eigen::Vector3f(
  207. position.init_position.pose.position.x,
  208. position.init_position.pose.position.y,
  209. tf::getYaw(position.init_position.pose.orientation)
  210. );
  211. is_located_ = false;
  212. if (position.mode == QUIT) { //退出定位
  213. location_base::quitLocation();
  214. return;
  215. }else if (position.mode == FAST) { //指定位置启动
  216. location_base::setInitPose(
  217. init_location_pose_(0),
  218. init_location_pose_(1),
  219. init_location_pose_(2)
  220. );
  221. __CacluLaserToBaseLinkTransform();
  222. is_located_ = true;
  223. }else if (position.mode == EXACT) {
  224. __CacluLaserToBaseLinkTransform();
  225. }else if (position.mode == CALIBRATION || is_calibration_) {
  226. transforms_.clear();
  227. Eigen::Matrix<float, 4, 4> transform;
  228. transform.setIdentity();
  229. transforms_.emplace(std::make_pair("laser", transform));
  230. }else {
  231. return;
  232. }
  233. if (!location_base::initMap(position.map_path + ".png", position.yaml_path + ".json")) { // 读取地图失败,退出
  234. is_located_ = false;
  235. LOG(INFO)<<"LOC[ERROR]: 读取地图失败!!!: "<<position.map_path;
  236. return;
  237. }else {
  238. __mapPub(position.map_path + ".png", position.yaml_path + ".json");
  239. }
  240. Json::Value lasers = __readLaserConfig();
  241. subs_.clear();
  242. for (int i = 0;i < lasers.size();i++) {
  243. std::string topic = "";
  244. if (space::jsonValueTo(lasers[i]["topic"], topic)) {
  245. subs_.push_back(nh_->subscribe(topic, 1, &__laserDataCallback));
  246. }
  247. }
  248. odom_data_sub_ = nh_->subscribe<nav_msgs::Odometry>("odom", 1, &__odomDataCallback);
  249. }
  250. }
  251. PointCloud __transformRangeData2PointCloudAndWeights(const sensor_msgs::LaserScan& laser_data,
  252. std::vector<float>& weights, Eigen::Matrix<float, 4, 4> transform)
  253. {
  254. PointCloud point_cloud;
  255. float theta = laser_data.angle_max;
  256. float sum = 0;
  257. float offseta = laser_data.angle_max + laser_data.angle_min;
  258. point_cloud.clear();
  259. for (const float& range : laser_data.ranges) {
  260. theta -= laser_data.angle_increment;
  261. if (range > laser_data.range_max) continue;
  262. if (range < laser_data.range_min) continue;
  263. if (theta < laser_data.angle_min) continue;
  264. if (theta > laser_data.angle_max) continue;
  265. if (std::isnan(range)) continue;
  266. const Eigen::Matrix<float, 4, 1> point(range * cos(theta - offseta),
  267. -range * sin(theta - offseta),
  268. 0.0,
  269. 1.0);
  270. // TimePointCloud time_point;
  271. // time_point.position = Eigen::Vector3f(base_link_coord(0),
  272. // base_link_coord(1),
  273. // 0);
  274. // time_point.time = std::chrono::system_clock::now();
  275. // point_cloud.push_back(time_point);
  276. }
  277. float revers = 1.0 / sum;
  278. for (float& value : weights) {
  279. value *= revers;
  280. }
  281. Eigen::MatrixXf map;
  282. map.setZero(3000, 3000);
  283. map(0, 0);
  284. return point_cloud;
  285. }
  286. static void __laserDataCallback(const sensor_msgs::LaserScanConstPtr& msg)
  287. {
  288. std::map<std::string, Eigen::Matrix<float, 4, 4>>::iterator it =
  289. transforms_.find(msg->header.frame_id);
  290. if (it == transforms_.end()) {
  291. return;
  292. }
  293. static std::map<std::string, PointCloudWeight> pointcloud_weights;
  294. std::vector<float> weights;
  295. PointCloud match_cloud = __transformRangeData2PointCloudAndWeights(*msg, weights, it->second);
  296. pointcloud_weights[msg->header.frame_id] = PointCloudWeight({match_cloud, weights, msg->header.stamp});
  297. if (pointcloud_weights.size() >= transforms_.size()) {
  298. weights.clear();
  299. match_cloud.clear();
  300. for (std::map<std::string, PointCloudWeight>::iterator pt = pointcloud_weights.begin();pt != pointcloud_weights.end();pt++) {
  301. if ((ros::Time::now() - pt->second.stamp).toSec() < 0.5) {
  302. weights.insert(weights.end(), pt->second.weights.begin(), pt->second.weights.end());
  303. match_cloud.insert(match_cloud.end(), pt->second.point_cloud.begin(), pt->second.point_cloud.end());
  304. }
  305. }
  306. pointcloud_weights.clear();
  307. }else {
  308. return;
  309. }
  310. ros::Time stamp = msg->header.stamp;
  311. if (!matchThread_.joinable()) {
  312. matchThread_ = std::thread([match_cloud, weights, stamp] {
  313. START_LOCATION_LOCK()
  314. __match(match_cloud, weights, stamp);
  315. usleep(1000 * 5);
  316. matchThread_.detach();
  317. });
  318. }
  319. }
  320. static void __mapPub(std::string map_file, std::string config_path)
  321. {
  322. static nav_msgs::GetMap::Response map_res;
  323. cv::Mat image;
  324. float x_origin, y_origin, resolution, occupied_thresh, free_thresh;
  325. image = cv::imread(map_file, cv::IMREAD_GRAYSCALE);
  326. tf::Quaternion q;
  327. q.setRPY(0, 0, 0);
  328. Json::Value c = space::readConfig(config_path);
  329. bool ok = space::jsonValueTo(c["x_origin"], x_origin) &&
  330. space::jsonValueTo(c["y_origin"], y_origin) &&
  331. space::jsonValueTo(c["resolution"], resolution) &&
  332. space::jsonValueTo(c["occupied_thresh"], occupied_thresh) &&
  333. space::jsonValueTo(c["free_thresh"], free_thresh);
  334. map_res.map.info.map_load_time = ros::Time::now();
  335. map_res.map.header.frame_id = "map";
  336. map_res.map.header.stamp = ros::Time::now();
  337. map_res.map.info.width = image.cols;
  338. map_res.map.info.height = image.rows;
  339. map_res.map.info.resolution = resolution;
  340. map_res.map.info.origin.position.x = -x_origin;
  341. map_res.map.info.origin.position.y = -y_origin;
  342. map_res.map.info.origin.position.z = 0.0;
  343. map_res.map.info.origin.orientation.x = q.x();
  344. map_res.map.info.origin.orientation.y = q.y();
  345. map_res.map.info.origin.orientation.z = q.z();
  346. map_res.map.info.origin.orientation.w = q.w();
  347. map_res.map.data.resize(map_res.map.info.width * map_res.map.info.height);
  348. unsigned char *p;
  349. unsigned char value;
  350. unsigned char pix = 0;
  351. for (size_t x = 0; x < image.rows; ++x) {
  352. p = image.ptr<uchar>(x);
  353. for(size_t y = 0; y < image.cols; ++y) {
  354. pix = *(p + y);
  355. float cm = float(pix) / 255.f;
  356. if (cm < 1 - occupied_thresh) {
  357. value = (1 - cm) * 255;
  358. }else if (cm > 1 - free_thresh) {
  359. value = 0;
  360. }else {
  361. value = 0;
  362. }
  363. map_res.map.data[MAP_IDX(map_res.map.info.width, y, map_res.map.info.height - x - 1)] = value;
  364. }
  365. }
  366. LOG(INFO)<<"Read a "<<map_res.map.info.width<<" * "<<map_res.map.info.height
  367. <<" @ "<<map_res.map.info.resolution<<" Map!";
  368. map_pub_.publish(map_res.map);
  369. }
  370. static void __tfMapToOdom(const float& x, const float& y, const float& yaw, ros::Time stamp)
  371. {
  372. tf::Stamped<tf::Pose> odom_to_map;
  373. ros::Time copy_stamp = stamp;
  374. transform_tolerance_.fromSec(0.3);
  375. try {
  376. /*tmp_tf,从map原点看base_link的位置*/
  377. tf::Transform tmp_tf(tf::createQuaternionFromYaw(yaw),
  378. tf::Vector3(x, y, 0.0));
  379. /*tmp_tf.inverse(),以为Mp为原点,map原点的位置,
  380. 就是在base_link坐标系下map 原点的位置*/
  381. tf::Stamped<tf::Pose> tmp_tf_stamped(tmp_tf.inverse(),
  382. copy_stamp, //tf_time
  383. base_frame_id_);
  384. /*进行 base_link坐标系下的点转换到odom坐标系,
  385. 也就是把map原点转换到odom坐标系下,
  386. 等于从odom原点看map原点的位置。放到tf_transform_变量里面*/
  387. tf_->transformPose(odom_frame_id_, tmp_tf_stamped, odom_to_map);
  388. }catch (tf::TransformException) {
  389. // LOG(INFO)<<"Location Failed to subtract base to odom transform";
  390. return;
  391. }
  392. tf_transform_ = tf::Transform(tf::Quaternion(odom_to_map.getRotation()),
  393. tf::Point(odom_to_map.getOrigin()));
  394. ros::Time transform_expiration = (copy_stamp + transform_tolerance_);
  395. /*发布tf转换关系,latest_tf_.inverse() 得到的是从map原点看odom原点的位置,也就是 odom->map的转换关系*/
  396. tf::StampedTransform tmp_tf_stamped(tf_transform_.inverse(),
  397. transform_expiration,
  398. global_frame_id_, odom_frame_id_);
  399. trans_tfb_->sendTransform(tmp_tf_stamped);
  400. }
  401. inline static void __quitLocation()
  402. {
  403. for (auto sub : subs_) {
  404. sub.shutdown();
  405. }
  406. odom_data_sub_.shutdown();
  407. location_base::quitLocation();
  408. }
  409. static void __odomDataCallback(const nav_msgs::OdometryConstPtr& msg)
  410. {
  411. // return;
  412. location_base::addOdomData(msg->pose.pose.position.x, msg->pose.pose.position.y,
  413. tf::getYaw(msg->pose.pose.orientation));
  414. }
  415. static void __locationMsgsCallback(const base_msgs::global_positionConstPtr& msg)
  416. {
  417. START_LOCATION_LOCK()
  418. __quitLocation();
  419. std::thread monitorThread(&__initLocation, *msg);
  420. monitorThread.detach();
  421. }
  422. static void __pubMapPose(const float& x, const float& y, const float& yaw)
  423. {
  424. geometry_msgs::Pose2D map_pose;
  425. map_pose.x = x;
  426. map_pose.y = y;
  427. map_pose.theta = yaw;
  428. map_pose_pub_.publish(map_pose);
  429. }
  430. }
  431. int main(int argc, char** argv)
  432. {
  433. ros::init(argc, argv, "space_location");
  434. is_calibration_.store(false);
  435. is_located_.store(false);
  436. nh_ = new ros::NodeHandle;
  437. trans_tfb_ = std::unique_ptr<tf::TransformBroadcaster>(new tf::TransformBroadcaster());
  438. tf_ = std::unique_ptr<tf::TransformListener>(new tf::TransformListener());
  439. map_pub_ = nh_->advertise<nav_msgs::OccupancyGrid>("map", 1, true);
  440. map_pose_pub_ = nh_->advertise<geometry_msgs::Pose2D>("map_pose", 1);
  441. location_msgs_sub_ =
  442. nh_->subscribe<base_msgs::global_position>("location_msgs", 1, &__locationMsgsCallback);
  443. ros::spin();
  444. delete nh_;
  445. }