navigation.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  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 NavParameter::Navigation_parameter& parameter)
  61. {
  62. parameter_=parameter;
  63. NavParameter::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. NavParameter::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. NavParameter::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. if (running_)
  149. {
  150. statu.set_key(global_navCmd_.key());
  151. }
  152. //发布MPC信息
  153. //发布mpc 预选点
  154. if (selected_traj_.timeout() == false) {
  155. for (int i = 0; i < selected_traj_.Get().size(); ++i) {
  156. Pose2d pt = selected_traj_.Get()[i];
  157. NavMessage::Pose2d *pose = statu.mutable_selected_traj()->add_poses();
  158. pose->set_x(pt.x());
  159. pose->set_y(pt.y());
  160. pose->set_theta(pt.theta());
  161. }
  162. }
  163. //发布 mpc 预测点
  164. if (predict_traj_.timeout() == false) {
  165. for (int i = 0; i < predict_traj_.Get().size(); ++i) {
  166. Pose2d pt = predict_traj_.Get()[i];
  167. NavMessage::Pose2d *pose = statu.mutable_predict_traj()->add_poses();
  168. pose->set_x(pt.x());
  169. pose->set_y(pt.y());
  170. pose->set_theta(pt.theta());
  171. }
  172. }
  173. //std::cout<<"nav statu:"<<statu.DebugString()<<std::endl;
  174. MqttMsg msg;
  175. msg.fromProtoMessage(statu);
  176. if(terminator_)
  177. terminator_->Publish(parameter_.terminal_emqx().pubnavstatutopic(),msg);
  178. //发布位姿 ------robot状态--------------------------
  179. NavMessage::RobotStatu robot;
  180. if(CreateRobotStatuMsg(robot)) {
  181. if (terminator_) {
  182. MqttMsg msg;
  183. msg.fromProtoMessage(robot);
  184. terminator_->Publish(parameter_.terminal_emqx().pubstatutopic(), msg);
  185. }
  186. }
  187. }
  188. bool Navigation::CreateRobotStatuMsg(NavMessage::RobotStatu& robotStatu)
  189. {
  190. //printf(" %d %d %d \n",timedPose_.timeout(),timedV_.timeout(),timedA_.timeout());
  191. if (timedPose_.timeout() == false) {
  192. Pose2d pose = timedPose_.Get();
  193. robotStatu.set_x(pose.x());
  194. robotStatu.set_y(pose.y());
  195. robotStatu.set_theta(pose.theta());
  196. if((timedV_.timeout() == false && timedA_.timeout() == false)) {
  197. NavMessage::AgvStatu plc;
  198. plc.set_v(timedV_.Get());
  199. plc.set_w(timedA_.Get());
  200. plc.set_clamp(timed_clamp_.Get());
  201. //printf(" timed_clamp_:%d\n ",timed_clamp_.Get());
  202. robotStatu.mutable_agvstatu()->CopyFrom(plc);
  203. }
  204. return true;
  205. }
  206. return false;
  207. }
  208. void Navigation::ResetStatu(double v,double a)
  209. {
  210. timedV_.reset(v,0.5);
  211. timedA_.reset(a,0.5);
  212. }
  213. void Navigation::ResetClamp(ClampStatu statu){
  214. timed_clamp_.reset(statu,1);
  215. }
  216. void Navigation::ResetPose(const Pose2d& pose)
  217. {
  218. timedPose_.reset(pose,1.0);
  219. }
  220. bool Navigation::Start(const NavMessage::NavCmd& cmd)
  221. {
  222. if(newUnfinished_cations_.empty()==false) //正在运行中,上一次指令未完成
  223. {
  224. if(pause_)
  225. {
  226. pause_=false;
  227. return true;
  228. }
  229. printf(" navigation is running pls cancel before\n");
  230. return false;
  231. }
  232. if(thread_!= nullptr)
  233. {
  234. if(thread_->joinable())
  235. thread_->join();
  236. delete thread_;
  237. }
  238. //add 先检查当前点与起点的距离
  239. global_navCmd_=cmd;
  240. for (int i = 0; i < cmd.newactions_size(); ++i)
  241. newUnfinished_cations_.push(cmd.newactions(i));
  242. thread_=new std::thread(&Navigation::navigatting,this);
  243. return true;
  244. }
  245. void Navigation::Cancel()
  246. {
  247. cancel_=true;
  248. }
  249. bool Navigation::Stop() {
  250. if(monitor_)
  251. {
  252. monitor_->stop();
  253. while(cancel_==false)
  254. {
  255. if(timedV_.timeout()==false && timedA_.timeout()==false)
  256. {
  257. if(fabs(timedV_.Get())<1e-6 && fabs(timedA_.Get())<1e-6)
  258. return true;
  259. else
  260. monitor_->stop();
  261. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  262. }else{
  263. printf("Stop failed V/A timeout\n");
  264. return false;
  265. }
  266. }
  267. }
  268. return false;
  269. }
  270. void Navigation::Pause()
  271. {
  272. if(Stop())
  273. pause_=true;
  274. }
  275. Navigation::Navigation()
  276. {
  277. move_mode_=Monitor_emqx::eSingle;
  278. thread_= nullptr;
  279. monitor_= nullptr;
  280. terminator_= nullptr;
  281. timedBrotherPose_.reset(Pose2d(-100,0,0),0.1);
  282. }
  283. void Navigation::BrotherAgvStatuCallback(const MqttMsg& msg,void* context)
  284. {
  285. Navigation* navigator=(Navigation*)context;
  286. NavMessage::LidarOdomStatu brother_statu;
  287. if(msg.toProtoMessage(brother_statu)==false) {
  288. std::cout<<" msg transform to AGVStatu failed,msg:"<<msg.data()<<std::endl;
  289. return;
  290. }
  291. //std::cout<<brother_nav.DebugString()<<std::endl<<std::endl;
  292. Pose2d pose(brother_statu.x(),brother_statu.y(),brother_statu.theta());
  293. navigator->timedBrotherPose_.reset(pose,1);
  294. navigator->timedBrotherV_.reset(brother_statu.v(),1);
  295. navigator->timedBrotherA_.reset(brother_statu.vth(),1);
  296. }
  297. void Navigation::HandleNavCmd(const NavMessage::NavCmd& cmd)
  298. {
  299. if(cmd.action()==3)
  300. {
  301. printf(" Nav cancel\n");
  302. Cancel();
  303. return ;
  304. }
  305. if(cmd.action()==2) {
  306. printf(" Nav continue\n");
  307. pause_=false;
  308. return ;
  309. }
  310. if(cmd.action()==1) {
  311. printf(" Nav pause\n");
  312. Pause();
  313. return ;
  314. }
  315. if(cmd.action()==0||cmd.action()==6)
  316. {
  317. Start(cmd);
  318. }
  319. else
  320. printf(" Invalid action ,action:%d\n",cmd.action());
  321. }
  322. void Navigation::NavCmdCallback(const MqttMsg& msg,void* context)
  323. {
  324. NavMessage::NavCmd cmd;
  325. if(msg.toProtoMessage(cmd)==false) {
  326. printf(" msg transform to NavCmd failed ..!!\n");
  327. return;
  328. }
  329. Navigation* navigator=(Navigation*)context;
  330. navigator->HandleNavCmd(cmd);
  331. }
  332. bool Navigation::execute_adjust_action(const Pose2d& target,const Pose2d& target_diff,stLimit limit_v,
  333. stLimit limit_h,stLimit limit_rotate,bool anyDitect)
  334. {
  335. std::cout<<" adjust target:"<<target<<" target diff:"<<target_diff<<std::endl;
  336. if(inited_==false) {
  337. printf(" navigation has not inited\n");
  338. return false;
  339. }
  340. Pose2d accuracy=target_diff;
  341. Pose2d thresh=Pose2d::abs(accuracy);
  342. int action=0; //1 原地旋转,2横移,3前进
  343. while(cancel_==false) {
  344. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  345. if (pause_ == true) {
  346. //发送暂停消息
  347. continue;
  348. }
  349. if (timedPose_.timeout() || timedV_.timeout() || timedA_.timeout()) {
  350. printf(" navigation Error:Pose/v/a is timeout \n");
  351. break;
  352. }
  353. //判断是否到达目标点
  354. int direct=0;
  355. if(anyDitect) direct=2;
  356. if (IsArrived(timedPose_.Get(), timedV_.Get(), timedA_.Get(), target, accuracy,direct)) {
  357. if(Stop()) {
  358. printf("adjust completed anyDitect :%d\n",anyDitect);
  359. return true;
  360. }
  361. return false;
  362. }
  363. //计算目标点在当前pose下的pose
  364. Pose2d diff = Pose2d::relativePose(target, timedPose_.Get());
  365. //停止状态
  366. if (action == 0) {
  367. //
  368. if (Pose2d::abs(diff).x() > thresh.x()) {
  369. //前进
  370. action = 3;
  371. }else if (Pose2d::abs(diff).y() > thresh.y()) {
  372. //横移
  373. action = 2;
  374. }
  375. else if (Pose2d::abs(diff).theta() > thresh.theta()) {
  376. action = 1; //原地旋转
  377. }
  378. }
  379. else
  380. {
  381. double acc_v=0.6;
  382. double acc_angular=10.0*M_PI/180.0;
  383. double dt=0.1;
  384. if (action == 1) {
  385. float minYawDiff=diff.theta();
  386. if(anyDitect){
  387. Pose2d p0=timedPose_.Get();
  388. float yawdiff[4]={0};
  389. yawdiff[0]=diff.theta();
  390. yawdiff[1]=Pose2d::relativePose(target,p0-Pose2d(0,0,M_PI/2)).theta(); ////使用减法,保证角度在【-pi pi】
  391. yawdiff[2]=Pose2d::relativePose(target,p0-Pose2d(0,0,M_PI)).theta();
  392. yawdiff[3]=Pose2d::relativePose(target,p0-Pose2d(0,0,3*M_PI/2)).theta();
  393. for(int i=1;i<4;++i){
  394. if(fabs(yawdiff[i])<fabs(minYawDiff)){
  395. minYawDiff=yawdiff[i];
  396. }
  397. }
  398. }
  399. if (fabs(minYawDiff) > thresh.theta()) {
  400. double theta = limit_gause(minYawDiff,limit_rotate.min,limit_rotate.max);
  401. double angular=next_speed(timedA_.Get(),theta,acc_angular,dt);
  402. double limit_angular=limit(angular,limit_rotate.min,limit_rotate.max);
  403. SendMoveCmd(move_mode_,Monitor_emqx::eRotate, 0, limit_angular);
  404. actionType_=eRotation;
  405. printf(" Ratate | input anguar:%f,next angular:%f,down:%f diff:%f anyDitect:%d\n",
  406. timedA_.Get(),angular,limit_angular,minYawDiff,anyDitect);
  407. continue;
  408. }
  409. }
  410. if (action == 2) {
  411. if (Pose2d::abs(diff).y() > thresh.y()) {
  412. double hv=limit_gause(diff.y(),limit_h.min,limit_h.max);
  413. double velocity=limit(next_speed(timedV_.Get(),hv,acc_v,dt),limit_h.min,limit_h.max);
  414. SendMoveCmd(move_mode_,Monitor_emqx::eHorizontal,velocity , 0);
  415. actionType_=eHorizon;
  416. printf(" Horizontal input:%f out:%f\n",timedV_.Get(),velocity);
  417. continue;
  418. }
  419. }
  420. if (action == 3) {
  421. if (Pose2d::abs(diff).x() > thresh.x()) {
  422. double v=limit_gause(diff.x(),limit_v.min,limit_v.max);
  423. double velocity=limit(next_speed(timedV_.Get(),v,acc_v,dt),limit_v.min,limit_v.max);
  424. SendMoveCmd(move_mode_,Monitor_emqx::eMPC, velocity, 0);
  425. actionType_=eVertical;
  426. printf(" Vrtical input:%f,out:%f\n",timedV_.Get(),velocity);
  427. continue;
  428. }
  429. }
  430. if(Stop()) {
  431. printf(" monitor type :%d completed!!! reset action type!!!\n", action);
  432. action = 0;
  433. }
  434. }
  435. }
  436. return false;
  437. }
  438. bool Navigation::execute_nodes(NavMessage::NewAction action)
  439. {
  440. if(action.type()==3 || action.type()==4) //最优动作导航 or 导航中保证朝向严格一致
  441. {
  442. if(!action.has_nodevelocitylimit() || !action.has_nodeangularlimit()||
  443. !action.has_adjustvelocitylimit()|| !action.has_adjusthorizonlimit()
  444. || action.pathnodes_size()==0) {
  445. std::cout << "execute pathNodes failed ,Action invalid:" << action.DebugString() << std::endl;
  446. return false;
  447. }
  448. bool anyDirect=(action.type()==3);
  449. // if (move_mode_==Monitor_emqx::eMain) //双车模式静止自由方向做MPC
  450. // anyDirect=false;
  451. //原地调整起点
  452. NavMessage::PathNode first=action.pathnodes(0);
  453. //速度限制
  454. stLimit adjust_x={ action.adjustvelocitylimit().min(),action.adjustvelocitylimit().max() };
  455. stLimit adjust_h={ action.adjusthorizonlimit().min(),action.adjusthorizonlimit().max() };
  456. stLimit adjust_angular={ action.nodeangularlimit().min(),action.nodeangularlimit().max() };
  457. stLimit mpc_velocity={ action.nodevelocitylimit().min(),action.nodevelocitylimit().max() };
  458. //目标,精度
  459. double first_yaw=timedPose_.Get().theta();
  460. if(1<action.pathnodes_size()){
  461. NavMessage::PathNode next=action.pathnodes(1);
  462. first_yaw=Pose2d::vector2yaw(next.pose().x()-first.pose().x(),next.pose().y()-first.pose().y());
  463. }
  464. Pose2d first_target(first.pose().x(),first.pose().y(),first_yaw);
  465. Pose2d first_accuracy(first.accuracy().x(),first.accuracy().y(),first.accuracy().theta());
  466. execute_adjust_action(first_target,first_accuracy,adjust_x,adjust_h,adjust_angular,anyDirect);
  467. Pose2d last_node=first_target;
  468. for(int i=1;i< action.pathnodes_size();++i)
  469. {
  470. NavMessage::PathNode node = action.pathnodes(i);
  471. /// 巡线到目标点,判断巡线方向
  472. Pose2d target(node.pose().x(), node.pose().y(), node.pose().theta());
  473. Pose2d accuracy(node.accuracy().x(), node.accuracy().y(), node.accuracy().theta());
  474. if (execute_along_action(last_node, target, accuracy, mpc_velocity, anyDirect) == false)
  475. return false;
  476. //不是最后一个点,则原地当前点朝向
  477. if(i!=action.pathnodes_size()-1)
  478. {
  479. //目标,精度
  480. double adjust_yaw=timedPose_.Get().theta();
  481. NavMessage::PathNode next=action.pathnodes(i+1);
  482. adjust_yaw=Pose2d::vector2yaw(next.pose().x()-node.pose().x(),next.pose().y()-node.pose().y());
  483. Pose2d adjust_target(node.pose().x(),node.pose().y(),adjust_yaw);
  484. Pose2d adjust_accuracy(node.accuracy().x(),node.accuracy().y(),node.accuracy().theta());
  485. execute_adjust_action(adjust_target,adjust_accuracy,adjust_x,adjust_h,adjust_angular,anyDirect);
  486. last_node=adjust_target;
  487. }
  488. }
  489. return true;
  490. }
  491. printf("execute PathNode failed ,action type is not 3/4 :%d\n",action.type());
  492. return false;
  493. }
  494. bool Navigation::execute_vehicle_mode(NavMessage::NewAction action){
  495. if(action.type()==5 ) //最优动作导航 or 导航中保证朝向严格一致
  496. {
  497. if (!action.has_nodevelocitylimit() || !action.has_nodeangularlimit() ||
  498. !action.has_adjustvelocitylimit() || !action.has_adjusthorizonlimit()
  499. || action.pathnodes_size() == 0) {
  500. std::cout << "execute pathNodes failed ,Action invalid:" << action.DebugString() << std::endl;
  501. return false;
  502. //原地调整起点
  503. NavMessage::PathNode first=action.pathnodes(0);
  504. //速度限制
  505. stLimit adjust_x={ action.adjustvelocitylimit().min(),action.adjustvelocitylimit().max() };
  506. stLimit adjust_h={ action.adjusthorizonlimit().min(),action.adjusthorizonlimit().max() };
  507. stLimit adjust_angular={ action.nodeangularlimit().min(),action.nodeangularlimit().max() };
  508. stLimit mpc_velocity={ action.nodevelocitylimit().min(),action.nodevelocitylimit().max() };
  509. //目标,精度
  510. double first_yaw=timedPose_.Get().theta();
  511. if(1<action.pathnodes_size()){
  512. NavMessage::PathNode next=action.pathnodes(1);
  513. first_yaw=Pose2d::vector2yaw(next.pose().x()-first.pose().x(),next.pose().y()-first.pose().y());
  514. }
  515. Pose2d first_target(first.pose().x(),first.pose().y(),first_yaw);
  516. Pose2d first_accuracy(first.accuracy().x(),first.accuracy().y(),first.accuracy().theta());
  517. //execute_adjust_action(first_target,first_accuracy,adjust_x,adjust_h,adjust_angular,anyDirect);
  518. return false;
  519. }
  520. }else{
  521. return false;
  522. }
  523. }
  524. bool Navigation::execute_InOut_space(NavMessage::NewAction action) {
  525. if (action.type() != 1 && action.type() != 2) {
  526. printf(" Inout_space failed : msg action type must ==1\n ");
  527. return false;
  528. }
  529. if (!action.has_inoutvlimit() || !action.has_spacenode() ||
  530. !action.has_streetnode()) {
  531. std::cout << "execute enter_space failed ,Action miss some infos:" << action.DebugString() << std::endl;
  532. return false;
  533. }
  534. if (timedPose_.timeout() == true) {
  535. printf(" inout_space failed type:%d : current pose is timeout\n", action.type());
  536. return false;
  537. }
  538. Pose2d begin, target, begin_accuracy, target_accuracy;
  539. //入库,起点为streetNode
  540. begin = Pose2d(action.streetnode().pose().x(), action.streetnode().pose().y(), action.streetnode().pose().theta());
  541. begin_accuracy = Pose2d(action.streetnode().accuracy().x(),
  542. action.streetnode().accuracy().y(),
  543. action.streetnode().accuracy().theta());
  544. target = Pose2d(action.spacenode().pose().x(), action.spacenode().pose().y(), action.spacenode().pose().theta());
  545. //目标点精度
  546. target_accuracy = Pose2d(action.spacenode().accuracy().x()*2,
  547. action.spacenode().accuracy().y()*2,
  548. action.spacenode().accuracy().theta()*2);
  549. double yaw = Pose2d::vector2yaw(target.x() - begin.x(), target.y() - begin.y());
  550. if (action.type() == 2) { //出库起点终点对调
  551. Pose2d mid = target;
  552. Pose2d mid_accuracy = target_accuracy;
  553. target = begin;
  554. target_accuracy = begin_accuracy;
  555. begin = mid;
  556. begin_accuracy = mid_accuracy;
  557. yaw = Pose2d::vector2yaw(begin.x() - target.x(), begin.y() - target.y());
  558. }
  559. //给起点赋予朝向,保证agv以正对车位的方向行进
  560. begin.mutable_theta() = yaw;
  561. //严格调整到起点
  562. stLimit adjust_x = {0.05, 0.2};
  563. stLimit adjust_h = {0.05, 0.2};
  564. stLimit adjust_angular = {2 * M_PI / 180.0, 20 * M_PI / 180.0};
  565. stLimit mpc_velocity = {0.05, 0.3};
  566. //判断当前点与起点的距离
  567. Pose2d distance(1, 1, M_PI * 2);
  568. if (action.type() == 2) { //出库要求起点距离当前点非常近
  569. distance = Pose2d(1, 0.1, 3 * M_PI);
  570. adjust_x = {0.03, 0.1};
  571. adjust_h = {0.03, 0.1};
  572. adjust_angular = {2 * M_PI / 180.0, 5 * M_PI / 180.0};
  573. }
  574. Pose2d relativeDiff=Pose2d::relativePose(begin,timedPose_.Get());
  575. if (!(Pose2d::abs(relativeDiff) < distance)) {
  576. printf(" Inout space failed type:%d: current pose too far from begin node\n", action.type());
  577. std::cout << " begin:" << begin << " current:" << timedPose_.Get()<<" relative:"<<relativeDiff << std::endl;
  578. return false;
  579. }
  580. if (action.type() == 1) //1,进库
  581. if (execute_adjust_action(begin, begin_accuracy, adjust_x, adjust_h, adjust_angular, false) == false)
  582. return false;
  583. //if (action.type() == 2) //2,出库
  584. if (execute_along_action(begin, target, target_accuracy, mpc_velocity, false) == false)
  585. return false;
  586. return true;
  587. }
  588. bool Navigation::mpc_once(Trajectory traj,stLimit limit_v,std::vector<double>& out,bool directY) {
  589. if (timedPose_.timeout() == true) {
  590. printf(" MPC once Error:Pose is timeout \n");
  591. return false;
  592. }
  593. if(timedV_.timeout() == true || timedA_.timeout() == true){
  594. printf(" MPC once Error:V/A is timeout \n");
  595. return false;
  596. }
  597. if (traj.size() == 0) {
  598. printf("traj size ==0\n");
  599. return false;
  600. }
  601. Pose2d pose = timedPose_.Get();
  602. double velocity = timedV_.Get(); //从plc获取状态
  603. double angular = timedA_.Get();
  604. Pose2d brother = timedBrotherPose_.Get();
  605. Pose2d relative = Pose2d::relativePose(brother, pose);//计算另一节在当前小车坐标系下的坐标
  606. if (move_mode_ == Monitor_emqx::ActionMode::eMain)
  607. relative = Pose2d(-1e8, -1e8, 0);
  608. Eigen::VectorXd statu = Eigen::VectorXd::Zero(5);//agv状态
  609. statu[0] = pose.x();
  610. statu[1] = pose.y();
  611. statu[2] = pose.theta();
  612. statu[3] = velocity;
  613. statu[4] = angular;
  614. Trajectory optimize_trajectory;
  615. Trajectory selected_trajectory;
  616. NavParameter::MPC_parameter mpc_parameter=parameter_.x_mpc_parameter();
  617. if (directY == true) {
  618. //将车身朝向旋转90°,车身朝向在(-pi,pi]
  619. statu[2] += M_PI / 2;
  620. if (statu[2] > M_PI)
  621. statu[2] -= 2 * M_PI;
  622. mpc_parameter=parameter_.y_mpc_parameter();
  623. }
  624. bool ret = false;
  625. LoadedMPC MPC(relative, limit_v.min, limit_v.max);
  626. LoadedMPC::MPC_parameter parameter={mpc_parameter.shortest_radius(),mpc_parameter.dt(),
  627. mpc_parameter.acc_velocity(),mpc_parameter.acc_angular()};
  628. //printf(" r:%f dt:%f acc:%f acc_a:%f\n",mpc_parameter.shortest_radius(),
  629. // mpc_parameter.dt(),mpc_parameter.acc_velocity(),mpc_parameter.acc_angular());
  630. ret = MPC.solve(traj, traj[traj.size() - 1], statu,parameter,
  631. out, selected_trajectory, optimize_trajectory);
  632. //std::cout<<" traj size %d %d -------- "<<selected_trajectory.size()<<","<<optimize_trajectory.size()<<std::endl;
  633. predict_traj_.reset(optimize_trajectory, 1);
  634. selected_traj_.reset(selected_trajectory, 1);
  635. return ret;
  636. }
  637. bool Navigation::IsArrived(const Pose2d& cur,double velocity,double angular,
  638. const Pose2d& target,const Pose2d& diff,int direct)
  639. {
  640. //std::cout<<cur<<","<<target<<","<<nearest_yaw<<",v"<<velocity<<"a:"<<angular<<"diff:"<<diff<<std::endl;
  641. Pose2d distance=Pose2d::relativePose(target,cur);
  642. Pose2d absDiff=Pose2d::abs(distance);
  643. //std::cout<<" arrive distanc:"<<distance<<",direct:"<<direct<<std::endl;
  644. if(direct==1){ //纵向MPC
  645. if(absDiff.x()<diff.x() && absDiff.y()<diff.y())
  646. {
  647. float diffYaw=absDiff.theta(); //[0-pi)
  648. float diffYaw2=absDiff.theta()-M_PI;
  649. bool yawArrived=( fabs(diffYaw)<diff.theta() || fabs(diffYaw2)<diff.theta() );
  650. if(yawArrived && fabs(velocity) < 0.06 && fabs(angular) < 5 * M_PI / 180.0)
  651. return true;
  652. }
  653. }else if(direct==2){ //横向MPC
  654. if(absDiff.x()<diff.x() && absDiff.y()<diff.y())
  655. {
  656. float diffYaw=absDiff.theta(); //[0-pi)
  657. float diffYaw1=absDiff.theta()-M_PI/2;
  658. float diffYaw2=absDiff.theta()-M_PI;
  659. float diffYaw3=absDiff.theta()-3*M_PI/2;
  660. printf(" diff 123 :%f %f %f %f\n",diffYaw,diffYaw1,diffYaw2,diffYaw3);
  661. bool yawArrived=( fabs(diffYaw)<diff.theta() || fabs(diffYaw1)<diff.theta()
  662. || fabs(diffYaw2)<diff.theta() ||fabs(diffYaw3)<diff.theta() );
  663. if(yawArrived && fabs(velocity) < 0.06 && fabs(angular) < 5 * M_PI / 180.0)
  664. return true;
  665. }
  666. }else{ //原地调整
  667. if (absDiff < diff) {
  668. if (fabs(velocity) < 0.03 && fabs(angular) < 5 * M_PI / 180.0)
  669. return true;
  670. }
  671. }
  672. //std::cout<<"distance:"<<distance<<" diff:"<<diff<<" v:"<<velocity<<" a:"<<angular<<std::endl;
  673. return false;
  674. }
  675. void Navigation::SendMoveCmd(Monitor_emqx::ActionMode mode,Monitor_emqx::ActionType type,
  676. double v,double angular){
  677. if(monitor_) {
  678. monitor_->set_speed(mode, type, v, angular);
  679. }
  680. }
  681. bool Navigation::clamp_close()
  682. {
  683. if(monitor_) {
  684. printf("Clamp closing...\n");
  685. monitor_->clamp_close(move_mode_);
  686. actionType_=eClampClose;
  687. while (cancel_ == false) {
  688. if (timed_clamp_.timeout()) {
  689. printf("timed clamp is timeout\n");
  690. return false;
  691. }
  692. if (timed_clamp_.Get() == eClosed)
  693. return true;
  694. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  695. monitor_->clamp_close(move_mode_);
  696. actionType_=eClampClose;
  697. }
  698. return false;
  699. }
  700. return false;
  701. }
  702. bool Navigation::clamp_open() {
  703. if(monitor_) {
  704. printf("Clamp openning...\n");
  705. monitor_->clamp_open(move_mode_);
  706. actionType_=eClampOpen;
  707. while(cancel_==false)
  708. {
  709. if(timed_clamp_.timeout())
  710. {
  711. printf("timed clamp is timeout\n");
  712. return false;
  713. }
  714. if(timed_clamp_.Get()==eOpened)
  715. return true;
  716. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  717. monitor_->clamp_open(move_mode_);
  718. actionType_=eClampOpen;
  719. }
  720. return false;
  721. }
  722. return false;
  723. }
  724. bool Navigation::execute_along_action(const Pose2d& begin,const Pose2d& target,const Pose2d& target_diff,
  725. stLimit limit_v,bool autoDirect) {
  726. if (inited_ == false) {
  727. printf(" navigation has not inited\n");
  728. return false;
  729. }
  730. if (timedPose_.timeout()) {
  731. printf(" navigation Error:Pose is timeout \n");
  732. return false;
  733. }
  734. //生成轨迹
  735. Trajectory traj = Trajectory::create_line_trajectory(begin, target);
  736. if (traj.size() == 0)
  737. return true;
  738. //判断 巡线方向
  739. bool directY=false;
  740. if(autoDirect){
  741. Pose2d target_relative=Pose2d::relativePose(target,timedPose_.Get());
  742. if( fabs(target_relative.y())>fabs(target_relative.x())) { //目标轨迹点在当前点Y轴上
  743. std::cout<<" MPC Y axis target_relative:"<<target_relative<<std::endl;
  744. directY = true;
  745. }else{
  746. std::cout<<" MPC X axis target_relative:"<<target_relative<<std::endl;
  747. }
  748. }
  749. printf(" exec along autoDirect:%d\n",autoDirect);
  750. while (cancel_ == false) {
  751. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  752. if (pause_ == true) {
  753. //发送暂停消息
  754. continue;
  755. }
  756. if (timedPose_.timeout()) {
  757. printf(" navigation Error:Pose is timeout \n");
  758. return false;
  759. }
  760. if(timedV_.timeout() || timedA_.timeout()){
  761. printf(" navigation Error:v/a is timeout \n");
  762. return false;
  763. }
  764. //判断是否到达终点
  765. /*int direct=1;
  766. if(directY) direct=2;*/
  767. if (IsArrived(timedPose_.Get(), timedV_.Get(), timedA_.Get(), target, target_diff,2)) {
  768. if (Stop()) {
  769. printf(" exec along completed !!!\n");
  770. return true;
  771. }
  772. }
  773. /*
  774. * 判断周边是否有障碍物,半径r,当障碍物进入r内,停下等待,当障碍物远离 1.2*r,恢复
  775. * */
  776. if(move_mode_==Monitor_emqx::eSingle) {
  777. double r = 2.4;
  778. static bool obs_stoped = false;
  779. Pose2d obs_relative = Pose2d::relativePose(timedBrotherPose_.Get(), timedPose_.Get());
  780. double distance = sqrt(obs_relative.x() * obs_relative.x() + obs_relative.y() * obs_relative.y());
  781. if (obs_stoped == false) {
  782. if (distance < r && fabs(obs_relative.x()) > 0.2) {
  783. std::cout << "find obs stop to wait...." << std::endl;
  784. Stop();
  785. obs_stoped = true;
  786. continue;
  787. }
  788. } else {
  789. //障碍解除
  790. if (distance > 1.2 * r) {
  791. std::cout << "obs release continue MPC" << std::endl;
  792. obs_stoped = false;
  793. } else {
  794. continue;
  795. }
  796. }
  797. }
  798. //一次变速
  799. std::vector<double> out;
  800. bool ret;
  801. TimerRecord::Execute([&, this]() {
  802. ret = mpc_once(traj, limit_v, out,directY);
  803. }, "mpc_once");
  804. if (ret == false) {
  805. Stop();
  806. return false;
  807. }
  808. if(directY==false)
  809. SendMoveCmd(move_mode_, Monitor_emqx::eMPC, out[0], out[1]);
  810. else
  811. SendMoveCmd(move_mode_, Monitor_emqx::eHorizontal, out[0], out[1]);
  812. actionType_=eMPC;
  813. /*
  814. * 判断车辆是否在终点附近徘徊,无法到达终点
  815. */
  816. if (mpc_possible_to_end(target, target_diff,directY) == false) {
  817. printf(" --------------MPC imposible to target -----------------------\n");
  818. if(fabs(timedV_.Get())>0.1 || fabs(timedA_.Get())>5*M_PI/180.0)
  819. Stop();
  820. //调整到目标点
  821. stLimit limitv, limitR;
  822. limitv.min = 0.05;
  823. limitv.max = 0.1;
  824. limitR.min = 2 * M_PI / 180.0;
  825. limitR.max = 10 * M_PI / 180.0;
  826. Pose2d accuracy(target_diff.x(),target_diff.y(),M_PI*2);
  827. if (execute_adjust_action(target, accuracy, limitv, limitv, limitR,false))
  828. return true;
  829. else
  830. return false;
  831. }
  832. //std::this_thread::sleep_for(std::chrono::milliseconds (400));
  833. }
  834. return false;
  835. }
  836. bool Navigation::mpc_possible_to_end(const Pose2d& target,const Pose2d& target_diff,bool directY)
  837. {
  838. if(timedPose_.timeout()==false) {
  839. Pose2d current=timedPose_.Get();
  840. if(directY){
  841. float yaw=current.theta();
  842. yaw += M_PI / 2;
  843. if (yaw > M_PI)
  844. yaw -= 2 * M_PI;
  845. current.mutable_theta()=yaw;
  846. }
  847. Pose2d diff = Pose2d::relativePose(target, current);
  848. if (fabs(diff.y()) < target_diff.y() && fabs(diff.x()) < target_diff.x()) { //xy在精度内
  849. if (timedV_.timeout() == true)
  850. return false;
  851. /*if(fabs(timedV_.Get())<0.05 && fabs(diff.theta())>target_diff.theta())
  852. return false;*/
  853. return true;
  854. } else { //xy不在精度内
  855. if(directY==false) {
  856. if (fabs(diff.x()) < 1e-3)
  857. return false; //x已到达,Y未到达,则不可能到达目标点
  858. }
  859. double theta = fabs(atan(diff.y() / diff.x()));
  860. if (theta > 5 * M_PI / 180.0) {
  861. if (timedV_.timeout() == true)
  862. return false;
  863. if (fabs(timedV_.Get()) < 0.05)
  864. return false;
  865. else
  866. return true;
  867. } else {
  868. return true;
  869. }
  870. }
  871. }
  872. return false;
  873. }
  874. void Navigation::navigatting() {
  875. if (inited_ == false) {
  876. printf(" navigation has not inited\n");
  877. return;
  878. }
  879. pause_ = false;
  880. cancel_ = false;
  881. running_ = true;
  882. actionType_ = eReady;
  883. printf(" navigation beg...\n");
  884. while (newUnfinished_cations_.empty() == false && cancel_ == false) {
  885. std::cout << "unfinished size:" << newUnfinished_cations_.size() << std::endl;
  886. NavMessage::NewAction act = newUnfinished_cations_.front();
  887. if(act.type()==1){ //入库
  888. if(!execute_InOut_space(act)){
  889. printf(" In space failed\n");
  890. break;
  891. }
  892. }
  893. else if(act.type()==2){ //出库
  894. if(!execute_InOut_space(act)){
  895. printf(" out space failed\n");
  896. break;
  897. }
  898. }else if (act.type() == 3 || act.type() == 4) { //马路导航
  899. if (!execute_nodes(act))
  900. break;
  901. }else if(act.type()==5){
  902. printf(" 汽车模型导航....\n");
  903. }else if (act.type() == 6) {//夹持
  904. if (this->clamp_close() == false) {
  905. printf("夹持failed ...\n");
  906. break;
  907. }
  908. } else if (act.type() == 7) {
  909. if (this->clamp_open() == false) {
  910. printf("打开夹持 failed...\n");
  911. break;
  912. }
  913. } else if(act.type()==8){ //切换模式
  914. SwitchMode(Monitor_emqx::ActionMode(act.changedmode()),act.wheelbase());
  915. }else{
  916. printf(" action type invalid not handled !!\n");
  917. break;
  918. }
  919. newUnfinished_cations_.pop();
  920. }
  921. actionType_ = eReady;
  922. Stop();
  923. if (cancel_ == true) {
  924. printf(" navigation canceled\n");
  925. while (newUnfinished_cations_.empty() == false)
  926. newUnfinished_cations_.pop();
  927. } else {
  928. if (newUnfinished_cations_.empty())
  929. printf("navigation completed!!!\n");
  930. else {
  931. printf(" navigation Failed\n");
  932. while (newUnfinished_cations_.empty() == false)
  933. newUnfinished_cations_.pop();
  934. }
  935. }
  936. running_ = false;
  937. }
  938. void Navigation::SwitchMode(Monitor_emqx::ActionMode mode,float wheelBase){
  939. printf("Child AGV can not Switch Mode\n");
  940. }