navigation.cpp 33 KB

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