navigation.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403
  1. //
  2. // Created by zx on 22-12-2.
  3. //
  4. #include "navigation.h"
  5. #include "loaded_mpc.h"
  6. #include "rotate_mpc.h"
  7. #include "../define/TimerRecord.h"
  8. Navigation::~Navigation() {
  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. if (pubthread_->joinable())
  18. pubthread_->join();
  19. delete pubthread_;
  20. }
  21. }
  22. /*
  23. * 高斯函数压缩,x=3
  24. */
  25. double limit_gause(double x, double min, double max) {
  26. double r = x >= 0 ? 1.0 : -1.0;
  27. double delta = max / 1.0;
  28. return (max - (max - min) * exp(-x * x / (delta * delta))) * r;
  29. }
  30. double limit(double x, double min, double max) {
  31. double ret = x;
  32. if (x >= 0) {
  33. if (x > max) ret = max;
  34. if (x < min) ret = min;
  35. } else {
  36. if (x < -max) ret = -max;
  37. if (x > -min) ret = -min;
  38. }
  39. return ret;
  40. }
  41. double next_speed(double speed, double target_speed, double acc, double dt) {
  42. if (fabs(target_speed - speed) / dt < acc) {
  43. return target_speed;
  44. } else {
  45. double r = target_speed - speed >= 0. ? 1.0 : -1.0;
  46. return speed + r * acc * dt;
  47. }
  48. }
  49. bool Navigation::PoseTimeout() {
  50. // if (timedPose_.timeout() == false && timedBrotherPose_.timeout() == false) {
  51. if (timedPose_.timeout() == false) {
  52. return false;
  53. } else {
  54. if (timedPose_.timeout()) {
  55. printf(" current pose is timeout \n");
  56. }
  57. // if (timedBrotherPose_.timeout()) {
  58. // printf(" brother pose is timeout \n");
  59. // }
  60. return true;
  61. }
  62. }
  63. bool Navigation::Init(const NavParameter::Navigation_parameter &parameter) {
  64. parameter_ = parameter;
  65. NavParameter::AgvEmqx_parameter agv_p = parameter.agv_emqx();
  66. if (monitor_ == nullptr) {
  67. monitor_ = new Monitor_emqx(agv_p.nodeid());
  68. if (monitor_->Connect(agv_p.ip(), agv_p.port()) == false) {
  69. printf(" agv emqx connected failed\n");
  70. return false;
  71. }
  72. monitor_->set_speedcmd_topic(agv_p.pubspeedtopic());
  73. monitor_->AddCallback(agv_p.subposetopic(), Navigation::RobotPoseCallback, this);
  74. monitor_->AddCallback(agv_p.subspeedtopic(), Navigation::RobotSpeedCallback, this);
  75. }
  76. NavParameter::Emqx_parameter terminal_p = parameter.terminal_emqx();
  77. if (terminator_ == nullptr) {
  78. terminator_ = new Terminator_emqx(terminal_p.nodeid());
  79. if (terminator_->Connect(terminal_p.ip(), terminal_p.port()) == false) {
  80. printf(" terminator emqx connected failed\n");
  81. return false;
  82. }
  83. }
  84. if (parameter.has_brother_emqx()) {
  85. NavParameter::BrotherEmqx brotherEmqx = parameter.brother_emqx();
  86. if (brotherEmqx_ == nullptr) {
  87. brotherEmqx_ = new Terminator_emqx(brotherEmqx.nodeid());
  88. if (brotherEmqx_->Connect(brotherEmqx.ip(), brotherEmqx.port()) == true) {
  89. brotherEmqx_->AddCallback(brotherEmqx.subbrotherstatutopic(), Navigation::BrotherAgvStatuCallback,
  90. this);
  91. } else {
  92. printf(" brother emqx connected failed\n");
  93. // return false;
  94. }
  95. //
  96. }
  97. }
  98. inited_ = true;
  99. if (pubthread_ != nullptr) {
  100. exit_ = true;
  101. if (pubthread_->joinable())
  102. pubthread_->join();
  103. delete pubthread_;
  104. }
  105. exit_ = false;
  106. pubthread_ = new std::thread(&Navigation::pubStatuThreadFuc, this);
  107. return true;
  108. }
  109. void Navigation::RobotPoseCallback(const MqttMsg &msg, void *context) {
  110. Navigation *navigator = (Navigation *) context;
  111. NavMessage::LidarOdomStatu statu;
  112. if (msg.toProtoMessage(statu)) {
  113. navigator->ResetPose(Pose2d(statu.x(), statu.y(), statu.theta()));
  114. }
  115. }
  116. void Navigation::HandleAgvStatu(const MqttMsg &msg) {
  117. NavMessage::AgvStatu speed;
  118. if (msg.toProtoMessage(speed)) {
  119. ResetStatu(speed.v(), speed.w());
  120. ResetClamp((ClampStatu) speed.clamp());
  121. ResetLifter((LifterStatus) speed.lifter());
  122. }
  123. }
  124. void Navigation::RobotSpeedCallback(const MqttMsg &msg, void *context) {
  125. Navigation *navigator = (Navigation *) context;
  126. navigator->HandleAgvStatu(msg);
  127. }
  128. void Navigation::pubStatuThreadFuc(void *p) {
  129. Navigation *navogator = (Navigation *) p;
  130. if (navogator) {
  131. while (navogator->exit_ == false) {
  132. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  133. NavMessage::NavStatu statu;
  134. statu.set_main_agv(false);
  135. navogator->publish_statu(statu);
  136. }
  137. }
  138. }
  139. void Navigation::publish_statu(NavMessage::NavStatu &statu) {
  140. if (timedPose_.timeout() == false) {
  141. NavMessage::LidarOdomStatu odom;
  142. odom.set_x(timedPose_.Get().x());
  143. odom.set_y(timedPose_.Get().y());
  144. odom.set_theta(timedPose_.Get().theta());
  145. if (timedV_.timeout() == false)
  146. odom.set_v(timedV_.Get());
  147. if (timedA_.timeout() == false)
  148. odom.set_vth(timedA_.Get());
  149. statu.mutable_odom()->CopyFrom(odom);
  150. }
  151. statu.set_in_space(isInSpace_);
  152. if (isInSpace_) statu.set_space_id(space_id_);
  153. //发布nav状态
  154. statu.set_statu(actionType_); //
  155. statu.set_move_mode(move_mode_);
  156. if (running_) {
  157. statu.set_key(global_navCmd_.key());
  158. }
  159. //发布MPC信息
  160. //发布mpc 预选点
  161. if (selected_traj_.timeout() == false) {
  162. for (int i = 0; i < selected_traj_.Get().size(); ++i) {
  163. Pose2d pt = selected_traj_.Get()[i];
  164. NavMessage::Pose2d *pose = statu.mutable_selected_traj()->add_poses();
  165. pose->set_x(pt.x());
  166. pose->set_y(pt.y());
  167. pose->set_theta(pt.theta());
  168. }
  169. }
  170. //发布 mpc 预测点
  171. if (predict_traj_.timeout() == false) {
  172. for (int i = 0; i < predict_traj_.Get().size(); ++i) {
  173. Pose2d pt = predict_traj_.Get()[i];
  174. NavMessage::Pose2d *pose = statu.mutable_predict_traj()->add_poses();
  175. pose->set_x(pt.x());
  176. pose->set_y(pt.y());
  177. pose->set_theta(pt.theta());
  178. }
  179. }
  180. // std::cout<<"nav statu:"<<statu.DebugString()<<std::endl;
  181. MqttMsg msg;
  182. msg.fromProtoMessage(statu);
  183. if (terminator_)
  184. terminator_->Publish(parameter_.terminal_emqx().pubnavstatutopic(), msg);
  185. //发布位姿 ------robot状态--------------------------
  186. NavMessage::RobotStatu robot;
  187. if (CreateRobotStatuMsg(robot)) {
  188. if (terminator_) {
  189. MqttMsg msg;
  190. msg.fromProtoMessage(robot);
  191. terminator_->Publish(parameter_.terminal_emqx().pubstatutopic(), msg);
  192. }
  193. }
  194. }
  195. bool Navigation::CreateRobotStatuMsg(NavMessage::RobotStatu &robotStatu) {
  196. //printf(" %d %d %d \n",timedPose_.timeout(),timedV_.timeout(),timedA_.timeout());
  197. if (timedPose_.timeout() == false) {
  198. Pose2d pose = timedPose_.Get();
  199. robotStatu.set_x(pose.x());
  200. robotStatu.set_y(pose.y());
  201. robotStatu.set_theta(pose.theta());
  202. if ((timedV_.timeout() == false && timedA_.timeout() == false)) {
  203. NavMessage::AgvStatu plc;
  204. plc.set_v(timedV_.Get());
  205. plc.set_w(timedA_.Get());
  206. plc.set_clamp(timed_clamp_.Get());
  207. plc.set_lifter(timed_lifter_.Get());
  208. //printf(" timed_clamp_:%d\n ",timed_clamp_.Get());
  209. robotStatu.mutable_agvstatu()->CopyFrom(plc);
  210. }
  211. return true;
  212. }
  213. return false;
  214. }
  215. void Navigation::ResetStatu(double v, double a) {
  216. timedV_.reset(v, 0.5);
  217. timedA_.reset(a, 0.5);
  218. }
  219. void Navigation::ResetClamp(ClampStatu statu) {
  220. timed_clamp_.reset(statu, 1);
  221. }
  222. void Navigation::ResetLifter(LifterStatus status) {
  223. timed_lifter_.reset(status, 1);
  224. }
  225. void Navigation::ResetPose(const Pose2d &pose) {
  226. timedPose_.reset(pose, 1.0);
  227. }
  228. void Navigation::Cancel(const NavMessage::NavCmd &cmd, NavMessage::NavResponse &response) {
  229. cancel_ = true;
  230. response.set_ret(0);
  231. }
  232. bool Navigation::Stop() {
  233. if (monitor_) {
  234. monitor_->stop();
  235. while (cancel_ == false) {
  236. if (timedV_.timeout() == false && timedA_.timeout() == false) {
  237. if (fabs(timedV_.Get()) < 1e-2 && fabs(timedA_.Get()) < 1e-3)
  238. return true;
  239. else
  240. monitor_->stop();
  241. printf("Stoped wait V/A ==0(1e-4,1e-4),V:%f,A:%f\n", fabs(timedV_.Get()), fabs(timedA_.Get()));
  242. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  243. } else {
  244. printf("Stop failed V/A timeout\n");
  245. return false;
  246. }
  247. }
  248. }
  249. printf("stoped ret false.\n");
  250. return false;
  251. }
  252. bool Navigation::SlowlyStop() {
  253. double acc = 3.0;
  254. double dt = 0.1;
  255. while (cancel_ == false) {
  256. if (timedV_.timeout() == false) {
  257. double v = timedV_.Get();
  258. if (fabs(v < 1e-2 && fabs(timedA_.Get()) < 1e-3))
  259. return true;
  260. if (v > 0) {
  261. double new_v = v - acc * dt;
  262. new_v = new_v > 0 ? new_v : 0;
  263. SendMoveCmd(move_mode_, actionType_, new_v, 0);
  264. } else {
  265. double new_v = v + acc * dt;
  266. new_v = new_v < 0 ? new_v : 0;
  267. SendMoveCmd(move_mode_, actionType_, new_v, 0);
  268. }
  269. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  270. } else {
  271. printf("Stop failed V/A timeout\n");
  272. return false;
  273. }
  274. }
  275. printf("stoped ret false.\n");
  276. return false;
  277. }
  278. Navigation::Navigation() {
  279. isInSpace_ = false; //是否在车位或者正在进入车位
  280. RWheel_position_ = eUnknow;
  281. move_mode_ = eSingle;
  282. monitor_ = nullptr;
  283. terminator_ = nullptr;
  284. timedBrotherPose_.reset(Pose2d(-100, 0, 0), 0.5);
  285. }
  286. void Navigation::BrotherAgvStatuCallback(const MqttMsg &msg, void *context) {
  287. Navigation *navigator = (Navigation *) context;
  288. NavMessage::NavStatu brother_statu;
  289. if (msg.toProtoMessage(brother_statu) == false) {
  290. std::cout << " msg transform to AGVStatu failed,msg:" << msg.data() << std::endl;
  291. return;
  292. }
  293. //std::cout<<brother_nav.DebugString()<<std::endl<<std::endl;
  294. if (brother_statu.has_odom()) {
  295. NavMessage::LidarOdomStatu odom = brother_statu.odom();
  296. Pose2d pose(odom.x(), odom.y(), odom.theta());
  297. navigator->timedBrotherPose_.reset(pose, 1);
  298. navigator->timedBrotherV_.reset(odom.v(), 1);
  299. navigator->timedBrotherA_.reset(odom.vth(), 1);
  300. navigator->timedBrotherNavStatu_.reset(brother_statu, 0.1);
  301. }
  302. }
  303. //未使用
  304. bool Navigation::RotateReferToTarget(const Pose2d &target, stLimit limit_rotate, bool anyDirect) {
  305. while (cancel_ == false) {
  306. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  307. if (timedPose_.timeout()) {
  308. printf(" RotateBytarget failed pose timeout\n");
  309. return false;
  310. }
  311. if (timedA_.timeout()) {
  312. printf(" RotateBytarget failed wmg timeout\n");
  313. return false;
  314. }
  315. Pose2d targetInPose = Pose2d::relativePose(target, timedPose_.Get());
  316. float yawDiff = Pose2d::vector2yaw(targetInPose.x(), targetInPose.y());
  317. float minYawdiff = yawDiff;
  318. if (anyDirect) {
  319. Pose2d p0 = timedPose_.Get();
  320. float yawdiff[4] = {0};
  321. yawdiff[0] = yawDiff;
  322. Pose2d relativePose;
  323. relativePose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, M_PI / 2));
  324. yawdiff[1] = Pose2d::vector2yaw(relativePose.x(), relativePose.y()); ////使用减法,保证角度在【-pi pi】
  325. relativePose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, M_PI));
  326. yawdiff[2] = Pose2d::vector2yaw(relativePose.x(), relativePose.y());
  327. relativePose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, 3 * M_PI / 2));
  328. yawdiff[3] = Pose2d::vector2yaw(relativePose.x(), relativePose.y());
  329. for (int i = 1; i < 4; ++i) {
  330. if (fabs(yawdiff[i]) < fabs(minYawdiff)) {
  331. minYawdiff = yawdiff[i];
  332. targetInPose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, i * M_PI / 2.0));
  333. }
  334. }
  335. }
  336. //std::cout<<" Rotate refer to target:"<<target<<",targetInPose:"
  337. //<<targetInPose<<",anyDirect:"<<anyDirect<<std::endl;
  338. //以当前点为原点,想方向经过目标点的二次曲线曲率>0.25,则需要调整 y=a x*x
  339. float cuv = compute_cuv(targetInPose);
  340. float dt = 0.1;
  341. float acc_angular = 15 * M_PI / 180.0;
  342. if (cuv > 2 * M_PI / 180.0) {
  343. double theta = limit_gause(minYawdiff, limit_rotate.min, limit_rotate.max);
  344. double angular = next_speed(timedA_.Get(), theta, acc_angular, dt);
  345. double limit_angular = limit(angular, limit_rotate.min, limit_rotate.max);
  346. SendMoveCmd(move_mode_, eRotation, 0, limit_angular);
  347. actionType_ = eRotation;
  348. printf(" Rotate | input angular:%f,next angular:%f,down:%f diff:%f anyDirect:%d\n",
  349. timedA_.Get(), angular, limit_angular, minYawdiff, anyDirect);
  350. continue;
  351. } else {
  352. if (fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  353. printf(" Rotate refer target completed,cuv:%f\n", cuv);
  354. return true;
  355. }
  356. continue;
  357. }
  358. }
  359. return false;
  360. }
  361. Navigation::MpcResult Navigation::RotateReferToTarget(NavMessage::PathNode node, stLimit limit_rotate, int directions) {
  362. if (inited_ == false) {
  363. printf(" MPC_rotate has not inited\n");
  364. return eMpcFailed;
  365. }
  366. if (PoseTimeout()) {
  367. printf(" MPC_rotate Error:Pose is timeout \n");
  368. return eMpcFailed;
  369. }
  370. printf(" exec MPC_rotate autoDirect:%d\n", directions);
  371. while (cancel_ == false) {
  372. std::this_thread::sleep_for(std::chrono::milliseconds(30));
  373. if (pause_ == true) {
  374. //发送暂停消息
  375. continue;
  376. }
  377. // if (PoseTimeout()) {
  378. // printf(" MPC_rotate Error:Pose is timeout \n");
  379. // return eMpcFailed;
  380. // }
  381. // if (timedA_.timeout()) {
  382. // printf(" MPC_rotate Error:v/a is timeout \n");
  383. // return eMpcFailed;
  384. // }
  385. Pose2d current = timedPose_.Get();
  386. Pose2d target(node.x(), node.y(), node.theta());
  387. Pose2d targetInPose = Pose2d::relativePose(target, current);
  388. // 需要旋转的角度
  389. float target_yaw_diff = Pose2d::vector2yaw(targetInPose.x(), targetInPose.y());
  390. // 自由方向
  391. if (directions) {
  392. std::vector<double> yaw_diffs;
  393. if (directions & Direction::eForward) {
  394. yaw_diffs.push_back(target_yaw_diff);
  395. }
  396. if (directions & Direction::eBackward) {
  397. Pose2d relative_pose = Pose2d::relativePose(targetInPose, Pose2d(0, 0, M_PI));
  398. yaw_diffs.push_back(Pose2d::vector2yaw(relative_pose.x(), relative_pose.y()));
  399. }
  400. if (directions & Direction::eLeft) {
  401. Pose2d relative_pose = Pose2d::relativePose(targetInPose, Pose2d(0, 0, 1.0 / 2 * M_PI));
  402. yaw_diffs.push_back(Pose2d::vector2yaw(relative_pose.x(), relative_pose.y()));
  403. }
  404. if (directions & Direction::eRight) {
  405. Pose2d relative_pose = Pose2d::relativePose(targetInPose, Pose2d(0, 0, 3.0 / 2 * M_PI));
  406. yaw_diffs.push_back(Pose2d::vector2yaw(relative_pose.x(), relative_pose.y()));
  407. }
  408. for (auto i = 0; i < yaw_diffs.size(); ++i) {
  409. if (fabs(yaw_diffs[i]) < fabs(target_yaw_diff))
  410. target_yaw_diff = yaw_diffs[i];
  411. }
  412. std::cout << std::endl;
  413. // std::cout << std::endl << " min_diff: " << current_to_target.theta() << std::endl;
  414. }
  415. //一次变速
  416. std::vector<double> out;
  417. bool ret;
  418. TimerRecord::Execute([&, this]() {
  419. ret = Rotation_mpc_once(Pose2d(0, 0, target_yaw_diff), limit_rotate, out);
  420. }, "Rotation_mpc_once");
  421. if (ret == false) {
  422. Stop();
  423. return eMpcFailed;
  424. }
  425. //下发速度
  426. if (fabs(target_yaw_diff) > 2 * M_PI / 180.0) {
  427. SendMoveCmd(move_mode_, eRotation, 0, out[0]);
  428. actionType_ = eRotation;
  429. printf(" MPC_rotate | input angular_v:%f, down:%f, diff:%f autoDirect:%d\n",
  430. timedA_.Get(), out[0], target_yaw_diff, directions);
  431. } else if (fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  432. printf(" MPC_rotate refer target completed,cuv:%f\n", target_yaw_diff);
  433. return eMpcSuccess;
  434. }
  435. continue;
  436. }
  437. return eMpcFailed;
  438. }
  439. bool Navigation::MoveToTarget(NavMessage::PathNode node, Navigation::stLimit limit_v, Navigation::stLimit limit_w,
  440. bool anyDirect, bool enable_rotate) {
  441. if (IsArrived(node)) {
  442. return true;
  443. }
  444. bool already_in_mpc = false;
  445. while (cancel_ == false) {
  446. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  447. if (PoseTimeout()) {
  448. printf(" navigation Error:Pose is timeout \n");
  449. break;
  450. }
  451. Pose2d current = timedPose_.Get();
  452. if (IsArrived(node)) {
  453. break;
  454. }
  455. //两个方向都无法到达目标点,旋转 朝向目标点
  456. bool x_enable = PossibleToTarget(node, false);
  457. bool y_enable = PossibleToTarget(node, true);
  458. bool enableTotarget = x_enable || y_enable;
  459. if (anyDirect == false) {
  460. enableTotarget = x_enable;
  461. }
  462. //巡线无法到达目标点
  463. if (enableTotarget == false) {
  464. if (already_in_mpc && enable_rotate == false) {
  465. printf(" Move to node failed ,impossible to target and rotate is not enabled\n");
  466. return false;
  467. }
  468. Pose2d target(node.x(), node.y(), 0);
  469. // if (RotateReferToTarget(target, limit_w, anyDirect) == false) {
  470. int directions = Direction::eForward;
  471. if (anyDirect)
  472. directions = Direction::eForward | Direction::eBackward |
  473. Direction::eLeft | Direction::eRight;
  474. if (RotateReferToTarget(node, limit_w, directions) != eMpcSuccess) {
  475. std::cout << " Rotate refer to target failed,target: " << target <<
  476. " directions: " << std::hex << directions << " line_: " << __LINE__ << std::endl;
  477. return false;
  478. }
  479. continue;
  480. }
  481. already_in_mpc = true;
  482. MpcResult ret = MpcToTarget(node, limit_v, anyDirect);
  483. if (ret == eMpcSuccess) {
  484. printf(" MPC to target:%f %f l:%f,w:%f theta:%f completed\n",
  485. node.x(), node.y(), node.l(), node.w(), node.theta());
  486. break;
  487. } else if (ret == eImpossibleToTarget) {
  488. printf(" MPC to target:%f %f l:%f,w:%f theta:%f impossible ,retry ...\n",
  489. node.x(), node.y(), node.l(), node.w(), node.theta());
  490. } else {
  491. return false;
  492. }
  493. }
  494. if (cancel_) {
  495. return false;
  496. }
  497. return true;
  498. }
  499. bool Navigation::execute_nodes(NavMessage::NewAction action) {
  500. if (action.type() == 3 || action.type() == 4) //最优动作导航 or 导航中保证朝向严格一致
  501. {
  502. if (!parameter_.has_nodeangularlimit() || !parameter_.has_nodevelocitylimit() || action.pathnodes_size() == 0) {
  503. std::cout << "execute pathNodes failed ,Action invalid:" << action.DebugString() << std::endl;
  504. return false;
  505. }
  506. bool anyDirect = (action.type() == 3);
  507. //速度限制
  508. stLimit adjust_angular = {parameter_.nodeangularlimit().min(), parameter_.nodeangularlimit().max()};
  509. stLimit mpc_velocity = {parameter_.nodevelocitylimit().min(), parameter_.nodevelocitylimit().max()};
  510. for (int i = 0; i < action.pathnodes_size(); ++i) {
  511. NavMessage::PathNode node = action.pathnodes(i);
  512. if (i + 1 < action.pathnodes_size()) {
  513. NavMessage::PathNode next = action.pathnodes(i + 1);
  514. Pose2d vec(next.x() - node.x(), next.y() - node.y(), 0);
  515. node.set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  516. node.set_l(0.3);
  517. node.set_w(0.1);
  518. } else {
  519. node.set_theta(0);
  520. node.set_w(0.2);
  521. node.set_l(0.2);
  522. }
  523. if (MoveToTarget(node, mpc_velocity, adjust_angular, anyDirect, true) == false)
  524. return false;
  525. else
  526. isInSpace_ = false;
  527. }
  528. return true;
  529. }
  530. printf("execute PathNode failed ,action type is not 3/4 :%d\n", action.type());
  531. return false;
  532. }
  533. Navigation::MpcResult
  534. Navigation::RotateBeforeEnterSpace(NavMessage::PathNode space, double wheelbase, NavMessage::PathNode &target) {
  535. if (timedBrotherNavStatu_.timeout() || timedPose_.timeout()) {
  536. // if (timedPose_.timeout()) {
  537. printf(" rotate failed : timedBrotherNavStatu_ or pose timeout\n");
  538. return eMpcFailed;
  539. }
  540. NavMessage::NavStatu brother = timedBrotherNavStatu_.Get();
  541. stLimit limit_rotate = {2 * M_PI / 180.0, 15 * M_PI / 180.0};
  542. double acc_angular = 20 * M_PI / 180.0;
  543. double dt = 0.1;
  544. Pose2d rotated = timedPose_.Get();
  545. double x = space.x();
  546. double y = space.y();
  547. //前车先到,后车进入2点,保持与前车一致的朝向
  548. if (brother.in_space() && brother.space_id() == space.id()) {
  549. rotated.mutable_theta() = brother.odom().theta();
  550. if (move_mode_ == eSingle) {
  551. x -= wheelbase * cos(rotated.theta());
  552. y -= wheelbase * sin(rotated.theta());
  553. printf("确定车位点:eSingle\n");
  554. }
  555. } else { //当后车先到,倒车入库
  556. rotated.mutable_theta() = space.theta();
  557. rotated = rotated.rotate(rotated.x(), rotated.y(), M_PI);
  558. }
  559. target.set_x(x);
  560. target.set_y(y);
  561. target.set_theta(rotated.theta());
  562. target.set_l(0.05);
  563. target.set_w(0.05);
  564. target.set_id(space.id());
  565. // //整车协调的时候,保持前后与车位一致即可
  566. // if (move_mode_ == eDouble) {
  567. // double yawDiff1 = (rotated - timedPose_.Get()).theta();
  568. // double yawDiff2 = (rotated + Pose2d(0, 0, M_PI) - timedPose_.Get()).theta();
  569. // if (fabs(yawDiff1) < fabs(yawDiff2)) {
  570. // rotated = rotated + Pose2d(0, 0, M_PI);
  571. // }
  572. // }
  573. while (cancel_ == false) {
  574. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  575. Pose2d current = timedPose_.Get();
  576. double yawDiff = (rotated - current).theta();
  577. //一次变速
  578. std::vector<double> out;
  579. bool ret;
  580. TimerRecord::Execute([&, this]() {
  581. ret = Rotation_mpc_once(Pose2d(0, 0, yawDiff), limit_rotate, out);
  582. }, "Rotation_mpc_once");
  583. if (ret == false) {
  584. Stop();
  585. return eMpcFailed;
  586. }
  587. //下发速度
  588. if (fabs(yawDiff) < 0.5 * M_PI / 180.0 && fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  589. printf(" RotateBeforeEnterSpace refer target completed\\n,cuv:%f\n", yawDiff);
  590. Stop();
  591. return eMpcSuccess;
  592. } else{
  593. SendMoveCmd(move_mode_, eRotation, 0, out[0]);
  594. actionType_ = eRotation;
  595. printf(" RotateBeforeEnterSpace | input anguar:%f, down:%f(%f), diff:%f anyDirect:false\n",
  596. timedA_.Get(), out[0], out[0]/M_PI*180, yawDiff);
  597. }
  598. continue;
  599. }
  600. return eMpcFailed;
  601. }
  602. bool Navigation::execute_InOut_space(NavMessage::NewAction action) {
  603. if (action.type() != 1 && action.type() != 2) {
  604. printf(" Inout_space failed : msg action type must ==1\n ");
  605. return false;
  606. }
  607. if (!parameter_.has_inoutvlimit() || !action.has_spacenode() ||
  608. !action.has_streetnode()) {
  609. std::cout << "execute enter_space failed ,Action miss some infos:" << action.DebugString() << std::endl;
  610. return false;
  611. }
  612. if (PoseTimeout() == true) {
  613. printf(" inout_space failed type:%d : current pose is timeout\n", action.type());
  614. return false;
  615. }
  616. stLimit limit_v = {parameter_.inoutvlimit().min(), parameter_.inoutvlimit().max()};
  617. stLimit limit_w = {2 * M_PI / 180.0, 20 * M_PI / 180.0};
  618. //入库,起点为streetNode
  619. if (action.type() == 1) {
  620. Pose2d vec(action.spacenode().x() - action.streetnode().x(), action.spacenode().y() - action.streetnode().y(),
  621. 0);
  622. action.mutable_streetnode()->set_l(0.05);
  623. action.mutable_streetnode()->set_w(0.05);
  624. action.mutable_streetnode()->set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  625. if (MoveToTarget(action.streetnode(), limit_v, limit_w, true, true) == false) {
  626. printf(" Enter space failed type:%d: MoveTo StreetNode failed\n", action.type());
  627. return false;
  628. }
  629. //移动到库位点, 禁止任意方向// 不允许巡线中停下旋转(当无法到达目标点时,返回false)
  630. printf("inout ----------------------------------------\n");
  631. //计算车位朝向
  632. action.mutable_spacenode()->set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  633. //计算当前车是进入车位1点还是2点
  634. NavMessage::PathNode new_target;
  635. if (RotateBeforeEnterSpace(action.spacenode(), action.wheelbase(), new_target) == eMpcFailed) {
  636. return false;
  637. }
  638. //进库前提升机构上升
  639. if (lifter_rise() == false){
  640. printf(" Enter space | lifter rise failed. line:%d\n",__LINE__);
  641. }
  642. //移动到预入库点位,较高精度
  643. NavMessage::PathNode pre_target;
  644. bool jump_preenter = false;
  645. if (move_mode_ == eSingle){
  646. double x = action.spacenode().x();
  647. double y = action.spacenode().y();
  648. double theta = action.spacenode().theta();
  649. double back_distance = 3.3 + 0.2 + 1;//距载车板靠墙侧车轮挡板距离(距离车位点距离)
  650. Pose2d current = timedPose_.Get();
  651. double diff = Pose2d::distance(current, Pose2d(x,y,theta));
  652. if (diff < back_distance) jump_preenter = true;
  653. x -= back_distance* cos(theta);
  654. y -= back_distance* sin(theta);
  655. pre_target.set_x(x);
  656. pre_target.set_y(y);
  657. pre_target.set_theta(theta);
  658. pre_target.set_l(0.03);
  659. pre_target.set_w(0.03);
  660. pre_target.set_id("R_0");
  661. }
  662. else if (move_mode_ == eDouble){
  663. double x = action.spacenode().x();
  664. double y = action.spacenode().y();
  665. double theta = action.spacenode().theta();
  666. double back_distance = 3.3 + 0.2 + 1 + action.wheelbase()/2;//距载车板靠墙侧车轮挡板距离(距离车位点距离)
  667. Pose2d current = timedPose_.Get();
  668. double diff = Pose2d::distance(current, Pose2d(x,y,theta));
  669. if (diff < back_distance) jump_preenter = true;
  670. x -= back_distance* cos(theta);
  671. y -= back_distance* sin(theta);
  672. pre_target.set_x(x);
  673. pre_target.set_y(y);
  674. pre_target.set_theta(theta);
  675. pre_target.set_l(0.03);
  676. pre_target.set_w(0.03);
  677. pre_target.set_id("R_0");
  678. }
  679. else{ return printf("PreEnter space failed. move_mode_ error!. line: %d\n", __LINE__);}
  680. if (!jump_preenter) {
  681. if (MoveToTarget(pre_target, limit_v, limit_w, true, false) == false) {
  682. printf(" PreEnter space:%s failed. type:%d. line:%d\n", action.spacenode().id().data(), action.type(),
  683. __LINE__);
  684. return false;
  685. }
  686. }
  687. //入库
  688. if (MoveToTarget(new_target, limit_v, limit_w, true, false) == false) {
  689. printf(" Enter space:%s failed. type:%d\n",action.spacenode().id().data(), action.type());
  690. return false;
  691. }
  692. } else if (action.type() == 2) {
  693. Pose2d space(action.spacenode().x(), action.spacenode().y(), 0);
  694. Pose2d diff = Pose2d::abs(Pose2d::relativePose(space, timedPose_.Get()));
  695. if (diff.y() < 0.05) {
  696. //出库,移动到马路点,允许自由方向,不允许中途旋转
  697. Pose2d vec(action.streetnode().x() - action.spacenode().x(),
  698. action.streetnode().y() - action.spacenode().y(), 0);
  699. action.mutable_streetnode()->set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  700. action.mutable_streetnode()->set_l(0.2);
  701. action.mutable_streetnode()->set_w(0.1);
  702. if (MoveToTarget(action.streetnode(), limit_v, limit_w, true, false) == false) {
  703. printf(" out space failed type:%d: MoveTo StreetNode failed\n", action.type());
  704. return false;
  705. }
  706. } else {
  707. std::cout << " Out space failed: current pose too far from space node:" << space << ",diff:" << diff
  708. << std::endl;
  709. return false;
  710. }
  711. }
  712. return true;
  713. }
  714. /* current_to_target: current_to_target.theta()为所需旋转的角度
  715. * */
  716. bool Navigation::Rotation_mpc_once(Pose2d current_to_target, Navigation::stLimit limit_wmg, std::vector<double> &out,
  717. bool all_direct) {
  718. if (PoseTimeout() == true) {
  719. printf(" Rotation_mpc_once Error:Pose is timeout \n");
  720. return false;
  721. }
  722. if (timedV_.timeout() == true || timedA_.timeout() == true) {
  723. printf(" Rotation_mpc_once Error:V/A is timeout \n");
  724. return false;
  725. }
  726. Pose2d pose = timedPose_.Get();
  727. double line_velocity = timedV_.Get(); //从plc获取状态
  728. double angular_velocity = timedA_.Get();
  729. Eigen::VectorXd statu = Eigen::VectorXd::Zero(5);//agv状态
  730. statu[0] = pose.x();
  731. statu[1] = pose.y();
  732. statu[2] = pose.theta();
  733. statu[3] = line_velocity;
  734. statu[4] = angular_velocity;
  735. NavParameter::MPC_parameter mpc_parameter = parameter_.x_mpc_parameter();
  736. double obs_w = 0.95;//0.85;
  737. double obs_h = 1.55;//1.45;
  738. MpcError ret = failed;
  739. Pose2d brother = timedBrotherPose_.Get();
  740. Pose2d brother_in_self = Pose2d::relativePose(brother, pose);
  741. // std::cout<<" brother_in_self: "<<brother_in_self<<std::endl;
  742. if (move_mode_ == eDouble) {
  743. brother_in_self = Pose2d(pose.x() + 100, pose.y() + 100, 0);
  744. }
  745. RotateMPC MPC(brother_in_self, obs_w, obs_h, limit_wmg.min, limit_wmg.max);
  746. RotateMPC::MPC_parameter parameter = {mpc_parameter.shortest_radius(), mpc_parameter.dt(),
  747. mpc_parameter.acc_velocity(), mpc_parameter.acc_angular()};
  748. ret = MPC.solve(current_to_target, statu, parameter, out);
  749. if (ret == no_solution) {
  750. printf(" Rotation_mpc solve no solution set v/w = 0\n");
  751. out.clear();
  752. out.push_back(0);
  753. } else {
  754. // double min_angular_velocity = 1.0 / 180 * M_PI;
  755. double min_angular_velocity = 0.00001;
  756. if (fabs(out[0]) < min_angular_velocity) {
  757. if (out[0] > 0)
  758. out[0] = min_angular_velocity;
  759. else if (out[0] < 0)
  760. out[0] = -min_angular_velocity;
  761. else {}
  762. }
  763. }
  764. return ret == success || ret == no_solution;
  765. }
  766. bool Navigation::mpc_once(Trajectory traj, stLimit limit_v, std::vector<double> &out, bool directY) {
  767. if (PoseTimeout() == true) {
  768. printf(" MPC once Error:Pose is timeout \n");
  769. return false;
  770. }
  771. if (timedV_.timeout() == true || timedA_.timeout() == true) {
  772. printf(" MPC once Error:V/A is timeout \n");
  773. return false;
  774. }
  775. if (traj.size() == 0) {
  776. printf("traj size ==0\n");
  777. return false;
  778. }
  779. Pose2d pose = timedPose_.Get();
  780. double velocity = timedV_.Get(); //从plc获取状态
  781. double angular = timedA_.Get();
  782. Eigen::VectorXd statu = Eigen::VectorXd::Zero(5);//agv状态
  783. statu[0] = pose.x();
  784. statu[1] = pose.y();
  785. statu[2] = pose.theta();
  786. statu[3] = velocity;
  787. statu[4] = angular;
  788. Trajectory optimize_trajectory;
  789. Trajectory selected_trajectory;
  790. NavParameter::MPC_parameter mpc_parameter = parameter_.x_mpc_parameter();
  791. double obs_w = 0.95;//0.85;
  792. double obs_h = 1.55;//1.45;
  793. if (directY == true) {
  794. //将车身朝向旋转90°,车身朝向在(-pi,pi]
  795. statu[2] += M_PI / 2;
  796. if (statu[2] > M_PI)
  797. statu[2] -= 2 * M_PI;
  798. mpc_parameter = parameter_.y_mpc_parameter();
  799. obs_w = 0.95;//0.85;
  800. obs_h = 1.55;//1.45;
  801. }
  802. Pose2d brother = timedBrotherPose_.Get();
  803. Pose2d relative = Pose2d::relativePose(brother, pose);
  804. if (directY)
  805. relative = Pose2d::relativePose(brother.rotate(brother.x(), brother.y(), M_PI / 2),
  806. pose.rotate(pose.x(), pose.y(), M_PI / 2));//计算另一节在当前小车坐标系下的坐标
  807. //std::cout<<"pose:"<<pose<<", brother:"<<brother<<", relative:"<<relative<<std::endl;
  808. if (move_mode_ == eDouble)
  809. relative = Pose2d(-1e8, -1e8, 0);
  810. MpcError ret = failed;
  811. LoadedMPC MPC(relative, obs_w, obs_h, limit_v.min, limit_v.max);
  812. LoadedMPC::MPC_parameter parameter = {mpc_parameter.shortest_radius(), mpc_parameter.dt(),
  813. mpc_parameter.acc_velocity(), mpc_parameter.acc_angular()};
  814. //printf(" r:%f dt:%f acc:%f acc_a:%f\n",mpc_parameter.shortest_radius(),
  815. // mpc_parameter.dt(),mpc_parameter.acc_velocity(),mpc_parameter.acc_angular());
  816. ret = MPC.solve(traj, traj[traj.size() - 1], statu, parameter,
  817. out, selected_trajectory, optimize_trajectory);
  818. //std::cout<<" traj size %d %d -------- "<<selected_trajectory.size()<<","<<optimize_trajectory.size()<<std::endl;
  819. if (ret == no_solution) {
  820. printf(" mpc solve no solution set v/w = 0\n");
  821. out.clear();
  822. out.push_back(0);
  823. out.push_back(0);
  824. }
  825. predict_traj_.reset(optimize_trajectory, 1);
  826. selected_traj_.reset(selected_trajectory, 1);
  827. return ret == success || ret == no_solution;
  828. }
  829. bool Navigation::IsArrived(NavMessage::PathNode targetNode) {
  830. if (timedPose_.timeout() || timedV_.timeout() || timedA_.timeout()) {
  831. printf(" pose / v / w timeout,IsArrived return false\n");
  832. return false;
  833. }
  834. Pose2d current = timedPose_.Get();
  835. double x = current.x();
  836. double y = current.y();
  837. double tx = targetNode.x();
  838. double ty = targetNode.y();
  839. double l = fabs(targetNode.l());
  840. double w = fabs(targetNode.w());
  841. double theta = -targetNode.theta();
  842. if (l < 1e-10 || w < 1e-10) {
  843. printf("IsArrived: Error target l or w == 0\n");
  844. return false;
  845. }
  846. double a = (x - tx) * cos(theta) - (y - ty) * sin(theta);
  847. double b = (x - tx) * sin(theta) + (y - ty) * cos(theta);
  848. if (pow(a / l, 8) + pow(b / w, 8) <= 1) {
  849. if (fabs(timedV_.Get()) < 0.06 && fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  850. printf(" Arrived target: %f %f l:%f w:%f theta:%f\n", tx, ty, l, w, theta);
  851. return true;
  852. }
  853. }
  854. return false;
  855. }
  856. void Navigation::SendMoveCmd(int mode, ActionType type,
  857. double v, double angular) {
  858. if (monitor_) {
  859. monitor_->set_speed(mode, type, v, angular);
  860. if (type == eRotation)
  861. RWheel_position_ = eR;
  862. if (type == eVertical)
  863. RWheel_position_ = eX;
  864. if (type == eHorizontal)
  865. RWheel_position_ = eY;
  866. }
  867. }
  868. void Navigation::SendMoveCmd(int mode, ActionType type, double v, double angular, int space_id, double distance) {
  869. if (monitor_) {
  870. monitor_->set_ToAgvCmd(mode, type, v, angular, 0,space_id, distance);
  871. if (type == eRotation)
  872. RWheel_position_ = eR;
  873. if (type == eVertical)
  874. RWheel_position_ = eX;
  875. if (type == eHorizontal)
  876. RWheel_position_ = eY;
  877. }
  878. }
  879. bool Navigation::clamp_close() {
  880. if (monitor_) {
  881. printf("Clamp closing...\n");
  882. monitor_->clamp_close(move_mode_);
  883. actionType_ = eClampClose;
  884. while (cancel_ == false) {
  885. if (timed_clamp_.timeout()) {
  886. printf("timed clamp is timeout\n");
  887. return false;
  888. }
  889. if (timed_clamp_.Get() == eClosed)
  890. return true;
  891. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  892. monitor_->clamp_close(move_mode_);
  893. actionType_ = eClampClose;
  894. }
  895. return false;
  896. }
  897. return false;
  898. }
  899. bool Navigation::clamp_open() {
  900. if (monitor_) {
  901. printf("Clamp openning...\n");
  902. monitor_->clamp_open(move_mode_);
  903. actionType_ = eClampOpen;
  904. while (cancel_ == false) {
  905. if (timed_clamp_.timeout()) {
  906. printf("timed clamp is timeout\n");
  907. return false;
  908. }
  909. if (timed_clamp_.Get() == eOpened)
  910. return true;
  911. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  912. monitor_->clamp_open(move_mode_);
  913. actionType_ = eClampOpen;
  914. }
  915. return false;
  916. }
  917. return false;
  918. }
  919. bool Navigation::lifter_rise() {
  920. if (monitor_) {
  921. printf("Lifter upping...\n");
  922. monitor_->lifter_rise(move_mode_);
  923. actionType_ = eLifterRise;
  924. while (cancel_ == false) {
  925. if (timed_lifter_.timeout()) {
  926. printf("timed lifter is timeout\n");
  927. return false;
  928. }
  929. if (timed_lifter_.Get() == eRose)
  930. return true;
  931. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  932. monitor_->lifter_rise(move_mode_);
  933. actionType_ = eLifterRise;
  934. }
  935. return false;
  936. }
  937. return false;
  938. }
  939. bool Navigation::lifter_down() {
  940. if (monitor_) {
  941. printf("Lifter downing...\n");
  942. monitor_->lifter_down(move_mode_);
  943. actionType_ = eLifterDown;
  944. while (cancel_ == false) {
  945. if (timed_lifter_.timeout()) {
  946. printf("timed lifter is timeout\n");
  947. return false;
  948. }
  949. if (timed_lifter_.Get() == eDowned)
  950. return true;
  951. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  952. monitor_->lifter_down(move_mode_);
  953. actionType_ = eLifterDown;
  954. }
  955. return false;
  956. }
  957. return false;
  958. }
  959. Navigation::MpcResult Navigation::MpcToTarget(NavMessage::PathNode node, stLimit limit_v, bool autoDirect) {
  960. if (IsArrived(node)) {
  961. printf(" current already in target completed !!!\n");
  962. return eMpcSuccess;
  963. }
  964. if (inited_ == false) {
  965. printf(" navigation has not inited\n");
  966. return eMpcFailed;
  967. }
  968. if (PoseTimeout()) {
  969. printf(" navigation Error:Pose is timeout \n");
  970. return eMpcFailed;
  971. }
  972. Pose2d current = timedPose_.Get();
  973. Pose2d target(node.x(), node.y(), 0);
  974. //生成轨迹
  975. Trajectory traj = Trajectory::create_line_trajectory(current, target);
  976. if (traj.size() == 0)
  977. return eMpcSuccess;
  978. //判断 巡线方向
  979. bool directY = false;
  980. if (autoDirect) {
  981. Pose2d target_relative = Pose2d::relativePose(target, timedPose_.Get());
  982. if (fabs(target_relative.y()) > fabs(target_relative.x())) { //目标轨迹点在当前点Y轴上
  983. std::cout << " MPC Y axis target_relative:" << target_relative << std::endl;
  984. directY = true;
  985. } else {
  986. std::cout << " MPC X axis target_relative:" << target_relative << std::endl;
  987. }
  988. }
  989. printf(" exec along autoDirect:%d\n", autoDirect);
  990. while (cancel_ == false) {
  991. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  992. if (pause_ == true) {
  993. //发送暂停消息
  994. continue;
  995. }
  996. if (PoseTimeout()) {
  997. printf(" navigation Error:Pose is timeout \n");
  998. return eMpcFailed;
  999. }
  1000. if (timedV_.timeout() || timedA_.timeout()) {
  1001. printf(" navigation Error:v/a is timeout | __LINE__:%d \n", __LINE__);
  1002. return eMpcFailed;
  1003. }
  1004. //判断是否到达终点
  1005. if (IsArrived(node)) {
  1006. if (Stop()) {
  1007. printf(" exec along completed !!!\n");
  1008. return eMpcSuccess;
  1009. }
  1010. }
  1011. //一次变速
  1012. std::vector<double> out;
  1013. bool ret;
  1014. TimerRecord::Execute([&, this]() {
  1015. ret = mpc_once(traj, limit_v, out, directY);
  1016. }, "mpc_once");
  1017. if (ret == false) {
  1018. Stop();
  1019. return eMpcFailed;
  1020. }
  1021. /*
  1022. * AGV 在终点附近低速巡航时,设置最小速度0.05
  1023. */
  1024. Pose2d target_in_agv = Pose2d::relativePose(target, timedPose_.Get());
  1025. if (directY) {
  1026. target_in_agv = target_in_agv.rotate(M_PI / 2.0);
  1027. }
  1028. if (Pose2d::abs(target_in_agv) < Pose2d(0.2, 2, M_PI * 2)) {
  1029. if (out[0] >= 0 && out[0] < limit_v.min)
  1030. out[0] = limit_v.min;
  1031. if (out[0] < 0 && out[0] > -limit_v.min)
  1032. out[0] = -limit_v.min;
  1033. }
  1034. //行进方向上最后一米不纠偏
  1035. if(fabs(target_in_agv.x()) < 1.4){
  1036. out[1] = 0.0;
  1037. }
  1038. //下发速度
  1039. //printf(" nav input :%f out:%f\n",timedV_.Get(),out[0]);
  1040. //添加车位号,距目标点距离信息
  1041. double distance = Pose2d::distance(target_in_agv, Pose2d(0,0,0));
  1042. int space_id = 0;
  1043. if(node.id().find('S')){
  1044. std::string id = node.id().substr(1,node.id().length()-1);
  1045. space_id = stoi(id);
  1046. }
  1047. if (directY == false)
  1048. SendMoveCmd(move_mode_, eVertical, out[0], out[1], space_id, distance);
  1049. else
  1050. SendMoveCmd(move_mode_, eHorizontal, out[0], out[1], space_id, distance);
  1051. actionType_ = directY ? eHorizontal : eVertical;
  1052. /*
  1053. * 判断车辆是否在终点附近徘徊,无法到达终点
  1054. */
  1055. if (PossibleToTarget(node, directY) == false) {
  1056. printf(" --------------MPC imposible to target -------------------------------------------\n");
  1057. if (fabs(timedV_.Get()) > 0.1 || fabs(timedA_.Get()) > 10 * M_PI / 180.0)
  1058. SlowlyStop();
  1059. else
  1060. Stop();
  1061. return eImpossibleToTarget;
  1062. }
  1063. }
  1064. return eMpcFailed;
  1065. }
  1066. bool Navigation::PossibleToTarget(NavMessage::PathNode targetNode, bool directY) {
  1067. if (timedPose_.timeout()) {
  1068. return false;
  1069. }
  1070. Pose2d current = timedPose_.Get();
  1071. if(targetNode.id().find('S')){
  1072. //车位点强制可到达
  1073. return true;
  1074. }
  1075. double tx = targetNode.x();
  1076. double ty = targetNode.y();
  1077. double l = fabs(targetNode.l());
  1078. double w = fabs(targetNode.w());
  1079. double theta = -targetNode.theta();
  1080. // double W = 2.45;
  1081. // double L = 1.3;
  1082. // double minYaw = 3 * M_PI / 180.0;
  1083. // if (move_mode_ == eDouble) {
  1084. // L = 1.3 + 2.7;
  1085. //
  1086. // }
  1087. double W = 2.5;
  1088. double L = 1.565;
  1089. double minYaw = 3 * M_PI / 180.0;
  1090. if (move_mode_ == eDouble) {
  1091. L = 1.565 + 2.78;
  1092. }
  1093. if (directY) {
  1094. current = current.rotate(current.x(), current.y(), M_PI / 2);
  1095. double t = W;
  1096. W = L;
  1097. L = t;
  1098. }
  1099. double minR = W / 2 + L / tan(minYaw);
  1100. //printf("l:%f,w:%f\n",l,w);
  1101. std::vector<Pose2d> poses = Pose2d::generate_rectangle_vertexs(Pose2d(tx, ty, 0), l * 2, w * 2);
  1102. bool nagY = false;
  1103. bool posiY = false;
  1104. for (int i = 0; i < poses.size(); ++i) {
  1105. Pose2d rpos = poses[i].rotate(tx, ty, theta);
  1106. Pose2d relative = Pose2d::relativePose(rpos, current);
  1107. double ax = fabs(relative.x());
  1108. double ay = fabs(relative.y());
  1109. if (relative.y() > 0) posiY = true;
  1110. if (relative.y() < 0) nagY = true;
  1111. if (ax * ax + pow(ay - minR, 2) > minR * minR) {
  1112. /*printf(" possible to target:%f %f l:%f,w:%f theta:%f minR:%f ax:%f,ay:%f\n",
  1113. targetNode.x(),targetNode.y(),targetNode.l(),targetNode.w(),targetNode.theta(),
  1114. minR,ax,ay);*/
  1115. return true;
  1116. } else if (nagY && posiY) {
  1117. // std::cout << "nagY && posiY" << std::endl;
  1118. return true;
  1119. }
  1120. // printf("directY:%d targetInPose:%f %f l:%f,w:%f theta:%f minR:%f ax:%f,ay:%f\n", directY,
  1121. // relative.x(), relative.y(), targetNode.l(), targetNode.w(), targetNode.theta(),
  1122. // minR, ax, ay);
  1123. }
  1124. printf(" impossible to target:%f %f l:%f,w:%f theta:%f\n",
  1125. targetNode.x(), targetNode.y(), targetNode.l(), targetNode.w(), targetNode.theta());
  1126. return false;
  1127. }
  1128. void Navigation::Start(const NavMessage::NavCmd &cmd, NavMessage::NavResponse &response) {
  1129. if (inited_ == false) {
  1130. response.set_ret(-1);
  1131. response.set_info("navigation has not inited");
  1132. printf(" navigation has not inited\n");
  1133. return;
  1134. }
  1135. if (newUnfinished_cations_.empty() == false) //正在运行中,上一次指令未完成
  1136. {
  1137. response.set_ret(-2);
  1138. response.set_info("navigation is running pls cancel before");
  1139. printf(" navigation is running pls cancel before\n");
  1140. return;
  1141. }
  1142. //add 先检查当前点与起点的距离
  1143. global_navCmd_ = cmd;
  1144. for (int i = 0; i < cmd.newactions_size(); ++i)
  1145. newUnfinished_cations_.push(cmd.newactions(i));
  1146. pause_ = false;
  1147. cancel_ = false;
  1148. running_ = true;
  1149. actionType_ = eReady;
  1150. printf(" navigation beg...\n");
  1151. while (newUnfinished_cations_.empty() == false && cancel_ == false) {
  1152. std::cout << "unfinished size:" << newUnfinished_cations_.size() << std::endl;
  1153. NavMessage::NewAction act = newUnfinished_cations_.front();
  1154. if (act.type() == 1) { //入库
  1155. space_id_ = act.spacenode().id();
  1156. isInSpace_ = true;
  1157. if (!execute_InOut_space(act)) {
  1158. printf(" In space failed\n");
  1159. break;
  1160. }
  1161. } else if (act.type() == 2) { //出库
  1162. if (!execute_InOut_space(act)) {
  1163. printf(" out space failed\n");
  1164. break;
  1165. } else {
  1166. isInSpace_ = false;
  1167. }
  1168. } else if (act.type() == 3 || act.type() == 4) { //马路导航
  1169. if (!execute_nodes(act))
  1170. break;
  1171. } else if (act.type() == 5) {
  1172. printf(" 汽车模型导航....\n");
  1173. } else if (act.type() == 6) {//夹持
  1174. if (this->clamp_close() == false) {
  1175. printf("夹持failed ...\n");
  1176. break;
  1177. }
  1178. } else if (act.type() == 7) {
  1179. if (this->clamp_open() == false) {
  1180. printf("打开夹持 failed...\n");
  1181. break;
  1182. }
  1183. } else if (act.type() == 8) { //切换模式
  1184. SwitchMode(act.changedmode(), act.wheelbase());
  1185. } else if (act.type() == 9) { //提升机构提升
  1186. if (this->lifter_rise() == false) {
  1187. printf("提升failed ...\n");
  1188. break;
  1189. }
  1190. } else if (act.type() == 10) { //提升机构下降
  1191. if (this->lifter_down() == false) {
  1192. printf("下降failed ...\n");
  1193. break;
  1194. }
  1195. }else {
  1196. printf(" action type invalid not handled !!\n");break;
  1197. }
  1198. newUnfinished_cations_.pop();
  1199. }
  1200. actionType_ = eReady;
  1201. Stop();
  1202. if (cancel_ == true) {
  1203. response.set_ret(-3);
  1204. response.set_info("navigation canceled");
  1205. printf(" navigation canceled\n");
  1206. while (newUnfinished_cations_.empty() == false)
  1207. newUnfinished_cations_.pop();
  1208. } else {
  1209. if (newUnfinished_cations_.empty()) {
  1210. response.set_ret(0);
  1211. response.set_info("navigation completed!!!");
  1212. printf("navigation completed!!!\n");
  1213. } else {
  1214. response.set_ret(-4);
  1215. response.set_info("navigation Failed!!!!");
  1216. printf(" navigation Failed\n");
  1217. while (newUnfinished_cations_.empty() == false)
  1218. newUnfinished_cations_.pop();
  1219. }
  1220. }
  1221. running_ = false;
  1222. }
  1223. void Navigation::SwitchMode(int mode, float wheelBase) {
  1224. printf("Child AGV can not Switch Mode\n");
  1225. }
  1226. float Navigation::compute_cuv(const Pose2d &target) {
  1227. float x = fabs(target.x());
  1228. float y = fabs(target.y());
  1229. float cuv = atan(y / (x + 1e-8));
  1230. //printf(" ---------------------- cuv:%f\n",cuv);
  1231. return cuv;
  1232. }
  1233. void Navigation::ManualOperation(const NavMessage::ManualCmd &cmd, NavMessage::NavResponse &response) {
  1234. pause_ = false;
  1235. cancel_ = false;
  1236. running_ = true;
  1237. actionType_ = eReady;
  1238. printf("ManualOperation: %d | start...\n", cmd.operation_type());
  1239. float symbol = cmd.velocity() < 0 ? -1 : 1; // 判断为正方向or负方向
  1240. double velocity;
  1241. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1242. switch (cmd.operation_type()) {
  1243. case 1: // 旋转
  1244. velocity = 2.0 * M_PI / 180.0 * symbol;
  1245. SendMoveCmd(move_mode_, eRotation, 0, velocity);
  1246. actionType_ = eRotation;
  1247. printf(" ManualOperation: %d | input angular_v: %f, down: %f\n",
  1248. cmd.operation_type(), timedA_.Get(), velocity);
  1249. break;
  1250. case 2: // X平移
  1251. velocity = 1.0 * symbol;
  1252. SendMoveCmd(move_mode_, eVertical, velocity, 0);
  1253. actionType_ = eVertical;
  1254. printf(" ManualOperation: %d | input line_v : %f, down: %f\n",
  1255. cmd.operation_type(), timedV_.Get(), velocity);
  1256. break;
  1257. case 3: // Y平移
  1258. velocity = 1.0 * symbol;
  1259. SendMoveCmd(move_mode_, eHorizontal, velocity, 0);
  1260. actionType_ = eHorizontal;
  1261. printf(" ManualOperation: %d | input line_v: %f, down: %f\n",
  1262. cmd.operation_type(), timedV_.Get(), velocity);
  1263. break;
  1264. default:
  1265. break;
  1266. }
  1267. actionType_ = eReady;
  1268. response.set_ret(-3);
  1269. response.set_info("ManualOperation: %d, canceled!!!", cmd.operation_type());
  1270. printf("ManualOperation: %d | canceled!!!\n", cmd.operation_type());
  1271. running_ = false;
  1272. }