navigation.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  1. //
  2. // Created by zx on 22-12-2.
  3. //
  4. #include "navigation.h"
  5. #include "loaded_mpc.h"
  6. #include "../define/TimerRecord.h"
  7. Navigation::~Navigation()
  8. {
  9. exit_=true;
  10. if(terminator_)
  11. delete terminator_;
  12. if(brotherEmqx_)
  13. delete brotherEmqx_;
  14. if(monitor_)
  15. delete monitor_;
  16. if(thread_!= nullptr)
  17. {
  18. if(thread_->joinable())
  19. thread_->join();
  20. delete thread_;
  21. }
  22. if(pubthread_!= nullptr)
  23. {
  24. if(pubthread_->joinable())
  25. pubthread_->join();
  26. delete pubthread_;
  27. }
  28. }
  29. /*
  30. * 高斯函数压缩,x=3
  31. */
  32. double limit_gause(double x,double min,double max){
  33. double r=x>=0?1.0:-1.0;
  34. double delta=max/1.0;
  35. return (max-(max-min)*exp(-x*x/(delta*delta)))*r;
  36. }
  37. double limit(double x,double min,double max){
  38. double ret=x;
  39. if(x>=0){
  40. if(x>max) ret=max;
  41. if(x<min) ret=min;
  42. }else{
  43. if(x<-max) ret=-max;
  44. if(x>-min) ret=-min;
  45. }
  46. return ret;
  47. }
  48. double next_speed(double speed,double target_speed,double acc,double dt=0.1)
  49. {
  50. if(fabs(target_speed-speed)/dt<acc)
  51. {
  52. return target_speed;
  53. }
  54. else
  55. {
  56. double r=target_speed-speed>=0.?1.0:-1.0;
  57. return speed+r*acc*dt;
  58. }
  59. }
  60. bool Navigation::Init(const Navigation_parameter& parameter)
  61. {
  62. parameter_=parameter;
  63. AgvEmqx_parameter agv_p=parameter.agv_emqx();
  64. if(monitor_== nullptr) {
  65. monitor_ = new Monitor_emqx(agv_p.nodeid());
  66. if(monitor_->Connect(agv_p.ip(),agv_p.port())==false)
  67. {
  68. printf(" agv emqx connected failed\n");
  69. return false;
  70. }
  71. monitor_->set_speedcmd_topic(agv_p.pubspeedtopic());
  72. monitor_->AddCallback(agv_p.subposetopic(),Navigation::RobotPoseCallback,this);
  73. monitor_->AddCallback(agv_p.subspeedtopic(),Navigation::RobotSpeedCallback,this);
  74. }
  75. Emqx_parameter terminal_p=parameter.terminal_emqx();
  76. if(terminator_== nullptr) {
  77. terminator_ = new Terminator_emqx(terminal_p.nodeid());
  78. if(terminator_->Connect(terminal_p.ip(),terminal_p.port())==false)
  79. {
  80. printf(" terminator emqx connected failed\n");
  81. return false;
  82. }
  83. terminator_->AddCallback(terminal_p.subnavcmdtopic(),Navigation::NavCmdCallback,this);
  84. }
  85. if(parameter.has_brother_emqx()) {
  86. BrotherEmqx brotherEmqx = parameter.brother_emqx();
  87. if (brotherEmqx_ == nullptr) {
  88. brotherEmqx_ = new Terminator_emqx(brotherEmqx.nodeid());
  89. if (brotherEmqx_->Connect(brotherEmqx.ip(), brotherEmqx.port()) == true) {
  90. brotherEmqx_->AddCallback(brotherEmqx.subbrotherstatutopic(), Navigation::BrotherAgvStatuCallback, this);
  91. }else{
  92. printf(" brother emqx connected failed\n");
  93. // return false;
  94. }
  95. }
  96. }
  97. inited_=true;
  98. if(pubthread_!= nullptr)
  99. {
  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. {
  111. Navigation* navigator=(Navigation*)context;
  112. NavMessage::LidarOdomStatu statu;
  113. if(msg.toProtoMessage(statu))
  114. {
  115. navigator->ResetPose(Pose2d(statu.x(),statu.y(),statu.theta()));
  116. }
  117. }
  118. void Navigation::HandleAgvStatu(const MqttMsg& msg)
  119. {
  120. NavMessage::AgvStatu speed;
  121. if(msg.toProtoMessage(speed))
  122. {
  123. ResetStatu(speed.v(),speed.w());
  124. ResetClamp((ClampStatu)speed.clamp());
  125. }
  126. }
  127. void Navigation::RobotSpeedCallback(const MqttMsg& msg,void* context)
  128. {
  129. Navigation* navigator=(Navigation*)context;
  130. navigator->HandleAgvStatu(msg);
  131. }
  132. void Navigation::pubStatuThreadFuc(void* p) {
  133. Navigation *navogator = (Navigation *) p;
  134. if (navogator) {
  135. while (navogator->exit_ == false) {
  136. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  137. NavMessage::NavStatu statu;
  138. statu.set_main_agv(false);
  139. navogator->publish_statu(statu);
  140. }
  141. }
  142. }
  143. void Navigation::publish_statu(NavMessage::NavStatu& statu) {
  144. //发布nav状态
  145. statu.set_statu(actionType_); //
  146. //printf(" statu:%d\n",actionType_);
  147. statu.set_move_mode(move_mode_);
  148. NavMessage::Action *current_action = nullptr;
  149. if (running_)
  150. {
  151. statu.set_key(global_navCmd_.key());
  152. /*std::queue<NavMessage::Action> actios = unfinished_cations_;
  153. while (actios.empty() == false) {
  154. //保存当前动作
  155. NavMessage::Action *act = statu.add_unfinished_actions();
  156. current_action = new NavMessage::Action(*act);
  157. act->CopyFrom(actios.front());
  158. actios.pop();
  159. }*/
  160. }
  161. //发布MPC信息
  162. //发布mpc 预选点
  163. if (selected_traj_.timeout() == false) {
  164. for (int i = 0; i < selected_traj_.Get().size(); ++i) {
  165. Pose2d pt = selected_traj_.Get()[i];
  166. NavMessage::Pose2d *pose = statu.mutable_selected_traj()->add_poses();
  167. pose->set_x(pt.x());
  168. pose->set_y(pt.y());
  169. pose->set_theta(pt.theta());
  170. }
  171. }
  172. //发布 mpc 预测点
  173. if (predict_traj_.timeout() == false) {
  174. for (int i = 0; i < predict_traj_.Get().size(); ++i) {
  175. Pose2d pt = predict_traj_.Get()[i];
  176. NavMessage::Pose2d *pose = statu.mutable_predict_traj()->add_poses();
  177. pose->set_x(pt.x());
  178. pose->set_y(pt.y());
  179. pose->set_theta(pt.theta());
  180. }
  181. }
  182. //std::cout<<"nav statu:"<<statu.DebugString()<<std::endl;
  183. MqttMsg msg;
  184. msg.fromProtoMessage(statu);
  185. if(terminator_)
  186. terminator_->Publish(parameter_.terminal_emqx().pubnavstatutopic(),msg);
  187. //发布位姿 ------robot状态--------------------------
  188. NavMessage::RobotStatu robot;
  189. if(CreateRobotStatuMsg(robot)) {
  190. if (terminator_) {
  191. MqttMsg msg;
  192. msg.fromProtoMessage(robot);
  193. terminator_->Publish(parameter_.terminal_emqx().pubstatutopic(), msg);
  194. }
  195. }
  196. }
  197. bool Navigation::CreateRobotStatuMsg(NavMessage::RobotStatu& robotStatu)
  198. {
  199. //printf(" %d %d %d \n",timedPose_.timeout(),timedV_.timeout(),timedA_.timeout());
  200. if (timedPose_.timeout() == false) {
  201. Pose2d pose = timedPose_.Get();
  202. robotStatu.set_x(pose.x());
  203. robotStatu.set_y(pose.y());
  204. robotStatu.set_theta(pose.theta());
  205. if((timedV_.timeout() == false && timedA_.timeout() == false)) {
  206. NavMessage::AgvStatu plc;
  207. plc.set_v(timedV_.Get());
  208. plc.set_w(timedA_.Get());
  209. plc.set_clamp(timed_clamp_.Get());
  210. //printf(" timed_clamp_:%d\n ",timed_clamp_.Get());
  211. robotStatu.mutable_agvstatu()->CopyFrom(plc);
  212. }
  213. return true;
  214. }
  215. return false;
  216. }
  217. void Navigation::ResetStatu(double v,double a)
  218. {
  219. timedV_.reset(v,0.5);
  220. timedA_.reset(a,0.5);
  221. }
  222. void Navigation::ResetClamp(ClampStatu statu){
  223. timed_clamp_.reset(statu,1);
  224. }
  225. void Navigation::ResetPose(const Pose2d& pose)
  226. {
  227. timedPose_.reset(pose,0.5);
  228. }
  229. bool Navigation::Start(const NavMessage::NavCmd& cmd)
  230. {
  231. if(unfinished_cations_.empty()==false) //正在运行中,上一次指令未完成
  232. {
  233. if(pause_)
  234. {
  235. pause_=false;
  236. return true;
  237. }
  238. printf(" navigation is running pls cancel before\n");
  239. return false;
  240. }
  241. if(thread_!= nullptr)
  242. {
  243. if(thread_->joinable())
  244. thread_->join();
  245. delete thread_;
  246. }
  247. //add 先检查当前点与起点的距离
  248. global_navCmd_=cmd;
  249. if(cmd.action()==6)
  250. {
  251. for (int i = 0; i < cmd.newactions_size(); ++i)
  252. newUnfinished_cations_.push(cmd.newactions(i));
  253. }else {
  254. for (int i = 0; i < cmd.actions_size(); ++i)
  255. unfinished_cations_.push(cmd.actions(i));
  256. }
  257. thread_=new std::thread(&Navigation::navigatting,this);
  258. return true;
  259. }
  260. void Navigation::Cancel()
  261. {
  262. cancel_=true;
  263. }
  264. bool Navigation::Stop() {
  265. if(monitor_)
  266. {
  267. monitor_->stop();
  268. while(cancel_==false)
  269. {
  270. if(timedV_.timeout()==false && timedA_.timeout()==false)
  271. {
  272. if(fabs(timedV_.Get())<1e-6 && fabs(timedA_.Get())<1e-6)
  273. return true;
  274. else
  275. monitor_->stop();
  276. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  277. }else{
  278. printf("Stop failed V/A timeout\n");
  279. return false;
  280. }
  281. }
  282. }
  283. return false;
  284. }
  285. void Navigation::Pause()
  286. {
  287. if(Stop())
  288. pause_=true;
  289. }
  290. Navigation::Navigation()
  291. {
  292. move_mode_=Monitor_emqx::eSingle;
  293. thread_= nullptr;
  294. monitor_= nullptr;
  295. terminator_= nullptr;
  296. timedBrotherPose_.reset(Pose2d(-100,0,0),0.1);
  297. }
  298. void Navigation::BrotherAgvStatuCallback(const MqttMsg& msg,void* context)
  299. {
  300. Navigation* navigator=(Navigation*)context;
  301. NavMessage::LidarOdomStatu brother_statu;
  302. if(msg.toProtoMessage(brother_statu)==false) {
  303. std::cout<<" msg transform to AGVStatu failed,msg:"<<msg.data()<<std::endl;
  304. return;
  305. }
  306. //std::cout<<brother_nav.DebugString()<<std::endl<<std::endl;
  307. Pose2d pose(brother_statu.x(),brother_statu.y(),brother_statu.theta());
  308. navigator->timedBrotherPose_.reset(pose,1);
  309. navigator->timedBrotherV_.reset(brother_statu.v(),1);
  310. navigator->timedBrotherA_.reset(brother_statu.vth(),1);
  311. }
  312. void Navigation::HandleNavCmd(const NavMessage::NavCmd& cmd)
  313. {
  314. if(cmd.action()==3)
  315. {
  316. printf(" Nav cancel\n");
  317. Cancel();
  318. return ;
  319. }
  320. if(cmd.action()==2) {
  321. printf(" Nav continue\n");
  322. pause_=false;
  323. return ;
  324. }
  325. if(cmd.action()==1) {
  326. printf(" Nav pause\n");
  327. Pause();
  328. return ;
  329. }
  330. if(cmd.action()==0||cmd.action()==6)
  331. {
  332. Start(cmd);
  333. }
  334. else
  335. printf(" Invalid action ,action:%d\n",cmd.action());
  336. }
  337. void Navigation::NavCmdCallback(const MqttMsg& msg,void* context)
  338. {
  339. NavMessage::NavCmd cmd;
  340. if(msg.toProtoMessage(cmd)==false) {
  341. printf(" msg transform to NavCmd failed ..!!\n");
  342. return;
  343. }
  344. Navigation* navigator=(Navigation*)context;
  345. navigator->HandleNavCmd(cmd);
  346. }
  347. bool Navigation::execute_adjust_action(const Pose2d& target,const Pose2d& target_diff,stLimit limit_v,
  348. stLimit limit_h,stLimit limit_rotate,bool anyDitect)
  349. {
  350. std::cout<<" adjust target:"<<target<<" target diff:"<<target_diff<<std::endl;
  351. if(inited_==false) {
  352. printf(" navigation has not inited\n");
  353. return false;
  354. }
  355. Pose2d accuracy=target_diff;
  356. Pose2d thresh=Pose2d::abs(accuracy);
  357. int action=0; //1 原地旋转,2横移,3前进
  358. while(cancel_==false) {
  359. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  360. if (pause_ == true) {
  361. //发送暂停消息
  362. continue;
  363. }
  364. if (timedPose_.timeout() || timedV_.timeout() || timedA_.timeout()) {
  365. printf(" navigation Error:Pose/v/a is timeout \n");
  366. break;
  367. }
  368. //判断是否到达目标点
  369. if (IsArrived(timedPose_.Get(), timedV_.Get(), timedA_.Get(), target, accuracy,anyDitect)) {
  370. if(Stop()) {
  371. printf("adjust completed anyDitect :%d\n",anyDitect);
  372. return true;
  373. }
  374. return false;
  375. }
  376. //计算目标点在当前pose下的pose
  377. Pose2d diff = Pose2d::relativePose(target, timedPose_.Get());
  378. //停止状态
  379. if (action == 0) {
  380. //
  381. if (Pose2d::abs(diff).x() > thresh.x()) {
  382. //前进
  383. action = 3;
  384. }else if (Pose2d::abs(diff).y() > thresh.y()) {
  385. //横移
  386. action = 2;
  387. }
  388. else if (Pose2d::abs(diff).theta() > thresh.theta()) {
  389. action = 1; //原地旋转
  390. }
  391. }
  392. else
  393. {
  394. double acc_v=2.0;
  395. double acc_angular=20.0*M_PI/180.0;
  396. double dt=0.1;
  397. if (action == 1) {
  398. if (Pose2d::abs(diff).theta() > thresh.theta()) {
  399. float diff_yaw=diff.theta();
  400. if(anyDitect==true)
  401. {
  402. int n=int(diff_yaw/(M_PI/4.0));
  403. if (n%2==1)
  404. {
  405. if(n>0)
  406. diff_yaw=diff_yaw-float((n+1)/2)*M_PI/2.0;
  407. else
  408. diff_yaw=diff_yaw-float((n-1)/2)*M_PI/2.0;
  409. }else{
  410. diff_yaw=diff_yaw-float(n/2)*M_PI/2.0;
  411. }
  412. }
  413. double theta = limit_gause(diff_yaw,limit_rotate.min,limit_rotate.max);
  414. double angular=next_speed(timedA_.Get(),theta,acc_angular,dt);
  415. double limit_angular=limit(angular,limit_rotate.min,limit_rotate.max);
  416. SendMoveCmd(move_mode_,Monitor_emqx::eRotate, 0, limit_angular);
  417. actionType_=eRotation;
  418. printf(" Ratate | input anguar:%f,next angular:%f,down:%f diff:%f anyDitect:%d\n",
  419. timedA_.Get(),angular,limit_angular,diff_yaw,anyDitect);
  420. continue;
  421. }
  422. }
  423. if (action == 2) {
  424. if (Pose2d::abs(diff).y() > thresh.y()) {
  425. double hv=limit_gause(diff.y(),limit_h.min,limit_h.max);
  426. double velocity=limit(next_speed(timedV_.Get(),hv,acc_v,dt),limit_h.min,limit_h.max);
  427. SendMoveCmd(move_mode_,Monitor_emqx::eHorizontal,velocity , 0);
  428. actionType_=eHorizon;
  429. printf(" Horizontal input:%f out:%f\n",timedV_.Get(),velocity);
  430. continue;
  431. }
  432. }
  433. if (action == 3) {
  434. if (Pose2d::abs(diff).x() > thresh.x()) {
  435. double v=limit_gause(diff.x(),limit_v.min,limit_v.max);
  436. double velocity=limit(next_speed(timedV_.Get(),v,acc_v,dt),limit_v.min,limit_v.max);
  437. SendMoveCmd(move_mode_,Monitor_emqx::eMPC, velocity, 0);
  438. actionType_=eVertical;
  439. printf(" Vrtical input:%f,out:%f\n",timedV_.Get(),velocity);
  440. continue;
  441. }
  442. }
  443. if(Stop()) {
  444. printf(" monitor type :%d completed!!! reset action type!!!\n", action);
  445. action = 0;
  446. }
  447. }
  448. }
  449. return false;
  450. }
  451. bool Navigation::execute_nodes(NavMessage::NewAction action)
  452. {
  453. if(action.type()==3 || action.type()==4) //最优动作导航 or 导航中保证朝向严格一致
  454. {
  455. if(!action.has_nodevelocitylimit() || !action.has_nodeangularlimit()||
  456. !action.has_adjustvelocitylimit()|| !action.has_adjusthorizonlimit()
  457. || action.pathnodes_size()==0) {
  458. std::cout << "execute pathNodes failed ,Action invalid:" << action.DebugString() << std::endl;
  459. return false;
  460. }
  461. bool anyDirect=(action.type()==3);
  462. //原地调整起点
  463. NavMessage::PathNode first=action.pathnodes(0);
  464. //速度限制
  465. stLimit adjust_x={ action.adjustvelocitylimit().min(),action.adjustvelocitylimit().max() };
  466. stLimit adjust_h={ action.adjusthorizonlimit().min(),action.adjusthorizonlimit().max() };
  467. stLimit adjust_angular={ action.nodeangularlimit().min(),action.nodeangularlimit().max() };
  468. stLimit mpc_velocity={ action.nodevelocitylimit().min(),action.nodevelocitylimit().max() };
  469. //目标,精度
  470. double first_yaw=timedPose_.Get().theta();
  471. if(1<action.pathnodes_size()){
  472. NavMessage::PathNode next=action.pathnodes(1);
  473. first_yaw=Pose2d::vector2yaw(next.pose().x()-first.pose().x(),next.pose().y()-first.pose().y());
  474. }
  475. Pose2d first_target(first.pose().x(),first.pose().y(),first_yaw);
  476. Pose2d first_accuracy(first.accuracy().x(),first.accuracy().y(),first.accuracy().theta());
  477. execute_adjust_action(first_target,first_accuracy,adjust_x,adjust_h,adjust_angular,anyDirect);
  478. Pose2d last_node=first_target;
  479. for(int i=1;i< action.pathnodes_size();++i)
  480. {
  481. NavMessage::PathNode node = action.pathnodes(i);
  482. /// 巡线到目标点,判断巡线方向
  483. Pose2d target(node.pose().x(), node.pose().y(), node.pose().theta());
  484. Pose2d accuracy(node.accuracy().x(), node.accuracy().y(), node.accuracy().theta());
  485. if (execute_along_action(last_node, target, accuracy, mpc_velocity, anyDirect) == false)
  486. return false;
  487. //不是最后一个点,则原地当前点朝向
  488. if(i!=action.pathnodes_size()-1)
  489. {
  490. //目标,精度
  491. double adjust_yaw=timedPose_.Get().theta();
  492. NavMessage::PathNode next=action.pathnodes(i+1);
  493. adjust_yaw=Pose2d::vector2yaw(next.pose().x()-node.pose().x(),next.pose().y()-node.pose().y());
  494. Pose2d adjust_target(node.pose().x(),node.pose().y(),adjust_yaw);
  495. Pose2d adjust_accuracy(node.accuracy().x(),node.accuracy().y(),node.accuracy().theta());
  496. execute_adjust_action(adjust_target,adjust_accuracy,adjust_x,adjust_h,adjust_angular,anyDirect);
  497. last_node=adjust_target;
  498. }
  499. }
  500. return true;
  501. }
  502. printf("execute PathNode failed ,action type is not 3/4 :%d\n",action.type());
  503. return false;
  504. }
  505. bool Navigation::mpc_once(Trajectory traj,stLimit limit_v,std::vector<double>& out,bool directY) {
  506. if (timedPose_.timeout() == true && timedV_.timeout() == false && timedA_.timeout() == false) {
  507. printf(" MPC once Error:Pose/V/A is timeout \n");
  508. return false;
  509. }
  510. if (traj.size() == 0) {
  511. printf("traj size ==0\n");
  512. return false;
  513. }
  514. Pose2d pose = timedPose_.Get();
  515. double velocity = timedV_.Get(); //从plc获取状态
  516. double angular = timedA_.Get();
  517. Pose2d brother = timedBrotherPose_.Get();
  518. Pose2d relative = Pose2d::relativePose(brother, pose);//计算另一节在当前小车坐标系下的坐标
  519. if (move_mode_ == Monitor_emqx::ActionMode::eMain)
  520. relative = Pose2d(-1e8, -1e8, 0);
  521. Eigen::VectorXd statu = Eigen::VectorXd::Zero(5);//agv状态
  522. statu[0] = pose.x();
  523. statu[1] = pose.y();
  524. statu[2] = pose.theta();
  525. statu[3] = velocity;
  526. statu[4] = angular;
  527. Trajectory optimize_trajectory;
  528. Trajectory selected_trajectory;
  529. if (directY == true) {
  530. //将车身朝向旋转90°,车身朝向在(-pi,pi]
  531. statu[2] += M_PI / 2;
  532. if (statu[2] > M_PI)
  533. statu[2] -= 2 * M_PI;
  534. }
  535. bool ret = false;
  536. LoadedMPC MPC(relative, limit_v.min, limit_v.max);
  537. ret = MPC.solve(traj, traj[traj.size() - 1], statu, out, selected_trajectory, optimize_trajectory);
  538. //std::cout<<" traj size %d %d -------- "<<selected_trajectory.size()<<","<<optimize_trajectory.size()<<std::endl;
  539. predict_traj_.reset(optimize_trajectory, 1);
  540. selected_traj_.reset(selected_trajectory, 1);
  541. return ret;
  542. }
  543. bool Navigation::IsArrived(const Pose2d& cur,double velocity,double angular,
  544. const Pose2d& target,const Pose2d& diff,bool nearest_yaw)
  545. {
  546. //std::cout<<cur<<","<<target<<","<<nearest_yaw<<",v"<<velocity<<"a:"<<angular<<"diff:"<<diff<<std::endl;
  547. Pose2d distance=Pose2d::relativePose(target,cur);
  548. Pose2d absDiff=Pose2d::abs(distance);
  549. if(nearest_yaw==false) {
  550. if (absDiff < diff) {
  551. if (fabs(velocity) < 0.05 && fabs(angular) < 10 * M_PI / 180.0)
  552. return true;
  553. }
  554. }else{
  555. if(absDiff.x()<diff.x() && absDiff.y()<diff.x())
  556. {
  557. double theta=absDiff.theta();
  558. int n=int(theta/(M_PI/4.0));
  559. if (n%2==1)
  560. {
  561. theta=float((n+1)/2)*M_PI/2.0-theta;
  562. }else{
  563. theta=theta-float(n/2)*M_PI/2.0;
  564. }
  565. if(theta<diff.theta() && fabs(velocity) < 0.05 && fabs(angular) < 10 * M_PI / 180.0)
  566. return true;
  567. }
  568. }
  569. //std::cout<<"distance:"<<distance<<" diff:"<<diff<<" v:"<<velocity<<" a:"<<angular<<std::endl;
  570. return false;
  571. }
  572. void Navigation::SendMoveCmd(Monitor_emqx::ActionMode mode,Monitor_emqx::ActionType type,
  573. double v,double angular){
  574. if(monitor_) {
  575. monitor_->set_speed(mode, type, v, angular);
  576. }
  577. }
  578. bool Navigation::clamp_close()
  579. {
  580. if(monitor_) {
  581. monitor_->clamp_close(move_mode_);
  582. actionType_=eClampClose;
  583. while (cancel_ == false) {
  584. if (timed_clamp_.timeout()) {
  585. printf("timed clamp is timeout\n");
  586. return false;
  587. }
  588. if (timed_clamp_.Get() == eClosed)
  589. return true;
  590. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  591. monitor_->clamp_close(move_mode_);
  592. actionType_=eClampClose;
  593. }
  594. return false;
  595. }
  596. return false;
  597. }
  598. bool Navigation::clamp_open() {
  599. if(monitor_) {
  600. monitor_->clamp_open(move_mode_);
  601. actionType_=eClampOpen;
  602. while(cancel_==false)
  603. {
  604. if(timed_clamp_.timeout())
  605. {
  606. printf("timed clamp is timeout\n");
  607. return false;
  608. }
  609. if(timed_clamp_.Get()==eOpened)
  610. return true;
  611. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  612. monitor_->clamp_open(move_mode_);
  613. actionType_=eClampOpen;
  614. }
  615. return false;
  616. }
  617. return false;
  618. }
  619. bool Navigation::execute_along_action(const Pose2d& begin,const Pose2d& target,const Pose2d& target_diff,
  620. stLimit limit_v,bool autoDirect) {
  621. if (inited_ == false) {
  622. printf(" navigation has not inited\n");
  623. return false;
  624. }
  625. if (timedPose_.timeout()) {
  626. printf(" navigation Error:Pose is timeout \n");
  627. return false;
  628. }
  629. //生成轨迹
  630. Trajectory traj = Trajectory::create_line_trajectory(begin, target);
  631. if (traj.size() == 0)
  632. return true;
  633. //判断 巡线方向
  634. bool directY=false;
  635. if(autoDirect){
  636. Pose2d target_relative=Pose2d::relativePose(target,timedPose_.Get());
  637. if( fabs(target_relative.y()>fabs(target_relative.x()))) //目标轨迹点在当前点Y轴上
  638. directY=true;
  639. }
  640. printf(" exec along autoDirect:%d\n",autoDirect);
  641. while (cancel_ == false) {
  642. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  643. if (pause_ == true) {
  644. //发送暂停消息
  645. continue;
  646. }
  647. if (timedPose_.timeout() || timedV_.timeout() || timedA_.timeout()) {
  648. printf(" navigation Error:Pose/v/a is timeout \n");
  649. return false;
  650. }
  651. //判断是否到达终点
  652. if (IsArrived(timedPose_.Get(), timedV_.Get(), timedA_.Get(), target, target_diff,directY)) {
  653. if (Stop()) {
  654. printf(" exec along completed !!!\n");
  655. return true;
  656. }
  657. }
  658. /*
  659. * 判断周边是否有障碍物,半径r,当障碍物进入r内,停下等待,当障碍物远离 1.2*r,恢复
  660. * */
  661. if(move_mode_==Monitor_emqx::eSingle) {
  662. double r = 2.8;
  663. static bool obs_stoped = false;
  664. Pose2d obs_relative = Pose2d::relativePose(timedBrotherPose_.Get(), timedPose_.Get());
  665. double distance = sqrt(obs_relative.x() * obs_relative.x() + obs_relative.y() * obs_relative.y());
  666. if (obs_stoped == false) {
  667. if (distance < r && fabs(obs_relative.x()) > 0.2) {
  668. std::cout << "find obs stop to wait...." << std::endl;
  669. Stop();
  670. obs_stoped = true;
  671. continue;
  672. }
  673. } else {
  674. //障碍解除
  675. if (distance > 1.2 * r) {
  676. std::cout << "obs release continue MPC" << std::endl;
  677. obs_stoped = false;
  678. } else {
  679. continue;
  680. }
  681. }
  682. }
  683. //一次变速
  684. std::vector<double> out;
  685. bool ret;
  686. TimerRecord::Execute([&, this]() {
  687. ret = mpc_once(traj, limit_v, out,directY);
  688. }, "mpc_once");
  689. if (ret == false) {
  690. Stop();
  691. return false;
  692. }
  693. if(directY==false)
  694. SendMoveCmd(move_mode_, Monitor_emqx::eMPC, out[0], out[1]);
  695. else
  696. SendMoveCmd(move_mode_, Monitor_emqx::eHorizontal, out[0], out[1]);
  697. actionType_=eMPC;
  698. /*
  699. * 判断车辆是否在终点附近徘徊,无法到达终点
  700. */
  701. if (mpc_possible_to_end(target, target_diff) == false) {
  702. printf(" --------------MPC imposible to target -----------------------\n");
  703. Stop();
  704. //调整到目标点
  705. stLimit limitv, limitR;
  706. limitv.min = 0.05;
  707. limitv.max = 0.1;
  708. limitR.min = 2 * M_PI / 180.0;
  709. limitR.max = 10 * M_PI / 180.0;
  710. Pose2d accuracy(target_diff.x(),target_diff.y(),M_PI*2);
  711. if (execute_adjust_action(target, accuracy, limitv, limitv, limitR,false))
  712. return true;
  713. else
  714. return false;
  715. }
  716. //std::this_thread::sleep_for(std::chrono::milliseconds (400));
  717. }
  718. return false;
  719. }
  720. bool Navigation::mpc_possible_to_end(const Pose2d& target,const Pose2d& target_diff)
  721. {
  722. if(timedPose_.timeout()==false) {
  723. Pose2d diff = Pose2d::relativePose(target, timedPose_.Get());
  724. if (fabs(diff.y()) < target_diff.y() && fabs(diff.x()) < target_diff.x()) { //xy在精度内
  725. if (timedV_.timeout() == true)
  726. return false;
  727. if(fabs(timedV_.Get())<0.05 && fabs(diff.theta())>target_diff.theta())
  728. return false;
  729. return true;
  730. } else { //xy不在精度内
  731. if (fabs(diff.x()) < 1e-3)
  732. return false; //x已到达,Y未到达,则不可能到达目标点
  733. double theta = fabs(atan(diff.y() / diff.x()));
  734. if (theta > 5 * M_PI / 180.0) {
  735. if (timedV_.timeout() == true)
  736. return false;
  737. if (fabs(timedV_.Get()) < 0.05)
  738. return false;
  739. else
  740. return true;
  741. } else {
  742. return true;
  743. }
  744. }
  745. }
  746. return false;
  747. }
  748. void Navigation::navigatting()
  749. {
  750. if(inited_==false) {
  751. printf(" navigation has not inited\n");
  752. return ;
  753. }
  754. pause_=false;
  755. cancel_=false;
  756. running_=true;
  757. actionType_=eReady;
  758. printf(" navigation beg...\n");
  759. if(global_navCmd_.action()==6)
  760. {
  761. printf("exec new nav cmd ...\n");
  762. while(newUnfinished_cations_.empty()==false && cancel_==false)
  763. {
  764. std::cout<<"unfinished size:"<<newUnfinished_cations_.size()<<std::endl;
  765. NavMessage::NewAction act=newUnfinished_cations_.front();
  766. if(act.type()==5) {//夹持
  767. if(this->clamp_close()==false){
  768. printf("夹持failed ...\n");
  769. break;
  770. }
  771. }else if(act.type()==6){
  772. if(this->clamp_open()==false){
  773. printf("打开夹持 failed...\n");
  774. break;
  775. }
  776. }else if(act.type()==3 || act.type()==4){
  777. if(!execute_nodes(act))
  778. break;
  779. }else{
  780. printf(" action type 1/2 not handled !!\n");
  781. }
  782. newUnfinished_cations_.pop();
  783. }
  784. actionType_=eReady;
  785. Stop();
  786. if(cancel_==true) {
  787. printf(" navigation canceled\n");
  788. while(newUnfinished_cations_.empty()==false)
  789. newUnfinished_cations_.pop();
  790. }else {
  791. if (newUnfinished_cations_.empty())
  792. printf("navigation completed!!!\n");
  793. else{
  794. printf(" navigation Failed\n");
  795. while(newUnfinished_cations_.empty()==false)
  796. newUnfinished_cations_.pop();
  797. }
  798. }
  799. running_=false;
  800. return ;
  801. }
  802. //---------------------
  803. while(unfinished_cations_.empty()==false && cancel_==false)
  804. {
  805. NavMessage::Action act=unfinished_cations_.front();
  806. Pose2d target(act.target().x(),act.target().y(),act.target().theta());
  807. Pose2d target_diff(act.target_diff().x(),act.target_diff().y(),act.target_diff().theta());
  808. if(act.type()==1)
  809. {
  810. printf(" adjust to (%.3f %.3f %.3f) diff:(%.3f,%.3f,%.3f)\n",
  811. act.target().x(),act.target().y(),act.target().theta(),
  812. act.target_diff().x(),act.target_diff().y(),act.target_diff().theta());
  813. stLimit limit_angular,limit_velocity,limint_horize;
  814. limit_velocity.min=act.velocity_limit().min();
  815. limit_velocity.max=act.velocity_limit().max();
  816. limit_angular.min=act.angular_limit().min();
  817. limit_angular.max=act.angular_limit().max();
  818. limint_horize.min=act.horize_limit().min();
  819. limint_horize.max=act.horize_limit().max();
  820. if(execute_adjust_action(target,target_diff,limit_velocity,limint_horize,limit_angular,false)==false)
  821. {
  822. printf("execute adjust action failed\n");
  823. break;
  824. }
  825. }
  826. else if(act.type()==2)
  827. {
  828. Pose2d begin(act.begin().x(),act.begin().y(),act.begin().theta());
  829. stLimit limit_velocity;
  830. limit_velocity.min=act.velocity_limit().min();
  831. limit_velocity.max=act.velocity_limit().max();
  832. printf(" MPC to (%.3f %.3f %.3f) diff:(%.3f,%.3f,%.3f)\n",
  833. act.target().x(),act.target().y(),act.target().theta(),
  834. act.target_diff().x(),act.target_diff().y(),act.target_diff().theta());
  835. if(execute_along_action(begin,target,target_diff,limit_velocity,false)==false) {
  836. printf("execute along action failed\n");
  837. break;
  838. }
  839. }
  840. else if(act.type()==3) //夹持
  841. {
  842. if(this->clamp_close()==false)
  843. {
  844. printf("夹持failed ...\n");
  845. break;
  846. }
  847. }
  848. else if(act.type()==4)
  849. {
  850. if(this->clamp_open()==false)
  851. {
  852. printf("打开夹持 failed...\n");
  853. break;
  854. }
  855. }
  856. else
  857. {
  858. printf(" unknow action type:%d\n",act.type());
  859. break;
  860. }
  861. unfinished_cations_.pop();
  862. }
  863. actionType_=eReady;
  864. Stop();
  865. if(cancel_==true) {
  866. printf(" navigation canceled\n");
  867. while(unfinished_cations_.empty()==false)
  868. unfinished_cations_.pop();
  869. }else {
  870. if (unfinished_cations_.empty())
  871. printf("navigation completed!!!\n");
  872. else{
  873. printf(" navigation Failed\n");
  874. while(unfinished_cations_.empty()==false)
  875. unfinished_cations_.pop();
  876. }
  877. }
  878. running_=false;
  879. }