navigation.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327
  1. //
  2. // Created by zx on 22-12-2.
  3. //
  4. #include "navigation.h"
  5. #include "loaded_mpc.h"
  6. #include "rotate_mpc.h"
  7. #include "../define/TimerRecord.h"
  8. Navigation::~Navigation() {
  9. exit_ = true;
  10. if (terminator_)
  11. delete terminator_;
  12. if (brotherEmqx_)
  13. delete brotherEmqx_;
  14. if (monitor_)
  15. delete monitor_;
  16. if (pubthread_ != nullptr) {
  17. if (pubthread_->joinable())
  18. pubthread_->join();
  19. delete pubthread_;
  20. }
  21. }
  22. /*
  23. * 高斯函数压缩,x=3
  24. */
  25. double limit_gause(double x, double min, double max) {
  26. double r = x >= 0 ? 1.0 : -1.0;
  27. double delta = max / 1.0;
  28. return (max - (max - min) * exp(-x * x / (delta * delta))) * r;
  29. }
  30. double limit(double x, double min, double max) {
  31. double ret = x;
  32. if (x >= 0) {
  33. if (x > max) ret = max;
  34. if (x < min) ret = min;
  35. } else {
  36. if (x < -max) ret = -max;
  37. if (x > -min) ret = -min;
  38. }
  39. return ret;
  40. }
  41. double next_speed(double speed, double target_speed, double acc, double dt) {
  42. if (fabs(target_speed - speed) / dt < acc) {
  43. return target_speed;
  44. } else {
  45. double r = target_speed - speed >= 0. ? 1.0 : -1.0;
  46. return speed + r * acc * dt;
  47. }
  48. }
  49. bool Navigation::PoseTimeout() {
  50. // if (timedPose_.timeout() == false && timedBrotherPose_.timeout() == false) {
  51. if (timedPose_.timeout() == false) {
  52. return false;
  53. } else {
  54. if (timedPose_.timeout()) {
  55. printf(" current pose is timeout \n");
  56. }
  57. // if (timedBrotherPose_.timeout()) {
  58. // printf(" brother pose is timeout \n");
  59. // }
  60. return true;
  61. }
  62. }
  63. bool Navigation::Init(const NavParameter::Navigation_parameter &parameter) {
  64. parameter_ = parameter;
  65. NavParameter::AgvEmqx_parameter agv_p = parameter.agv_emqx();
  66. if (monitor_ == nullptr) {
  67. monitor_ = new Monitor_emqx(agv_p.nodeid());
  68. if (monitor_->Connect(agv_p.ip(), agv_p.port()) == false) {
  69. printf(" agv emqx connected failed\n");
  70. return false;
  71. }
  72. monitor_->set_speedcmd_topic(agv_p.pubspeedtopic());
  73. monitor_->AddCallback(agv_p.subposetopic(), Navigation::RobotPoseCallback, this);
  74. monitor_->AddCallback(agv_p.subspeedtopic(), Navigation::RobotSpeedCallback, this);
  75. }
  76. NavParameter::Emqx_parameter terminal_p = parameter.terminal_emqx();
  77. if (terminator_ == nullptr) {
  78. terminator_ = new Terminator_emqx(terminal_p.nodeid());
  79. if (terminator_->Connect(terminal_p.ip(), terminal_p.port()) == false) {
  80. printf(" terminator emqx connected failed\n");
  81. return false;
  82. }
  83. }
  84. if (parameter.has_brother_emqx()) {
  85. NavParameter::BrotherEmqx brotherEmqx = parameter.brother_emqx();
  86. if (brotherEmqx_ == nullptr) {
  87. brotherEmqx_ = new Terminator_emqx(brotherEmqx.nodeid());
  88. if (brotherEmqx_->Connect(brotherEmqx.ip(), brotherEmqx.port()) == true) {
  89. brotherEmqx_->AddCallback(brotherEmqx.subbrotherstatutopic(), Navigation::BrotherAgvStatuCallback,
  90. this);
  91. } else {
  92. printf(" brother emqx connected failed\n");
  93. // return false;
  94. }
  95. //
  96. }
  97. }
  98. inited_ = true;
  99. if (pubthread_ != nullptr) {
  100. exit_ = true;
  101. if (pubthread_->joinable())
  102. pubthread_->join();
  103. delete pubthread_;
  104. }
  105. exit_ = false;
  106. pubthread_ = new std::thread(&Navigation::pubStatuThreadFuc, this);
  107. return true;
  108. }
  109. void Navigation::RobotPoseCallback(const MqttMsg &msg, void *context) {
  110. Navigation *navigator = (Navigation *) context;
  111. NavMessage::LidarOdomStatu statu;
  112. if (msg.toProtoMessage(statu)) {
  113. navigator->ResetPose(Pose2d(statu.x(), statu.y(), statu.theta()));
  114. }
  115. }
  116. void Navigation::HandleAgvStatu(const MqttMsg &msg) {
  117. NavMessage::AgvStatu speed;
  118. if (msg.toProtoMessage(speed)) {
  119. ResetStatu(speed.v(), speed.w());
  120. ResetClamp((ClampStatu) speed.clamp());
  121. ResetLifter((LifterStatus) speed.lifter());
  122. }
  123. }
  124. void Navigation::RobotSpeedCallback(const MqttMsg &msg, void *context) {
  125. Navigation *navigator = (Navigation *) context;
  126. navigator->HandleAgvStatu(msg);
  127. }
  128. void Navigation::pubStatuThreadFuc(void *p) {
  129. Navigation *navogator = (Navigation *) p;
  130. if (navogator) {
  131. while (navogator->exit_ == false) {
  132. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  133. NavMessage::NavStatu statu;
  134. statu.set_main_agv(false);
  135. navogator->publish_statu(statu);
  136. }
  137. }
  138. }
  139. void Navigation::publish_statu(NavMessage::NavStatu &statu) {
  140. if (timedPose_.timeout() == false) {
  141. NavMessage::LidarOdomStatu odom;
  142. odom.set_x(timedPose_.Get().x());
  143. odom.set_y(timedPose_.Get().y());
  144. odom.set_theta(timedPose_.Get().theta());
  145. if (timedV_.timeout() == false)
  146. odom.set_v(timedV_.Get());
  147. if (timedA_.timeout() == false)
  148. odom.set_vth(timedA_.Get());
  149. statu.mutable_odom()->CopyFrom(odom);
  150. }
  151. statu.set_in_space(isInSpace_);
  152. if (isInSpace_) statu.set_space_id(space_id_);
  153. //发布nav状态
  154. statu.set_statu(actionType_); //
  155. statu.set_move_mode(move_mode_);
  156. if (running_) {
  157. statu.set_key(global_navCmd_.key());
  158. }
  159. //发布MPC信息
  160. //发布mpc 预选点
  161. if (selected_traj_.timeout() == false) {
  162. for (int i = 0; i < selected_traj_.Get().size(); ++i) {
  163. Pose2d pt = selected_traj_.Get()[i];
  164. NavMessage::Pose2d *pose = statu.mutable_selected_traj()->add_poses();
  165. pose->set_x(pt.x());
  166. pose->set_y(pt.y());
  167. pose->set_theta(pt.theta());
  168. }
  169. }
  170. //发布 mpc 预测点
  171. if (predict_traj_.timeout() == false) {
  172. for (int i = 0; i < predict_traj_.Get().size(); ++i) {
  173. Pose2d pt = predict_traj_.Get()[i];
  174. NavMessage::Pose2d *pose = statu.mutable_predict_traj()->add_poses();
  175. pose->set_x(pt.x());
  176. pose->set_y(pt.y());
  177. pose->set_theta(pt.theta());
  178. }
  179. }
  180. // std::cout<<"nav statu:"<<statu.DebugString()<<std::endl;
  181. MqttMsg msg;
  182. msg.fromProtoMessage(statu);
  183. if (terminator_)
  184. terminator_->Publish(parameter_.terminal_emqx().pubnavstatutopic(), msg);
  185. //发布位姿 ------robot状态--------------------------
  186. NavMessage::RobotStatu robot;
  187. if (CreateRobotStatuMsg(robot)) {
  188. if (terminator_) {
  189. MqttMsg msg;
  190. msg.fromProtoMessage(robot);
  191. terminator_->Publish(parameter_.terminal_emqx().pubstatutopic(), msg);
  192. }
  193. }
  194. }
  195. bool Navigation::CreateRobotStatuMsg(NavMessage::RobotStatu &robotStatu) {
  196. //printf(" %d %d %d \n",timedPose_.timeout(),timedV_.timeout(),timedA_.timeout());
  197. if (timedPose_.timeout() == false) {
  198. Pose2d pose = timedPose_.Get();
  199. robotStatu.set_x(pose.x());
  200. robotStatu.set_y(pose.y());
  201. robotStatu.set_theta(pose.theta());
  202. if ((timedV_.timeout() == false && timedA_.timeout() == false)) {
  203. NavMessage::AgvStatu plc;
  204. plc.set_v(timedV_.Get());
  205. plc.set_w(timedA_.Get());
  206. plc.set_clamp(timed_clamp_.Get());
  207. plc.set_lifter(timed_lifter_.Get());
  208. //printf(" timed_clamp_:%d\n ",timed_clamp_.Get());
  209. robotStatu.mutable_agvstatu()->CopyFrom(plc);
  210. }
  211. return true;
  212. }
  213. return false;
  214. }
  215. void Navigation::ResetStatu(double v, double a) {
  216. timedV_.reset(v, 0.5);
  217. timedA_.reset(a, 0.5);
  218. }
  219. void Navigation::ResetClamp(ClampStatu statu) {
  220. timed_clamp_.reset(statu, 1);
  221. }
  222. void Navigation::ResetLifter(LifterStatus status) {
  223. timed_lifter_.reset(status, 1);
  224. }
  225. void Navigation::ResetPose(const Pose2d &pose) {
  226. timedPose_.reset(pose, 1.0);
  227. }
  228. void Navigation::Cancel(const NavMessage::NavCmd &cmd, NavMessage::NavResponse &response) {
  229. cancel_ = true;
  230. response.set_ret(0);
  231. }
  232. bool Navigation::Stop() {
  233. if (monitor_) {
  234. monitor_->stop();
  235. while (cancel_ == false) {
  236. if (timedV_.timeout() == false && timedA_.timeout() == false) {
  237. if (fabs(timedV_.Get()) < 1e-2 && fabs(timedA_.Get()) < 1e-3)
  238. return true;
  239. else
  240. monitor_->stop();
  241. printf("Stoped wait V/A ==0(1e-4,1e-4),V:%f,A:%f\n", fabs(timedV_.Get()), fabs(timedA_.Get()));
  242. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  243. } else {
  244. printf("Stop failed V/A timeout\n");
  245. return false;
  246. }
  247. }
  248. }
  249. printf("stoped ret false.\n");
  250. return false;
  251. }
  252. bool Navigation::SlowlyStop() {
  253. double acc = 3.0;
  254. double dt = 0.1;
  255. while (cancel_ == false) {
  256. if (timedV_.timeout() == false) {
  257. double v = timedV_.Get();
  258. if (fabs(v < 1e-2 && fabs(timedA_.Get()) < 1e-3))
  259. return true;
  260. if (v > 0) {
  261. double new_v = v - acc * dt;
  262. new_v = new_v > 0 ? new_v : 0;
  263. SendMoveCmd(move_mode_, actionType_, new_v, 0);
  264. } else {
  265. double new_v = v + acc * dt;
  266. new_v = new_v < 0 ? new_v : 0;
  267. SendMoveCmd(move_mode_, actionType_, new_v, 0);
  268. }
  269. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  270. } else {
  271. printf("Stop failed V/A timeout\n");
  272. return false;
  273. }
  274. }
  275. printf("stoped ret false.\n");
  276. return false;
  277. }
  278. Navigation::Navigation() {
  279. isInSpace_ = false; //是否在车位或者正在进入车位
  280. RWheel_position_ = eUnknow;
  281. move_mode_ = eSingle;
  282. monitor_ = nullptr;
  283. terminator_ = nullptr;
  284. timedBrotherPose_.reset(Pose2d(-100, 0, 0), 0.5);
  285. }
  286. void Navigation::BrotherAgvStatuCallback(const MqttMsg &msg, void *context) {
  287. Navigation *navigator = (Navigation *) context;
  288. NavMessage::NavStatu brother_statu;
  289. if (msg.toProtoMessage(brother_statu) == false) {
  290. std::cout << " msg transform to AGVStatu failed,msg:" << msg.data() << std::endl;
  291. return;
  292. }
  293. //std::cout<<brother_nav.DebugString()<<std::endl<<std::endl;
  294. if (brother_statu.has_odom()) {
  295. NavMessage::LidarOdomStatu odom = brother_statu.odom();
  296. Pose2d pose(odom.x(), odom.y(), odom.theta());
  297. navigator->timedBrotherPose_.reset(pose, 1);
  298. navigator->timedBrotherV_.reset(odom.v(), 1);
  299. navigator->timedBrotherA_.reset(odom.vth(), 1);
  300. navigator->timedBrotherNavStatu_.reset(brother_statu, 0.1);
  301. }
  302. }
  303. //未使用
  304. bool Navigation::RotateReferToTarget(const Pose2d &target, stLimit limit_rotate, bool anyDirect) {
  305. while (cancel_ == false) {
  306. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  307. if (timedPose_.timeout()) {
  308. printf(" RotateBytarget failed pose timeout\n");
  309. return false;
  310. }
  311. if (timedA_.timeout()) {
  312. printf(" RotateBytarget failed wmg timeout\n");
  313. return false;
  314. }
  315. Pose2d targetInPose = Pose2d::relativePose(target, timedPose_.Get());
  316. float yawDiff = Pose2d::vector2yaw(targetInPose.x(), targetInPose.y());
  317. float minYawdiff = yawDiff;
  318. if (anyDirect) {
  319. Pose2d p0 = timedPose_.Get();
  320. float yawdiff[4] = {0};
  321. yawdiff[0] = yawDiff;
  322. Pose2d relativePose;
  323. relativePose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, M_PI / 2));
  324. yawdiff[1] = Pose2d::vector2yaw(relativePose.x(), relativePose.y()); ////使用减法,保证角度在【-pi pi】
  325. relativePose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, M_PI));
  326. yawdiff[2] = Pose2d::vector2yaw(relativePose.x(), relativePose.y());
  327. relativePose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, 3 * M_PI / 2));
  328. yawdiff[3] = Pose2d::vector2yaw(relativePose.x(), relativePose.y());
  329. for (int i = 1; i < 4; ++i) {
  330. if (fabs(yawdiff[i]) < fabs(minYawdiff)) {
  331. minYawdiff = yawdiff[i];
  332. targetInPose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, i * M_PI / 2.0));
  333. }
  334. }
  335. }
  336. //std::cout<<" Rotate refer to target:"<<target<<",targetInPose:"
  337. //<<targetInPose<<",anyDirect:"<<anyDirect<<std::endl;
  338. //以当前点为原点,想方向经过目标点的二次曲线曲率>0.25,则需要调整 y=a x*x
  339. float cuv = compute_cuv(targetInPose);
  340. float dt = 0.1;
  341. float acc_angular = 15 * M_PI / 180.0;
  342. if (cuv > 2 * M_PI / 180.0) {
  343. double theta = limit_gause(minYawdiff, limit_rotate.min, limit_rotate.max);
  344. double angular = next_speed(timedA_.Get(), theta, acc_angular, dt);
  345. double limit_angular = limit(angular, limit_rotate.min, limit_rotate.max);
  346. SendMoveCmd(move_mode_, eRotation, 0, limit_angular);
  347. actionType_ = eRotation;
  348. printf(" Rotate | input angular:%f,next angular:%f,down:%f diff:%f anyDirect:%d\n",
  349. timedA_.Get(), angular, limit_angular, minYawdiff, anyDirect);
  350. continue;
  351. } else {
  352. if (fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  353. printf(" Rotate refer target completed,cuv:%f\n", cuv);
  354. return true;
  355. }
  356. continue;
  357. }
  358. }
  359. return false;
  360. }
  361. Navigation::MpcResult Navigation::RotateReferToTarget(NavMessage::PathNode node, stLimit limit_rotate, int directions) {
  362. if (inited_ == false) {
  363. printf(" MPC_rotate has not inited\n");
  364. return eMpcFailed;
  365. }
  366. if (PoseTimeout()) {
  367. printf(" MPC_rotate Error:Pose is timeout \n");
  368. return eMpcFailed;
  369. }
  370. printf(" exec MPC_rotate autoDirect:%d\n", directions);
  371. while (cancel_ == false) {
  372. std::this_thread::sleep_for(std::chrono::milliseconds(30));
  373. if (pause_ == true) {
  374. //发送暂停消息
  375. continue;
  376. }
  377. // if (PoseTimeout()) {
  378. // printf(" MPC_rotate Error:Pose is timeout \n");
  379. // return eMpcFailed;
  380. // }
  381. // if (timedA_.timeout()) {
  382. // printf(" MPC_rotate Error:v/a is timeout \n");
  383. // return eMpcFailed;
  384. // }
  385. Pose2d current = timedPose_.Get();
  386. Pose2d target(node.x(), node.y(), node.theta());
  387. Pose2d targetInPose = Pose2d::relativePose(target, current);
  388. // 需要旋转的角度
  389. float target_yaw_diff = Pose2d::vector2yaw(targetInPose.x(), targetInPose.y());
  390. // 自由方向
  391. if (directions) {
  392. std::vector<double> yaw_diffs;
  393. if (directions & Direction::eForward) {
  394. yaw_diffs.push_back(target_yaw_diff);
  395. }
  396. if (directions & Direction::eBackward) {
  397. Pose2d relative_pose = Pose2d::relativePose(targetInPose, Pose2d(0, 0, M_PI));
  398. yaw_diffs.push_back(Pose2d::vector2yaw(relative_pose.x(), relative_pose.y()));
  399. }
  400. if (directions & Direction::eLeft) {
  401. Pose2d relative_pose = Pose2d::relativePose(targetInPose, Pose2d(0, 0, 1.0 / 2 * M_PI));
  402. yaw_diffs.push_back(Pose2d::vector2yaw(relative_pose.x(), relative_pose.y()));
  403. }
  404. if (directions & Direction::eRight) {
  405. Pose2d relative_pose = Pose2d::relativePose(targetInPose, Pose2d(0, 0, 3.0 / 2 * M_PI));
  406. yaw_diffs.push_back(Pose2d::vector2yaw(relative_pose.x(), relative_pose.y()));
  407. }
  408. for (auto i = 0; i < yaw_diffs.size(); ++i) {
  409. if (fabs(yaw_diffs[i]) < fabs(target_yaw_diff))
  410. target_yaw_diff = yaw_diffs[i];
  411. }
  412. std::cout << std::endl;
  413. // std::cout << std::endl << " min_diff: " << current_to_target.theta() << std::endl;
  414. }
  415. //一次变速
  416. std::vector<double> out;
  417. bool ret;
  418. TimerRecord::Execute([&, this]() {
  419. ret = Rotation_mpc_once(Pose2d(0, 0, target_yaw_diff), limit_rotate, out);
  420. }, "Rotation_mpc_once");
  421. if (ret == false) {
  422. Stop();
  423. return eMpcFailed;
  424. }
  425. //下发速度
  426. if (fabs(target_yaw_diff) > 2 * M_PI / 180.0) {
  427. SendMoveCmd(move_mode_, eRotation, 0, out[0]);
  428. actionType_ = eRotation;
  429. printf(" MPC_rotate | input angular_v:%f, down:%f, diff:%f autoDirect:%d\n",
  430. timedA_.Get(), out[0], target_yaw_diff, directions);
  431. } else if (fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  432. printf(" MPC_rotate refer target completed,cuv:%f\n", target_yaw_diff);
  433. return eMpcSuccess;
  434. }
  435. continue;
  436. }
  437. return eMpcFailed;
  438. }
  439. bool Navigation::MoveToTarget(NavMessage::PathNode node, Navigation::stLimit limit_v, Navigation::stLimit limit_w,
  440. bool anyDirect, bool enable_rotate) {
  441. if (IsArrived(node)) {
  442. return true;
  443. }
  444. bool already_in_mpc = false;
  445. while (cancel_ == false) {
  446. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  447. if (PoseTimeout()) {
  448. printf(" navigation Error:Pose is timeout \n");
  449. break;
  450. }
  451. Pose2d current = timedPose_.Get();
  452. if (IsArrived(node)) {
  453. break;
  454. }
  455. //两个方向都无法到达目标点,旋转 朝向目标点
  456. bool x_enable = PossibleToTarget(node, false);
  457. bool y_enable = PossibleToTarget(node, true);
  458. bool enableTotarget = x_enable || y_enable;
  459. if (anyDirect == false) {
  460. enableTotarget = x_enable;
  461. }
  462. //巡线无法到达目标点
  463. if (enableTotarget == false) {
  464. if (already_in_mpc && enable_rotate == false) {
  465. printf(" Move to node failed ,impossible to target and rotate is not enabled\n");
  466. return false;
  467. }
  468. Pose2d target(node.x(), node.y(), 0);
  469. // if (RotateReferToTarget(target, limit_w, anyDirect) == false) {
  470. int directions = Direction::eForward;
  471. if (anyDirect)
  472. directions = Direction::eForward | Direction::eBackward |
  473. Direction::eLeft | Direction::eRight;
  474. if (RotateReferToTarget(node, limit_w, directions) != eMpcSuccess) {
  475. std::cout << " Rotate refer to target failed,target: " << target <<
  476. " directions: " << std::hex << directions << " line_: " << __LINE__ << std::endl;
  477. return false;
  478. }
  479. continue;
  480. }
  481. already_in_mpc = true;
  482. MpcResult ret = MpcToTarget(node, limit_v, anyDirect);
  483. if (ret == eMpcSuccess) {
  484. printf(" MPC to target:%f %f l:%f,w:%f theta:%f completed\n",
  485. node.x(), node.y(), node.l(), node.w(), node.theta());
  486. break;
  487. } else if (ret == eImpossibleToTarget) {
  488. printf(" MPC to target:%f %f l:%f,w:%f theta:%f impossible ,retry ...\n",
  489. node.x(), node.y(), node.l(), node.w(), node.theta());
  490. } else {
  491. return false;
  492. }
  493. }
  494. if (cancel_) {
  495. return false;
  496. }
  497. return true;
  498. }
  499. bool Navigation::execute_nodes(NavMessage::NewAction action) {
  500. if (action.type() == 3 || action.type() == 4) //最优动作导航 or 导航中保证朝向严格一致
  501. {
  502. if (!parameter_.has_nodeangularlimit() || !parameter_.has_nodevelocitylimit() || action.pathnodes_size() == 0) {
  503. std::cout << "execute pathNodes failed ,Action invalid:" << action.DebugString() << std::endl;
  504. return false;
  505. }
  506. bool anyDirect = (action.type() == 3);
  507. //速度限制
  508. stLimit adjust_angular = {parameter_.nodeangularlimit().min(), parameter_.nodeangularlimit().max()};
  509. stLimit mpc_velocity = {parameter_.nodevelocitylimit().min(), parameter_.nodevelocitylimit().max()};
  510. for (int i = 0; i < action.pathnodes_size(); ++i) {
  511. NavMessage::PathNode node = action.pathnodes(i);
  512. if (i + 1 < action.pathnodes_size()) {
  513. NavMessage::PathNode next = action.pathnodes(i + 1);
  514. Pose2d vec(next.x() - node.x(), next.y() - node.y(), 0);
  515. node.set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  516. node.set_l(0.3);
  517. node.set_w(0.1);
  518. } else {
  519. node.set_theta(0);
  520. node.set_w(0.2);
  521. node.set_l(0.2);
  522. }
  523. if (MoveToTarget(node, mpc_velocity, adjust_angular, anyDirect, true) == false)
  524. return false;
  525. else
  526. isInSpace_ = false;
  527. }
  528. return true;
  529. }
  530. printf("execute PathNode failed ,action type is not 3/4 :%d\n", action.type());
  531. return false;
  532. }
  533. Navigation::MpcResult
  534. Navigation::RotateBeforeEnterSpace(NavMessage::PathNode space, double wheelbase, NavMessage::PathNode &target) {
  535. // if (timedBrotherNavStatu_.timeout() || timedPose_.timeout()) {
  536. // if (timedPose_.timeout()) {
  537. // printf(" rotate failed : timedBrotherNavStatu_ or pose timeout\n");
  538. // return eMpcFailed;
  539. // }
  540. NavMessage::NavStatu brother = timedBrotherNavStatu_.Get();
  541. stLimit limit_rotate = {2 * M_PI / 180.0, 15 * M_PI / 180.0};
  542. double acc_angular = 20 * M_PI / 180.0;
  543. double dt = 0.1;
  544. Pose2d rotated = timedPose_.Get();
  545. //前车先到,当前车进入2点,保持与前车一致的朝向
  546. if (brother.in_space() && brother.space_id() == space.id()) {
  547. rotated.mutable_theta() = brother.odom().theta();
  548. } else { //当前车先到(后车),倒车入库
  549. rotated.mutable_theta() = space.theta();
  550. rotated = rotated.rotate(rotated.x(), rotated.y(), M_PI);
  551. }
  552. double x = space.x();
  553. double y = space.y();
  554. if (move_mode_ == eSingle) {
  555. x -= wheelbase / 2 * cos(rotated.theta());
  556. y -= wheelbase / 2 * sin(rotated.theta());
  557. printf("确定车位点:eSingle\n");
  558. }
  559. target.set_x(x);
  560. target.set_y(y);
  561. target.set_theta(rotated.theta());
  562. target.set_l(0.10);
  563. target.set_w(0.05);
  564. target.set_id(space.id());
  565. //整车协调的时候,保持前后与车位一致即可
  566. if (move_mode_ == eDouble) {
  567. double yawDiff1 = (rotated - timedPose_.Get()).theta();
  568. double yawDiff2 = (rotated + Pose2d(0, 0, M_PI) - timedPose_.Get()).theta();
  569. if (fabs(yawDiff1) < fabs(yawDiff2)) {
  570. rotated = rotated + Pose2d(0, 0, M_PI);
  571. }
  572. }
  573. while (cancel_ == false) {
  574. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  575. Pose2d current = timedPose_.Get();
  576. double yawDiff = (rotated - current).theta();
  577. //一次变速
  578. std::vector<double> out;
  579. bool ret;
  580. TimerRecord::Execute([&, this]() {
  581. ret = Rotation_mpc_once(Pose2d(0, 0, yawDiff), limit_rotate, out);
  582. }, "Rotation_mpc_once");
  583. if (ret == false) {
  584. Stop();
  585. return eMpcFailed;
  586. }
  587. //下发速度
  588. if (fabs(yawDiff) < 0.5 * M_PI / 180.0 && fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  589. printf(" RotateBeforeEnterSpace refer target completed\\n,cuv:%f\n", yawDiff);
  590. Stop();
  591. return eMpcSuccess;
  592. } else{
  593. SendMoveCmd(move_mode_, eRotation, 0, out[0]);
  594. actionType_ = eRotation;
  595. printf(" RotateBeforeEnterSpace | input anguar:%f, down:%f(%f), diff:%f anyDirect:false\n",
  596. timedA_.Get(), out[0], out[0]/M_PI*180, yawDiff);
  597. }
  598. continue;
  599. }
  600. return eMpcFailed;
  601. }
  602. bool Navigation::execute_InOut_space(NavMessage::NewAction action) {
  603. if (action.type() != 1 && action.type() != 2) {
  604. printf(" Inout_space failed : msg action type must ==1\n ");
  605. return false;
  606. }
  607. if (!parameter_.has_inoutvlimit() || !action.has_spacenode() ||
  608. !action.has_streetnode()) {
  609. std::cout << "execute enter_space failed ,Action miss some infos:" << action.DebugString() << std::endl;
  610. return false;
  611. }
  612. if (PoseTimeout() == true) {
  613. printf(" inout_space failed type:%d : current pose is timeout\n", action.type());
  614. return false;
  615. }
  616. stLimit limit_v = {parameter_.inoutvlimit().min(), parameter_.inoutvlimit().max()};
  617. stLimit limit_w = {2 * M_PI / 180.0, 20 * M_PI / 180.0};
  618. //入库,起点为streetNode
  619. if (action.type() == 1) {
  620. Pose2d vec(action.spacenode().x() - action.streetnode().x(), action.spacenode().y() - action.streetnode().y(),
  621. 0);
  622. action.mutable_streetnode()->set_l(0.2);
  623. action.mutable_streetnode()->set_w(0.05);
  624. action.mutable_streetnode()->set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  625. if (MoveToTarget(action.streetnode(), limit_v, limit_w, true, true) == false) {
  626. printf(" Enter space failed type:%d: MoveTo StreetNode failed\n", action.type());
  627. return false;
  628. }
  629. //进库前提升机构上升
  630. if (lifter_rise() == false){
  631. printf(" Enter space | lifter rise failed, line:%d\n",__LINE__);
  632. }
  633. //移动到库位点, 禁止任意方向// 不允许巡线中停下旋转(当无法到达目标点时,返回false)
  634. printf("inout ----------------------------------------\n");
  635. //计算车位朝向
  636. action.mutable_spacenode()->set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  637. //计算当前车是进入车位1点还是2点
  638. NavMessage::PathNode new_target;
  639. if (RotateBeforeEnterSpace(action.spacenode(), action.wheelbase(), new_target) == eMpcFailed) {
  640. return false;
  641. }
  642. if (MoveToTarget(new_target, limit_v, limit_w, true, false) == false) {
  643. printf(" Enter space failed type:%d: MoveTo StreetNode failed\n", action.type());
  644. return false;
  645. }
  646. } else if (action.type() == 2) {
  647. Pose2d space(action.spacenode().x(), action.spacenode().y(), 0);
  648. Pose2d diff = Pose2d::abs(Pose2d::relativePose(space, timedPose_.Get()));
  649. if (diff.y() < 0.05) {
  650. //出库,移动到马路点,允许自由方向,不允许中途旋转
  651. Pose2d vec(action.streetnode().x() - action.spacenode().x(),
  652. action.streetnode().y() - action.spacenode().y(), 0);
  653. action.mutable_streetnode()->set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  654. action.mutable_streetnode()->set_l(0.2);
  655. action.mutable_streetnode()->set_w(0.1);
  656. if (MoveToTarget(action.streetnode(), limit_v, limit_w, true, false) == false) {
  657. printf(" out space failed type:%d: MoveTo StreetNode failed\n", action.type());
  658. return false;
  659. }
  660. } else {
  661. std::cout << " Out space failed: current pose too far from space node:" << space << ",diff:" << diff
  662. << std::endl;
  663. return false;
  664. }
  665. }
  666. return true;
  667. }
  668. /* current_to_target: current_to_target.theta()为所需旋转的角度
  669. * */
  670. bool Navigation::Rotation_mpc_once(Pose2d current_to_target, Navigation::stLimit limit_wmg, std::vector<double> &out,
  671. bool all_direct) {
  672. if (PoseTimeout() == true) {
  673. printf(" Rotation_mpc_once Error:Pose is timeout \n");
  674. return false;
  675. }
  676. if (timedV_.timeout() == true || timedA_.timeout() == true) {
  677. printf(" Rotation_mpc_once Error:V/A is timeout \n");
  678. return false;
  679. }
  680. Pose2d pose = timedPose_.Get();
  681. double line_velocity = timedV_.Get(); //从plc获取状态
  682. double angular_velocity = timedA_.Get();
  683. Eigen::VectorXd statu = Eigen::VectorXd::Zero(5);//agv状态
  684. statu[0] = pose.x();
  685. statu[1] = pose.y();
  686. statu[2] = pose.theta();
  687. statu[3] = line_velocity;
  688. statu[4] = angular_velocity;
  689. NavParameter::MPC_parameter mpc_parameter = parameter_.x_mpc_parameter();
  690. double obs_w = 0.95;//0.85;
  691. double obs_h = 1.55;//1.45;
  692. MpcError ret = failed;
  693. Pose2d brother = timedBrotherPose_.Get();
  694. Pose2d brother_in_self = Pose2d::relativePose(brother, pose);
  695. // std::cout<<" brother_in_self: "<<brother_in_self<<std::endl;
  696. if (move_mode_ == eDouble) {
  697. brother_in_self = Pose2d(pose.x() + 100, pose.y() + 100, 0);
  698. }
  699. RotateMPC MPC(brother_in_self, obs_w, obs_h, limit_wmg.min, limit_wmg.max);
  700. RotateMPC::MPC_parameter parameter = {mpc_parameter.shortest_radius(), mpc_parameter.dt(),
  701. mpc_parameter.acc_velocity(), mpc_parameter.acc_angular()};
  702. ret = MPC.solve(current_to_target, statu, parameter, out);
  703. if (ret == no_solution) {
  704. printf(" Rotation_mpc solve no solution set v/w = 0\n");
  705. out.clear();
  706. out.push_back(0);
  707. } else {
  708. // double min_angular_velocity = 1.0 / 180 * M_PI;
  709. double min_angular_velocity = 0.00001;
  710. if (fabs(out[0]) < min_angular_velocity) {
  711. if (out[0] > 0)
  712. out[0] = min_angular_velocity;
  713. else if (out[0] < 0)
  714. out[0] = -min_angular_velocity;
  715. else {}
  716. }
  717. }
  718. return ret == success || ret == no_solution;
  719. }
  720. bool Navigation::mpc_once(Trajectory traj, stLimit limit_v, std::vector<double> &out, bool directY) {
  721. if (PoseTimeout() == true) {
  722. printf(" MPC once Error:Pose is timeout \n");
  723. return false;
  724. }
  725. if (timedV_.timeout() == true || timedA_.timeout() == true) {
  726. printf(" MPC once Error:V/A is timeout \n");
  727. return false;
  728. }
  729. if (traj.size() == 0) {
  730. printf("traj size ==0\n");
  731. return false;
  732. }
  733. Pose2d pose = timedPose_.Get();
  734. double velocity = timedV_.Get(); //从plc获取状态
  735. double angular = timedA_.Get();
  736. Eigen::VectorXd statu = Eigen::VectorXd::Zero(5);//agv状态
  737. statu[0] = pose.x();
  738. statu[1] = pose.y();
  739. statu[2] = pose.theta();
  740. statu[3] = velocity;
  741. statu[4] = angular;
  742. Trajectory optimize_trajectory;
  743. Trajectory selected_trajectory;
  744. NavParameter::MPC_parameter mpc_parameter = parameter_.x_mpc_parameter();
  745. double obs_w = 0.95;//0.85;
  746. double obs_h = 1.55;//1.45;
  747. if (directY == true) {
  748. //将车身朝向旋转90°,车身朝向在(-pi,pi]
  749. statu[2] += M_PI / 2;
  750. if (statu[2] > M_PI)
  751. statu[2] -= 2 * M_PI;
  752. mpc_parameter = parameter_.y_mpc_parameter();
  753. obs_w = 0.95;//0.85;
  754. obs_h = 1.55;//1.45;
  755. }
  756. Pose2d brother = timedBrotherPose_.Get();
  757. Pose2d relative = Pose2d::relativePose(brother, pose);
  758. if (directY)
  759. relative = Pose2d::relativePose(brother.rotate(brother.x(), brother.y(), M_PI / 2),
  760. pose.rotate(pose.x(), pose.y(), M_PI / 2));//计算另一节在当前小车坐标系下的坐标
  761. //std::cout<<"pose:"<<pose<<", brother:"<<brother<<", relative:"<<relative<<std::endl;
  762. if (move_mode_ == eDouble)
  763. relative = Pose2d(-1e8, -1e8, 0);
  764. MpcError ret = failed;
  765. LoadedMPC MPC(relative, obs_w, obs_h, limit_v.min, limit_v.max);
  766. LoadedMPC::MPC_parameter parameter = {mpc_parameter.shortest_radius(), mpc_parameter.dt(),
  767. mpc_parameter.acc_velocity(), mpc_parameter.acc_angular()};
  768. //printf(" r:%f dt:%f acc:%f acc_a:%f\n",mpc_parameter.shortest_radius(),
  769. // mpc_parameter.dt(),mpc_parameter.acc_velocity(),mpc_parameter.acc_angular());
  770. ret = MPC.solve(traj, traj[traj.size() - 1], statu, parameter,
  771. out, selected_trajectory, optimize_trajectory);
  772. //std::cout<<" traj size %d %d -------- "<<selected_trajectory.size()<<","<<optimize_trajectory.size()<<std::endl;
  773. if (ret == no_solution) {
  774. printf(" mpc solve no solution set v/w = 0\n");
  775. out.clear();
  776. out.push_back(0);
  777. out.push_back(0);
  778. }
  779. predict_traj_.reset(optimize_trajectory, 1);
  780. selected_traj_.reset(selected_trajectory, 1);
  781. return ret == success || ret == no_solution;
  782. }
  783. bool Navigation::IsArrived(NavMessage::PathNode targetNode) {
  784. if (timedPose_.timeout() || timedV_.timeout() || timedA_.timeout()) {
  785. printf(" pose / v / w timeout,IsArrived return false\n");
  786. return false;
  787. }
  788. Pose2d current = timedPose_.Get();
  789. double x = current.x();
  790. double y = current.y();
  791. double tx = targetNode.x();
  792. double ty = targetNode.y();
  793. double l = fabs(targetNode.l());
  794. double w = fabs(targetNode.w());
  795. double theta = -targetNode.theta();
  796. if (l < 1e-10 || w < 1e-10) {
  797. printf("IsArrived: Error target l or w == 0\n");
  798. return false;
  799. }
  800. double a = (x - tx) * cos(theta) - (y - ty) * sin(theta);
  801. double b = (x - tx) * sin(theta) + (y - ty) * cos(theta);
  802. if (pow(a / l, 8) + pow(b / w, 8) <= 1) {
  803. if (fabs(timedV_.Get()) < 0.06 && fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  804. printf(" Arrived target: %f %f l:%f w:%f theta:%f\n", tx, ty, l, w, theta);
  805. return true;
  806. }
  807. }
  808. return false;
  809. }
  810. void Navigation::SendMoveCmd(int mode, ActionType type,
  811. double v, double angular) {
  812. if (monitor_) {
  813. monitor_->set_speed(mode, type, v, angular);
  814. if (type == eRotation)
  815. RWheel_position_ = eR;
  816. if (type == eVertical)
  817. RWheel_position_ = eX;
  818. if (type == eHorizontal)
  819. RWheel_position_ = eY;
  820. }
  821. }
  822. bool Navigation::clamp_close() {
  823. if (monitor_) {
  824. printf("Clamp closing...\n");
  825. monitor_->clamp_close(move_mode_);
  826. actionType_ = eClampClose;
  827. while (cancel_ == false) {
  828. if (timed_clamp_.timeout()) {
  829. printf("timed clamp is timeout\n");
  830. return false;
  831. }
  832. if (timed_clamp_.Get() == eClosed)
  833. return true;
  834. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  835. monitor_->clamp_close(move_mode_);
  836. actionType_ = eClampClose;
  837. }
  838. return false;
  839. }
  840. return false;
  841. }
  842. bool Navigation::clamp_open() {
  843. if (monitor_) {
  844. printf("Clamp openning...\n");
  845. monitor_->clamp_open(move_mode_);
  846. actionType_ = eClampOpen;
  847. while (cancel_ == false) {
  848. if (timed_clamp_.timeout()) {
  849. printf("timed clamp is timeout\n");
  850. return false;
  851. }
  852. if (timed_clamp_.Get() == eOpened)
  853. return true;
  854. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  855. monitor_->clamp_open(move_mode_);
  856. actionType_ = eClampOpen;
  857. }
  858. return false;
  859. }
  860. return false;
  861. }
  862. bool Navigation::lifter_rise() {
  863. if (monitor_) {
  864. printf("Lifter upping...\n");
  865. monitor_->lifter_rise(move_mode_);
  866. actionType_ = eLifterRise;
  867. while (cancel_ == false) {
  868. if (timed_lifter_.timeout()) {
  869. printf("timed lifter is timeout\n");
  870. return false;
  871. }
  872. if (timed_lifter_.Get() == eRose)
  873. return true;
  874. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  875. monitor_->lifter_rise(move_mode_);
  876. actionType_ = eLifterRise;
  877. }
  878. return false;
  879. }
  880. return false;
  881. }
  882. bool Navigation::lifter_down() {
  883. if (monitor_) {
  884. printf("Lifter downing...\n");
  885. monitor_->lifter_down(move_mode_);
  886. actionType_ = eLifterDown;
  887. while (cancel_ == false) {
  888. if (timed_lifter_.timeout()) {
  889. printf("timed lifter is timeout\n");
  890. return false;
  891. }
  892. if (timed_lifter_.Get() == eDowned)
  893. return true;
  894. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  895. monitor_->lifter_down(move_mode_);
  896. actionType_ = eLifterDown;
  897. }
  898. return false;
  899. }
  900. return false;
  901. }
  902. Navigation::MpcResult Navigation::MpcToTarget(NavMessage::PathNode node, stLimit limit_v, bool autoDirect) {
  903. if (IsArrived(node)) {
  904. printf(" current already in target completed !!!\n");
  905. return eMpcSuccess;
  906. }
  907. if (inited_ == false) {
  908. printf(" navigation has not inited\n");
  909. return eMpcFailed;
  910. }
  911. if (PoseTimeout()) {
  912. printf(" navigation Error:Pose is timeout \n");
  913. return eMpcFailed;
  914. }
  915. Pose2d current = timedPose_.Get();
  916. Pose2d target(node.x(), node.y(), 0);
  917. //生成轨迹
  918. Trajectory traj = Trajectory::create_line_trajectory(current, target);
  919. if (traj.size() == 0)
  920. return eMpcSuccess;
  921. //判断 巡线方向
  922. bool directY = false;
  923. if (autoDirect) {
  924. Pose2d target_relative = Pose2d::relativePose(target, timedPose_.Get());
  925. if (fabs(target_relative.y()) > fabs(target_relative.x())) { //目标轨迹点在当前点Y轴上
  926. std::cout << " MPC Y axis target_relative:" << target_relative << std::endl;
  927. directY = true;
  928. } else {
  929. std::cout << " MPC X axis target_relative:" << target_relative << std::endl;
  930. }
  931. }
  932. printf(" exec along autoDirect:%d\n", autoDirect);
  933. while (cancel_ == false) {
  934. std::this_thread::sleep_for(std::chrono::milliseconds(30));
  935. if (pause_ == true) {
  936. //发送暂停消息
  937. continue;
  938. }
  939. if (PoseTimeout()) {
  940. printf(" navigation Error:Pose is timeout \n");
  941. return eMpcFailed;
  942. }
  943. if (timedV_.timeout() || timedA_.timeout()) {
  944. printf(" navigation Error:v/a is timeout | __LINE__:%d \n", __LINE__);
  945. return eMpcFailed;
  946. }
  947. //判断是否到达终点
  948. if (IsArrived(node)) {
  949. if (Stop()) {
  950. printf(" exec along completed !!!\n");
  951. return eMpcSuccess;
  952. }
  953. }
  954. //一次变速
  955. std::vector<double> out;
  956. bool ret;
  957. TimerRecord::Execute([&, this]() {
  958. ret = mpc_once(traj, limit_v, out, directY);
  959. }, "mpc_once");
  960. if (ret == false) {
  961. Stop();
  962. return eMpcFailed;
  963. }
  964. /*
  965. * AGV 在终点附近低速巡航时,设置最小速度0.05
  966. */
  967. Pose2d target_in_agv = Pose2d::relativePose(target, timedPose_.Get());
  968. if (directY) {
  969. target_in_agv = target_in_agv.rotate(M_PI / 2.0);
  970. }
  971. if (Pose2d::abs(target_in_agv) < Pose2d(0.2, 2, M_PI * 2)) {
  972. if (out[0] >= 0 && out[0] < limit_v.min)
  973. out[0] = limit_v.min;
  974. if (out[0] < 0 && out[0] > -limit_v.min)
  975. out[0] = -limit_v.min;
  976. }
  977. //下发速度
  978. //printf(" nav input :%f out:%f\n",timedV_.Get(),out[0]);
  979. if (directY == false)
  980. SendMoveCmd(move_mode_, eVertical, out[0], out[1]);
  981. else
  982. SendMoveCmd(move_mode_, eHorizontal, out[0], out[1]);
  983. actionType_ = directY ? eHorizontal : eVertical;
  984. /*
  985. * 判断车辆是否在终点附近徘徊,无法到达终点
  986. */
  987. if (PossibleToTarget(node, directY) == false) {
  988. printf(" --------------MPC imposible to target -------------------------------------------\n");
  989. if (fabs(timedV_.Get()) > 0.1 || fabs(timedA_.Get()) > 10 * M_PI / 180.0)
  990. SlowlyStop();
  991. else
  992. Stop();
  993. return eImpossibleToTarget;
  994. }
  995. }
  996. return eMpcFailed;
  997. }
  998. bool Navigation::PossibleToTarget(NavMessage::PathNode targetNode, bool directY) {
  999. if (timedPose_.timeout()) {
  1000. return false;
  1001. }
  1002. Pose2d current = timedPose_.Get();
  1003. if(targetNode.id().find('S')){
  1004. //车位点强制可到达
  1005. return true;
  1006. }
  1007. double tx = targetNode.x();
  1008. double ty = targetNode.y();
  1009. double l = fabs(targetNode.l());
  1010. double w = fabs(targetNode.w());
  1011. double theta = -targetNode.theta();
  1012. // double W = 2.45;
  1013. // double L = 1.3;
  1014. // double minYaw = 3 * M_PI / 180.0;
  1015. // if (move_mode_ == eDouble) {
  1016. // L = 1.3 + 2.7;
  1017. //
  1018. // }
  1019. double W = 2.5;
  1020. double L = 1.565;
  1021. double minYaw = 3 * M_PI / 180.0;
  1022. if (move_mode_ == eDouble) {
  1023. L = 1.565 + 2.78;
  1024. }
  1025. if (directY) {
  1026. current = current.rotate(current.x(), current.y(), M_PI / 2);
  1027. double t = W;
  1028. W = L;
  1029. L = t;
  1030. }
  1031. double minR = W / 2 + L / tan(minYaw);
  1032. //printf("l:%f,w:%f\n",l,w);
  1033. std::vector<Pose2d> poses = Pose2d::generate_rectangle_vertexs(Pose2d(tx, ty, 0), l * 2, w * 2);
  1034. bool nagY = false;
  1035. bool posiY = false;
  1036. for (int i = 0; i < poses.size(); ++i) {
  1037. Pose2d rpos = poses[i].rotate(tx, ty, theta);
  1038. Pose2d relative = Pose2d::relativePose(rpos, current);
  1039. double ax = fabs(relative.x());
  1040. double ay = fabs(relative.y());
  1041. if (relative.y() > 0) posiY = true;
  1042. if (relative.y() < 0) nagY = true;
  1043. if (ax * ax + pow(ay - minR, 2) > minR * minR) {
  1044. /*printf(" possible to target:%f %f l:%f,w:%f theta:%f minR:%f ax:%f,ay:%f\n",
  1045. targetNode.x(),targetNode.y(),targetNode.l(),targetNode.w(),targetNode.theta(),
  1046. minR,ax,ay);*/
  1047. return true;
  1048. } else if (nagY && posiY) {
  1049. // std::cout << "nagY && posiY" << std::endl;
  1050. return true;
  1051. }
  1052. // printf("directY:%d targetInPose:%f %f l:%f,w:%f theta:%f minR:%f ax:%f,ay:%f\n", directY,
  1053. // relative.x(), relative.y(), targetNode.l(), targetNode.w(), targetNode.theta(),
  1054. // minR, ax, ay);
  1055. }
  1056. printf(" impossible to target:%f %f l:%f,w:%f theta:%f\n",
  1057. targetNode.x(), targetNode.y(), targetNode.l(), targetNode.w(), targetNode.theta());
  1058. return false;
  1059. }
  1060. void Navigation::Start(const NavMessage::NavCmd &cmd, NavMessage::NavResponse &response) {
  1061. if (inited_ == false) {
  1062. response.set_ret(-1);
  1063. response.set_info("navigation has not inited");
  1064. printf(" navigation has not inited\n");
  1065. return;
  1066. }
  1067. if (newUnfinished_cations_.empty() == false) //正在运行中,上一次指令未完成
  1068. {
  1069. response.set_ret(-2);
  1070. response.set_info("navigation is running pls cancel before");
  1071. printf(" navigation is running pls cancel before\n");
  1072. return;
  1073. }
  1074. //add 先检查当前点与起点的距离
  1075. global_navCmd_ = cmd;
  1076. for (int i = 0; i < cmd.newactions_size(); ++i)
  1077. newUnfinished_cations_.push(cmd.newactions(i));
  1078. pause_ = false;
  1079. cancel_ = false;
  1080. running_ = true;
  1081. actionType_ = eReady;
  1082. printf(" navigation beg...\n");
  1083. while (newUnfinished_cations_.empty() == false && cancel_ == false) {
  1084. std::cout << "unfinished size:" << newUnfinished_cations_.size() << std::endl;
  1085. NavMessage::NewAction act = newUnfinished_cations_.front();
  1086. if (act.type() == 1) { //入库
  1087. space_id_ = act.spacenode().id();
  1088. isInSpace_ = true;
  1089. if (!execute_InOut_space(act)) {
  1090. printf(" In space failed\n");
  1091. break;
  1092. }
  1093. } else if (act.type() == 2) { //出库
  1094. if (!execute_InOut_space(act)) {
  1095. printf(" out space failed\n");
  1096. break;
  1097. } else {
  1098. isInSpace_ = false;
  1099. }
  1100. } else if (act.type() == 3 || act.type() == 4) { //马路导航
  1101. if (!execute_nodes(act))
  1102. break;
  1103. } else if (act.type() == 5) {
  1104. printf(" 汽车模型导航....\n");
  1105. } else if (act.type() == 6) {//夹持
  1106. if (this->clamp_close() == false) {
  1107. printf("夹持failed ...\n");
  1108. break;
  1109. }
  1110. } else if (act.type() == 7) {
  1111. if (this->clamp_open() == false) {
  1112. printf("打开夹持 failed...\n");
  1113. break;
  1114. }
  1115. } else if (act.type() == 8) { //切换模式
  1116. SwitchMode(act.changedmode(), act.wheelbase());
  1117. } else if (act.type() == 9) { //提升机构提升
  1118. if (this->lifter_rise() == false) {
  1119. printf("提升failed ...\n");
  1120. break;
  1121. }
  1122. } else if (act.type() == 10) { //提升机构下降
  1123. if (this->lifter_down() == false) {
  1124. printf("下降failed ...\n");
  1125. break;
  1126. }
  1127. }else {
  1128. printf(" action type invalid not handled !!\n");break;
  1129. }
  1130. newUnfinished_cations_.pop();
  1131. }
  1132. actionType_ = eReady;
  1133. Stop();
  1134. if (cancel_ == true) {
  1135. response.set_ret(-3);
  1136. response.set_info("navigation canceled");
  1137. printf(" navigation canceled\n");
  1138. while (newUnfinished_cations_.empty() == false)
  1139. newUnfinished_cations_.pop();
  1140. } else {
  1141. if (newUnfinished_cations_.empty()) {
  1142. response.set_ret(0);
  1143. response.set_info("navigation completed!!!");
  1144. printf("navigation completed!!!\n");
  1145. } else {
  1146. response.set_ret(-4);
  1147. response.set_info("navigation Failed!!!!");
  1148. printf(" navigation Failed\n");
  1149. while (newUnfinished_cations_.empty() == false)
  1150. newUnfinished_cations_.pop();
  1151. }
  1152. }
  1153. running_ = false;
  1154. }
  1155. void Navigation::SwitchMode(int mode, float wheelBase) {
  1156. printf("Child AGV can not Switch Mode\n");
  1157. }
  1158. float Navigation::compute_cuv(const Pose2d &target) {
  1159. float x = fabs(target.x());
  1160. float y = fabs(target.y());
  1161. float cuv = atan(y / (x + 1e-8));
  1162. //printf(" ---------------------- cuv:%f\n",cuv);
  1163. return cuv;
  1164. }
  1165. void Navigation::ManualOperation(const NavMessage::ManualCmd &cmd, NavMessage::NavResponse &response) {
  1166. pause_ = false;
  1167. cancel_ = false;
  1168. running_ = true;
  1169. actionType_ = eReady;
  1170. printf("ManualOperation: %d | start...\n", cmd.operation_type());
  1171. float symbol = cmd.velocity() < 0 ? -1 : 1; // 判断为正方向or负方向
  1172. double velocity;
  1173. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1174. switch (cmd.operation_type()) {
  1175. case 1: // 旋转
  1176. velocity = 2.0 * M_PI / 180.0 * symbol;
  1177. SendMoveCmd(move_mode_, eRotation, 0, velocity);
  1178. actionType_ = eRotation;
  1179. printf(" ManualOperation: %d | input angular_v: %f, down: %f\n",
  1180. cmd.operation_type(), timedA_.Get(), velocity);
  1181. break;
  1182. case 2: // X平移
  1183. velocity = 1.0 * symbol;
  1184. SendMoveCmd(move_mode_, eVertical, velocity, 0);
  1185. actionType_ = eVertical;
  1186. printf(" ManualOperation: %d | input line_v : %f, down: %f\n",
  1187. cmd.operation_type(), timedV_.Get(), velocity);
  1188. break;
  1189. case 3: // Y平移
  1190. velocity = 1.0 * symbol;
  1191. SendMoveCmd(move_mode_, eHorizontal, velocity, 0);
  1192. actionType_ = eHorizontal;
  1193. printf(" ManualOperation: %d | input line_v: %f, down: %f\n",
  1194. cmd.operation_type(), timedV_.Get(), velocity);
  1195. break;
  1196. default:
  1197. break;
  1198. }
  1199. actionType_ = eReady;
  1200. response.set_ret(-3);
  1201. response.set_info("ManualOperation: %d, canceled!!!", cmd.operation_type());
  1202. printf("ManualOperation: %d | canceled!!!\n", cmd.operation_type());
  1203. running_ = false;
  1204. }