navigation.cpp 45 KB

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