navigation.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446
  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) < 0.5 * M_PI / 180.0 && fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  427. printf(" MPC_rotate | refer target completed\\n,cuv:%f\n", target_yaw_diff);
  428. Stop();
  429. return eMpcSuccess;
  430. } else{
  431. SendMoveCmd(move_mode_, eRotation, 0, out[0]);
  432. actionType_ = eRotation;
  433. printf(" MPC_rotate | input anguar:%f, down:%f(%f), diff:%f anyDirect:%d\n",
  434. timedA_.Get(), out[0], out[0]/M_PI*180, target_yaw_diff, directions);
  435. }
  436. continue;
  437. // //下发速度
  438. // if (fabs(target_yaw_diff) > 2 * M_PI / 180.0) {
  439. // SendMoveCmd(move_mode_, eRotation, 0, out[0]);
  440. // actionType_ = eRotation;
  441. // printf(" MPC_rotate | input angular_v:%f, down:%f, diff:%f autoDirect:%d\n",
  442. // timedA_.Get(), out[0], target_yaw_diff, directions);
  443. // } else if (fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  444. // printf(" MPC_rotate refer target completed,cuv:%f\n", target_yaw_diff);
  445. // return eMpcSuccess;
  446. // }
  447. // continue;
  448. }
  449. return eMpcFailed;
  450. }
  451. bool Navigation::MoveToTarget(NavMessage::PathNode node, Navigation::stLimit limit_v, Navigation::stLimit limit_w,
  452. bool anyDirect, bool enable_rotate) {
  453. if (IsArrived(node)) {
  454. return true;
  455. }
  456. bool already_in_mpc = false;
  457. while (cancel_ == false) {
  458. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  459. if (PoseTimeout()) {
  460. printf(" navigation Error:Pose is timeout \n");
  461. break;
  462. }
  463. Pose2d current = timedPose_.Get();
  464. if (IsArrived(node)) {
  465. break;
  466. }
  467. //两个方向都无法到达目标点,旋转 朝向目标点
  468. bool x_enable = PossibleToTarget(node, false);
  469. bool y_enable = PossibleToTarget(node, true);
  470. bool enableTotarget = x_enable || y_enable;
  471. if (anyDirect == false) {
  472. enableTotarget = x_enable;
  473. }
  474. //巡线无法到达目标点
  475. if (enableTotarget == false) {
  476. if (already_in_mpc && enable_rotate == false) {
  477. printf(" Move to node failed ,impossible to target and rotate is not enabled\n");
  478. return false;
  479. }
  480. Pose2d target(node.x(), node.y(), 0);
  481. // if (RotateReferToTarget(target, limit_w, anyDirect) == false) {
  482. int directions = Direction::eForward;
  483. if (anyDirect)
  484. directions = Direction::eForward | Direction::eBackward |
  485. Direction::eLeft | Direction::eRight;
  486. if (RotateReferToTarget(node, limit_w, directions) != eMpcSuccess) {
  487. std::cout << " Rotate refer to target failed,target: " << target <<
  488. " directions: " << std::hex << directions << " line_: " << __LINE__ << std::endl;
  489. return false;
  490. }
  491. continue;
  492. }
  493. already_in_mpc = true;
  494. MpcResult ret = MpcToTarget(node, limit_v, anyDirect);
  495. if (ret == eMpcSuccess) {
  496. printf(" MPC to target:%f %f l:%f,w:%f theta:%f completed\n",
  497. node.x(), node.y(), node.l(), node.w(), node.theta());
  498. break;
  499. } else if (ret == eImpossibleToTarget) {
  500. printf(" MPC to target:%f %f l:%f,w:%f theta:%f impossible ,retry ...\n",
  501. node.x(), node.y(), node.l(), node.w(), node.theta());
  502. } else {
  503. return false;
  504. }
  505. }
  506. if (cancel_) {
  507. return false;
  508. }
  509. return true;
  510. }
  511. bool Navigation::execute_nodes(NavMessage::NewAction action) {
  512. if (action.type() == 3 || action.type() == 4) //最优动作导航 or 导航中保证朝向严格一致
  513. {
  514. if (!parameter_.has_nodeangularlimit() || !parameter_.has_nodevelocitylimit() || action.pathnodes_size() == 0) {
  515. std::cout << "execute pathNodes failed ,Action invalid:" << action.DebugString() << std::endl;
  516. return false;
  517. }
  518. bool anyDirect = (action.type() == 3);
  519. //速度限制
  520. stLimit adjust_angular = {parameter_.nodeangularlimit().min(), parameter_.nodeangularlimit().max()};
  521. stLimit mpc_velocity = {parameter_.nodevelocitylimit().min(), parameter_.nodevelocitylimit().max()};
  522. for (int i = 0; i < action.pathnodes_size(); ++i) {
  523. NavMessage::PathNode node = action.pathnodes(i);
  524. if (i + 1 < action.pathnodes_size()) {
  525. NavMessage::PathNode next = action.pathnodes(i + 1);
  526. Pose2d vec(next.x() - node.x(), next.y() - node.y(), 0);
  527. node.set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  528. node.set_l(0.10);
  529. node.set_w(0.10);
  530. } else {
  531. node.set_theta(0);
  532. node.set_w(0.10);
  533. node.set_l(0.10);
  534. }
  535. if (MoveToTarget(node, mpc_velocity, adjust_angular, anyDirect, true) == false)
  536. return false;
  537. else
  538. isInSpace_ = false;
  539. }
  540. return true;
  541. }
  542. printf("execute PathNode failed ,action type is not 3/4 :%d\n", action.type());
  543. return false;
  544. }
  545. Navigation::MpcResult
  546. Navigation::RotateBeforeEnterSpace(NavMessage::PathNode space, double wheelbase, NavMessage::PathNode &target) {
  547. // if (timedBrotherNavStatu_.timeout() || timedPose_.timeout()) {
  548. if (timedPose_.timeout()) {
  549. printf(" rotate failed : timedBrotherNavStatu_ or pose timeout\n");
  550. return eMpcFailed;
  551. }
  552. NavMessage::NavStatu brother = timedBrotherNavStatu_.Get();
  553. stLimit limit_rotate = {2 * M_PI / 180.0, 15 * M_PI / 180.0};
  554. double acc_angular = 20 * M_PI / 180.0;
  555. double dt = 0.1;
  556. Pose2d rotated = timedPose_.Get();
  557. double x = space.x();
  558. double y = space.y();
  559. //前车先到,后车进入2点,保持与前车一致的朝向
  560. if (brother.in_space() && brother.space_id() == space.id()) {
  561. printf("RotateBeforeEnterSpace | 前车先到, __LINE__ = %d\n", __LINE__);
  562. rotated.mutable_theta() = brother.odom().theta();
  563. if (move_mode_ == eSingle) {
  564. x -= wheelbase * cos(rotated.theta());
  565. y -= wheelbase * sin(rotated.theta());
  566. printf("确定车位点:eSingle\n");
  567. }
  568. } else { //当后车先到,倒车入库
  569. printf("RotateBeforeEnterSpace | 后车先到, __LINE__ = %d\n", __LINE__);
  570. rotated.mutable_theta() = space.theta();
  571. rotated = rotated.rotate(rotated.x(), rotated.y(), M_PI);
  572. }
  573. target.set_x(x);
  574. target.set_y(y);
  575. target.set_theta(rotated.theta());
  576. target.set_l(0.05);
  577. target.set_w(0.05);
  578. target.set_id(space.id());
  579. printf("RotateBeforeEnterSpace | target:[x:%f,y:%f,theta:%f]\n",x,y,target.theta());
  580. // //整车协调的时候,保持前后与车位一致即可
  581. // if (move_mode_ == eDouble) {
  582. // double yawDiff1 = (rotated - timedPose_.Get()).theta();
  583. // double yawDiff2 = (rotated + Pose2d(0, 0, M_PI) - timedPose_.Get()).theta();
  584. // if (fabs(yawDiff1) < fabs(yawDiff2)) {
  585. // rotated = rotated + Pose2d(0, 0, M_PI);
  586. // }
  587. // }
  588. while (cancel_ == false) {
  589. std::this_thread::sleep_for(std::chrono::milliseconds(30));
  590. Pose2d current = timedPose_.Get();
  591. double yawDiff = (rotated - current).theta();
  592. //一次变速
  593. std::vector<double> out;
  594. bool ret;
  595. TimerRecord::Execute([&, this]() {
  596. ret = Rotation_mpc_once(Pose2d(0, 0, yawDiff), limit_rotate, out);
  597. }, "Rotation_mpc_once");
  598. if (ret == false) {
  599. Stop();
  600. return eMpcFailed;
  601. }
  602. //下发速度
  603. if (fabs(yawDiff) < 0.5 * M_PI / 180.0 && fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  604. printf(" RotateBeforeEnterSpace refer target completed\\n,cuv:%f\n", yawDiff);
  605. Stop();
  606. return eMpcSuccess;
  607. } else{
  608. SendMoveCmd(move_mode_, eRotation, 0, out[0]);
  609. actionType_ = eRotation;
  610. printf(" RotateBeforeEnterSpace | input anguar:%f, down:%f(%f), diff:%f anyDirect:false\n",
  611. timedA_.Get(), out[0], out[0]/M_PI*180, yawDiff);
  612. }
  613. continue;
  614. }
  615. return eMpcFailed;
  616. }
  617. bool Navigation::execute_InOut_space(NavMessage::NewAction action) {
  618. if (action.type() != 1 && action.type() != 2) {
  619. printf(" Inout_space failed : msg action type must ==1\n ");
  620. return false;
  621. }
  622. if (!parameter_.has_inoutvlimit() || !action.has_spacenode() ||
  623. !action.has_streetnode()) {
  624. std::cout << "execute enter_space failed ,Action miss some infos:" << action.DebugString() << std::endl;
  625. return false;
  626. }
  627. if (PoseTimeout() == true) {
  628. printf(" inout_space failed type:%d : current pose is timeout\n", action.type());
  629. return false;
  630. }
  631. stLimit limit_v = {parameter_.inoutvlimit().min(), parameter_.inoutvlimit().max()};
  632. stLimit limit_w = {2 * M_PI / 180.0, 20 * M_PI / 180.0};
  633. //入库,起点为streetNode
  634. if (action.type() == 1) {
  635. Pose2d vec(action.spacenode().x() - action.streetnode().x(), action.spacenode().y() - action.streetnode().y(),
  636. 0);
  637. action.mutable_streetnode()->set_l(0.06);
  638. action.mutable_streetnode()->set_w(0.06);
  639. action.mutable_streetnode()->set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  640. if (MoveToTarget(action.streetnode(), limit_v, limit_w, true, true) == false) {
  641. printf(" Enter space failed type:%d: MoveTo StreetNode failed\n", action.type());
  642. return false;
  643. }
  644. //移动到库位点, 禁止任意方向// 不允许巡线中停下旋转(当无法到达目标点时,返回false)
  645. printf("inout ----------------------------------------\n");
  646. //计算车位朝向
  647. action.mutable_spacenode()->set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  648. //计算当前车是进入车位1点还是2点
  649. NavMessage::PathNode new_target;
  650. if (RotateBeforeEnterSpace(action.spacenode(), action.wheelbase(), new_target) == eMpcFailed) {
  651. return false;
  652. }
  653. //进库前提升机构上升
  654. if (lifter_rise() == false){
  655. printf(" Enter space | lifter rise failed. line:%d\n",__LINE__);
  656. }
  657. //移动到预入库点位,较高精度
  658. NavMessage::PathNode pre_target;
  659. bool jump_preenter = false;
  660. if (move_mode_ == eSingle){
  661. double x = action.spacenode().x();
  662. double y = action.spacenode().y();
  663. double theta = action.spacenode().theta();
  664. double back_distance = 3.3 + 0.2 + 1;//距载车板靠墙侧车轮挡板距离(距离车位点距离)
  665. Pose2d current = timedPose_.Get();
  666. double diff = Pose2d::distance(current, Pose2d(x,y,theta));
  667. if (diff < back_distance) jump_preenter = true;
  668. x -= back_distance* cos(theta);
  669. y -= back_distance* sin(theta);
  670. pre_target.set_x(x);
  671. pre_target.set_y(y);
  672. pre_target.set_theta(theta);
  673. pre_target.set_l(0.05);
  674. pre_target.set_w(0.05);
  675. pre_target.set_id("R_0");
  676. }
  677. else if (move_mode_ == eDouble){
  678. double x = action.spacenode().x();
  679. double y = action.spacenode().y();
  680. double theta = action.spacenode().theta();
  681. double back_distance = 3.3 + 0.2 + 1 + action.wheelbase()/2;//距载车板靠墙侧车轮挡板距离(距离车位点距离)
  682. Pose2d current = timedPose_.Get();
  683. double diff = Pose2d::distance(current, Pose2d(x,y,theta));
  684. if (diff < back_distance) jump_preenter = true;
  685. x -= back_distance* cos(theta);
  686. y -= back_distance* sin(theta);
  687. pre_target.set_x(x);
  688. pre_target.set_y(y);
  689. pre_target.set_theta(theta);
  690. pre_target.set_l(0.05);
  691. pre_target.set_w(0.05);
  692. pre_target.set_id("R_0");
  693. }
  694. else{ return printf("PreEnter space failed. move_mode_ error!. line: %d\n", __LINE__);}
  695. if (!jump_preenter) {
  696. printf("PreEnter space beg...\npre_target: x:%f, y:%f, theta:%f\n",pre_target.x(),pre_target.y(),pre_target.theta());
  697. if (MoveToTarget(pre_target, limit_v, limit_w, true, false) == false) {
  698. printf(" PreEnter pre_space:%s failed. type:%d. line:%d\n", pre_target.id().data(), action.type(),
  699. __LINE__);
  700. return false;
  701. }
  702. }
  703. //入库
  704. printf("Enter space beg...\n");
  705. if (MoveToTarget(new_target, limit_v, limit_w, true, false) == false) {
  706. printf(" Enter space:%s failed. type:%d\n",action.spacenode().id().data(), action.type());
  707. return false;
  708. }
  709. } else if (action.type() == 2) {
  710. Pose2d space(action.spacenode().x(), action.spacenode().y(), 0);
  711. Pose2d diff = Pose2d::abs(Pose2d::relativePose(space, timedPose_.Get()));
  712. if (diff.x() < 0.05 || diff.y() < 0.05) {
  713. //出库,移动到马路点,允许自由方向,不允许中途旋转
  714. Pose2d vec(action.streetnode().x() - action.spacenode().x(),
  715. action.streetnode().y() - action.spacenode().y(), 0);
  716. action.mutable_streetnode()->set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  717. action.mutable_streetnode()->set_l(0.2);
  718. action.mutable_streetnode()->set_w(0.1);
  719. std::cout << " Out space target street node:" << space << std::endl;
  720. if (MoveToTarget(action.streetnode(), limit_v, limit_w, true, false) == false) {
  721. printf(" out space failed type:%d: MoveTo StreetNode failed\n", action.type());
  722. return false;
  723. }
  724. //出库后提升机构下降
  725. if (lifter_down() == false){
  726. printf(" Out space | lifter down failed. line:%d\n",__LINE__);
  727. }
  728. } else {
  729. std::cout << " Out space failed: current pose too far from space node:" << space << ",diff:" << diff
  730. << std::endl;
  731. return false;
  732. }
  733. }
  734. return true;
  735. }
  736. /* current_to_target: current_to_target.theta()为所需旋转的角度
  737. * */
  738. bool Navigation::Rotation_mpc_once(Pose2d current_to_target, Navigation::stLimit limit_wmg, std::vector<double> &out,
  739. bool all_direct) {
  740. if (PoseTimeout() == true) {
  741. printf(" Rotation_mpc_once Error:Pose is timeout \n");
  742. return false;
  743. }
  744. if (timedV_.timeout() == true || timedA_.timeout() == true) {
  745. printf(" Rotation_mpc_once Error:V/A is timeout \n");
  746. return false;
  747. }
  748. Pose2d pose = timedPose_.Get();
  749. double line_velocity = timedV_.Get(); //从plc获取状态
  750. double angular_velocity = timedA_.Get();
  751. Eigen::VectorXd statu = Eigen::VectorXd::Zero(5);//agv状态
  752. statu[0] = pose.x();
  753. statu[1] = pose.y();
  754. statu[2] = pose.theta();
  755. statu[3] = line_velocity;
  756. statu[4] = angular_velocity;
  757. NavParameter::MPC_parameter mpc_parameter = parameter_.x_mpc_parameter();
  758. double obs_w = 0.95;//0.85;
  759. double obs_h = 1.55;//1.45;
  760. MpcError ret = failed;
  761. Pose2d brother = timedBrotherPose_.Get();
  762. Pose2d brother_in_self = Pose2d::relativePose(brother, pose);
  763. // std::cout<<" brother_in_self: "<<brother_in_self<<std::endl;
  764. if (move_mode_ == eDouble) {
  765. brother_in_self = Pose2d(pose.x() + 100, pose.y() + 100, 0);
  766. }
  767. RotateMPC MPC(brother_in_self, obs_w, obs_h, limit_wmg.min, limit_wmg.max);
  768. RotateMPC::MPC_parameter parameter = {mpc_parameter.shortest_radius(), mpc_parameter.dt(),
  769. mpc_parameter.acc_velocity(), mpc_parameter.acc_angular()};
  770. ret = MPC.solve(current_to_target, statu, parameter, out);
  771. if (ret == no_solution) {
  772. printf(" Rotation_mpc solve no solution set v/w = 0\n");
  773. out.clear();
  774. out.push_back(0);
  775. } else {
  776. // double min_angular_velocity = 1.0 / 180 * M_PI;
  777. double min_angular_velocity = 0.00001;
  778. if (fabs(out[0]) < min_angular_velocity) {
  779. if (out[0] > 0)
  780. out[0] = min_angular_velocity;
  781. else if (out[0] < 0)
  782. out[0] = -min_angular_velocity;
  783. else {}
  784. }
  785. }
  786. return ret == success || ret == no_solution;
  787. }
  788. bool Navigation::mpc_once(Trajectory traj, stLimit limit_v, std::vector<double> &out, bool directY) {
  789. if (PoseTimeout() == true) {
  790. printf(" MPC once Error:Pose is timeout \n");
  791. return false;
  792. }
  793. if (timedV_.timeout() == true || timedA_.timeout() == true) {
  794. printf(" MPC once Error:V/A is timeout \n");
  795. return false;
  796. }
  797. if (traj.size() == 0) {
  798. printf("traj size ==0\n");
  799. return false;
  800. }
  801. Pose2d pose = timedPose_.Get();
  802. double velocity = timedV_.Get(); //从plc获取状态
  803. double angular = timedA_.Get();
  804. Eigen::VectorXd statu = Eigen::VectorXd::Zero(5);//agv状态
  805. statu[0] = pose.x();
  806. statu[1] = pose.y();
  807. statu[2] = pose.theta();
  808. statu[3] = velocity;
  809. statu[4] = angular;
  810. Trajectory optimize_trajectory;
  811. Trajectory selected_trajectory;
  812. NavParameter::MPC_parameter mpc_parameter = parameter_.x_mpc_parameter();
  813. double obs_w = 0.95;//0.85;
  814. double obs_h = 1.55;//1.45;
  815. if (directY == true) {
  816. //将车身朝向旋转90°,车身朝向在(-pi,pi]
  817. statu[2] += M_PI / 2;
  818. if (statu[2] > M_PI)
  819. statu[2] -= 2 * M_PI;
  820. mpc_parameter = parameter_.y_mpc_parameter();
  821. obs_w = 0.95;//0.85;
  822. obs_h = 1.55;//1.45;
  823. }
  824. Pose2d brother = timedBrotherPose_.Get();
  825. Pose2d relative = Pose2d::relativePose(brother, pose);
  826. if (directY)
  827. relative = Pose2d::relativePose(brother.rotate(brother.x(), brother.y(), M_PI / 2),
  828. pose.rotate(pose.x(), pose.y(), M_PI / 2));//计算另一节在当前小车坐标系下的坐标
  829. //std::cout<<"pose:"<<pose<<", brother:"<<brother<<", relative:"<<relative<<std::endl;
  830. if (move_mode_ == eDouble)
  831. relative = Pose2d(-1e8, -1e8, 0);
  832. MpcError ret = failed;
  833. LoadedMPC MPC(relative, obs_w, obs_h, limit_v.min, limit_v.max);
  834. LoadedMPC::MPC_parameter parameter = {mpc_parameter.shortest_radius(), mpc_parameter.dt(),
  835. mpc_parameter.acc_velocity(), mpc_parameter.acc_angular()};
  836. //printf(" r:%f dt:%f acc:%f acc_a:%f\n",mpc_parameter.shortest_radius(),
  837. // mpc_parameter.dt(),mpc_parameter.acc_velocity(),mpc_parameter.acc_angular());
  838. ret = MPC.solve(traj, traj[traj.size() - 1], statu, parameter,
  839. out, selected_trajectory, optimize_trajectory);
  840. //std::cout<<" traj size %d %d -------- "<<selected_trajectory.size()<<","<<optimize_trajectory.size()<<std::endl;
  841. if (ret == no_solution) {
  842. printf(" mpc solve no solution set v/w = 0\n");
  843. out.clear();
  844. out.push_back(0);
  845. out.push_back(0);
  846. }
  847. predict_traj_.reset(optimize_trajectory, 1);
  848. selected_traj_.reset(selected_trajectory, 1);
  849. return ret == success || ret == no_solution;
  850. }
  851. bool Navigation::IsArrived(NavMessage::PathNode targetNode) {
  852. if (timedPose_.timeout() || timedV_.timeout() || timedA_.timeout()) {
  853. printf(" pose / v / w timeout,IsArrived return false\n");
  854. return false;
  855. }
  856. Pose2d current = timedPose_.Get();
  857. double x = current.x();
  858. double y = current.y();
  859. double tx = targetNode.x();
  860. double ty = targetNode.y();
  861. double l = fabs(targetNode.l());
  862. double w = fabs(targetNode.w());
  863. double theta = -targetNode.theta();
  864. if (newUnfinished_cations_.front().type() == 1 && targetNode.id().find('S')!=-1){//入库只判断前后方向上是否到达
  865. tx = x;
  866. }
  867. if (l < 1e-10 || w < 1e-10) {
  868. printf("IsArrived: Error target l or w == 0\n");
  869. return false;
  870. }
  871. double a = (x - tx) * cos(theta) - (y - ty) * sin(theta);
  872. double b = (x - tx) * sin(theta) + (y - ty) * cos(theta);
  873. if (pow(a / l, 8) + pow(b / w, 8) <= 1) {
  874. if (fabs(timedV_.Get()) < 0.06 && fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  875. printf(" Arrived target: %f %f l:%f w:%f theta:%f\n", tx, ty, l, w, theta);
  876. return true;
  877. }
  878. }
  879. return false;
  880. }
  881. void Navigation::SendMoveCmd(int mode, ActionType type,
  882. double v, double angular) {
  883. if (monitor_) {
  884. monitor_->set_speed(mode, type, v, angular);
  885. if (type == eRotation)
  886. RWheel_position_ = eR;
  887. if (type == eVertical)
  888. RWheel_position_ = eX;
  889. if (type == eHorizontal)
  890. RWheel_position_ = eY;
  891. }
  892. }
  893. void Navigation::SendMoveCmd(int mode, ActionType type, double v, double angular, int space_id, double distance) {
  894. if (monitor_) {
  895. monitor_->set_ToAgvCmd(mode, type, v, angular, 0,space_id, distance);
  896. if (type == eRotation)
  897. RWheel_position_ = eR;
  898. if (type == eVertical)
  899. RWheel_position_ = eX;
  900. if (type == eHorizontal)
  901. RWheel_position_ = eY;
  902. }
  903. }
  904. bool Navigation::clamp_close() {
  905. if (monitor_) {
  906. printf("Clamp closing...\n");
  907. monitor_->clamp_close(move_mode_);
  908. actionType_ = eClampClose;
  909. while (cancel_ == false) {
  910. if (timed_clamp_.timeout()) {
  911. printf("timed clamp is timeout\n");
  912. return false;
  913. }
  914. if (timed_clamp_.Get() == eClosed)
  915. return true;
  916. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  917. monitor_->clamp_close(move_mode_);
  918. actionType_ = eClampClose;
  919. }
  920. return false;
  921. }
  922. return false;
  923. }
  924. bool Navigation::clamp_open() {
  925. if (monitor_) {
  926. printf("Clamp openning...\n");
  927. monitor_->clamp_open(move_mode_);
  928. actionType_ = eClampOpen;
  929. while (cancel_ == false) {
  930. if (timed_clamp_.timeout()) {
  931. printf("timed clamp is timeout\n");
  932. return false;
  933. }
  934. if (timed_clamp_.Get() == eOpened)
  935. return true;
  936. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  937. monitor_->clamp_open(move_mode_);
  938. actionType_ = eClampOpen;
  939. }
  940. return false;
  941. }
  942. return false;
  943. }
  944. bool Navigation::lifter_rise() {
  945. if (monitor_) {
  946. printf("Lifter upping...\n");
  947. monitor_->lifter_rise(move_mode_);
  948. actionType_ = eLifterRise;
  949. while (cancel_ == false) {
  950. if (timed_lifter_.timeout()) {
  951. printf("timed lifter is timeout\n");
  952. return false;
  953. }
  954. if (timed_lifter_.Get() == eRose)
  955. return true;
  956. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  957. monitor_->lifter_rise(move_mode_);
  958. actionType_ = eLifterRise;
  959. }
  960. return false;
  961. }
  962. return false;
  963. }
  964. bool Navigation::lifter_down() {
  965. if (monitor_) {
  966. printf("Lifter downing...\n");
  967. monitor_->lifter_down(move_mode_);
  968. actionType_ = eLifterDown;
  969. while (cancel_ == false) {
  970. if (timed_lifter_.timeout()) {
  971. printf("timed lifter is timeout\n");
  972. return false;
  973. }
  974. if (timed_lifter_.Get() == eDowned)
  975. return true;
  976. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  977. monitor_->lifter_down(move_mode_);
  978. actionType_ = eLifterDown;
  979. }
  980. return false;
  981. }
  982. return false;
  983. }
  984. Navigation::MpcResult Navigation::MpcToTarget(NavMessage::PathNode node, stLimit limit_v, bool autoDirect) {
  985. if (IsArrived(node)) {
  986. printf(" current already in target completed !!!\n");
  987. return eMpcSuccess;
  988. }
  989. if (inited_ == false) {
  990. printf(" navigation has not inited\n");
  991. return eMpcFailed;
  992. }
  993. if (PoseTimeout()) {
  994. printf(" navigation Error:Pose is timeout \n");
  995. return eMpcFailed;
  996. }
  997. Pose2d current = timedPose_.Get();
  998. Pose2d target(node.x(), node.y(), 0);
  999. //生成轨迹
  1000. Trajectory traj = Trajectory::create_line_trajectory(current, target);
  1001. if (traj.size() == 0)
  1002. return eMpcSuccess;
  1003. //判断 巡线方向
  1004. bool directY = false;
  1005. if (autoDirect) {
  1006. Pose2d target_relative = Pose2d::relativePose(target, timedPose_.Get());
  1007. if (fabs(target_relative.y()) > fabs(target_relative.x())) { //目标轨迹点在当前点Y轴上
  1008. std::cout << " MPC Y axis target_relative:" << target_relative << std::endl;
  1009. directY = true;
  1010. } else {
  1011. std::cout << " MPC X axis target_relative:" << target_relative << std::endl;
  1012. }
  1013. }
  1014. printf(" exec along autoDirect:%d\n", autoDirect);
  1015. while (cancel_ == false) {
  1016. std::this_thread::sleep_for(std::chrono::milliseconds(30));
  1017. if (pause_ == true) {
  1018. //发送暂停消息
  1019. continue;
  1020. }
  1021. if (PoseTimeout()) {
  1022. printf(" navigation Error:Pose is timeout \n");
  1023. return eMpcFailed;
  1024. }
  1025. if (timedV_.timeout() || timedA_.timeout()) {
  1026. printf(" navigation Error:v/a is timeout | __LINE__:%d \n", __LINE__);
  1027. return eMpcFailed;
  1028. }
  1029. //判断是否到达终点
  1030. if (IsArrived(node)) {
  1031. if (Stop()) {
  1032. printf(" exec along completed !!!\n");
  1033. return eMpcSuccess;
  1034. }
  1035. }
  1036. //一次变速
  1037. std::vector<double> out;
  1038. bool ret;
  1039. TimerRecord::Execute([&, this]() {
  1040. ret = mpc_once(traj, limit_v, out, directY);
  1041. }, "mpc_once");
  1042. if (ret == false) {
  1043. Stop();
  1044. return eMpcFailed;
  1045. }
  1046. /*
  1047. * AGV 在终点附近低速巡航时,设置最小速度0.05
  1048. */
  1049. Pose2d target_in_agv = Pose2d::relativePose(target, timedPose_.Get());
  1050. if (directY) {
  1051. target_in_agv = target_in_agv.rotate(M_PI / 2.0);
  1052. }
  1053. if (Pose2d::abs(target_in_agv) < Pose2d(0.2, 2, M_PI * 2)) {
  1054. if (out[0] >= 0 && out[0] < limit_v.min)
  1055. out[0] = limit_v.min;
  1056. if (out[0] < 0 && out[0] > -limit_v.min)
  1057. out[0] = -limit_v.min;
  1058. }
  1059. //放大角速度
  1060. out[1] *= 10;
  1061. //入库,行进方向上最后一米不纠偏
  1062. if (newUnfinished_cations_.front().type() == 1 && node.id().find('S')!=-1){//入库
  1063. if(fabs(target_in_agv.x()) < 1.4){
  1064. printf("target_in_agv: %f", target_in_agv.x());
  1065. out[1] = 0.0;
  1066. }
  1067. }else if (newUnfinished_cations_.front().type() == 2){//出库,行进方向上开始一米不纠偏
  1068. Pose2d agv_in_space =
  1069. Pose2d::relativePose(
  1070. Pose2d(newUnfinished_cations_.front().spacenode().x(), newUnfinished_cations_.front().spacenode().y(), 0),
  1071. timedPose_.Get());
  1072. if(fabs(agv_in_space.x()) < 1.3){
  1073. printf("agv_in_space: %f", agv_in_space.x());
  1074. out[1] = 0.0;
  1075. }
  1076. }
  1077. //下发速度
  1078. //printf(" nav input :%f out:%f\n",timedV_.Get(),out[0]);
  1079. //添加车位号,距目标点距离信息
  1080. double distance = Pose2d::distance(target_in_agv, Pose2d(0,0,0));
  1081. int space_id = 0;
  1082. if(node.id().find('S') != -1){
  1083. std::string id = node.id().substr(1,node.id().length()-1);
  1084. space_id = stoi(id);
  1085. }
  1086. if (directY == false)
  1087. SendMoveCmd(move_mode_, eVertical, out[0], out[1], space_id, distance);
  1088. else
  1089. SendMoveCmd(move_mode_, eHorizontal, out[0], out[1], space_id, distance);
  1090. actionType_ = directY ? eHorizontal : eVertical;
  1091. /*
  1092. * 判断车辆是否在终点附近徘徊,无法到达终点
  1093. */
  1094. if (PossibleToTarget(node, directY) == false) {
  1095. printf(" --------------MPC imposible to target -------------------------------------------\n");
  1096. if (fabs(timedV_.Get()) > 0.1 || fabs(timedA_.Get()) > 10 * M_PI / 180.0)
  1097. SlowlyStop();
  1098. else
  1099. Stop();
  1100. return eImpossibleToTarget;
  1101. }
  1102. }
  1103. return eMpcFailed;
  1104. }
  1105. bool Navigation::PossibleToTarget(NavMessage::PathNode targetNode, bool directY) {
  1106. if (timedPose_.timeout()) {
  1107. return false;
  1108. }
  1109. Pose2d current = timedPose_.Get();
  1110. if(targetNode.id().find('S') != -1){
  1111. //车位点强制可到达
  1112. return true;
  1113. }
  1114. double tx = targetNode.x();
  1115. double ty = targetNode.y();
  1116. double l = fabs(targetNode.l());
  1117. double w = fabs(targetNode.w());
  1118. double theta = -targetNode.theta();
  1119. // double W = 2.45;
  1120. // double L = 1.3;
  1121. // double minYaw = 3 * M_PI / 180.0;
  1122. // if (move_mode_ == eDouble) {
  1123. // L = 1.3 + 2.7;
  1124. //
  1125. // }
  1126. double W = 2.5;
  1127. double L = 1.565;
  1128. double minYaw = 5 * M_PI / 180.0;
  1129. if (move_mode_ == eDouble) {
  1130. L = 1.565 + 2.78;
  1131. }
  1132. if (directY) {
  1133. current = current.rotate(current.x(), current.y(), M_PI / 2);
  1134. double t = W;
  1135. W = L;
  1136. L = t;
  1137. }
  1138. double minR = W / 2 + L / tan(minYaw);
  1139. //printf("l:%f,w:%f\n",l,w);
  1140. std::vector<Pose2d> poses = Pose2d::generate_rectangle_vertexs(Pose2d(tx, ty, 0), l * 2, w * 2);
  1141. bool nagY = false;
  1142. bool posiY = false;
  1143. for (int i = 0; i < poses.size(); ++i) {
  1144. Pose2d rpos = poses[i].rotate(tx, ty, theta);
  1145. Pose2d relative = Pose2d::relativePose(rpos, current);
  1146. double ax = fabs(relative.x());
  1147. double ay = fabs(relative.y());
  1148. if (relative.y() > 0) posiY = true;
  1149. if (relative.y() < 0) nagY = true;
  1150. if (ax * ax + pow(ay - minR, 2) > minR * minR) {
  1151. /*printf(" possible to target:%f %f l:%f,w:%f theta:%f minR:%f ax:%f,ay:%f\n",
  1152. targetNode.x(),targetNode.y(),targetNode.l(),targetNode.w(),targetNode.theta(),
  1153. minR,ax,ay);*/
  1154. return true;
  1155. } else if (nagY && posiY) {
  1156. // std::cout << "nagY && posiY" << std::endl;
  1157. return true;
  1158. }
  1159. // printf("directY:%d targetInPose:%f %f l:%f,w:%f theta:%f minR:%f ax:%f,ay:%f\n", directY,
  1160. // relative.x(), relative.y(), targetNode.l(), targetNode.w(), targetNode.theta(),
  1161. // minR, ax, ay);
  1162. }
  1163. printf(" impossible to target:%f %f l:%f,w:%f theta:%f\n",
  1164. targetNode.x(), targetNode.y(), targetNode.l(), targetNode.w(), targetNode.theta());
  1165. return false;
  1166. }
  1167. void Navigation::Start(const NavMessage::NavCmd &cmd, NavMessage::NavResponse &response) {
  1168. if (inited_ == false) {
  1169. response.set_ret(-1);
  1170. response.set_info("navigation has not inited");
  1171. printf(" navigation has not inited\n");
  1172. return;
  1173. }
  1174. if (newUnfinished_cations_.empty() == false) //正在运行中,上一次指令未完成
  1175. {
  1176. response.set_ret(-2);
  1177. response.set_info("navigation is running pls cancel before");
  1178. printf(" navigation is running pls cancel before\n");
  1179. return;
  1180. }
  1181. //add 先检查当前点与起点的距离
  1182. global_navCmd_ = cmd;
  1183. for (int i = 0; i < cmd.newactions_size(); ++i)
  1184. newUnfinished_cations_.push(cmd.newactions(i));
  1185. pause_ = false;
  1186. cancel_ = false;
  1187. running_ = true;
  1188. actionType_ = eReady;
  1189. printf("Navigation beg...\n");
  1190. while (newUnfinished_cations_.empty() == false && cancel_ == false) {
  1191. std::cout << "unfinished size:" << newUnfinished_cations_.size() << std::endl;
  1192. NavMessage::NewAction act = newUnfinished_cations_.front();
  1193. if (act.type() == 1) { //入库
  1194. space_id_ = act.spacenode().id();
  1195. isInSpace_ = true;
  1196. if (!execute_InOut_space(act)) {
  1197. printf(" In space failed\n");
  1198. break;
  1199. }
  1200. } else if (act.type() == 2) { //出库
  1201. if (!execute_InOut_space(act)) {
  1202. printf(" out space failed\n");
  1203. break;
  1204. } else {
  1205. isInSpace_ = false;
  1206. }
  1207. } else if (act.type() == 3 || act.type() == 4) { //马路导航
  1208. if (!execute_nodes(act))
  1209. break;
  1210. } else if (act.type() == 5) {
  1211. printf(" 汽车模型导航....\n");
  1212. } else if (act.type() == 6) {//夹持
  1213. if (this->clamp_close() == false) {
  1214. printf("夹持failed ...\n");
  1215. break;
  1216. }
  1217. } else if (act.type() == 7) {
  1218. if (this->clamp_open() == false) {
  1219. printf("打开夹持 failed...\n");
  1220. break;
  1221. }
  1222. } else if (act.type() == 8) { //切换模式
  1223. SwitchMode(act.changedmode(), act.wheelbase());
  1224. } else if (act.type() == 9) { //提升机构提升
  1225. if (this->lifter_rise() == false) {
  1226. printf("提升failed ...\n");
  1227. break;
  1228. }
  1229. } else if (act.type() == 10) { //提升机构下降
  1230. if (this->lifter_down() == false) {
  1231. printf("下降failed ...\n");
  1232. break;
  1233. }
  1234. }else {
  1235. printf(" action type invalid not handled !!\n");break;
  1236. }
  1237. newUnfinished_cations_.pop();
  1238. }
  1239. actionType_ = eReady;
  1240. Stop();
  1241. if (cancel_ == true) {
  1242. response.set_ret(-3);
  1243. response.set_info("navigation canceled");
  1244. printf(" navigation canceled\n");
  1245. while (newUnfinished_cations_.empty() == false)
  1246. newUnfinished_cations_.pop();
  1247. } else {
  1248. if (newUnfinished_cations_.empty()) {
  1249. response.set_ret(0);
  1250. response.set_info("navigation completed!!!");
  1251. printf("navigation completed!!!\n");
  1252. } else {
  1253. response.set_ret(-4);
  1254. response.set_info("navigation Failed!!!!");
  1255. printf(" navigation Failed\n");
  1256. while (newUnfinished_cations_.empty() == false)
  1257. newUnfinished_cations_.pop();
  1258. }
  1259. }
  1260. running_ = false;
  1261. }
  1262. void Navigation::SwitchMode(int mode, float wheelBase) {
  1263. printf("Child AGV can not Switch Mode\n");
  1264. }
  1265. float Navigation::compute_cuv(const Pose2d &target) {
  1266. float x = fabs(target.x());
  1267. float y = fabs(target.y());
  1268. float cuv = atan(y / (x + 1e-8));
  1269. //printf(" ---------------------- cuv:%f\n",cuv);
  1270. return cuv;
  1271. }
  1272. void Navigation::ManualOperation(const NavMessage::ManualCmd &cmd, NavMessage::NavResponse &response) {
  1273. pause_ = false;
  1274. cancel_ = false;
  1275. running_ = true;
  1276. actionType_ = eReady;
  1277. printf("ManualOperation: %d | start...\n", cmd.operation_type());
  1278. float symbol = cmd.velocity() < 0 ? -1 : 1; // 判断为正方向or负方向
  1279. double velocity;
  1280. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1281. switch (cmd.operation_type()) {
  1282. case 1: // 旋转
  1283. velocity = 2.0 * M_PI / 180.0 * symbol;
  1284. SendMoveCmd(move_mode_, eRotation, 0, velocity);
  1285. actionType_ = eRotation;
  1286. printf(" ManualOperation: %d | input angular_v: %f, down: %f\n",
  1287. cmd.operation_type(), timedA_.Get(), velocity);
  1288. break;
  1289. case 2: // X平移
  1290. velocity = 1.0 * symbol;
  1291. SendMoveCmd(move_mode_, eVertical, velocity, 0);
  1292. actionType_ = eVertical;
  1293. printf(" ManualOperation: %d | input line_v : %f, down: %f\n",
  1294. cmd.operation_type(), timedV_.Get(), velocity);
  1295. break;
  1296. case 3: // Y平移
  1297. velocity = 1.0 * symbol;
  1298. SendMoveCmd(move_mode_, eHorizontal, velocity, 0);
  1299. actionType_ = eHorizontal;
  1300. printf(" ManualOperation: %d | input line_v: %f, down: %f\n",
  1301. cmd.operation_type(), timedV_.Get(), velocity);
  1302. break;
  1303. default:
  1304. break;
  1305. }
  1306. actionType_ = eReady;
  1307. response.set_ret(-3);
  1308. response.set_info("ManualOperation: %d, canceled!!!", cmd.operation_type());
  1309. printf("ManualOperation: %d | canceled!!!\n", cmd.operation_type());
  1310. running_ = false;
  1311. }