navigation.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  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. double x = space.x() - wheelbase/2 * cos(rotated.theta());
  484. double y = space.y() - wheelbase/2 * sin(rotated.theta());
  485. target.set_x(x);
  486. target.set_y(y);
  487. target.set_theta(rotated.theta());
  488. target.set_l(0.05);
  489. target.set_w(0.03);
  490. target.set_id(space.id());
  491. //整车协调的时候,保持前后与车位一致即可
  492. if(move_mode_==Monitor_emqx::eMain){
  493. double yawDiff1 = (rotated - timedPose_.Get()).theta();
  494. double yawDiff2 = (rotated+Pose2d(0,0,M_PI) - timedPose_.Get()).theta();
  495. if(fabs(yawDiff1)<fabs(yawDiff2)){
  496. rotated=rotated+Pose2d(0,0,M_PI);
  497. }
  498. }
  499. while (cancel_ == false) {
  500. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  501. Pose2d current = timedPose_.Get();
  502. double yawDiff = (rotated - current).theta();
  503. if (fabs(yawDiff) > 1 * M_PI / 180.0) {
  504. double theta = limit_gause(yawDiff, limit_rotate.min, limit_rotate.max);
  505. double angular = next_speed(timedA_.Get(), theta, acc_angular, dt);
  506. double limit_angular = limit(angular, limit_rotate.min, limit_rotate.max);
  507. SendMoveCmd(move_mode_, Monitor_emqx::eRotate, 0, limit_angular);
  508. actionType_ = eRotation;
  509. printf(" RotateBeforeEnterSpace | input anguar:%f,next angular:%f,down:%f diff:%f anyDirect:false\n",
  510. timedA_.Get(), angular, limit_angular, yawDiff);
  511. continue;
  512. } else {
  513. if (fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  514. printf(" RotateBeforeEnterSpace refer target completed\n");
  515. printf("---------------- update new target :%f %f %f \n",target.x(),target.y(),target.theta());
  516. return true;
  517. }
  518. }
  519. }
  520. return false;
  521. }
  522. bool Navigation::execute_InOut_space(NavMessage::NewAction action) {
  523. if (action.type() != 1 && action.type() != 2) {
  524. printf(" Inout_space failed : msg action type must ==1\n ");
  525. return false;
  526. }
  527. if (!parameter_.has_inoutvlimit() || !action.has_spacenode() ||
  528. !action.has_streetnode()) {
  529. std::cout << "execute enter_space failed ,Action miss some infos:" << action.DebugString() << std::endl;
  530. return false;
  531. }
  532. if (PoseTimeout() == true) {
  533. printf(" inout_space failed type:%d : current pose is timeout\n", action.type());
  534. return false;
  535. }
  536. stLimit limit_v={parameter_.inoutvlimit().min(),parameter_.inoutvlimit().max()};
  537. stLimit limit_w={2*M_PI/180.0,20*M_PI/180.0};
  538. //入库,起点为streetNode
  539. if(action.type()==1){
  540. Pose2d vec(action.spacenode().x()-action.streetnode().x(),action.spacenode().y()-action.streetnode().y(),0);
  541. action.mutable_streetnode()->set_l(0.2);
  542. action.mutable_streetnode()->set_w(0.05);
  543. action.mutable_streetnode()->set_theta(Pose2d::vector2yaw(vec.x(),vec.y()));
  544. if(MoveToTarget(action.streetnode(),limit_v,limit_w,true,true)==false)
  545. {
  546. printf(" Enter space failed type:%d: MoveTo StreetNode failed\n", action.type());
  547. return false;
  548. }
  549. //移动到库位点, 禁止任意方向// 不允许巡线中停下旋转(当无法到达目标点时,返回false)
  550. printf("inout ----------------------------------------\n");
  551. //计算车位朝向
  552. action.mutable_spacenode()->set_theta(Pose2d::vector2yaw(vec.x(),vec.y()));
  553. //计算当前车是进入车位1点还是2点
  554. NavMessage::PathNode new_atrget;
  555. if(RotateBeforeEnterSpace(action.spacenode(),action.wheelbase(),new_atrget)==false){
  556. return false;
  557. }
  558. if(MoveToTarget(new_atrget,limit_v,limit_w,true,false)==false)
  559. {
  560. printf(" Enter space failed type:%d: MoveTo StreetNode failed\n", action.type());
  561. return false;
  562. }
  563. }else if(action.type()==2){
  564. Pose2d space(action.spacenode().x(),action.spacenode().y(),0);
  565. Pose2d diff=Pose2d::abs(Pose2d::relativePose(space,timedPose_.Get()));
  566. if(diff.y()<0.05){
  567. //出库,移动到马路点,允许自由方向,不允许中途旋转
  568. Pose2d vec(action.streetnode().x()-action.spacenode().x(),action.streetnode().y()-action.spacenode().y(),0);
  569. action.mutable_streetnode()->set_theta(Pose2d::vector2yaw(vec.x(),vec.y()));
  570. action.mutable_streetnode()->set_l(0.2);
  571. action.mutable_streetnode()->set_w(0.1);
  572. if(MoveToTarget(action.streetnode(),limit_v,limit_w,true,false)==false){
  573. printf(" out space failed type:%d: MoveTo StreetNode failed\n", action.type());
  574. return false;
  575. }
  576. }else{
  577. std::cout<<" Out space failed: current pose too far from space node:"<<space<<",diff:"<<diff<<std::endl;
  578. return false;
  579. }
  580. }
  581. return true;
  582. }
  583. bool Navigation::mpc_once(Trajectory traj,stLimit limit_v,std::vector<double>& out,bool directY) {
  584. if (PoseTimeout() == true) {
  585. printf(" MPC once Error:Pose is timeout \n");
  586. return false;
  587. }
  588. if(timedV_.timeout() == true || timedA_.timeout() == true){
  589. printf(" MPC once Error:V/A is timeout \n");
  590. return false;
  591. }
  592. if (traj.size() == 0) {
  593. printf("traj size ==0\n");
  594. return false;
  595. }
  596. Pose2d pose = timedPose_.Get();
  597. double velocity = timedV_.Get(); //从plc获取状态
  598. double angular = timedA_.Get();
  599. Eigen::VectorXd statu = Eigen::VectorXd::Zero(5);//agv状态
  600. statu[0] = pose.x();
  601. statu[1] = pose.y();
  602. statu[2] = pose.theta();
  603. statu[3] = velocity;
  604. statu[4] = angular;
  605. Trajectory optimize_trajectory;
  606. Trajectory selected_trajectory;
  607. NavParameter::MPC_parameter mpc_parameter=parameter_.x_mpc_parameter();
  608. double obs_w=0.85;
  609. double obs_h=1.45;
  610. if (directY == true) {
  611. //将车身朝向旋转90°,车身朝向在(-pi,pi]
  612. statu[2] += M_PI / 2;
  613. if (statu[2] > M_PI)
  614. statu[2] -= 2 * M_PI;
  615. mpc_parameter=parameter_.y_mpc_parameter();
  616. obs_w=1.45;
  617. obs_h=0.85;
  618. }
  619. Pose2d brother = timedBrotherPose_.Get();
  620. Pose2d relative = Pose2d::relativePose(brother, pose);
  621. if(directY)
  622. relative = Pose2d::relativePose(brother.rotate(brother.x(),brother.y(),M_PI/2), pose.rotate(pose.x(),pose.y(),M_PI/2));//计算另一节在当前小车坐标系下的坐标
  623. //std::cout<<"pose:"<<pose<<", brother:"<<brother<<", relative:"<<relative<<std::endl;
  624. if (move_mode_ == Monitor_emqx::ActionMode::eMain)
  625. relative = Pose2d(-1e8, -1e8, 0);
  626. MpcError ret = failed;
  627. LoadedMPC MPC(relative, obs_w,obs_h,limit_v.min, limit_v.max);
  628. LoadedMPC::MPC_parameter parameter={mpc_parameter.shortest_radius(),mpc_parameter.dt(),
  629. mpc_parameter.acc_velocity(),mpc_parameter.acc_angular()};
  630. //printf(" r:%f dt:%f acc:%f acc_a:%f\n",mpc_parameter.shortest_radius(),
  631. // mpc_parameter.dt(),mpc_parameter.acc_velocity(),mpc_parameter.acc_angular());
  632. ret = MPC.solve(traj, traj[traj.size() - 1], statu,parameter,
  633. out, selected_trajectory, optimize_trajectory);
  634. //std::cout<<" traj size %d %d -------- "<<selected_trajectory.size()<<","<<optimize_trajectory.size()<<std::endl;
  635. if(ret==no_solution) {
  636. printf(" mpc solve no solution set v/w = 0\n");
  637. out.clear();
  638. out.push_back(0);
  639. out.push_back(0);
  640. }
  641. predict_traj_.reset(optimize_trajectory, 1);
  642. selected_traj_.reset(selected_trajectory, 1);
  643. return ret==success || ret==no_solution;
  644. }
  645. bool Navigation::IsArrived(NavMessage::PathNode targetNode)
  646. {
  647. if(timedPose_.timeout()|| timedV_.timeout()||timedA_.timeout()){
  648. printf(" pose / v / w timeout,IsArrived return false\n");
  649. return false;
  650. }
  651. Pose2d current=timedPose_.Get();
  652. double x=current.x();
  653. double y=current.y();
  654. double tx=targetNode.x();
  655. double ty=targetNode.y();
  656. double l=fabs(targetNode.l());
  657. double w=fabs(targetNode.w());
  658. double theta=-targetNode.theta();
  659. if(l<1e-10 || w<1e-10){
  660. printf("IsArrived: Error target l or w == 0\n");
  661. return false;
  662. }
  663. double a=(x-tx)*cos(theta)-(y-ty)*sin(theta);
  664. double b=(x-tx)*sin(theta)+(y-ty)*cos(theta);
  665. if( pow(a/l,8)+pow(b/w,8) <=1){
  666. if(fabs(timedV_.Get())<0.06 && fabs(timedA_.Get())<5*M_PI/180.0) {
  667. printf(" Arrived target: %f %f l:%f w:%f theta:%f\n",tx,ty,l,w,theta);
  668. return true;
  669. }
  670. }
  671. return false;
  672. }
  673. void Navigation::SendMoveCmd(Monitor_emqx::ActionMode mode,Monitor_emqx::ActionType type,
  674. double v,double angular){
  675. if(monitor_) {
  676. monitor_->set_speed(mode, type, v, angular);
  677. if(mode==ActionType::eRotation)
  678. RWheel_position_=eR;
  679. if(mode==ActionType::eVertical)
  680. RWheel_position_=eX;
  681. if(mode==ActionType::eHorizon)
  682. RWheel_position_=eY;
  683. }
  684. }
  685. bool Navigation::clamp_close()
  686. {
  687. if(monitor_) {
  688. printf("Clamp closing...\n");
  689. monitor_->clamp_close(move_mode_);
  690. actionType_=eClampClose;
  691. while (cancel_ == false) {
  692. if (timed_clamp_.timeout()) {
  693. printf("timed clamp is timeout\n");
  694. return false;
  695. }
  696. if (timed_clamp_.Get() == eClosed)
  697. return true;
  698. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  699. monitor_->clamp_close(move_mode_);
  700. actionType_=eClampClose;
  701. }
  702. return false;
  703. }
  704. return false;
  705. }
  706. bool Navigation::clamp_open() {
  707. if(monitor_) {
  708. printf("Clamp openning...\n");
  709. monitor_->clamp_open(move_mode_);
  710. actionType_=eClampOpen;
  711. while(cancel_==false)
  712. {
  713. if(timed_clamp_.timeout())
  714. {
  715. printf("timed clamp is timeout\n");
  716. return false;
  717. }
  718. if(timed_clamp_.Get()==eOpened)
  719. return true;
  720. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  721. monitor_->clamp_open(move_mode_);
  722. actionType_=eClampOpen;
  723. }
  724. return false;
  725. }
  726. return false;
  727. }
  728. Navigation::MpcResult Navigation::MpcToTarget(NavMessage::PathNode node,stLimit limit_v,bool autoDirect) {
  729. if (IsArrived(node)) {
  730. printf(" current already in target completed !!!\n");
  731. return eMpcSuccess;
  732. }
  733. if (inited_ == false) {
  734. printf(" navigation has not inited\n");
  735. return eMpcFailed;
  736. }
  737. if (PoseTimeout()) {
  738. printf(" navigation Error:Pose is timeout \n");
  739. return eMpcFailed;
  740. }
  741. Pose2d current=timedPose_.Get();
  742. Pose2d target(node.x(),node.y(),0);
  743. //生成轨迹
  744. Trajectory traj = Trajectory::create_line_trajectory(current, target);
  745. if (traj.size() == 0)
  746. return eMpcSuccess;
  747. //判断 巡线方向
  748. bool directY=false;
  749. if(autoDirect){
  750. Pose2d target_relative=Pose2d::relativePose(target,timedPose_.Get());
  751. if( fabs(target_relative.y())>fabs(target_relative.x())) { //目标轨迹点在当前点Y轴上
  752. std::cout<<" MPC Y axis target_relative:"<<target_relative<<std::endl;
  753. directY = true;
  754. }else{
  755. std::cout<<" MPC X axis target_relative:"<<target_relative<<std::endl;
  756. }
  757. }
  758. printf(" exec along autoDirect:%d\n",autoDirect);
  759. while (cancel_ == false) {
  760. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  761. if (pause_ == true) {
  762. //发送暂停消息
  763. continue;
  764. }
  765. if (PoseTimeout()) {
  766. printf(" navigation Error:Pose is timeout \n");
  767. return eMpcFailed;
  768. }
  769. if(timedV_.timeout() || timedA_.timeout()){
  770. printf(" navigation Error:v/a is timeout \n");
  771. return eMpcFailed;
  772. }
  773. //判断是否到达终点
  774. if (IsArrived(node)) {
  775. if (Stop()) {
  776. printf(" exec along completed !!!\n");
  777. return eMpcSuccess;
  778. }
  779. }
  780. //一次变速
  781. std::vector<double> out;
  782. bool ret;
  783. TimerRecord::Execute([&, this]() {
  784. ret = mpc_once(traj, limit_v, out,directY);
  785. }, "mpc_once");
  786. if (ret == false) {
  787. Stop();
  788. return eMpcFailed;
  789. }
  790. /*
  791. * AGV 在终点附近低速巡航时,设置最小速度0.05
  792. */
  793. Pose2d target_in_agv=Pose2d::relativePose(target,timedPose_.Get());
  794. if (directY) {
  795. target_in_agv=target_in_agv.rotate(M_PI / 2.0);
  796. }
  797. if(Pose2d::abs(target_in_agv)<Pose2d(0.2,2,M_PI*2)) {
  798. if (out[0] >= 0 && out[0] < limit_v.min)
  799. out[0] = limit_v.min;
  800. if (out[0] < 0 && out[0] > -limit_v.min)
  801. out[0] = -limit_v.min;
  802. }
  803. //下发速度
  804. if(directY==false)
  805. SendMoveCmd(move_mode_, Monitor_emqx::eVertical, out[0], out[1]);
  806. else
  807. SendMoveCmd(move_mode_, Monitor_emqx::eHorizontal, out[0], out[1]);
  808. actionType_=directY?eHorizon:eVertical;
  809. /*
  810. * 判断车辆是否在终点附近徘徊,无法到达终点
  811. */
  812. if (PossibleToTarget(node, directY) == false) {
  813. printf(" --------------MPC imposible to target -------------------------------------------\n");
  814. if(fabs(timedV_.Get())>0.1 || fabs(timedA_.Get())>10*M_PI/180.0)
  815. SlowlyStop();
  816. else
  817. Stop();
  818. return eImpossibleToTarget;
  819. }
  820. }
  821. return eMpcFailed;
  822. }
  823. bool Navigation::PossibleToTarget(NavMessage::PathNode targetNode,bool directY) {
  824. if (timedPose_.timeout()) {
  825. return false;
  826. }
  827. Pose2d current = timedPose_.Get();
  828. double tx = targetNode.x();
  829. double ty = targetNode.y();
  830. double l = fabs(targetNode.l());
  831. double w = fabs(targetNode.w());
  832. double theta = -targetNode.theta();
  833. double W = 2.45;
  834. double L = 1.3;
  835. double minYaw=5*M_PI/180.0;
  836. if(move_mode_==Monitor_emqx::eMain){
  837. L=1.3+2.7;
  838. }
  839. if(directY){
  840. current=current.rotate(current.x(),current.y(),M_PI/2);
  841. double t=W;
  842. W=L;
  843. L=t;
  844. }
  845. double minR = W / 2 + L / tan(minYaw);
  846. //printf("l:%f,w:%f\n",l,w);
  847. std::vector<Pose2d> poses = Pose2d::generate_rectangle_vertexs(Pose2d(tx, ty, 0), l*2, w*2);
  848. bool nagY=false;
  849. bool posiY=false;
  850. for (int i = 0; i < poses.size(); ++i) {
  851. Pose2d rpos = poses[i].rotate(tx, ty, theta);
  852. Pose2d relative=Pose2d::relativePose(rpos,current);
  853. double ax =fabs(relative.x());
  854. double ay = fabs(relative.y());
  855. if(relative.y()>0) posiY=true;
  856. if(relative.y()<0) nagY=true;
  857. if (ax * ax + pow(ay - minR, 2) > minR*minR) {
  858. /*printf(" possible to target:%f %f l:%f,w:%f theta:%f minR:%f ax:%f,ay:%f\n",
  859. targetNode.x(),targetNode.y(),targetNode.l(),targetNode.w(),targetNode.theta(),
  860. minR,ax,ay);*/
  861. return true;
  862. }else if(nagY&&posiY){
  863. return true;
  864. }
  865. printf("directY:%d targetInPose:%f %f l:%f,w:%f theta:%f minR:%f ax:%f,ay:%f\n",directY,
  866. relative.x(),relative.y(),targetNode.l(),targetNode.w(),targetNode.theta(),
  867. minR,ax,ay);
  868. }
  869. printf(" impossible to target:%f %f l:%f,w:%f theta:%f\n",
  870. targetNode.x(),targetNode.y(),targetNode.l(),targetNode.w(),targetNode.theta());
  871. return false;
  872. }
  873. void Navigation::Start(const NavMessage::NavCmd& cmd,NavMessage::NavResponse& response) {
  874. if (inited_ == false) {
  875. response.set_ret(-1);
  876. response.set_info("navigation has not inited");
  877. printf(" navigation has not inited\n");
  878. return ;
  879. }
  880. if(newUnfinished_cations_.empty()==false) //正在运行中,上一次指令未完成
  881. {
  882. response.set_ret(-2);
  883. response.set_info("navigation is running pls cancel before");
  884. printf(" navigation is running pls cancel before\n");
  885. return ;
  886. }
  887. //add 先检查当前点与起点的距离
  888. global_navCmd_=cmd;
  889. for (int i = 0; i < cmd.newactions_size(); ++i)
  890. newUnfinished_cations_.push(cmd.newactions(i));
  891. pause_ = false;
  892. cancel_ = false;
  893. running_ = true;
  894. actionType_ = eReady;
  895. printf(" navigation beg...\n");
  896. while (newUnfinished_cations_.empty() == false && cancel_ == false) {
  897. std::cout << "unfinished size:" << newUnfinished_cations_.size() << std::endl;
  898. NavMessage::NewAction act = newUnfinished_cations_.front();
  899. if(act.type()==1){ //入库
  900. space_id_=act.spacenode().id();
  901. isInSpace_=true;
  902. if(!execute_InOut_space(act)){
  903. printf(" In space failed\n");
  904. break;
  905. }
  906. }
  907. else if(act.type()==2){ //出库
  908. if(!execute_InOut_space(act)){
  909. printf(" out space failed\n");
  910. break;
  911. }else{
  912. isInSpace_=false;
  913. }
  914. }else if (act.type() == 3 || act.type() == 4) { //马路导航
  915. if (!execute_nodes(act))
  916. break;
  917. }else if(act.type()==5){
  918. printf(" 汽车模型导航....\n");
  919. }else if (act.type() == 6) {//夹持
  920. if (this->clamp_close() == false) {
  921. printf("夹持failed ...\n");
  922. break;
  923. }
  924. } else if (act.type() == 7) {
  925. if (this->clamp_open() == false) {
  926. printf("打开夹持 failed...\n");
  927. break;
  928. }
  929. } else if(act.type()==8){ //切换模式
  930. SwitchMode(Monitor_emqx::ActionMode(act.changedmode()),act.wheelbase());
  931. }else{
  932. printf(" action type invalid not handled !!\n");
  933. break;
  934. }
  935. newUnfinished_cations_.pop();
  936. }
  937. actionType_ = eReady;
  938. Stop();
  939. if (cancel_ == true) {
  940. response.set_ret(-3);
  941. response.set_info("navigation canceled");
  942. printf(" navigation canceled\n");
  943. while (newUnfinished_cations_.empty() == false)
  944. newUnfinished_cations_.pop();
  945. } else {
  946. if (newUnfinished_cations_.empty()) {
  947. response.set_ret(0);
  948. response.set_info("navigation completed!!!");
  949. printf("navigation completed!!!\n");
  950. }
  951. else {
  952. response.set_ret(-4);
  953. response.set_info("navigation Failed!!!!");
  954. printf(" navigation Failed\n");
  955. while (newUnfinished_cations_.empty() == false)
  956. newUnfinished_cations_.pop();
  957. }
  958. }
  959. running_ = false;
  960. }
  961. void Navigation::SwitchMode(Monitor_emqx::ActionMode mode,float wheelBase){
  962. printf("Child AGV can not Switch Mode\n");
  963. }
  964. float Navigation::compute_cuv(const Pose2d& target)
  965. {
  966. float x=fabs(target.x());
  967. float y=fabs(target.y());
  968. float cuv= atan(y/(x+1e-8));
  969. //printf(" ---------------------- cuv:%f\n",cuv);
  970. return cuv;
  971. }