navigation.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330
  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. bool Navigation::RotateReferToTarget(const Pose2d &target, stLimit limit_rotate, bool anyDirect) {
  304. while (cancel_ == false) {
  305. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  306. if (timedPose_.timeout()) {
  307. printf(" RotateBytarget failed pose timeout\n");
  308. return false;
  309. }
  310. if (timedA_.timeout()) {
  311. printf(" RotateBytarget failed wmg timeout\n");
  312. return false;
  313. }
  314. Pose2d targetInPose = Pose2d::relativePose(target, timedPose_.Get());
  315. float yawDiff = Pose2d::vector2yaw(targetInPose.x(), targetInPose.y());
  316. float minYawdiff = yawDiff;
  317. if (anyDirect) {
  318. Pose2d p0 = timedPose_.Get();
  319. float yawdiff[4] = {0};
  320. yawdiff[0] = yawDiff;
  321. Pose2d relativePose;
  322. relativePose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, M_PI / 2));
  323. yawdiff[1] = Pose2d::vector2yaw(relativePose.x(), relativePose.y()); ////使用减法,保证角度在【-pi pi】
  324. relativePose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, M_PI));
  325. yawdiff[2] = Pose2d::vector2yaw(relativePose.x(), relativePose.y());
  326. relativePose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, 3 * M_PI / 2));
  327. yawdiff[3] = Pose2d::vector2yaw(relativePose.x(), relativePose.y());
  328. for (int i = 1; i < 4; ++i) {
  329. if (fabs(yawdiff[i]) < fabs(minYawdiff)) {
  330. minYawdiff = yawdiff[i];
  331. targetInPose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, i * M_PI / 2.0));
  332. }
  333. }
  334. }
  335. //std::cout<<" Rotate refer to target:"<<target<<",targetInPose:"
  336. //<<targetInPose<<",anyDirect:"<<anyDirect<<std::endl;
  337. //以当前点为原点,想方向经过目标点的二次曲线曲率>0.25,则需要调整 y=a x*x
  338. float cuv = compute_cuv(targetInPose);
  339. float dt = 0.1;
  340. float acc_angular = 15 * M_PI / 180.0;
  341. if (cuv > 2 * M_PI / 180.0) {
  342. double theta = limit_gause(minYawdiff, limit_rotate.min, limit_rotate.max);
  343. double angular = next_speed(timedA_.Get(), theta, acc_angular, dt);
  344. double limit_angular = limit(angular, limit_rotate.min, limit_rotate.max);
  345. SendMoveCmd(move_mode_, eRotation, 0, limit_angular);
  346. actionType_ = eRotation;
  347. printf(" Rotate | input angular:%f,next angular:%f,down:%f diff:%f anyDirect:%d\n",
  348. timedA_.Get(), angular, limit_angular, minYawdiff, anyDirect);
  349. continue;
  350. } else {
  351. if (fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  352. printf(" Rotate refer target completed,cuv:%f\n", cuv);
  353. return true;
  354. }
  355. continue;
  356. }
  357. }
  358. return false;
  359. }
  360. Navigation::MpcResult Navigation::RotateReferToTarget(NavMessage::PathNode node, stLimit limit_rotate, int directions) {
  361. if (inited_ == false) {
  362. printf(" MPC_rotate has not inited\n");
  363. return eMpcFailed;
  364. }
  365. if (PoseTimeout()) {
  366. printf(" MPC_rotate Error:Pose is timeout \n");
  367. return eMpcFailed;
  368. }
  369. printf(" exec MPC_rotate autoDirect:%d\n", directions);
  370. while (cancel_ == false) {
  371. std::this_thread::sleep_for(std::chrono::milliseconds(30));
  372. if (pause_ == true) {
  373. //发送暂停消息
  374. continue;
  375. }
  376. // if (PoseTimeout()) {
  377. // printf(" MPC_rotate Error:Pose is timeout \n");
  378. // return eMpcFailed;
  379. // }
  380. // if (timedA_.timeout()) {
  381. // printf(" MPC_rotate Error:v/a is timeout \n");
  382. // return eMpcFailed;
  383. // }
  384. Pose2d current = timedPose_.Get();
  385. Pose2d target(node.x(), node.y(), node.theta());
  386. Pose2d targetInPose = Pose2d::relativePose(target, current);
  387. // 需要旋转的角度
  388. float target_yaw_diff = Pose2d::vector2yaw(targetInPose.x(), targetInPose.y());
  389. // 自由方向
  390. if (directions) {
  391. std::vector<double> yaw_diffs;
  392. if (directions & Direction::eForward) {
  393. yaw_diffs.push_back(target_yaw_diff);
  394. }
  395. if (directions & Direction::eBackward) {
  396. Pose2d relative_pose = Pose2d::relativePose(targetInPose, Pose2d(0, 0, M_PI));
  397. yaw_diffs.push_back(Pose2d::vector2yaw(relative_pose.x(), relative_pose.y()));
  398. }
  399. if (directions & Direction::eLeft) {
  400. Pose2d relative_pose = Pose2d::relativePose(targetInPose, Pose2d(0, 0, 1.0 / 2 * M_PI));
  401. yaw_diffs.push_back(Pose2d::vector2yaw(relative_pose.x(), relative_pose.y()));
  402. }
  403. if (directions & Direction::eRight) {
  404. Pose2d relative_pose = Pose2d::relativePose(targetInPose, Pose2d(0, 0, 3.0 / 2 * M_PI));
  405. yaw_diffs.push_back(Pose2d::vector2yaw(relative_pose.x(), relative_pose.y()));
  406. }
  407. for (auto i = 0; i < yaw_diffs.size(); ++i) {
  408. if (fabs(yaw_diffs[i]) < fabs(target_yaw_diff))
  409. target_yaw_diff = yaw_diffs[i];
  410. }
  411. std::cout << std::endl;
  412. // std::cout << std::endl << " min_diff: " << current_to_target.theta() << std::endl;
  413. }
  414. //一次变速
  415. std::vector<double> out;
  416. bool ret;
  417. TimerRecord::Execute([&, this]() {
  418. ret = Rotation_mpc_once(Pose2d(0, 0, target_yaw_diff), limit_rotate, out);
  419. }, "Rotation_mpc_once");
  420. if (ret == false) {
  421. Stop();
  422. return eMpcFailed;
  423. }
  424. //下发速度
  425. if (fabs(target_yaw_diff) > 2 * M_PI / 180.0) {
  426. SendMoveCmd(move_mode_, eRotation, 0, out[0]);
  427. actionType_ = eRotation;
  428. printf(" MPC_rotate | input angular_v:%f, down:%f, diff:%f autoDirect:%d\n",
  429. timedA_.Get(), out[0], target_yaw_diff, directions);
  430. } else if (fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  431. printf(" MPC_rotate refer target completed,cuv:%f\n", target_yaw_diff);
  432. return eMpcSuccess;
  433. }
  434. continue;
  435. }
  436. return eMpcFailed;
  437. }
  438. bool Navigation::MoveToTarget(NavMessage::PathNode node, Navigation::stLimit limit_v, Navigation::stLimit limit_w,
  439. bool anyDirect, bool enable_rotate) {
  440. if (IsArrived(node)) {
  441. return true;
  442. }
  443. bool already_in_mpc = false;
  444. while (cancel_ == false) {
  445. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  446. if (PoseTimeout()) {
  447. printf(" navigation Error:Pose is timeout \n");
  448. break;
  449. }
  450. Pose2d current = timedPose_.Get();
  451. if (IsArrived(node)) {
  452. break;
  453. }
  454. //两个方向都无法到达目标点,旋转 朝向目标点
  455. bool x_enable = PossibleToTarget(node, false);
  456. bool y_enable = PossibleToTarget(node, true);
  457. bool enableTotarget = x_enable || y_enable;
  458. if (anyDirect == false) {
  459. enableTotarget = x_enable;
  460. }
  461. //巡线无法到达目标点
  462. if (enableTotarget == false) {
  463. if (already_in_mpc && enable_rotate == false) {
  464. printf(" Move to node failed ,impossible to target and rotate is not enabled\n");
  465. return false;
  466. }
  467. Pose2d target(node.x(), node.y(), 0);
  468. // if (RotateReferToTarget(target, limit_w, anyDirect) == false) {
  469. int directions = Direction::eForward;
  470. if (anyDirect)
  471. directions = Direction::eForward | Direction::eBackward |
  472. Direction::eLeft | Direction::eRight;
  473. if (RotateReferToTarget(node, limit_w, directions) != eMpcSuccess) {
  474. std::cout << " Rotate refer to target failed,target: " << target <<
  475. " directions: " << std::hex << directions << " line_: " << __LINE__ << std::endl;
  476. return false;
  477. }
  478. continue;
  479. }
  480. already_in_mpc = true;
  481. MpcResult ret = MpcToTarget(node, limit_v, anyDirect);
  482. if (ret == eMpcSuccess) {
  483. printf(" MPC to target:%f %f l:%f,w:%f theta:%f completed\n",
  484. node.x(), node.y(), node.l(), node.w(), node.theta());
  485. break;
  486. } else if (ret == eImpossibleToTarget) {
  487. printf(" MPC to target:%f %f l:%f,w:%f theta:%f impossible ,retry ..............................\n",
  488. node.x(), node.y(), node.l(), node.w(), node.theta());
  489. } else {
  490. return false;
  491. }
  492. }
  493. if (cancel_) {
  494. return false;
  495. }
  496. return true;
  497. }
  498. bool Navigation::execute_nodes(NavMessage::NewAction action) {
  499. if (action.type() == 3 || action.type() == 4) //最优动作导航 or 导航中保证朝向严格一致
  500. {
  501. if (!parameter_.has_nodeangularlimit() || !parameter_.has_nodevelocitylimit() || action.pathnodes_size() == 0) {
  502. std::cout << "execute pathNodes failed ,Action invalid:" << action.DebugString() << std::endl;
  503. return false;
  504. }
  505. bool anyDirect = (action.type() == 3);
  506. //速度限制
  507. stLimit adjust_angular = {parameter_.nodeangularlimit().min(), parameter_.nodeangularlimit().max()};
  508. stLimit mpc_velocity = {parameter_.nodevelocitylimit().min(), parameter_.nodevelocitylimit().max()};
  509. for (int i = 0; i < action.pathnodes_size(); ++i) {
  510. NavMessage::PathNode node = action.pathnodes(i);
  511. if (i + 1 < action.pathnodes_size()) {
  512. NavMessage::PathNode next = action.pathnodes(i + 1);
  513. Pose2d vec(next.x() - node.x(), next.y() - node.y(), 0);
  514. node.set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  515. node.set_l(0.3);
  516. node.set_w(0.1);
  517. } else {
  518. node.set_theta(0);
  519. node.set_w(0.2);
  520. node.set_l(0.2);
  521. }
  522. if (MoveToTarget(node, mpc_velocity, adjust_angular, anyDirect, true) == false)
  523. return false;
  524. else
  525. isInSpace_ = false;
  526. }
  527. return true;
  528. }
  529. printf("execute PathNode failed ,action type is not 3/4 :%d\n", action.type());
  530. return false;
  531. }
  532. Navigation::MpcResult
  533. Navigation::RotateBeforeEnterSpace(NavMessage::PathNode space, double wheelbase, NavMessage::PathNode &target) {
  534. // if (timedBrotherNavStatu_.timeout() || timedPose_.timeout()) {
  535. // if (timedPose_.timeout()) {
  536. // printf(" rotate failed : timedBrotherNavStatu_ or pose timeout\n");
  537. // return eMpcFailed;
  538. // }
  539. NavMessage::NavStatu brother = timedBrotherNavStatu_.Get();
  540. stLimit limit_rotate = {2 * M_PI / 180.0, 15 * M_PI / 180.0};
  541. double acc_angular = 20 * M_PI / 180.0;
  542. double dt = 0.1;
  543. Pose2d rotated = timedPose_.Get();
  544. //前车先到,当前车进入2点,保持与前车一致的朝向
  545. if (brother.in_space() && brother.space_id() == space.id()) {
  546. rotated.mutable_theta() = brother.odom().theta();
  547. } else { //当前车先到(后车),倒车入库
  548. rotated.mutable_theta() = space.theta();
  549. rotated = rotated.rotate(rotated.x(), rotated.y(), M_PI);
  550. }
  551. double x = space.x();
  552. double y = space.y();
  553. if (move_mode_ == eSingle) {
  554. x -= wheelbase / 2 * cos(rotated.theta());
  555. y -= wheelbase / 2 * sin(rotated.theta());
  556. printf("确定车位点:eSingle\n");
  557. }
  558. target.set_x(x);
  559. target.set_y(y);
  560. target.set_theta(rotated.theta());
  561. target.set_l(0.05);
  562. target.set_w(0.03);
  563. target.set_id(space.id());
  564. //整车协调的时候,保持前后与车位一致即可
  565. if (move_mode_ == eDouble) {
  566. double yawDiff1 = (rotated - timedPose_.Get()).theta();
  567. double yawDiff2 = (rotated + Pose2d(0, 0, M_PI) - timedPose_.Get()).theta();
  568. if (fabs(yawDiff1) < fabs(yawDiff2)) {
  569. rotated = rotated + Pose2d(0, 0, M_PI);
  570. }
  571. }
  572. while (cancel_ == false) {
  573. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  574. Pose2d current = timedPose_.Get();
  575. double yawDiff = (rotated - current).theta();
  576. //一次变速
  577. std::vector<double> out;
  578. bool ret;
  579. TimerRecord::Execute([&, this]() {
  580. ret = Rotation_mpc_once(Pose2d(0, 0, yawDiff), limit_rotate, out);
  581. }, "Rotation_mpc_once");
  582. if (ret == false) {
  583. Stop();
  584. return eMpcFailed;
  585. }
  586. //下发速度
  587. if (fabs(yawDiff) > 1 * M_PI / 180.0) {
  588. SendMoveCmd(move_mode_, eRotation, 0, out[0]);
  589. actionType_ = eRotation;
  590. printf(" RotateBeforeEnterSpace | input anguar:%f, down:%f diff:%f anyDirect:false\n",
  591. timedA_.Get(), out[0], yawDiff);
  592. } else if (fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  593. printf(" RotateBeforeEnterSpace refer target completed\\n,cuv:%f\n", yawDiff);
  594. return eMpcSuccess;
  595. }
  596. continue;
  597. // if (fabs(yawDiff) > 1 * M_PI / 180.0) {
  598. // double theta = limit_gause(yawDiff, limit_rotate.min, limit_rotate.max);
  599. // double angular = next_speed(timedA_.Get(), theta, acc_angular, dt);
  600. // double limit_angular = limit(angular, limit_rotate.min, limit_rotate.max);
  601. //
  602. // SendMoveCmd(move_mode_, Monitor_emqx::eRotation, 0, limit_angular);
  603. // actionType_ = eRotation;
  604. // printf(" RotateBeforeEnterSpace | input anguar:%f,next angular:%f,down:%f diff:%f anyDirect:false\n",
  605. // timedA_.Get(), angular, limit_angular, yawDiff);
  606. //
  607. // continue;
  608. // } else {
  609. // if (fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  610. // printf(" RotateBeforeEnterSpace refer target completed\n");
  611. // printf("---------------- update new target :%f %f %f \n", target.x(), target.y(), target.theta());
  612. // return true;
  613. // }
  614. // }
  615. }
  616. return eMpcFailed;
  617. }
  618. bool Navigation::execute_InOut_space(NavMessage::NewAction action) {
  619. if (action.type() != 1 && action.type() != 2) {
  620. printf(" Inout_space failed : msg action type must ==1\n ");
  621. return false;
  622. }
  623. if (!parameter_.has_inoutvlimit() || !action.has_spacenode() ||
  624. !action.has_streetnode()) {
  625. std::cout << "execute enter_space failed ,Action miss some infos:" << action.DebugString() << std::endl;
  626. return false;
  627. }
  628. if (PoseTimeout() == true) {
  629. printf(" inout_space failed type:%d : current pose is timeout\n", action.type());
  630. return false;
  631. }
  632. stLimit limit_v = {parameter_.inoutvlimit().min(), parameter_.inoutvlimit().max()};
  633. stLimit limit_w = {2 * M_PI / 180.0, 20 * M_PI / 180.0};
  634. //入库,起点为streetNode
  635. if (action.type() == 1) {
  636. Pose2d vec(action.spacenode().x() - action.streetnode().x(), action.spacenode().y() - action.streetnode().y(),
  637. 0);
  638. action.mutable_streetnode()->set_l(0.2);
  639. action.mutable_streetnode()->set_w(0.05);
  640. action.mutable_streetnode()->set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  641. if (MoveToTarget(action.streetnode(), limit_v, limit_w, true, true) == false) {
  642. printf(" Enter space failed type:%d: MoveTo StreetNode failed\n", action.type());
  643. return false;
  644. }
  645. //移动到库位点, 禁止任意方向// 不允许巡线中停下旋转(当无法到达目标点时,返回false)
  646. printf("inout ----------------------------------------\n");
  647. //计算车位朝向
  648. action.mutable_spacenode()->set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  649. //计算当前车是进入车位1点还是2点
  650. NavMessage::PathNode new_target;
  651. if (RotateBeforeEnterSpace(action.spacenode(), action.wheelbase(), new_target) == eMpcFailed) {
  652. return false;
  653. }
  654. if (MoveToTarget(new_target, limit_v, limit_w, true, false) == false) {
  655. printf(" Enter space failed type:%d: MoveTo StreetNode failed\n", action.type());
  656. return false;
  657. }
  658. } else if (action.type() == 2) {
  659. Pose2d space(action.spacenode().x(), action.spacenode().y(), 0);
  660. Pose2d diff = Pose2d::abs(Pose2d::relativePose(space, timedPose_.Get()));
  661. if (diff.y() < 0.05) {
  662. //出库,移动到马路点,允许自由方向,不允许中途旋转
  663. Pose2d vec(action.streetnode().x() - action.spacenode().x(),
  664. action.streetnode().y() - action.spacenode().y(), 0);
  665. action.mutable_streetnode()->set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  666. action.mutable_streetnode()->set_l(0.2);
  667. action.mutable_streetnode()->set_w(0.1);
  668. if (MoveToTarget(action.streetnode(), limit_v, limit_w, true, false) == false) {
  669. printf(" out space failed type:%d: MoveTo StreetNode failed\n", action.type());
  670. return false;
  671. }
  672. } else {
  673. std::cout << " Out space failed: current pose too far from space node:" << space << ",diff:" << diff
  674. << std::endl;
  675. return false;
  676. }
  677. }
  678. return true;
  679. }
  680. /* current_to_target: current_to_target.theta()为所需旋转的角度
  681. * */
  682. bool Navigation::Rotation_mpc_once(Pose2d current_to_target, Navigation::stLimit limit_wmg, std::vector<double> &out,
  683. bool all_direct) {
  684. if (PoseTimeout() == true) {
  685. printf(" Rotation_mpc_once Error:Pose is timeout \n");
  686. return false;
  687. }
  688. if (timedV_.timeout() == true || timedA_.timeout() == true) {
  689. printf(" Rotation_mpc_once Error:V/A is timeout \n");
  690. return false;
  691. }
  692. Pose2d pose = timedPose_.Get();
  693. double line_velocity = timedV_.Get(); //从plc获取状态
  694. double angular_velocity = timedA_.Get();
  695. Eigen::VectorXd statu = Eigen::VectorXd::Zero(5);//agv状态
  696. statu[0] = pose.x();
  697. statu[1] = pose.y();
  698. statu[2] = pose.theta();
  699. statu[3] = line_velocity;
  700. statu[4] = angular_velocity;
  701. NavParameter::MPC_parameter mpc_parameter = parameter_.x_mpc_parameter();
  702. double obs_w = 0.95;//0.85;
  703. double obs_h = 1.55;//1.45;
  704. MpcError ret = failed;
  705. Pose2d brother = timedBrotherPose_.Get();
  706. Pose2d brother_in_self = Pose2d::relativePose(brother, pose);
  707. // std::cout<<" brother_in_self: "<<brother_in_self<<std::endl;
  708. if (move_mode_ == eDouble) {
  709. brother_in_self = Pose2d(pose.x() + 100, pose.y() + 100, 0);
  710. }
  711. RotateMPC MPC(brother_in_self, obs_w, obs_h, limit_wmg.min, limit_wmg.max);
  712. RotateMPC::MPC_parameter parameter = {mpc_parameter.shortest_radius(), mpc_parameter.dt(),
  713. mpc_parameter.acc_velocity(), mpc_parameter.acc_angular()};
  714. ret = MPC.solve(current_to_target, statu, parameter, out);
  715. if (ret == no_solution) {
  716. printf(" Rotation_mpc solve no solution set v/w = 0\n");
  717. out.clear();
  718. out.push_back(0);
  719. } else {
  720. double min_angular_velocity = 3.0 / 180 * M_PI;
  721. if (fabs(out[0]) < min_angular_velocity) {
  722. if (out[0] > 0)
  723. out[0] = min_angular_velocity;
  724. else if (out[0] < 0)
  725. out[0] = -min_angular_velocity;
  726. else {}
  727. }
  728. }
  729. return ret == success || ret == no_solution;
  730. }
  731. bool Navigation::mpc_once(Trajectory traj, stLimit limit_v, std::vector<double> &out, bool directY) {
  732. if (PoseTimeout() == true) {
  733. printf(" MPC once Error:Pose is timeout \n");
  734. return false;
  735. }
  736. if (timedV_.timeout() == true || timedA_.timeout() == true) {
  737. printf(" MPC once Error:V/A is timeout \n");
  738. return false;
  739. }
  740. if (traj.size() == 0) {
  741. printf("traj size ==0\n");
  742. return false;
  743. }
  744. Pose2d pose = timedPose_.Get();
  745. double velocity = timedV_.Get(); //从plc获取状态
  746. double angular = timedA_.Get();
  747. Eigen::VectorXd statu = Eigen::VectorXd::Zero(5);//agv状态
  748. statu[0] = pose.x();
  749. statu[1] = pose.y();
  750. statu[2] = pose.theta();
  751. statu[3] = velocity;
  752. statu[4] = angular;
  753. Trajectory optimize_trajectory;
  754. Trajectory selected_trajectory;
  755. NavParameter::MPC_parameter mpc_parameter = parameter_.x_mpc_parameter();
  756. double obs_w = 0.95;//0.85;
  757. double obs_h = 1.55;//1.45;
  758. if (directY == true) {
  759. //将车身朝向旋转90°,车身朝向在(-pi,pi]
  760. statu[2] += M_PI / 2;
  761. if (statu[2] > M_PI)
  762. statu[2] -= 2 * M_PI;
  763. mpc_parameter = parameter_.y_mpc_parameter();
  764. obs_w = 0.95;//0.85;
  765. obs_h = 1.55;//1.45;
  766. }
  767. Pose2d brother = timedBrotherPose_.Get();
  768. Pose2d relative = Pose2d::relativePose(brother, pose);
  769. if (directY)
  770. relative = Pose2d::relativePose(brother.rotate(brother.x(), brother.y(), M_PI / 2),
  771. pose.rotate(pose.x(), pose.y(), M_PI / 2));//计算另一节在当前小车坐标系下的坐标
  772. //std::cout<<"pose:"<<pose<<", brother:"<<brother<<", relative:"<<relative<<std::endl;
  773. if (move_mode_ == eDouble)
  774. relative = Pose2d(-1e8, -1e8, 0);
  775. MpcError ret = failed;
  776. LoadedMPC MPC(relative, obs_w, obs_h, limit_v.min, limit_v.max);
  777. LoadedMPC::MPC_parameter parameter = {mpc_parameter.shortest_radius(), mpc_parameter.dt(),
  778. mpc_parameter.acc_velocity(), mpc_parameter.acc_angular()};
  779. //printf(" r:%f dt:%f acc:%f acc_a:%f\n",mpc_parameter.shortest_radius(),
  780. // mpc_parameter.dt(),mpc_parameter.acc_velocity(),mpc_parameter.acc_angular());
  781. ret = MPC.solve(traj, traj[traj.size() - 1], statu, parameter,
  782. out, selected_trajectory, optimize_trajectory);
  783. //std::cout<<" traj size %d %d -------- "<<selected_trajectory.size()<<","<<optimize_trajectory.size()<<std::endl;
  784. if (ret == no_solution) {
  785. printf(" mpc solve no solution set v/w = 0\n");
  786. out.clear();
  787. out.push_back(0);
  788. out.push_back(0);
  789. }
  790. predict_traj_.reset(optimize_trajectory, 1);
  791. selected_traj_.reset(selected_trajectory, 1);
  792. return ret == success || ret == no_solution;
  793. }
  794. bool Navigation::IsArrived(NavMessage::PathNode targetNode) {
  795. if (timedPose_.timeout() || timedV_.timeout() || timedA_.timeout()) {
  796. printf(" pose / v / w timeout,IsArrived return false\n");
  797. return false;
  798. }
  799. Pose2d current = timedPose_.Get();
  800. double x = current.x();
  801. double y = current.y();
  802. double tx = targetNode.x();
  803. double ty = targetNode.y();
  804. double l = fabs(targetNode.l());
  805. double w = fabs(targetNode.w());
  806. double theta = -targetNode.theta();
  807. if (l < 1e-10 || w < 1e-10) {
  808. printf("IsArrived: Error target l or w == 0\n");
  809. return false;
  810. }
  811. double a = (x - tx) * cos(theta) - (y - ty) * sin(theta);
  812. double b = (x - tx) * sin(theta) + (y - ty) * cos(theta);
  813. if (pow(a / l, 8) + pow(b / w, 8) <= 1) {
  814. if (fabs(timedV_.Get()) < 0.06 && fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  815. printf(" Arrived target: %f %f l:%f w:%f theta:%f\n", tx, ty, l, w, theta);
  816. return true;
  817. }
  818. }
  819. return false;
  820. }
  821. void Navigation::SendMoveCmd(int mode, ActionType type,
  822. double v, double angular) {
  823. if (monitor_) {
  824. monitor_->set_speed(mode, type, v, angular);
  825. if (type == eRotation)
  826. RWheel_position_ = eR;
  827. if (type == eVertical)
  828. RWheel_position_ = eX;
  829. if (type == eHorizontal)
  830. RWheel_position_ = eY;
  831. }
  832. }
  833. bool Navigation::clamp_close() {
  834. if (monitor_) {
  835. printf("Clamp closing...\n");
  836. monitor_->clamp_close(move_mode_);
  837. actionType_ = eClampClose;
  838. while (cancel_ == false) {
  839. if (timed_clamp_.timeout()) {
  840. printf("timed clamp is timeout\n");
  841. return false;
  842. }
  843. if (timed_clamp_.Get() == eClosed)
  844. return true;
  845. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  846. monitor_->clamp_close(move_mode_);
  847. actionType_ = eClampClose;
  848. }
  849. return false;
  850. }
  851. return false;
  852. }
  853. bool Navigation::clamp_open() {
  854. if (monitor_) {
  855. printf("Clamp openning...\n");
  856. monitor_->clamp_open(move_mode_);
  857. actionType_ = eClampOpen;
  858. while (cancel_ == false) {
  859. if (timed_clamp_.timeout()) {
  860. printf("timed clamp is timeout\n");
  861. return false;
  862. }
  863. if (timed_clamp_.Get() == eOpened)
  864. return true;
  865. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  866. monitor_->clamp_open(move_mode_);
  867. actionType_ = eClampOpen;
  868. }
  869. return false;
  870. }
  871. return false;
  872. }
  873. bool Navigation::lifter_rise() {
  874. if (monitor_) {
  875. printf("Lifter upping...\n");
  876. monitor_->lifter_rise(move_mode_);
  877. actionType_ = eLifterRise;
  878. while (cancel_ == false) {
  879. if (timed_lifter_.timeout()) {
  880. printf("timed lifter is timeout\n");
  881. return false;
  882. }
  883. if (timed_lifter_.Get() == eRose)
  884. return true;
  885. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  886. monitor_->lifter_rise(move_mode_);
  887. actionType_ = eLifterRise;
  888. }
  889. return false;
  890. }
  891. return false;
  892. }
  893. bool Navigation::lifter_down() {
  894. if (monitor_) {
  895. printf("Lifter downing...\n");
  896. monitor_->lifter_down(move_mode_);
  897. actionType_ = eLifterDown;
  898. while (cancel_ == false) {
  899. if (timed_lifter_.timeout()) {
  900. printf("timed lifter is timeout\n");
  901. return false;
  902. }
  903. if (timed_lifter_.Get() == eDowned)
  904. return true;
  905. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  906. monitor_->lifter_down(move_mode_);
  907. actionType_ = eLifterDown;
  908. }
  909. return false;
  910. }
  911. return false;
  912. }
  913. Navigation::MpcResult Navigation::MpcToTarget(NavMessage::PathNode node, stLimit limit_v, bool autoDirect) {
  914. if (IsArrived(node)) {
  915. printf(" current already in target completed !!!\n");
  916. return eMpcSuccess;
  917. }
  918. if (inited_ == false) {
  919. printf(" navigation has not inited\n");
  920. return eMpcFailed;
  921. }
  922. if (PoseTimeout()) {
  923. printf(" navigation Error:Pose is timeout \n");
  924. return eMpcFailed;
  925. }
  926. Pose2d current = timedPose_.Get();
  927. Pose2d target(node.x(), node.y(), 0);
  928. //生成轨迹
  929. Trajectory traj = Trajectory::create_line_trajectory(current, target);
  930. if (traj.size() == 0)
  931. return eMpcSuccess;
  932. //判断 巡线方向
  933. bool directY = false;
  934. if (autoDirect) {
  935. Pose2d target_relative = Pose2d::relativePose(target, timedPose_.Get());
  936. if (fabs(target_relative.y()) > fabs(target_relative.x())) { //目标轨迹点在当前点Y轴上
  937. std::cout << " MPC Y axis target_relative:" << target_relative << std::endl;
  938. directY = true;
  939. } else {
  940. std::cout << " MPC X axis target_relative:" << target_relative << std::endl;
  941. }
  942. }
  943. printf(" exec along autoDirect:%d\n", autoDirect);
  944. while (cancel_ == false) {
  945. std::this_thread::sleep_for(std::chrono::milliseconds(30));
  946. if (pause_ == true) {
  947. //发送暂停消息
  948. continue;
  949. }
  950. if (PoseTimeout()) {
  951. printf(" navigation Error:Pose is timeout \n");
  952. return eMpcFailed;
  953. }
  954. if (timedV_.timeout() || timedA_.timeout()) {
  955. printf(" navigation Error:v/a is timeout | __LINE__:%d \n", __LINE__);
  956. return eMpcFailed;
  957. }
  958. //判断是否到达终点
  959. if (IsArrived(node)) {
  960. if (Stop()) {
  961. printf(" exec along completed !!!\n");
  962. return eMpcSuccess;
  963. }
  964. }
  965. //一次变速
  966. std::vector<double> out;
  967. bool ret;
  968. TimerRecord::Execute([&, this]() {
  969. ret = mpc_once(traj, limit_v, out, directY);
  970. }, "mpc_once");
  971. if (ret == false) {
  972. Stop();
  973. return eMpcFailed;
  974. }
  975. /*
  976. * AGV 在终点附近低速巡航时,设置最小速度0.05
  977. */
  978. Pose2d target_in_agv = Pose2d::relativePose(target, timedPose_.Get());
  979. if (directY) {
  980. target_in_agv = target_in_agv.rotate(M_PI / 2.0);
  981. }
  982. if (Pose2d::abs(target_in_agv) < Pose2d(0.2, 2, M_PI * 2)) {
  983. if (out[0] >= 0 && out[0] < limit_v.min)
  984. out[0] = limit_v.min;
  985. if (out[0] < 0 && out[0] > -limit_v.min)
  986. out[0] = -limit_v.min;
  987. }
  988. //下发速度
  989. //printf(" nav input :%f out:%f\n",timedV_.Get(),out[0]);
  990. if (directY == false)
  991. SendMoveCmd(move_mode_, eVertical, out[0], out[1]);
  992. else
  993. SendMoveCmd(move_mode_, eHorizontal, out[0], out[1]);
  994. actionType_ = directY ? eHorizontal : eVertical;
  995. /*
  996. * 判断车辆是否在终点附近徘徊,无法到达终点
  997. */
  998. if (PossibleToTarget(node, directY) == false) {
  999. printf(" --------------MPC imposible to target -------------------------------------------\n");
  1000. if (fabs(timedV_.Get()) > 0.1 || fabs(timedA_.Get()) > 10 * M_PI / 180.0)
  1001. SlowlyStop();
  1002. else
  1003. Stop();
  1004. return eImpossibleToTarget;
  1005. }
  1006. }
  1007. return eMpcFailed;
  1008. }
  1009. bool Navigation::PossibleToTarget(NavMessage::PathNode targetNode, bool directY) {
  1010. if (timedPose_.timeout()) {
  1011. return false;
  1012. }
  1013. Pose2d current = timedPose_.Get();
  1014. double tx = targetNode.x();
  1015. double ty = targetNode.y();
  1016. double l = fabs(targetNode.l());
  1017. double w = fabs(targetNode.w());
  1018. double theta = -targetNode.theta();
  1019. double W = 2.45;
  1020. double L = 1.3;
  1021. double minYaw = 3 * M_PI / 180.0;
  1022. if (move_mode_ == eDouble) {
  1023. L = 1.3 + 2.7;
  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. }