navigation.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332
  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. //前车先到,当前车进入2点,保持与前车一致的朝向
  546. if (brother.in_space() && brother.space_id() == space.id()) {
  547. rotated.mutable_theta() = brother.odom().theta();
  548. } else { //当前车先到(后车),倒车入库
  549. rotated.mutable_theta() = space.theta();
  550. rotated = rotated.rotate(rotated.x(), rotated.y(), M_PI);
  551. }
  552. double x = space.x();
  553. double y = space.y();
  554. if (move_mode_ == eSingle) {
  555. x -= wheelbase / 2 * cos(rotated.theta());
  556. y -= wheelbase / 2 * sin(rotated.theta());
  557. printf("确定车位点:eSingle\n");
  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.03);
  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. // if (fabs(yawDiff) > 1 * M_PI / 180.0) {
  600. // double theta = limit_gause(yawDiff, limit_rotate.min, limit_rotate.max);
  601. // double angular = next_speed(timedA_.Get(), theta, acc_angular, dt);
  602. // double limit_angular = limit(angular, limit_rotate.min, limit_rotate.max);
  603. //
  604. // SendMoveCmd(move_mode_, Monitor_emqx::eRotation, 0, limit_angular);
  605. // actionType_ = eRotation;
  606. // printf(" RotateBeforeEnterSpace | input anguar:%f,next angular:%f,down:%f diff:%f anyDirect:false\n",
  607. // timedA_.Get(), angular, limit_angular, yawDiff);
  608. //
  609. // continue;
  610. // } else {
  611. // if (fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  612. // printf(" RotateBeforeEnterSpace refer target completed\n");
  613. // printf("---------------- update new target :%f %f %f \n", target.x(), target.y(), target.theta());
  614. // return true;
  615. // }
  616. // }
  617. }
  618. return eMpcFailed;
  619. }
  620. bool Navigation::execute_InOut_space(NavMessage::NewAction action) {
  621. if (action.type() != 1 && action.type() != 2) {
  622. printf(" Inout_space failed : msg action type must ==1\n ");
  623. return false;
  624. }
  625. if (!parameter_.has_inoutvlimit() || !action.has_spacenode() ||
  626. !action.has_streetnode()) {
  627. std::cout << "execute enter_space failed ,Action miss some infos:" << action.DebugString() << std::endl;
  628. return false;
  629. }
  630. if (PoseTimeout() == true) {
  631. printf(" inout_space failed type:%d : current pose is timeout\n", action.type());
  632. return false;
  633. }
  634. stLimit limit_v = {parameter_.inoutvlimit().min(), parameter_.inoutvlimit().max()};
  635. stLimit limit_w = {2 * M_PI / 180.0, 20 * M_PI / 180.0};
  636. //入库,起点为streetNode
  637. if (action.type() == 1) {
  638. Pose2d vec(action.spacenode().x() - action.streetnode().x(), action.spacenode().y() - action.streetnode().y(),
  639. 0);
  640. action.mutable_streetnode()->set_l(0.2);
  641. action.mutable_streetnode()->set_w(0.05);
  642. action.mutable_streetnode()->set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  643. if (MoveToTarget(action.streetnode(), limit_v, limit_w, true, true) == false) {
  644. printf(" Enter space failed type:%d: MoveTo StreetNode failed\n", action.type());
  645. return false;
  646. }
  647. //移动到库位点, 禁止任意方向// 不允许巡线中停下旋转(当无法到达目标点时,返回false)
  648. printf("inout ----------------------------------------\n");
  649. //计算车位朝向
  650. action.mutable_spacenode()->set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  651. //计算当前车是进入车位1点还是2点
  652. NavMessage::PathNode new_target;
  653. if (RotateBeforeEnterSpace(action.spacenode(), action.wheelbase(), new_target) == eMpcFailed) {
  654. return false;
  655. }
  656. if (MoveToTarget(new_target, limit_v, limit_w, true, false) == false) {
  657. printf(" Enter space failed type:%d: MoveTo StreetNode failed\n", action.type());
  658. return false;
  659. }
  660. } else if (action.type() == 2) {
  661. Pose2d space(action.spacenode().x(), action.spacenode().y(), 0);
  662. Pose2d diff = Pose2d::abs(Pose2d::relativePose(space, timedPose_.Get()));
  663. if (diff.y() < 0.05) {
  664. //出库,移动到马路点,允许自由方向,不允许中途旋转
  665. Pose2d vec(action.streetnode().x() - action.spacenode().x(),
  666. action.streetnode().y() - action.spacenode().y(), 0);
  667. action.mutable_streetnode()->set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  668. action.mutable_streetnode()->set_l(0.2);
  669. action.mutable_streetnode()->set_w(0.1);
  670. if (MoveToTarget(action.streetnode(), limit_v, limit_w, true, false) == false) {
  671. printf(" out space failed type:%d: MoveTo StreetNode failed\n", action.type());
  672. return false;
  673. }
  674. } else {
  675. std::cout << " Out space failed: current pose too far from space node:" << space << ",diff:" << diff
  676. << std::endl;
  677. return false;
  678. }
  679. }
  680. return true;
  681. }
  682. /* current_to_target: current_to_target.theta()为所需旋转的角度
  683. * */
  684. bool Navigation::Rotation_mpc_once(Pose2d current_to_target, Navigation::stLimit limit_wmg, std::vector<double> &out,
  685. bool all_direct) {
  686. if (PoseTimeout() == true) {
  687. printf(" Rotation_mpc_once Error:Pose is timeout \n");
  688. return false;
  689. }
  690. if (timedV_.timeout() == true || timedA_.timeout() == true) {
  691. printf(" Rotation_mpc_once Error:V/A is timeout \n");
  692. return false;
  693. }
  694. Pose2d pose = timedPose_.Get();
  695. double line_velocity = timedV_.Get(); //从plc获取状态
  696. double angular_velocity = timedA_.Get();
  697. Eigen::VectorXd statu = Eigen::VectorXd::Zero(5);//agv状态
  698. statu[0] = pose.x();
  699. statu[1] = pose.y();
  700. statu[2] = pose.theta();
  701. statu[3] = line_velocity;
  702. statu[4] = angular_velocity;
  703. NavParameter::MPC_parameter mpc_parameter = parameter_.x_mpc_parameter();
  704. double obs_w = 0.95;//0.85;
  705. double obs_h = 1.55;//1.45;
  706. MpcError ret = failed;
  707. Pose2d brother = timedBrotherPose_.Get();
  708. Pose2d brother_in_self = Pose2d::relativePose(brother, pose);
  709. // std::cout<<" brother_in_self: "<<brother_in_self<<std::endl;
  710. if (move_mode_ == eDouble) {
  711. brother_in_self = Pose2d(pose.x() + 100, pose.y() + 100, 0);
  712. }
  713. RotateMPC MPC(brother_in_self, obs_w, obs_h, limit_wmg.min, limit_wmg.max);
  714. RotateMPC::MPC_parameter parameter = {mpc_parameter.shortest_radius(), mpc_parameter.dt(),
  715. mpc_parameter.acc_velocity(), mpc_parameter.acc_angular()};
  716. ret = MPC.solve(current_to_target, statu, parameter, out);
  717. if (ret == no_solution) {
  718. printf(" Rotation_mpc solve no solution set v/w = 0\n");
  719. out.clear();
  720. out.push_back(0);
  721. } else {
  722. // double min_angular_velocity = 1.0 / 180 * M_PI;
  723. double min_angular_velocity = 0.00001;
  724. if (fabs(out[0]) < min_angular_velocity) {
  725. if (out[0] > 0)
  726. out[0] = min_angular_velocity;
  727. else if (out[0] < 0)
  728. out[0] = -min_angular_velocity;
  729. else {}
  730. }
  731. }
  732. return ret == success || ret == no_solution;
  733. }
  734. bool Navigation::mpc_once(Trajectory traj, stLimit limit_v, std::vector<double> &out, bool directY) {
  735. if (PoseTimeout() == true) {
  736. printf(" MPC once Error:Pose is timeout \n");
  737. return false;
  738. }
  739. if (timedV_.timeout() == true || timedA_.timeout() == true) {
  740. printf(" MPC once Error:V/A is timeout \n");
  741. return false;
  742. }
  743. if (traj.size() == 0) {
  744. printf("traj size ==0\n");
  745. return false;
  746. }
  747. Pose2d pose = timedPose_.Get();
  748. double velocity = timedV_.Get(); //从plc获取状态
  749. double angular = timedA_.Get();
  750. Eigen::VectorXd statu = Eigen::VectorXd::Zero(5);//agv状态
  751. statu[0] = pose.x();
  752. statu[1] = pose.y();
  753. statu[2] = pose.theta();
  754. statu[3] = velocity;
  755. statu[4] = angular;
  756. Trajectory optimize_trajectory;
  757. Trajectory selected_trajectory;
  758. NavParameter::MPC_parameter mpc_parameter = parameter_.x_mpc_parameter();
  759. double obs_w = 0.95;//0.85;
  760. double obs_h = 1.55;//1.45;
  761. if (directY == true) {
  762. //将车身朝向旋转90°,车身朝向在(-pi,pi]
  763. statu[2] += M_PI / 2;
  764. if (statu[2] > M_PI)
  765. statu[2] -= 2 * M_PI;
  766. mpc_parameter = parameter_.y_mpc_parameter();
  767. obs_w = 0.95;//0.85;
  768. obs_h = 1.55;//1.45;
  769. }
  770. Pose2d brother = timedBrotherPose_.Get();
  771. Pose2d relative = Pose2d::relativePose(brother, pose);
  772. if (directY)
  773. relative = Pose2d::relativePose(brother.rotate(brother.x(), brother.y(), M_PI / 2),
  774. pose.rotate(pose.x(), pose.y(), M_PI / 2));//计算另一节在当前小车坐标系下的坐标
  775. //std::cout<<"pose:"<<pose<<", brother:"<<brother<<", relative:"<<relative<<std::endl;
  776. if (move_mode_ == eDouble)
  777. relative = Pose2d(-1e8, -1e8, 0);
  778. MpcError ret = failed;
  779. LoadedMPC MPC(relative, obs_w, obs_h, limit_v.min, limit_v.max);
  780. LoadedMPC::MPC_parameter parameter = {mpc_parameter.shortest_radius(), mpc_parameter.dt(),
  781. mpc_parameter.acc_velocity(), mpc_parameter.acc_angular()};
  782. //printf(" r:%f dt:%f acc:%f acc_a:%f\n",mpc_parameter.shortest_radius(),
  783. // mpc_parameter.dt(),mpc_parameter.acc_velocity(),mpc_parameter.acc_angular());
  784. ret = MPC.solve(traj, traj[traj.size() - 1], statu, parameter,
  785. out, selected_trajectory, optimize_trajectory);
  786. //std::cout<<" traj size %d %d -------- "<<selected_trajectory.size()<<","<<optimize_trajectory.size()<<std::endl;
  787. if (ret == no_solution) {
  788. printf(" mpc solve no solution set v/w = 0\n");
  789. out.clear();
  790. out.push_back(0);
  791. out.push_back(0);
  792. }
  793. predict_traj_.reset(optimize_trajectory, 1);
  794. selected_traj_.reset(selected_trajectory, 1);
  795. return ret == success || ret == no_solution;
  796. }
  797. bool Navigation::IsArrived(NavMessage::PathNode targetNode) {
  798. if (timedPose_.timeout() || timedV_.timeout() || timedA_.timeout()) {
  799. printf(" pose / v / w timeout,IsArrived return false\n");
  800. return false;
  801. }
  802. Pose2d current = timedPose_.Get();
  803. double x = current.x();
  804. double y = current.y();
  805. double tx = targetNode.x();
  806. double ty = targetNode.y();
  807. double l = fabs(targetNode.l());
  808. double w = fabs(targetNode.w());
  809. double theta = -targetNode.theta();
  810. if (l < 1e-10 || w < 1e-10) {
  811. printf("IsArrived: Error target l or w == 0\n");
  812. return false;
  813. }
  814. double a = (x - tx) * cos(theta) - (y - ty) * sin(theta);
  815. double b = (x - tx) * sin(theta) + (y - ty) * cos(theta);
  816. if (pow(a / l, 8) + pow(b / w, 8) <= 1) {
  817. if (fabs(timedV_.Get()) < 0.06 && fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  818. printf(" Arrived target: %f %f l:%f w:%f theta:%f\n", tx, ty, l, w, theta);
  819. return true;
  820. }
  821. }
  822. return false;
  823. }
  824. void Navigation::SendMoveCmd(int mode, ActionType type,
  825. double v, double angular) {
  826. if (monitor_) {
  827. monitor_->set_speed(mode, type, v, angular);
  828. if (type == eRotation)
  829. RWheel_position_ = eR;
  830. if (type == eVertical)
  831. RWheel_position_ = eX;
  832. if (type == eHorizontal)
  833. RWheel_position_ = eY;
  834. }
  835. }
  836. bool Navigation::clamp_close() {
  837. if (monitor_) {
  838. printf("Clamp closing...\n");
  839. monitor_->clamp_close(move_mode_);
  840. actionType_ = eClampClose;
  841. while (cancel_ == false) {
  842. if (timed_clamp_.timeout()) {
  843. printf("timed clamp is timeout\n");
  844. return false;
  845. }
  846. if (timed_clamp_.Get() == eClosed)
  847. return true;
  848. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  849. monitor_->clamp_close(move_mode_);
  850. actionType_ = eClampClose;
  851. }
  852. return false;
  853. }
  854. return false;
  855. }
  856. bool Navigation::clamp_open() {
  857. if (monitor_) {
  858. printf("Clamp openning...\n");
  859. monitor_->clamp_open(move_mode_);
  860. actionType_ = eClampOpen;
  861. while (cancel_ == false) {
  862. if (timed_clamp_.timeout()) {
  863. printf("timed clamp is timeout\n");
  864. return false;
  865. }
  866. if (timed_clamp_.Get() == eOpened)
  867. return true;
  868. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  869. monitor_->clamp_open(move_mode_);
  870. actionType_ = eClampOpen;
  871. }
  872. return false;
  873. }
  874. return false;
  875. }
  876. bool Navigation::lifter_rise() {
  877. if (monitor_) {
  878. printf("Lifter upping...\n");
  879. monitor_->lifter_rise(move_mode_);
  880. actionType_ = eLifterRise;
  881. while (cancel_ == false) {
  882. if (timed_lifter_.timeout()) {
  883. printf("timed lifter is timeout\n");
  884. return false;
  885. }
  886. if (timed_lifter_.Get() == eRose)
  887. return true;
  888. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  889. monitor_->lifter_rise(move_mode_);
  890. actionType_ = eLifterRise;
  891. }
  892. return false;
  893. }
  894. return false;
  895. }
  896. bool Navigation::lifter_down() {
  897. if (monitor_) {
  898. printf("Lifter downing...\n");
  899. monitor_->lifter_down(move_mode_);
  900. actionType_ = eLifterDown;
  901. while (cancel_ == false) {
  902. if (timed_lifter_.timeout()) {
  903. printf("timed lifter is timeout\n");
  904. return false;
  905. }
  906. if (timed_lifter_.Get() == eDowned)
  907. return true;
  908. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  909. monitor_->lifter_down(move_mode_);
  910. actionType_ = eLifterDown;
  911. }
  912. return false;
  913. }
  914. return false;
  915. }
  916. Navigation::MpcResult Navigation::MpcToTarget(NavMessage::PathNode node, stLimit limit_v, bool autoDirect) {
  917. if (IsArrived(node)) {
  918. printf(" current already in target completed !!!\n");
  919. return eMpcSuccess;
  920. }
  921. if (inited_ == false) {
  922. printf(" navigation has not inited\n");
  923. return eMpcFailed;
  924. }
  925. if (PoseTimeout()) {
  926. printf(" navigation Error:Pose is timeout \n");
  927. return eMpcFailed;
  928. }
  929. Pose2d current = timedPose_.Get();
  930. Pose2d target(node.x(), node.y(), 0);
  931. //生成轨迹
  932. Trajectory traj = Trajectory::create_line_trajectory(current, target);
  933. if (traj.size() == 0)
  934. return eMpcSuccess;
  935. //判断 巡线方向
  936. bool directY = false;
  937. if (autoDirect) {
  938. Pose2d target_relative = Pose2d::relativePose(target, timedPose_.Get());
  939. if (fabs(target_relative.y()) > fabs(target_relative.x())) { //目标轨迹点在当前点Y轴上
  940. std::cout << " MPC Y axis target_relative:" << target_relative << std::endl;
  941. directY = true;
  942. } else {
  943. std::cout << " MPC X axis target_relative:" << target_relative << std::endl;
  944. }
  945. }
  946. printf(" exec along autoDirect:%d\n", autoDirect);
  947. while (cancel_ == false) {
  948. std::this_thread::sleep_for(std::chrono::milliseconds(30));
  949. if (pause_ == true) {
  950. //发送暂停消息
  951. continue;
  952. }
  953. if (PoseTimeout()) {
  954. printf(" navigation Error:Pose is timeout \n");
  955. return eMpcFailed;
  956. }
  957. if (timedV_.timeout() || timedA_.timeout()) {
  958. printf(" navigation Error:v/a is timeout | __LINE__:%d \n", __LINE__);
  959. return eMpcFailed;
  960. }
  961. //判断是否到达终点
  962. if (IsArrived(node)) {
  963. if (Stop()) {
  964. printf(" exec along completed !!!\n");
  965. return eMpcSuccess;
  966. }
  967. }
  968. //一次变速
  969. std::vector<double> out;
  970. bool ret;
  971. TimerRecord::Execute([&, this]() {
  972. ret = mpc_once(traj, limit_v, out, directY);
  973. }, "mpc_once");
  974. if (ret == false) {
  975. Stop();
  976. return eMpcFailed;
  977. }
  978. /*
  979. * AGV 在终点附近低速巡航时,设置最小速度0.05
  980. */
  981. Pose2d target_in_agv = Pose2d::relativePose(target, timedPose_.Get());
  982. if (directY) {
  983. target_in_agv = target_in_agv.rotate(M_PI / 2.0);
  984. }
  985. if (Pose2d::abs(target_in_agv) < Pose2d(0.2, 2, M_PI * 2)) {
  986. if (out[0] >= 0 && out[0] < limit_v.min)
  987. out[0] = limit_v.min;
  988. if (out[0] < 0 && out[0] > -limit_v.min)
  989. out[0] = -limit_v.min;
  990. }
  991. //下发速度
  992. //printf(" nav input :%f out:%f\n",timedV_.Get(),out[0]);
  993. if (directY == false)
  994. SendMoveCmd(move_mode_, eVertical, out[0], out[1]);
  995. else
  996. SendMoveCmd(move_mode_, eHorizontal, out[0], out[1]);
  997. actionType_ = directY ? eHorizontal : eVertical;
  998. /*
  999. * 判断车辆是否在终点附近徘徊,无法到达终点
  1000. */
  1001. if (PossibleToTarget(node, directY) == false) {
  1002. printf(" --------------MPC imposible to target -------------------------------------------\n");
  1003. if (fabs(timedV_.Get()) > 0.1 || fabs(timedA_.Get()) > 10 * M_PI / 180.0)
  1004. SlowlyStop();
  1005. else
  1006. Stop();
  1007. return eImpossibleToTarget;
  1008. }
  1009. }
  1010. return eMpcFailed;
  1011. }
  1012. bool Navigation::PossibleToTarget(NavMessage::PathNode targetNode, bool directY) {
  1013. if (timedPose_.timeout()) {
  1014. return false;
  1015. }
  1016. Pose2d current = timedPose_.Get();
  1017. double tx = targetNode.x();
  1018. double ty = targetNode.y();
  1019. double l = fabs(targetNode.l());
  1020. double w = fabs(targetNode.w());
  1021. double theta = -targetNode.theta();
  1022. double W = 2.45;
  1023. double L = 1.3;
  1024. double minYaw = 3 * M_PI / 180.0;
  1025. if (move_mode_ == eDouble) {
  1026. L = 1.3 + 2.7;
  1027. }
  1028. if (directY) {
  1029. current = current.rotate(current.x(), current.y(), M_PI / 2);
  1030. double t = W;
  1031. W = L;
  1032. L = t;
  1033. }
  1034. double minR = W / 2 + L / tan(minYaw);
  1035. //printf("l:%f,w:%f\n",l,w);
  1036. std::vector<Pose2d> poses = Pose2d::generate_rectangle_vertexs(Pose2d(tx, ty, 0), l * 2, w * 2);
  1037. bool nagY = false;
  1038. bool posiY = false;
  1039. for (int i = 0; i < poses.size(); ++i) {
  1040. Pose2d rpos = poses[i].rotate(tx, ty, theta);
  1041. Pose2d relative = Pose2d::relativePose(rpos, current);
  1042. double ax = fabs(relative.x());
  1043. double ay = fabs(relative.y());
  1044. if (relative.y() > 0) posiY = true;
  1045. if (relative.y() < 0) nagY = true;
  1046. if (ax * ax + pow(ay - minR, 2) > minR * minR) {
  1047. /*printf(" possible to target:%f %f l:%f,w:%f theta:%f minR:%f ax:%f,ay:%f\n",
  1048. targetNode.x(),targetNode.y(),targetNode.l(),targetNode.w(),targetNode.theta(),
  1049. minR,ax,ay);*/
  1050. return true;
  1051. } else if (nagY && posiY) {
  1052. // std::cout << "nagY && posiY" << std::endl;
  1053. return true;
  1054. }
  1055. // printf("directY:%d targetInPose:%f %f l:%f,w:%f theta:%f minR:%f ax:%f,ay:%f\n", directY,
  1056. // relative.x(), relative.y(), targetNode.l(), targetNode.w(), targetNode.theta(),
  1057. // minR, ax, ay);
  1058. }
  1059. printf(" impossible to target:%f %f l:%f,w:%f theta:%f\n",
  1060. targetNode.x(), targetNode.y(), targetNode.l(), targetNode.w(), targetNode.theta());
  1061. return false;
  1062. }
  1063. void Navigation::Start(const NavMessage::NavCmd &cmd, NavMessage::NavResponse &response) {
  1064. if (inited_ == false) {
  1065. response.set_ret(-1);
  1066. response.set_info("navigation has not inited");
  1067. printf(" navigation has not inited\n");
  1068. return;
  1069. }
  1070. if (newUnfinished_cations_.empty() == false) //正在运行中,上一次指令未完成
  1071. {
  1072. response.set_ret(-2);
  1073. response.set_info("navigation is running pls cancel before");
  1074. printf(" navigation is running pls cancel before\n");
  1075. return;
  1076. }
  1077. //add 先检查当前点与起点的距离
  1078. global_navCmd_ = cmd;
  1079. for (int i = 0; i < cmd.newactions_size(); ++i)
  1080. newUnfinished_cations_.push(cmd.newactions(i));
  1081. pause_ = false;
  1082. cancel_ = false;
  1083. running_ = true;
  1084. actionType_ = eReady;
  1085. printf(" navigation beg...\n");
  1086. while (newUnfinished_cations_.empty() == false && cancel_ == false) {
  1087. std::cout << "unfinished size:" << newUnfinished_cations_.size() << std::endl;
  1088. NavMessage::NewAction act = newUnfinished_cations_.front();
  1089. if (act.type() == 1) { //入库
  1090. space_id_ = act.spacenode().id();
  1091. isInSpace_ = true;
  1092. if (!execute_InOut_space(act)) {
  1093. printf(" In space failed\n");
  1094. break;
  1095. }
  1096. } else if (act.type() == 2) { //出库
  1097. if (!execute_InOut_space(act)) {
  1098. printf(" out space failed\n");
  1099. break;
  1100. } else {
  1101. isInSpace_ = false;
  1102. }
  1103. } else if (act.type() == 3 || act.type() == 4) { //马路导航
  1104. if (!execute_nodes(act))
  1105. break;
  1106. } else if (act.type() == 5) {
  1107. printf(" 汽车模型导航....\n");
  1108. } else if (act.type() == 6) {//夹持
  1109. if (this->clamp_close() == false) {
  1110. printf("夹持failed ...\n");
  1111. break;
  1112. }
  1113. } else if (act.type() == 7) {
  1114. if (this->clamp_open() == false) {
  1115. printf("打开夹持 failed...\n");
  1116. break;
  1117. }
  1118. } else if (act.type() == 8) { //切换模式
  1119. SwitchMode(act.changedmode(), act.wheelbase());
  1120. } else if (act.type() == 9) { //提升机构提升
  1121. if (this->lifter_rise() == false) {
  1122. printf("提升failed ...\n");
  1123. break;
  1124. }
  1125. } else if (act.type() == 10) { //提升机构下降
  1126. if (this->lifter_down() == false) {
  1127. printf("下降failed ...\n");
  1128. break;
  1129. }
  1130. }else {
  1131. printf(" action type invalid not handled !!\n");break;
  1132. }
  1133. newUnfinished_cations_.pop();
  1134. }
  1135. actionType_ = eReady;
  1136. Stop();
  1137. if (cancel_ == true) {
  1138. response.set_ret(-3);
  1139. response.set_info("navigation canceled");
  1140. printf(" navigation canceled\n");
  1141. while (newUnfinished_cations_.empty() == false)
  1142. newUnfinished_cations_.pop();
  1143. } else {
  1144. if (newUnfinished_cations_.empty()) {
  1145. response.set_ret(0);
  1146. response.set_info("navigation completed!!!");
  1147. printf("navigation completed!!!\n");
  1148. } else {
  1149. response.set_ret(-4);
  1150. response.set_info("navigation Failed!!!!");
  1151. printf(" navigation Failed\n");
  1152. while (newUnfinished_cations_.empty() == false)
  1153. newUnfinished_cations_.pop();
  1154. }
  1155. }
  1156. running_ = false;
  1157. }
  1158. void Navigation::SwitchMode(int mode, float wheelBase) {
  1159. printf("Child AGV can not Switch Mode\n");
  1160. }
  1161. float Navigation::compute_cuv(const Pose2d &target) {
  1162. float x = fabs(target.x());
  1163. float y = fabs(target.y());
  1164. float cuv = atan(y / (x + 1e-8));
  1165. //printf(" ---------------------- cuv:%f\n",cuv);
  1166. return cuv;
  1167. }
  1168. void Navigation::ManualOperation(const NavMessage::ManualCmd &cmd, NavMessage::NavResponse &response) {
  1169. pause_ = false;
  1170. cancel_ = false;
  1171. running_ = true;
  1172. actionType_ = eReady;
  1173. printf("ManualOperation: %d | start...\n", cmd.operation_type());
  1174. float symbol = cmd.velocity() < 0 ? -1 : 1; // 判断为正方向or负方向
  1175. double velocity;
  1176. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1177. switch (cmd.operation_type()) {
  1178. case 1: // 旋转
  1179. velocity = 2.0 * M_PI / 180.0 * symbol;
  1180. SendMoveCmd(move_mode_, eRotation, 0, velocity);
  1181. actionType_ = eRotation;
  1182. printf(" ManualOperation: %d | input angular_v: %f, down: %f\n",
  1183. cmd.operation_type(), timedA_.Get(), velocity);
  1184. break;
  1185. case 2: // X平移
  1186. velocity = 1.0 * symbol;
  1187. SendMoveCmd(move_mode_, eVertical, velocity, 0);
  1188. actionType_ = eVertical;
  1189. printf(" ManualOperation: %d | input line_v : %f, down: %f\n",
  1190. cmd.operation_type(), timedV_.Get(), velocity);
  1191. break;
  1192. case 3: // Y平移
  1193. velocity = 1.0 * symbol;
  1194. SendMoveCmd(move_mode_, eHorizontal, velocity, 0);
  1195. actionType_ = eHorizontal;
  1196. printf(" ManualOperation: %d | input line_v: %f, down: %f\n",
  1197. cmd.operation_type(), timedV_.Get(), velocity);
  1198. break;
  1199. default:
  1200. break;
  1201. }
  1202. actionType_ = eReady;
  1203. response.set_ret(-3);
  1204. response.set_info("ManualOperation: %d, canceled!!!", cmd.operation_type());
  1205. printf("ManualOperation: %d | canceled!!!\n", cmd.operation_type());
  1206. running_ = false;
  1207. }