navigation.cpp 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  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::PoseTimeout(){
  61. if(timedPose_.timeout()== false && timedBrotherPose_.timeout()==false){
  62. return false;
  63. }else{
  64. if(timedPose_.timeout()){
  65. printf(" current pose is timeout \n");
  66. }
  67. if(timedBrotherPose_.timeout()){
  68. printf(" brother pose is timeout \n");
  69. }
  70. return true;
  71. }
  72. }
  73. bool Navigation::Init(const NavParameter::Navigation_parameter& parameter)
  74. {
  75. parameter_=parameter;
  76. NavParameter::AgvEmqx_parameter agv_p=parameter.agv_emqx();
  77. if(monitor_== nullptr) {
  78. monitor_ = new Monitor_emqx(agv_p.nodeid());
  79. if(monitor_->Connect(agv_p.ip(),agv_p.port())==false)
  80. {
  81. printf(" agv emqx connected failed\n");
  82. return false;
  83. }
  84. monitor_->set_speedcmd_topic(agv_p.pubspeedtopic());
  85. monitor_->AddCallback(agv_p.subposetopic(),Navigation::RobotPoseCallback,this);
  86. monitor_->AddCallback(agv_p.subspeedtopic(),Navigation::RobotSpeedCallback,this);
  87. }
  88. NavParameter::Emqx_parameter terminal_p=parameter.terminal_emqx();
  89. if(terminator_== nullptr) {
  90. terminator_ = new Terminator_emqx(terminal_p.nodeid());
  91. if(terminator_->Connect(terminal_p.ip(),terminal_p.port())==false)
  92. {
  93. printf(" terminator emqx connected failed\n");
  94. return false;
  95. }
  96. terminator_->AddCallback(terminal_p.subnavcmdtopic(),Navigation::NavCmdCallback,this);
  97. }
  98. if(parameter.has_brother_emqx()) {
  99. NavParameter::BrotherEmqx brotherEmqx = parameter.brother_emqx();
  100. if (brotherEmqx_ == nullptr) {
  101. brotherEmqx_ = new Terminator_emqx(brotherEmqx.nodeid());
  102. if (brotherEmqx_->Connect(brotherEmqx.ip(), brotherEmqx.port()) == true) {
  103. brotherEmqx_->AddCallback(brotherEmqx.subbrotherstatutopic(), Navigation::BrotherAgvStatuCallback, this);
  104. }else{
  105. printf(" brother emqx connected failed\n");
  106. // return false;
  107. }
  108. }
  109. }
  110. inited_=true;
  111. if(pubthread_!= nullptr)
  112. {
  113. exit_=true;
  114. if(pubthread_->joinable())
  115. pubthread_->join();
  116. delete pubthread_;
  117. }
  118. exit_=false;
  119. pubthread_=new std::thread(&Navigation::pubStatuThreadFuc,this);
  120. return true;
  121. }
  122. void Navigation::RobotPoseCallback(const MqttMsg& msg,void* context)
  123. {
  124. Navigation* navigator=(Navigation*)context;
  125. NavMessage::LidarOdomStatu statu;
  126. if(msg.toProtoMessage(statu))
  127. {
  128. navigator->ResetPose(Pose2d(statu.x(),statu.y(),statu.theta()));
  129. }
  130. }
  131. void Navigation::HandleAgvStatu(const MqttMsg& msg)
  132. {
  133. NavMessage::AgvStatu speed;
  134. if(msg.toProtoMessage(speed))
  135. {
  136. ResetStatu(speed.v(),speed.w());
  137. ResetClamp((ClampStatu)speed.clamp());
  138. }
  139. }
  140. void Navigation::RobotSpeedCallback(const MqttMsg& msg,void* context)
  141. {
  142. Navigation* navigator=(Navigation*)context;
  143. navigator->HandleAgvStatu(msg);
  144. }
  145. void Navigation::pubStatuThreadFuc(void* p) {
  146. Navigation *navogator = (Navigation *) p;
  147. if (navogator) {
  148. while (navogator->exit_ == false) {
  149. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  150. NavMessage::NavStatu statu;
  151. statu.set_main_agv(false);
  152. navogator->publish_statu(statu);
  153. }
  154. }
  155. }
  156. void Navigation::publish_statu(NavMessage::NavStatu& statu) {
  157. if(timedPose_.timeout()==false){
  158. NavMessage::LidarOdomStatu odom;
  159. odom.set_x(timedPose_.Get().x());
  160. odom.set_y(timedPose_.Get().y());
  161. odom.set_theta(timedPose_.Get().theta());
  162. if(timedV_.timeout()==false)
  163. odom.set_v(timedV_.Get());
  164. if(timedA_.timeout()==false)
  165. odom.set_vth(timedA_.Get());
  166. statu.mutable_odom()->CopyFrom(odom);
  167. }
  168. statu.set_in_space(isInSpace_);
  169. if(isInSpace_) statu.set_space_id(space_id_);
  170. //发布nav状态
  171. statu.set_statu(actionType_); //
  172. statu.set_move_mode(move_mode_);
  173. if (running_)
  174. {
  175. statu.set_key(global_navCmd_.key());
  176. }
  177. //发布MPC信息
  178. //发布mpc 预选点
  179. if (selected_traj_.timeout() == false) {
  180. for (int i = 0; i < selected_traj_.Get().size(); ++i) {
  181. Pose2d pt = selected_traj_.Get()[i];
  182. NavMessage::Pose2d *pose = statu.mutable_selected_traj()->add_poses();
  183. pose->set_x(pt.x());
  184. pose->set_y(pt.y());
  185. pose->set_theta(pt.theta());
  186. }
  187. }
  188. //发布 mpc 预测点
  189. if (predict_traj_.timeout() == false) {
  190. for (int i = 0; i < predict_traj_.Get().size(); ++i) {
  191. Pose2d pt = predict_traj_.Get()[i];
  192. NavMessage::Pose2d *pose = statu.mutable_predict_traj()->add_poses();
  193. pose->set_x(pt.x());
  194. pose->set_y(pt.y());
  195. pose->set_theta(pt.theta());
  196. }
  197. }
  198. //std::cout<<"nav statu:"<<statu.DebugString()<<std::endl;
  199. MqttMsg msg;
  200. msg.fromProtoMessage(statu);
  201. if(terminator_)
  202. terminator_->Publish(parameter_.terminal_emqx().pubnavstatutopic(),msg);
  203. //发布位姿 ------robot状态--------------------------
  204. NavMessage::RobotStatu robot;
  205. if(CreateRobotStatuMsg(robot)) {
  206. if (terminator_) {
  207. MqttMsg msg;
  208. msg.fromProtoMessage(robot);
  209. terminator_->Publish(parameter_.terminal_emqx().pubstatutopic(), msg);
  210. }
  211. }
  212. }
  213. bool Navigation::CreateRobotStatuMsg(NavMessage::RobotStatu& robotStatu)
  214. {
  215. //printf(" %d %d %d \n",timedPose_.timeout(),timedV_.timeout(),timedA_.timeout());
  216. if (timedPose_.timeout() == false) {
  217. Pose2d pose = timedPose_.Get();
  218. robotStatu.set_x(pose.x());
  219. robotStatu.set_y(pose.y());
  220. robotStatu.set_theta(pose.theta());
  221. if((timedV_.timeout() == false && timedA_.timeout() == false)) {
  222. NavMessage::AgvStatu plc;
  223. plc.set_v(timedV_.Get());
  224. plc.set_w(timedA_.Get());
  225. plc.set_clamp(timed_clamp_.Get());
  226. //printf(" timed_clamp_:%d\n ",timed_clamp_.Get());
  227. robotStatu.mutable_agvstatu()->CopyFrom(plc);
  228. }
  229. return true;
  230. }
  231. return false;
  232. }
  233. void Navigation::ResetStatu(double v,double a)
  234. {
  235. timedV_.reset(v,0.5);
  236. timedA_.reset(a,0.5);
  237. }
  238. void Navigation::ResetClamp(ClampStatu statu){
  239. timed_clamp_.reset(statu,1);
  240. }
  241. void Navigation::ResetPose(const Pose2d& pose)
  242. {
  243. timedPose_.reset(pose,1.0);
  244. }
  245. bool Navigation::Start(const NavMessage::NavCmd& cmd)
  246. {
  247. if(newUnfinished_cations_.empty()==false) //正在运行中,上一次指令未完成
  248. {
  249. if(pause_)
  250. {
  251. pause_=false;
  252. return true;
  253. }
  254. printf(" navigation is running pls cancel before\n");
  255. return false;
  256. }
  257. if(thread_!= nullptr)
  258. {
  259. if(thread_->joinable())
  260. thread_->join();
  261. delete thread_;
  262. }
  263. //add 先检查当前点与起点的距离
  264. global_navCmd_=cmd;
  265. for (int i = 0; i < cmd.newactions_size(); ++i)
  266. newUnfinished_cations_.push(cmd.newactions(i));
  267. thread_=new std::thread(&Navigation::navigatting,this);
  268. return true;
  269. }
  270. void Navigation::Cancel()
  271. {
  272. cancel_=true;
  273. }
  274. bool Navigation::Stop() {
  275. if(monitor_)
  276. {
  277. monitor_->stop();
  278. while(cancel_==false)
  279. {
  280. if(timedV_.timeout()==false && timedA_.timeout()==false)
  281. {
  282. if(fabs(timedV_.Get())<1e-2 && fabs(timedA_.Get())<1e-3)
  283. return true;
  284. else
  285. monitor_->stop();
  286. printf("Stoped wait V/A ==0(1e-4,1e-4),V:%f,A:%f\n",fabs(timedV_.Get()),fabs(timedA_.Get()));
  287. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  288. }else{
  289. printf("Stop failed V/A timeout\n");
  290. return false;
  291. }
  292. }
  293. }
  294. printf("stoped ret false.\n");
  295. return false;
  296. }
  297. bool Navigation::SlowlyStop() {
  298. double acc = 5.0;
  299. double dt = 0.1;
  300. while (cancel_ == false) {
  301. if (timedV_.timeout() == false) {
  302. double v = timedV_.Get();
  303. if(fabs(v<1e-2 && fabs(timedA_.Get())<1e-3))
  304. return true;
  305. if (v > 0) {
  306. double new_v = v - acc * dt;
  307. new_v = new_v > 0 ? new_v : 0;
  308. SendMoveCmd(move_mode_, Monitor_emqx::ActionType(actionType_), new_v,0);
  309. }else{
  310. double new_v = v + acc * dt;
  311. new_v = new_v < 0 ? new_v : 0;
  312. SendMoveCmd(move_mode_, Monitor_emqx::ActionType(actionType_), new_v,0);
  313. }
  314. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  315. } else {
  316. printf("Stop failed V/A timeout\n");
  317. return false;
  318. }
  319. }
  320. printf("stoped ret false.\n");
  321. return false;
  322. }
  323. void Navigation::Pause()
  324. {
  325. if(Stop())
  326. pause_=true;
  327. }
  328. Navigation::Navigation()
  329. {
  330. isInSpace_=false; //是否在车位或者正在进入车位
  331. RWheel_position_=eUnknow;
  332. move_mode_=Monitor_emqx::eSingle;
  333. thread_= nullptr;
  334. monitor_= nullptr;
  335. terminator_= nullptr;
  336. timedBrotherPose_.reset(Pose2d(-100,0,0),0.5);
  337. }
  338. void Navigation::BrotherAgvStatuCallback(const MqttMsg& msg,void* context)
  339. {
  340. Navigation* navigator=(Navigation*)context;
  341. NavMessage::NavStatu brother_statu;
  342. if(msg.toProtoMessage(brother_statu)==false) {
  343. std::cout<<" msg transform to AGVStatu failed,msg:"<<msg.data()<<std::endl;
  344. return;
  345. }
  346. //std::cout<<brother_nav.DebugString()<<std::endl<<std::endl;
  347. if(brother_statu.has_odom()) {
  348. NavMessage::LidarOdomStatu odom = brother_statu.odom();
  349. Pose2d pose(odom.x(), odom.y(), odom.theta());
  350. navigator->timedBrotherPose_.reset(pose, 1);
  351. navigator->timedBrotherV_.reset(odom.v(), 1);
  352. navigator->timedBrotherA_.reset(odom.vth(), 1);
  353. navigator->timedBrotherNavStatu_.reset(brother_statu,0.1);
  354. }
  355. }
  356. void Navigation::HandleNavCmd(const NavMessage::NavCmd& cmd)
  357. {
  358. if(cmd.action()==3)
  359. {
  360. printf(" Nav cancel\n");
  361. Cancel();
  362. return ;
  363. }
  364. if(cmd.action()==2) {
  365. printf(" Nav continue\n");
  366. pause_=false;
  367. return ;
  368. }
  369. if(cmd.action()==1) {
  370. printf(" Nav pause\n");
  371. Pause();
  372. return ;
  373. }
  374. if(cmd.action()==0||cmd.action()==6)
  375. {
  376. Start(cmd);
  377. }
  378. else
  379. printf(" Invalid action ,action:%d\n",cmd.action());
  380. }
  381. void Navigation::NavCmdCallback(const MqttMsg& msg,void* context)
  382. {
  383. NavMessage::NavCmd cmd;
  384. if(msg.toProtoMessage(cmd)==false) {
  385. printf(" msg transform to NavCmd failed ..!!\n");
  386. return;
  387. }
  388. Navigation* navigator=(Navigation*)context;
  389. navigator->HandleNavCmd(cmd);
  390. }
  391. bool Navigation::RotateReferToTarget(const Pose2d& target,stLimit limit_rotate,bool anyDirect) {
  392. while(cancel_==false) {
  393. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  394. if (timedPose_.timeout()) {
  395. printf(" RotateBytarget failed pose timeout\n");
  396. return false;
  397. }
  398. if (timedA_.timeout()) {
  399. printf(" RotateBytarget failed wmg timeout\n");
  400. return false;
  401. }
  402. Pose2d targetInPose = Pose2d::relativePose(target, timedPose_.Get());
  403. float yawDiff = Pose2d::vector2yaw(targetInPose.x(), targetInPose.y());
  404. float minYawdiff = yawDiff;
  405. if (anyDirect) {
  406. Pose2d p0 = timedPose_.Get();
  407. float yawdiff[4] = {0};
  408. yawdiff[0] = yawDiff;
  409. Pose2d relativePose;
  410. relativePose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, M_PI / 2));
  411. yawdiff[1] = Pose2d::vector2yaw(relativePose.x(), relativePose.y()); ////使用减法,保证角度在【-pi pi】
  412. relativePose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, M_PI));
  413. yawdiff[2] = Pose2d::vector2yaw(relativePose.x(), relativePose.y());
  414. relativePose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, 3 * M_PI / 2));
  415. yawdiff[3] = Pose2d::vector2yaw(relativePose.x(), relativePose.y());
  416. for (int i = 1; i < 4; ++i) {
  417. if (fabs(yawdiff[i]) < fabs(minYawdiff)) {
  418. minYawdiff = yawdiff[i];
  419. targetInPose=Pose2d::relativePose(target,p0-Pose2d(0,0,i*M_PI/2.0));
  420. }
  421. }
  422. }
  423. /*std::cout<<" Rotate refer to target:"<<target<<",targetInPose:"
  424. <<targetInPose<<",anyDirect:"<<anyDirect<<std::endl;*/
  425. //以当前点为原点,想方向经过目标点的二次曲线曲率>0.25,则需要调整 y=a x*x
  426. float cuv=compute_cuv(targetInPose);
  427. float dt=0.1;
  428. float acc_angular=15*M_PI/180.0;
  429. if (cuv>2*M_PI/180.0) {
  430. double theta = limit_gause(minYawdiff, limit_rotate.min, limit_rotate.max);
  431. double angular = next_speed(timedA_.Get(), theta, acc_angular, dt);
  432. double limit_angular = limit(angular, limit_rotate.min, limit_rotate.max);
  433. SendMoveCmd(move_mode_, Monitor_emqx::eRotate, 0, limit_angular);
  434. actionType_ = eRotation;
  435. printf(" Ratate | input anguar:%f,next angular:%f,down:%f diff:%f anyDitect:%d\n",
  436. timedA_.Get(), angular, limit_angular, minYawdiff, anyDirect);
  437. continue;
  438. }else{
  439. if(fabs(timedA_.Get())<5*M_PI/180.0) {
  440. printf(" Rotate refer target completed,cuv:%f\n", cuv);
  441. return true;
  442. }
  443. continue;
  444. }
  445. }
  446. return false;
  447. }
  448. bool Navigation::MoveToTarget(NavMessage::PathNode node, Navigation::stLimit limit_v, Navigation::stLimit limit_w,
  449. bool anyDirect,bool enable_rotate) {
  450. if (IsArrived(node)) {
  451. return true;
  452. }
  453. bool already_in_mpc=false;
  454. while (cancel_ == false) {
  455. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  456. if (PoseTimeout()) {
  457. printf(" navigation Error:Pose is timeout \n");
  458. break;
  459. }
  460. Pose2d current=timedPose_.Get();
  461. if (IsArrived(node)) {
  462. break;
  463. }
  464. //两个方向都无法到达目标点,旋转 朝向目标点
  465. bool x_enable=PossibleToTarget(node,false);
  466. bool y_enable=PossibleToTarget(node,true);
  467. bool enableTotarget=x_enable||y_enable;
  468. if(anyDirect==false){
  469. enableTotarget=x_enable;
  470. }
  471. //巡线无法到达目标点
  472. if(enableTotarget==false) {
  473. if(already_in_mpc && enable_rotate==false) {
  474. printf(" Move to node failed ,impossible to target and rotate is not enabled\n");
  475. return false;
  476. }
  477. Pose2d target(node.x(), node.y(), 0);
  478. if (RotateReferToTarget(target, limit_w, anyDirect) == false) {
  479. std::cout << " Rotate refer to target failed,target:" << target <<
  480. " anyDirect:" << anyDirect << std::endl;
  481. return false;
  482. }
  483. continue;
  484. }
  485. already_in_mpc=true;
  486. MpcResult ret = MpcToTarget(node, limit_v, anyDirect);
  487. if (ret == eMpcSuccess) {
  488. printf(" MPC to target:%f %f l:%f,w:%f theta:%f completed\n",
  489. node.x(),node.y(),node.l(),node.w(),node.theta());
  490. break;
  491. } else if (ret == eImpossibleToTarget) {
  492. printf(" MPC to target:%f %f l:%f,w:%f theta:%f impossible ,retry ..............................\n",
  493. node.x(),node.y(),node.l(),node.w(),node.theta());
  494. } else {
  495. return false;
  496. }
  497. }
  498. if (cancel_) {
  499. return false;
  500. }
  501. return true;
  502. }
  503. bool Navigation::execute_nodes(NavMessage::NewAction action)
  504. {
  505. if(action.type()==3 || action.type()==4) //最优动作导航 or 导航中保证朝向严格一致
  506. {
  507. if(!action.has_nodevelocitylimit() || !action.has_nodeangularlimit()||
  508. !action.has_adjustvelocitylimit()|| !action.has_adjusthorizonlimit()
  509. || action.pathnodes_size()==0) {
  510. std::cout << "execute pathNodes failed ,Action invalid:" << action.DebugString() << std::endl;
  511. return false;
  512. }
  513. bool anyDirect=(action.type()==3);
  514. //速度限制
  515. stLimit adjust_angular={ action.nodeangularlimit().min(),action.nodeangularlimit().max() };
  516. stLimit mpc_velocity={ action.nodevelocitylimit().min(),action.nodevelocitylimit().max() };
  517. for(int i=0;i< action.pathnodes_size();++i) {
  518. NavMessage::PathNode node = action.pathnodes(i);
  519. if(MoveToTarget(node,mpc_velocity,adjust_angular,anyDirect,true)==false)
  520. return false;
  521. else
  522. isInSpace_=false;
  523. }
  524. return true;
  525. }
  526. printf("execute PathNode failed ,action type is not 3/4 :%d\n",action.type());
  527. return false;
  528. }
  529. bool Navigation::execute_InOut_space(NavMessage::NewAction action) {
  530. if (action.type() != 1 && action.type() != 2) {
  531. printf(" Inout_space failed : msg action type must ==1\n ");
  532. return false;
  533. }
  534. if (!action.has_inoutvlimit() || !action.has_spacenode() ||
  535. !action.has_streetnode()) {
  536. std::cout << "execute enter_space failed ,Action miss some infos:" << action.DebugString() << std::endl;
  537. return false;
  538. }
  539. if (PoseTimeout() == true) {
  540. printf(" inout_space failed type:%d : current pose is timeout\n", action.type());
  541. return false;
  542. }
  543. stLimit limit_v={action.inoutvlimit().min(),action.inoutvlimit().max()};
  544. stLimit limit_w={2*M_PI/180.0,10*M_PI/180.0};
  545. //入库,起点为streetNode
  546. if(action.type()==1){
  547. if(MoveToTarget(action.streetnode(),limit_v,limit_w,true,true)==false)
  548. {
  549. printf(" Enter space failed type:%d: MoveTo StreetNode failed\n", action.type());
  550. return false;
  551. }
  552. //移动到库位点, 禁止任意方向// 不允许巡线中停下旋转(当无法到达目标点时,返回false)
  553. printf("inout ----------------------------------------\n");
  554. //计算当前车是进入车位1点还是2点
  555. /*if(timedBrotherNavStatu_.timeout()){
  556. printf("Enter to space failed,timedBrotherNavStatu_ timeout\n");
  557. return false;
  558. }
  559. if(timedBrotherNavStatu_.Get().in_space()){
  560. }*/
  561. if(MoveToTarget(action.spacenode(),limit_v,limit_w,false,false)==false)
  562. {
  563. printf(" Enter space failed type:%d: MoveTo StreetNode failed\n", action.type());
  564. return false;
  565. }
  566. }else if(action.type()==2){
  567. Pose2d space(action.spacenode().x(),action.spacenode().y(),0);
  568. Pose2d diff=Pose2d::relativePose(space,timedPose_.Get());
  569. if(Pose2d::abs(diff)<Pose2d(0.03,0.1,2*M_PI)){
  570. //出库,移动到马路点,允许自由方向,不允许中途旋转
  571. if(MoveToTarget(action.streetnode(),limit_v,limit_w,true,false)==false){
  572. printf(" Enter space failed type:%d: MoveTo StreetNode failed\n", action.type());
  573. return false;
  574. }
  575. }else{
  576. std::cout<<" Out space failed: current pose too far from space node:"<<space<<std::endl;
  577. return false;
  578. }
  579. }
  580. return true;
  581. }
  582. bool Navigation::mpc_once(Trajectory traj,stLimit limit_v,std::vector<double>& out,bool directY) {
  583. if (PoseTimeout() == true) {
  584. printf(" MPC once Error:Pose is timeout \n");
  585. return false;
  586. }
  587. if(timedV_.timeout() == true || timedA_.timeout() == true){
  588. printf(" MPC once Error:V/A is timeout \n");
  589. return false;
  590. }
  591. if (traj.size() == 0) {
  592. printf("traj size ==0\n");
  593. return false;
  594. }
  595. Pose2d pose = timedPose_.Get();
  596. double velocity = timedV_.Get(); //从plc获取状态
  597. double angular = timedA_.Get();
  598. Eigen::VectorXd statu = Eigen::VectorXd::Zero(5);//agv状态
  599. statu[0] = pose.x();
  600. statu[1] = pose.y();
  601. statu[2] = pose.theta();
  602. statu[3] = velocity;
  603. statu[4] = angular;
  604. Trajectory optimize_trajectory;
  605. Trajectory selected_trajectory;
  606. NavParameter::MPC_parameter mpc_parameter=parameter_.x_mpc_parameter();
  607. double obs_w=0.85;
  608. double obs_h=1.45;
  609. if (directY == true) {
  610. //将车身朝向旋转90°,车身朝向在(-pi,pi]
  611. statu[2] += M_PI / 2;
  612. if (statu[2] > M_PI)
  613. statu[2] -= 2 * M_PI;
  614. mpc_parameter=parameter_.y_mpc_parameter();
  615. obs_w=1.45;
  616. obs_h=0.85;
  617. }
  618. Pose2d brother = timedBrotherPose_.Get();
  619. Pose2d relative = Pose2d::relativePose(brother, pose);
  620. if(directY)
  621. relative = Pose2d::relativePose(brother.rotate(brother.x(),brother.y(),M_PI/2), pose.rotate(pose.x(),pose.y(),M_PI/2));//计算另一节在当前小车坐标系下的坐标
  622. //std::cout<<"pose:"<<pose<<", brother:"<<brother<<", relative:"<<relative<<std::endl;
  623. if (move_mode_ == Monitor_emqx::ActionMode::eMain)
  624. relative = Pose2d(-1e8, -1e8, 0);
  625. MpcError ret = failed;
  626. LoadedMPC MPC(relative, obs_w,obs_h,limit_v.min, limit_v.max);
  627. LoadedMPC::MPC_parameter parameter={mpc_parameter.shortest_radius(),mpc_parameter.dt(),
  628. mpc_parameter.acc_velocity(),mpc_parameter.acc_angular()};
  629. //printf(" r:%f dt:%f acc:%f acc_a:%f\n",mpc_parameter.shortest_radius(),
  630. // mpc_parameter.dt(),mpc_parameter.acc_velocity(),mpc_parameter.acc_angular());
  631. ret = MPC.solve(traj, traj[traj.size() - 1], statu,parameter,
  632. out, selected_trajectory, optimize_trajectory);
  633. //std::cout<<" traj size %d %d -------- "<<selected_trajectory.size()<<","<<optimize_trajectory.size()<<std::endl;
  634. if(ret==no_solution) {
  635. printf(" mpc solve no solution set v/w = 0\n");
  636. out.clear();
  637. out.push_back(0);
  638. out.push_back(0);
  639. }
  640. predict_traj_.reset(optimize_trajectory, 1);
  641. selected_traj_.reset(selected_trajectory, 1);
  642. return ret==success || ret==no_solution;
  643. }
  644. bool Navigation::IsArrived(NavMessage::PathNode targetNode)
  645. {
  646. if(timedPose_.timeout()|| timedV_.timeout()||timedA_.timeout()){
  647. printf(" pose / v / w timeout,IsArrived return false\n");
  648. return false;
  649. }
  650. Pose2d current=timedPose_.Get();
  651. double x=current.x();
  652. double y=current.y();
  653. double tx=targetNode.x();
  654. double ty=targetNode.y();
  655. double l=fabs(targetNode.l());
  656. double w=fabs(targetNode.w());
  657. double theta=targetNode.theta();
  658. if(l<1e-10 || w<1e-10){
  659. printf("IsArrived: Error target l/w ==0\n");
  660. return false;
  661. }
  662. double a=(x-tx)*cos(theta)-(y-ty)*sin(theta);
  663. double b=(x-tx)*sin(theta)+(y-ty)*cos(theta);
  664. if( pow(a/l,8)+pow(b/w,8) <=1){
  665. if(fabs(timedV_.Get())<0.06 && fabs(timedA_.Get())<5*M_PI/180.0) {
  666. printf(" Arrived target: %f %f l:%f w:%f theta:%f\n",tx,ty,l,w,theta);
  667. return true;
  668. }
  669. }
  670. return false;
  671. }
  672. void Navigation::SendMoveCmd(Monitor_emqx::ActionMode mode,Monitor_emqx::ActionType type,
  673. double v,double angular){
  674. if(monitor_) {
  675. monitor_->set_speed(mode, type, v, angular);
  676. if(mode==ActionType::eRotation)
  677. RWheel_position_=eR;
  678. if(mode==ActionType::eVertical)
  679. RWheel_position_=eX;
  680. if(mode==ActionType::eHorizon)
  681. RWheel_position_=eY;
  682. }
  683. }
  684. bool Navigation::clamp_close()
  685. {
  686. if(monitor_) {
  687. printf("Clamp closing...\n");
  688. monitor_->clamp_close(move_mode_);
  689. actionType_=eClampClose;
  690. while (cancel_ == false) {
  691. if (timed_clamp_.timeout()) {
  692. printf("timed clamp is timeout\n");
  693. return false;
  694. }
  695. if (timed_clamp_.Get() == eClosed)
  696. return true;
  697. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  698. monitor_->clamp_close(move_mode_);
  699. actionType_=eClampClose;
  700. }
  701. return false;
  702. }
  703. return false;
  704. }
  705. bool Navigation::clamp_open() {
  706. if(monitor_) {
  707. printf("Clamp openning...\n");
  708. monitor_->clamp_open(move_mode_);
  709. actionType_=eClampOpen;
  710. while(cancel_==false)
  711. {
  712. if(timed_clamp_.timeout())
  713. {
  714. printf("timed clamp is timeout\n");
  715. return false;
  716. }
  717. if(timed_clamp_.Get()==eOpened)
  718. return true;
  719. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  720. monitor_->clamp_open(move_mode_);
  721. actionType_=eClampOpen;
  722. }
  723. return false;
  724. }
  725. return false;
  726. }
  727. Navigation::MpcResult Navigation::MpcToTarget(NavMessage::PathNode node,stLimit limit_v,bool autoDirect) {
  728. if (IsArrived(node)) {
  729. printf(" current already in target completed !!!\n");
  730. return eMpcSuccess;
  731. }
  732. if (inited_ == false) {
  733. printf(" navigation has not inited\n");
  734. return eMpcFailed;
  735. }
  736. if (PoseTimeout()) {
  737. printf(" navigation Error:Pose is timeout \n");
  738. return eMpcFailed;
  739. }
  740. Pose2d current=timedPose_.Get();
  741. Pose2d target(node.x(),node.y(),0);
  742. //生成轨迹
  743. Trajectory traj = Trajectory::create_line_trajectory(current, target);
  744. if (traj.size() == 0)
  745. return eMpcSuccess;
  746. //判断 巡线方向
  747. bool directY=false;
  748. if(autoDirect){
  749. Pose2d target_relative=Pose2d::relativePose(target,timedPose_.Get());
  750. if( fabs(target_relative.y())>fabs(target_relative.x())) { //目标轨迹点在当前点Y轴上
  751. std::cout<<" MPC Y axis target_relative:"<<target_relative<<std::endl;
  752. directY = true;
  753. }else{
  754. std::cout<<" MPC X axis target_relative:"<<target_relative<<std::endl;
  755. }
  756. }
  757. printf(" exec along autoDirect:%d\n",autoDirect);
  758. while (cancel_ == false) {
  759. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  760. if (pause_ == true) {
  761. //发送暂停消息
  762. continue;
  763. }
  764. if (PoseTimeout()) {
  765. printf(" navigation Error:Pose is timeout \n");
  766. return eMpcFailed;
  767. }
  768. if(timedV_.timeout() || timedA_.timeout()){
  769. printf(" navigation Error:v/a is timeout \n");
  770. return eMpcFailed;
  771. }
  772. //判断是否到达终点
  773. if (IsArrived(node)) {
  774. if (Stop()) {
  775. printf(" exec along completed !!!\n");
  776. return eMpcSuccess;
  777. }
  778. }
  779. //一次变速
  780. std::vector<double> out;
  781. bool ret;
  782. TimerRecord::Execute([&, this]() {
  783. ret = mpc_once(traj, limit_v, out,directY);
  784. }, "mpc_once");
  785. if (ret == false) {
  786. Stop();
  787. return eMpcFailed;
  788. }
  789. /*
  790. * AGV 在终点附近低速巡航时,设置最小速度0.05
  791. */
  792. Pose2d target_in_agv=Pose2d::relativePose(target,timedPose_.Get());
  793. if (directY) {
  794. target_in_agv=target_in_agv.rotate(M_PI / 2.0);
  795. }
  796. if(Pose2d::abs(target_in_agv)<Pose2d(0.2,2,M_PI*2)) {
  797. if (out[0] >= 0 && out[0] < limit_v.min)
  798. out[0] = limit_v.min;
  799. if (out[0] < 0 && out[0] > -limit_v.min)
  800. out[0] = -limit_v.min;
  801. }
  802. //下发速度
  803. if(directY==false)
  804. SendMoveCmd(move_mode_, Monitor_emqx::eVertical, out[0], out[1]);
  805. else
  806. SendMoveCmd(move_mode_, Monitor_emqx::eHorizontal, out[0], out[1]);
  807. actionType_=directY?eHorizon:eVertical;
  808. /*
  809. * 判断车辆是否在终点附近徘徊,无法到达终点
  810. */
  811. if (PossibleToTarget(node, directY) == false) {
  812. printf(" --------------MPC imposible to target -------------------------------------------\n");
  813. if(fabs(timedV_.Get())>0.1 || fabs(timedA_.Get())>10*M_PI/180.0)
  814. SlowlyStop();
  815. else
  816. Stop();
  817. return eImpossibleToTarget;
  818. }
  819. }
  820. return eMpcFailed;
  821. }
  822. bool Navigation::PossibleToTarget(NavMessage::PathNode targetNode,bool directY) {
  823. if (timedPose_.timeout()) {
  824. return false;
  825. }
  826. Pose2d current = timedPose_.Get();
  827. double tx = targetNode.x();
  828. double ty = targetNode.y();
  829. double l = fabs(targetNode.l());
  830. double w = fabs(targetNode.w());
  831. double theta = targetNode.theta();
  832. double W = 2.45;
  833. double L = 1.3;
  834. if(move_mode_==Monitor_emqx::eMain){
  835. L=1.3+2.7;
  836. }
  837. if(directY){
  838. current=current.rotate(current.x(),current.y(),M_PI/2);
  839. double t=W;
  840. W=L;
  841. L=t;
  842. }
  843. double minR = W / 2 + L / tan(5 * M_PI / 180.0);
  844. printf("l:%f,w:%f\n",l,w);
  845. std::vector<Pose2d> poses = Pose2d::generate_rectangle_vertexs(Pose2d(tx, ty, 0), l*2, w*2);
  846. bool nagY=false;
  847. bool posiY=false;
  848. for (int i = 0; i < poses.size(); ++i) {
  849. Pose2d rpos = poses[i].rotate(tx, ty, theta);
  850. Pose2d relative=Pose2d::relativePose(rpos,current);
  851. double ax =fabs(relative.x());
  852. double ay = fabs(relative.y());
  853. if(relative.y()>0) posiY=true;
  854. if(relative.y()<0) nagY=true;
  855. if (ax * ax + pow(ay - minR, 2) > minR*minR) {
  856. /*printf(" possible to target:%f %f l:%f,w:%f theta:%f minR:%f ax:%f,ay:%f\n",
  857. targetNode.x(),targetNode.y(),targetNode.l(),targetNode.w(),targetNode.theta(),
  858. minR,ax,ay);*/
  859. return true;
  860. }else if(nagY&&posiY){
  861. return true;
  862. }
  863. /*printf("directY:%d targetInPose:%f %f l:%f,w:%f theta:%f minR:%f ax:%f,ay:%f\n",directY,
  864. relative.x(),relative.y(),targetNode.l(),targetNode.w(),targetNode.theta(),
  865. minR,ax,ay);*/
  866. }
  867. printf(" impossible to target:%f %f l:%f,w:%f theta:%f\n",
  868. targetNode.x(),targetNode.y(),targetNode.l(),targetNode.w(),targetNode.theta());
  869. return false;
  870. }
  871. void Navigation::navigatting() {
  872. if (inited_ == false) {
  873. printf(" navigation has not inited\n");
  874. return;
  875. }
  876. pause_ = false;
  877. cancel_ = false;
  878. running_ = true;
  879. actionType_ = eReady;
  880. printf(" navigation beg...\n");
  881. while (newUnfinished_cations_.empty() == false && cancel_ == false) {
  882. std::cout << "unfinished size:" << newUnfinished_cations_.size() << std::endl;
  883. NavMessage::NewAction act = newUnfinished_cations_.front();
  884. if(act.type()==1){ //入库
  885. space_id_=act.spacenode().id();
  886. isInSpace_=true;
  887. if(!execute_InOut_space(act)){
  888. printf(" In space failed\n");
  889. break;
  890. }
  891. }
  892. else if(act.type()==2){ //出库
  893. if(!execute_InOut_space(act)){
  894. printf(" out space failed\n");
  895. break;
  896. }else{
  897. isInSpace_=false;
  898. }
  899. }else if (act.type() == 3 || act.type() == 4) { //马路导航
  900. if (!execute_nodes(act))
  901. break;
  902. }else if(act.type()==5){
  903. printf(" 汽车模型导航....\n");
  904. }else if (act.type() == 6) {//夹持
  905. if (this->clamp_close() == false) {
  906. printf("夹持failed ...\n");
  907. break;
  908. }
  909. } else if (act.type() == 7) {
  910. if (this->clamp_open() == false) {
  911. printf("打开夹持 failed...\n");
  912. break;
  913. }
  914. } else if(act.type()==8){ //切换模式
  915. SwitchMode(Monitor_emqx::ActionMode(act.changedmode()),act.wheelbase());
  916. }else{
  917. printf(" action type invalid not handled !!\n");
  918. break;
  919. }
  920. newUnfinished_cations_.pop();
  921. }
  922. actionType_ = eReady;
  923. Stop();
  924. if (cancel_ == true) {
  925. printf(" navigation canceled\n");
  926. while (newUnfinished_cations_.empty() == false)
  927. newUnfinished_cations_.pop();
  928. } else {
  929. if (newUnfinished_cations_.empty())
  930. printf("navigation completed!!!\n");
  931. else {
  932. printf(" navigation Failed\n");
  933. while (newUnfinished_cations_.empty() == false)
  934. newUnfinished_cations_.pop();
  935. }
  936. }
  937. running_ = false;
  938. }
  939. void Navigation::SwitchMode(Monitor_emqx::ActionMode mode,float wheelBase){
  940. printf("Child AGV can not Switch Mode\n");
  941. }
  942. float Navigation::compute_cuv(const Pose2d& target)
  943. {
  944. float x=fabs(target.x());
  945. float y=fabs(target.y());
  946. float cuv= atan(y/(x+1e-8));
  947. //printf(" ---------------------- cuv:%f\n",cuv);
  948. return cuv;
  949. }