navigation.cpp 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779
  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_->set_clampLifterCmd_topic(agv_p.pubclampliftertopic());
  74. monitor_->AddCallback(agv_p.subposetopic(), Navigation::RobotPoseCallback, this);
  75. monitor_->AddCallback(agv_p.subspeedtopic(), Navigation::RobotSpeedCallback, this);
  76. }
  77. NavParameter::Emqx_parameter terminal_p = parameter.terminal_emqx();
  78. if (terminator_ == nullptr) {
  79. terminator_ = new Terminator_emqx(terminal_p.nodeid());
  80. if (terminator_->Connect(terminal_p.ip(), terminal_p.port()) == false) {
  81. printf(" terminator emqx connected failed\n");
  82. return false;
  83. }
  84. }
  85. if (parameter.has_brother_emqx()) {
  86. NavParameter::BrotherEmqx brotherEmqx = parameter.brother_emqx();
  87. if (brotherEmqx_ == nullptr) {
  88. brotherEmqx_ = new Terminator_emqx(brotherEmqx.nodeid());
  89. if (brotherEmqx_->Connect(brotherEmqx.ip(), brotherEmqx.port()) == true) {
  90. brotherEmqx_->AddCallback(brotherEmqx.subbrotherstatutopic(), Navigation::BrotherAgvStatuCallback,
  91. this);
  92. } else {
  93. printf(" brother emqx connected failed\n");
  94. // return false;
  95. }
  96. //
  97. }
  98. }
  99. inited_ = true;
  100. if (pubthread_ != nullptr) {
  101. exit_ = true;
  102. if (pubthread_->joinable())
  103. pubthread_->join();
  104. delete pubthread_;
  105. }
  106. exit_ = false;
  107. pubthread_ = new std::thread(&Navigation::pubStatuThreadFuc, this);
  108. return true;
  109. }
  110. void Navigation::RobotPoseCallback(const MqttMsg &msg, void *context) {
  111. Navigation *navigator = (Navigation *) context;
  112. NavMessage::LidarOdomStatu statu;
  113. if (msg.toProtoMessage(statu)) {
  114. navigator->ResetPose(Pose2d(statu.x(), statu.y(), statu.theta()));
  115. }
  116. }
  117. void Navigation::HandleAgvStatu(const MqttMsg &msg) {
  118. NavMessage::AgvStatu speed;
  119. if (msg.toProtoMessage(speed)) {
  120. ResetStatu(speed.v(), speed.w());
  121. ResetClamp((ClampStatu) speed.clamp());
  122. ResetLifter((LifterStatus) speed.lifter());
  123. }
  124. }
  125. void Navigation::RobotSpeedCallback(const MqttMsg &msg, void *context) {
  126. Navigation *navigator = (Navigation *) context;
  127. navigator->HandleAgvStatu(msg);
  128. }
  129. void Navigation::pubStatuThreadFuc(void *p) {
  130. Navigation *navogator = (Navigation *) p;
  131. if (navogator) {
  132. while (navogator->exit_ == false) {
  133. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  134. NavMessage::NavStatu statu;
  135. statu.set_main_agv(false);
  136. navogator->publish_statu(statu);
  137. }
  138. }
  139. }
  140. void Navigation::publish_statu(NavMessage::NavStatu &statu) {
  141. if (timedPose_.timeout() == false) {
  142. NavMessage::LidarOdomStatu odom;
  143. odom.set_x(timedPose_.Get().x());
  144. odom.set_y(timedPose_.Get().y());
  145. odom.set_theta(timedPose_.Get().theta());
  146. if (timedV_.timeout() == false)
  147. odom.set_v(timedV_.Get());
  148. if (timedA_.timeout() == false)
  149. odom.set_vth(timedA_.Get());
  150. statu.mutable_odom()->CopyFrom(odom);
  151. }
  152. statu.set_in_space(isInSpace_);
  153. if (isInSpace_) statu.set_space_id(space_id_);
  154. //发布nav状态
  155. statu.set_statu(actionType_); //
  156. statu.set_move_mode(move_mode_);
  157. if (running_) {
  158. statu.set_key(global_navCmd_.key());
  159. }
  160. //发布MPC信息
  161. //发布mpc 预选点
  162. if (selected_traj_.timeout() == false) {
  163. for (int i = 0; i < selected_traj_.Get().size(); ++i) {
  164. Pose2d pt = selected_traj_.Get()[i];
  165. NavMessage::Pose2d *pose = statu.mutable_selected_traj()->add_poses();
  166. pose->set_x(pt.x());
  167. pose->set_y(pt.y());
  168. pose->set_theta(pt.theta());
  169. }
  170. }
  171. //发布 mpc 预测点
  172. if (predict_traj_.timeout() == false) {
  173. for (int i = 0; i < predict_traj_.Get().size(); ++i) {
  174. Pose2d pt = predict_traj_.Get()[i];
  175. NavMessage::Pose2d *pose = statu.mutable_predict_traj()->add_poses();
  176. pose->set_x(pt.x());
  177. pose->set_y(pt.y());
  178. pose->set_theta(pt.theta());
  179. }
  180. }
  181. // std::cout<<"nav statu:"<<statu.DebugString()<<std::endl;
  182. MqttMsg msg;
  183. msg.fromProtoMessage(statu);
  184. if (terminator_)
  185. terminator_->Publish(parameter_.terminal_emqx().pubnavstatutopic(), msg);
  186. //发布位姿 ------robot状态--------------------------
  187. NavMessage::RobotStatu robot;
  188. if (CreateRobotStatuMsg(robot)) {
  189. if (terminator_) {
  190. MqttMsg msg;
  191. msg.fromProtoMessage(robot);
  192. terminator_->Publish(parameter_.terminal_emqx().pubstatutopic(), msg);
  193. }
  194. }
  195. }
  196. bool Navigation::CreateRobotStatuMsg(NavMessage::RobotStatu &robotStatu) {
  197. //printf(" %d %d %d \n",timedPose_.timeout(),timedV_.timeout(),timedA_.timeout());
  198. if (timedPose_.timeout() == false) {
  199. Pose2d pose = timedPose_.Get();
  200. robotStatu.set_x(pose.x());
  201. robotStatu.set_y(pose.y());
  202. robotStatu.set_theta(pose.theta());
  203. if ((timedV_.timeout() == false && timedA_.timeout() == false)) {
  204. NavMessage::AgvStatu plc;
  205. plc.set_v(timedV_.Get());
  206. plc.set_w(timedA_.Get());
  207. plc.set_clamp(timed_clamp_.Get());
  208. plc.set_lifter(timed_lifter_.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. if (pose.theta() > 0) {
  228. if (parameter_.main_agv()) {
  229. isFront_.reset(true, 1.0);
  230. } else {
  231. isFront_.reset(false, 1.0);
  232. }
  233. } else {
  234. if (parameter_.main_agv()) {
  235. isFront_.reset(false, 1.0);
  236. } else {
  237. isFront_.reset(true, 1.0);
  238. }
  239. }
  240. }
  241. void Navigation::Cancel(const NavMessage::NavCmd &cmd, NavMessage::NavResponse &response) {
  242. cancel_ = true;
  243. response.set_ret(0);
  244. }
  245. bool Navigation::Stop() {
  246. if (monitor_) {
  247. monitor_->stop();
  248. while (cancel_ == false) {
  249. if (timedV_.timeout() == false && timedA_.timeout() == false) {
  250. if (fabs(timedV_.Get()) < 1e-2 && fabs(timedA_.Get()) < 1e-3)
  251. return true;
  252. else
  253. monitor_->stop();
  254. printf("Stoped wait V/A ==0(1e-4,1e-4),V:%f,A:%f\n", fabs(timedV_.Get()), fabs(timedA_.Get()));
  255. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  256. } else {
  257. printf("Stop failed V/A timeout\n");
  258. return false;
  259. }
  260. }
  261. }
  262. printf("stoped ret false.\n");
  263. return false;
  264. }
  265. bool Navigation::SlowlyStop() {
  266. double acc = 3.0;
  267. double dt = 0.1;
  268. while (cancel_ == false) {
  269. if (timedV_.timeout() == false) {
  270. double v = timedV_.Get();
  271. if (fabs(v < 1e-2 && fabs(timedA_.Get()) < 1e-3))
  272. return true;
  273. if (v > 0) {
  274. double new_v = v - acc * dt;
  275. new_v = new_v > 0 ? new_v : 0;
  276. SendMoveCmd(move_mode_, actionType_, new_v, 0);
  277. } else {
  278. double new_v = v + acc * dt;
  279. new_v = new_v < 0 ? new_v : 0;
  280. SendMoveCmd(move_mode_, actionType_, new_v, 0);
  281. }
  282. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  283. } else {
  284. printf("Stop failed V/A timeout\n");
  285. return false;
  286. }
  287. }
  288. printf("stoped ret false.\n");
  289. return false;
  290. }
  291. Navigation::Navigation() {
  292. wheelBase_ = 0;
  293. isInSpace_ = false; //是否在车位或者正在进入车位
  294. RWheel_position_ = eUnknow;
  295. move_mode_ = eSingle;
  296. monitor_ = nullptr;
  297. terminator_ = nullptr;
  298. obs_h_ = 4.0;
  299. obs_w_ = 2.0;
  300. timedBrotherPose_.reset(Pose2d(-100, 0, 0), 0.5);
  301. }
  302. void Navigation::BrotherAgvStatuCallback(const MqttMsg &msg, void *context) {
  303. Navigation *navigator = (Navigation *) context;
  304. NavMessage::NavStatu brother_statu;
  305. if (msg.toProtoMessage(brother_statu) == false) {
  306. std::cout << " msg transform to AGVStatu failed,msg:" << msg.data() << std::endl;
  307. return;
  308. }
  309. //std::cout<<brother_nav.DebugString()<<std::endl<<std::endl;
  310. if (brother_statu.has_odom()) {
  311. NavMessage::LidarOdomStatu odom = brother_statu.odom();
  312. Pose2d pose(odom.x(), odom.y(), odom.theta());
  313. navigator->timedBrotherPose_.reset(pose, 1);
  314. navigator->timedBrotherV_.reset(odom.v(), 1);
  315. navigator->timedBrotherA_.reset(odom.vth(), 1);
  316. navigator->timedBrotherNavStatu_.reset(brother_statu, 0.1);
  317. }
  318. }
  319. //未使用
  320. bool Navigation::RotateReferToTarget(const Pose2d &target, stLimit limit_rotate, bool anyDirect) {
  321. while (cancel_ == false) {
  322. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  323. if (timedPose_.timeout()) {
  324. printf(" RotateBytarget failed pose timeout\n");
  325. return false;
  326. }
  327. if (timedA_.timeout()) {
  328. printf(" RotateBytarget failed wmg timeout\n");
  329. return false;
  330. }
  331. Pose2d targetInPose = Pose2d::relativePose(target, timedPose_.Get());
  332. float yawDiff = Pose2d::vector2yaw(targetInPose.x(), targetInPose.y());
  333. float minYawdiff = yawDiff;
  334. if (anyDirect) {
  335. Pose2d p0 = timedPose_.Get();
  336. float yawdiff[4] = {0};
  337. yawdiff[0] = yawDiff;
  338. Pose2d relativePose;
  339. relativePose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, M_PI / 2));
  340. yawdiff[1] = Pose2d::vector2yaw(relativePose.x(), relativePose.y()); ////使用减法,保证角度在【-pi pi】
  341. relativePose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, M_PI));
  342. yawdiff[2] = Pose2d::vector2yaw(relativePose.x(), relativePose.y());
  343. relativePose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, 3 * M_PI / 2));
  344. yawdiff[3] = Pose2d::vector2yaw(relativePose.x(), relativePose.y());
  345. for (int i = 1; i < 4; ++i) {
  346. if (fabs(yawdiff[i]) < fabs(minYawdiff)) {
  347. minYawdiff = yawdiff[i];
  348. targetInPose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, i * M_PI / 2.0));
  349. }
  350. }
  351. }
  352. //std::cout<<" Rotate refer to target:"<<target<<",targetInPose:"
  353. //<<targetInPose<<",anyDirect:"<<anyDirect<<std::endl;
  354. //以当前点为原点,想方向经过目标点的二次曲线曲率>0.25,则需要调整 y=a x*x
  355. float cuv = compute_cuv(targetInPose);
  356. float dt = 0.1;
  357. float acc_angular = 15 * M_PI / 180.0;
  358. if (cuv > 2 * M_PI / 180.0) {
  359. double theta = limit_gause(minYawdiff, limit_rotate.min, limit_rotate.max);
  360. double angular = next_speed(timedA_.Get(), theta, acc_angular, dt);
  361. double limit_angular = limit(angular, limit_rotate.min, limit_rotate.max);
  362. SendMoveCmd(move_mode_, eRotation, 0, limit_angular);
  363. actionType_ = eRotation;
  364. printf(" Rotate | input angular:%f,next angular:%f,down:%f diff:%f anyDirect:%d\n",
  365. timedA_.Get(), angular, limit_angular, minYawdiff, anyDirect);
  366. continue;
  367. } else {
  368. if (fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  369. printf(" Rotate refer target completed,cuv:%f\n", cuv);
  370. return true;
  371. }
  372. continue;
  373. }
  374. }
  375. return false;
  376. }
  377. Navigation::MpcResult Navigation::RotateReferToTarget(NavMessage::PathNode node, stLimit limit_rotate, int directions) {
  378. if (inited_ == false) {
  379. printf(" MPC_rotate has not inited\n");
  380. return eMpcFailed;
  381. }
  382. if (PoseTimeout()) {
  383. printf(" MPC_rotate Error:Pose is timeout \n");
  384. return eMpcFailed;
  385. }
  386. printf(" exec MPC_rotate autoDirect:%d\n", directions);
  387. while (cancel_ == false) {
  388. std::this_thread::sleep_for(std::chrono::milliseconds(30));
  389. if (pause_ == true) {
  390. //发送暂停消息
  391. continue;
  392. }
  393. if (PoseTimeout()) {
  394. printf(" MPC_rotate Error:Pose is timeout \n");
  395. return eMpcFailed;
  396. }
  397. if (timedA_.timeout()) {
  398. printf(" MPC_rotate Error:v/a is timeout \n");
  399. return eMpcFailed;
  400. }
  401. Pose2d current = timedPose_.Get();
  402. Pose2d target(node.x(), node.y(), node.theta());
  403. Pose2d targetInPose = Pose2d::relativePose(target, current);
  404. // 需要旋转的角度
  405. float target_yaw_diff = Pose2d::vector2yaw(targetInPose.x(), targetInPose.y());
  406. // 自由方向
  407. if (directions) {
  408. std::vector<double> yaw_diffs;
  409. if (directions & Direction::eForward) {
  410. yaw_diffs.push_back(target_yaw_diff);
  411. }
  412. if (directions & Direction::eBackward) {
  413. Pose2d relative_pose = Pose2d::relativePose(targetInPose, Pose2d(0, 0, M_PI));
  414. yaw_diffs.push_back(Pose2d::vector2yaw(relative_pose.x(), relative_pose.y()));
  415. }
  416. if (directions & Direction::eLeft) {
  417. Pose2d relative_pose = Pose2d::relativePose(targetInPose, Pose2d(0, 0, 1.0 / 2 * M_PI));
  418. yaw_diffs.push_back(Pose2d::vector2yaw(relative_pose.x(), relative_pose.y()));
  419. }
  420. if (directions & Direction::eRight) {
  421. Pose2d relative_pose = Pose2d::relativePose(targetInPose, Pose2d(0, 0, 3.0 / 2 * M_PI));
  422. yaw_diffs.push_back(Pose2d::vector2yaw(relative_pose.x(), relative_pose.y()));
  423. }
  424. for (auto i = 0; i < yaw_diffs.size(); ++i) {
  425. if (fabs(yaw_diffs[i]) < fabs(target_yaw_diff))
  426. target_yaw_diff = yaw_diffs[i];
  427. }
  428. // std::cout << std::endl;
  429. // std::cout << std::endl << " min_diff: " << current_to_target.theta() << std::endl;
  430. }
  431. //一次变速
  432. std::vector<double> out;
  433. bool ret;
  434. TimerRecord::Execute([&, this]() {
  435. ret = Rotation_mpc_once(Pose2d(0, 0, target_yaw_diff), limit_rotate, out);
  436. }, "Rotation_mpc_once");
  437. if (ret == false) {
  438. Stop();
  439. return eMpcFailed;
  440. }
  441. //下发速度
  442. if (fabs(target_yaw_diff) < 0.2 * M_PI / 180.0 && fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  443. printf(" MPC_rotate | refer target completed\\n,cuv:%f\n", target_yaw_diff);
  444. Stop();
  445. return eMpcSuccess;
  446. } else {
  447. const int down_count = 3;
  448. double v[down_count] = {0, 0, 0};
  449. double w[down_count] = {out[0], out[1], out[2]};
  450. // if(out[0]>=0){
  451. // w[0]=1.*M_PI/180.0;
  452. // w[1]=1.*M_PI/180.0;
  453. // w[2]=1.*M_PI/180.0;
  454. // }else{
  455. // w[0]=-1.*M_PI/180.0;
  456. // w[1]=-1.*M_PI/180.0;
  457. // w[2]=-1.*M_PI/180.0;
  458. // }
  459. SendMoveCmd(move_mode_, eRotation, v, w);
  460. actionType_ = eRotation;
  461. double input_w = timedA_.Get();
  462. for (int i = 0; i < down_count; ++i) {
  463. printf(" MPC_rotate |P[%d], input anguar:%f, down:%f(%f), diff:%f anyDirect:%d\n",
  464. i, input_w, w[i], w[i] / M_PI * 180, target_yaw_diff, directions);
  465. }
  466. }
  467. continue;
  468. }
  469. return eMpcFailed;
  470. }
  471. bool Navigation::MoveToTarget(NavMessage::PathNode node, Navigation::stLimit limit_v, Navigation::stLimit limit_w,
  472. bool anyDirect, bool enable_rotate) {
  473. // LogWriter("MoveToTarget beg");
  474. if (IsArrived(node)) {
  475. return true;
  476. }
  477. bool already_in_mpc = false;
  478. while (cancel_ == false) {
  479. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  480. if (PoseTimeout()) {
  481. printf(" navigation Error:Pose is timeout \n");
  482. break;
  483. }
  484. Pose2d current = timedPose_.Get();
  485. if (IsArrived(node)) {
  486. break;
  487. }
  488. //两个方向都无法到达目标点,旋转 朝向目标点
  489. bool x_enable = PossibleToTarget(node, false);
  490. bool y_enable = PossibleToTarget(node, true);
  491. bool enableTotarget = x_enable || y_enable;
  492. if (anyDirect == false) {
  493. enableTotarget = x_enable;
  494. }
  495. //巡线无法到达目标点
  496. Pose2d target(node.x(), node.y(), 0);
  497. Pose2d targetInCurrent = Pose2d::relativePose(target, current);
  498. if (enableTotarget == false && Pose2d::distance(Pose2d(0, 0, 0), targetInCurrent) > 0.3) {
  499. if (already_in_mpc && enable_rotate == false) {
  500. printf(" Move to node failed ,impossible to target and rotate is not enabled\n");
  501. return false;
  502. }
  503. int directions = Direction::eForward;
  504. if (anyDirect)
  505. directions = Direction::eForward | Direction::eBackward |
  506. Direction::eLeft | Direction::eRight;
  507. if (RotateReferToTarget(node, limit_w, directions) != eMpcSuccess) {
  508. std::cout << " Rotate refer to target failed,target: " << target <<
  509. " directions: " << std::hex << directions << " line_: " << __LINE__ << std::endl;
  510. return false;
  511. }
  512. continue;
  513. }
  514. already_in_mpc = true;
  515. MpcResult ret = MpcToTarget(node, limit_v, anyDirect);
  516. if (ret == eMpcSuccess) {
  517. printf(" MPC to target:%f %f l:%f,w:%f theta:%f completed\n",
  518. node.x(), node.y(), node.l(), node.w(), node.theta());
  519. break;
  520. } else if (ret == eImpossibleToTarget) {
  521. printf(" MPC to target:%f %f l:%f,w:%f theta:%f impossible ,retry ...\n",
  522. node.x(), node.y(), node.l(), node.w(), node.theta());
  523. } else {
  524. return false;
  525. }
  526. }
  527. if (cancel_) {
  528. return false;
  529. }
  530. return true;
  531. }
  532. bool Navigation::execute_nodes(NavMessage::NewAction action, int space_id) {
  533. if (action.type() == 3 || action.type() == 4) //最优动作导航 or 导航中保证朝向严格一致
  534. {
  535. if (!parameter_.has_nodeangularlimit() || !parameter_.has_nodevelocitylimit() || action.pathnodes_size() == 0) {
  536. std::cout << "execute pathNodes failed ,Action invalid:" << action.DebugString() << std::endl;
  537. return false;
  538. }
  539. bool anyDirect = (action.type() == 3);
  540. //速度限制
  541. stLimit wmg_limit = {parameter_.nodeangularlimit().min(), parameter_.nodeangularlimit().max()};
  542. stLimit mpc_velocity = {parameter_.nodevelocitylimit().min(), parameter_.nodevelocitylimit().max()};
  543. /////////////////////////////////////////
  544. std::thread *thread_clampOpenHalf = nullptr;
  545. if(move_mode_==eSingle) {
  546. thread_clampOpenHalf = new std::thread(&Navigation::clamp_half_open, this);
  547. }
  548. ////////////////////////////////////////////////////////////
  549. for (int i = 0; i < action.pathnodes_size(); ++i) {
  550. NavMessage::PathNode node = action.pathnodes(i);
  551. if (i + 1 < action.pathnodes_size()) {
  552. NavMessage::PathNode next = action.pathnodes(i + 1);
  553. Pose2d vec(next.x() - node.x(), next.y() - node.y(), 0);
  554. node.set_theta(Pose2d::vector2yaw(vec.x(), vec.y()) + M_PI / 2.0);
  555. node.set_l(0.03);
  556. node.set_w(0.20);
  557. } else {
  558. NavMessage::PathNode befor = action.pathnodes(i - 1);
  559. Pose2d vec(node.x() - befor.x(), node.y() - befor.y(), 0);
  560. node.set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  561. node.set_l(0.02);
  562. node.set_w(0.2);
  563. }
  564. int directions = Direction::eForward;
  565. if (anyDirect)
  566. directions = Direction::eForward | Direction::eBackward |
  567. Direction::eLeft | Direction::eRight;
  568. if (i > 0) {
  569. if (RotateReferToTarget(node, wmg_limit, directions) != eMpcSuccess) {
  570. printf(" before move node RotateReferToNone Failed!!\n");
  571. return false;
  572. }
  573. }
  574. if (MoveToTarget(node, mpc_velocity, wmg_limit, anyDirect, true) == false)
  575. return false;
  576. else
  577. isInSpace_ = false;
  578. }
  579. if(move_mode_==eSingle) {
  580. printf(" wait clamp open half...\n");
  581. thread_clampOpenHalf->join();
  582. printf("clamp open half completed!!!\n");
  583. delete thread_clampOpenHalf;
  584. }
  585. if (cancel_ == true) {
  586. return false;
  587. }
  588. return true;
  589. }
  590. printf("execute PathNode failed ,action type is not 3/4 :%d\n", action.type());
  591. return false;
  592. }
  593. Navigation::MpcResult Navigation::RotateAfterOutSpace() {
  594. if (move_mode_ != eDouble)
  595. return eMpcSuccess;
  596. Pose2d init = timedPose_.Get();
  597. double diff1 = fabs(M_PI / 2.0 - init.theta());
  598. double diff2 = fabs(-M_PI / 2.0 - init.theta());
  599. double target = diff1 > diff2 ? M_PI / 2.0 : -M_PI / 2.0;
  600. stLimit limit_rotate = {3 * M_PI / 180.0, 15 * M_PI / 180.0};
  601. while (cancel_ == false) {
  602. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  603. Pose2d current = timedPose_.Get();
  604. double yawDiff = (target - current.theta());
  605. //一次变速
  606. std::vector<double> out;
  607. bool ret;
  608. TimerRecord::Execute([&, this]() {
  609. ret = Rotation_mpc_once(Pose2d(0, 0, yawDiff), limit_rotate, out);
  610. }, "Rotation_mpc_once");
  611. if (ret == false) {
  612. Stop();
  613. return eMpcFailed;
  614. }
  615. //下发速度
  616. if (fabs(yawDiff) < 0.3 * M_PI / 180.0 && fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  617. printf(" RotateBeforeEnterSpace refer target completed\\n,cuv:%f\n", yawDiff);
  618. Stop();
  619. return eMpcSuccess;
  620. } else {
  621. const int down_count = 3;
  622. double v[down_count] = {0, 0, 0};
  623. double w[down_count] = {out[0], out[1], out[2]};
  624. SendMoveCmd(move_mode_, eRotation, v, w);
  625. actionType_ = eRotation;
  626. printf(" RotateBeforeEnterSpace | input anguar:%f, down:%f(%f), diff:%f anyDirect:false\n",
  627. timedA_.Get(), out[0], out[0] / M_PI * 180, yawDiff);
  628. }
  629. continue;
  630. }
  631. return eMpcFailed;
  632. }
  633. Navigation::MpcResult
  634. Navigation::RotateBeforeEnterSpace(NavMessage::PathNode space,
  635. double wheelbase, NavMessage::PathNode &target) {
  636. // if (timedBrotherNavStatu_.timeout() || timedPose_.timeout()) {
  637. if (timedPose_.timeout()) {
  638. printf(" rotate failed : timedBrotherNavStatu_ or pose timeout\n");
  639. return eMpcFailed;
  640. }
  641. NavMessage::NavStatu brother = timedBrotherNavStatu_.Get();
  642. stLimit limit_rotate = {2 * M_PI / 180.0, 15 * M_PI / 180.0};
  643. double acc_angular = 20 * M_PI / 180.0;
  644. double dt = 0.1;
  645. Pose2d current = timedPose_.Get();
  646. double x = space.x();
  647. double y = space.y();
  648. Pose2d vec(x - current.x(), y - current.y(), 0);
  649. double vecTheta = Pose2d::vector2yaw(vec.x(), vec.y());
  650. bool isFront = isFront_.Get();
  651. printf(" front__:%d theta:%f\n", isFront, vecTheta);
  652. if (vecTheta < 0.)
  653. isFront = !isFront;
  654. //如果是后车,计算目标点(车位点-轴距)
  655. if (isFront == false) {
  656. printf("后车 RotateBeforeEnterSpace | , __LINE__ = %d\n", __LINE__);
  657. if (move_mode_ == eSingle) {
  658. x -= wheelbase * cos(vecTheta);
  659. y -= wheelbase * sin(vecTheta);
  660. printf("确定车位点:eSingle\n");
  661. }
  662. } else { //当后车先到,倒车入库
  663. printf("前车RotateBeforeEnterSpace | __LINE__ = %d\n", __LINE__);
  664. //rotated.mutable_theta() = space.theta();
  665. //rotated = rotated.rotate(rotated.x(), rotated.y(), M_PI);
  666. }
  667. Pose2d spaceInCurrent = Pose2d::relativePose(Pose2d(space.x(), space.y(), 0), current);
  668. target.set_x(x);
  669. target.set_y(y);
  670. target.set_theta(current.theta());
  671. target.set_l(0.02);
  672. target.set_w(0.05);
  673. target.set_id(space.id());
  674. printf("RotateBeforeEnterSpace | target:[x:%f,y:%f,theta:%f]\n", x, y, target.theta());
  675. // //整车协调的时候,保持前后与车位一致即可
  676. // if (move_mode_ == eDouble) {
  677. // double yawDiff1 = (rotated - timedPose_.Get()).theta();
  678. // double yawDiff2 = (rotated + Pose2d(0, 0, M_PI) - timedPose_.Get()).theta();
  679. // if (fabs(yawDiff1) < fabs(yawDiff2)) {
  680. // rotated = rotated + Pose2d(0, 0, M_PI);
  681. // }
  682. // }
  683. while (cancel_ == false) {
  684. std::this_thread::sleep_for(std::chrono::milliseconds(30));
  685. Pose2d current_now = timedPose_.Get();
  686. if (spaceInCurrent.x() < 0.)
  687. current_now = current_now.rotate(current_now.x(), current_now.y(), M_PI);
  688. double yawDiff = vecTheta - current_now.theta();
  689. //一次变速
  690. std::vector<double> out;
  691. bool ret;
  692. TimerRecord::Execute([&, this]() {
  693. ret = Rotation_mpc_once(Pose2d(0, 0, yawDiff), limit_rotate, out);
  694. }, "Rotation_mpc_once");
  695. if (ret == false) {
  696. Stop();
  697. return eMpcFailed;
  698. }
  699. //下发速度
  700. if (fabs(yawDiff) < 0.3 * M_PI / 180.0 && fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  701. printf(" RotateBeforeEnterSpace refer target completed\\n,cuv:%f\n", yawDiff);
  702. Stop();
  703. return eMpcSuccess;
  704. } else {
  705. const int down_count = 3;
  706. double v[down_count] = {0, 0, 0};
  707. double w[down_count] = {out[0], out[1], out[2]};
  708. SendMoveCmd(move_mode_, eRotation, v, w);
  709. actionType_ = eRotation;
  710. printf(" RotateBeforeEnterSpace | input anguar:%f, down:%f(%f), diff:%f anyDirect:false\n",
  711. timedA_.Get(), out[0], out[0] / M_PI * 180, yawDiff);
  712. }
  713. continue;
  714. }
  715. return eMpcFailed;
  716. }
  717. bool Navigation::execute_InOut_space(NavMessage::NewAction action) {
  718. // LogWriter("execute_InOut_space beg");
  719. if (action.type() != 1 && action.type() != 2) {
  720. printf(" Inout_space failed : msg action type must ==1\n ");
  721. return false;
  722. }
  723. if (!parameter_.has_inoutvlimit() || !action.has_spacenode() ||
  724. !action.has_streetnode()) {
  725. std::cout << "execute enter_space failed ,Action miss some infos:" << action.DebugString() << std::endl;
  726. return false;
  727. }
  728. if (PoseTimeout() == true) {
  729. printf(" inout_space failed type:%d : current pose is timeout\n", action.type());
  730. return false;
  731. }
  732. stLimit limit_v = {parameter_.inoutvlimit().min(), parameter_.inoutvlimit().max()};
  733. stLimit limit_w = {2 * M_PI / 180.0, 20 * M_PI / 180.0};
  734. //入库,起点为streetNode
  735. if (action.type() == 1) {
  736. // LogWriter("In space beg-");
  737. Pose2d vec(action.spacenode().x() - action.streetnode().x(),
  738. action.spacenode().y() - action.streetnode().y(),
  739. 0);
  740. action.mutable_streetnode()->set_l(0.02);
  741. action.mutable_streetnode()->set_w(0.2);
  742. action.mutable_streetnode()->set_theta(Pose2d::vector2yaw(vec.x(), vec.y())+M_PI/2.0);
  743. /*
  744. * 是否需要添加判断,距离较远才先运动到马路点=============================
  745. */
  746. if (MoveToTarget(action.streetnode(), limit_v, limit_w, true, true) == false) {
  747. printf(" Enter space failed type:%d: MoveTo StreetNode failed\n", action.type());
  748. return false;
  749. }
  750. //移动到库位点, 禁止任意方向// 不允许巡线中停下旋转(当无法到达目标点时,返回false)
  751. printf("inout ----------------------------------------\n");
  752. //计算车位朝向
  753. action.mutable_spacenode()->set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  754. //计算当前车是进入车位1点还是2点, 提升下降动作与旋转调整并行
  755. LifterStatus lifter_actType;
  756. std::thread *thread_lifter = nullptr;
  757. if (IsUperSpace(action.spacenode())) {
  758. //进载车板库前提升机构上升
  759. lifter_actType = eRose;
  760. thread_lifter = new std::thread(&Navigation::lifter_rise, this);
  761. } else {
  762. //否则下降
  763. lifter_actType = eDowned;
  764. thread_lifter = new std::thread(&Navigation::lifter_down, this);
  765. }
  766. NavMessage::PathNode new_target;
  767. bool retRotate=RotateBeforeEnterSpace(action.spacenode(), action.wheelbase(), new_target) == eMpcSuccess;
  768. printf(" wait lifter action:%d\n", lifter_actType);
  769. thread_lifter->join();
  770. delete thread_lifter;
  771. printf("lifter action:%d completed!!!\n", lifter_actType);
  772. if(retRotate==false){
  773. return false;
  774. }
  775. //入库
  776. Pose2d rotated = timedPose_.Get();
  777. double x = new_target.x();
  778. double y = new_target.y();
  779. Pose2d vecSpace(x - rotated.x(), y - rotated.y(), 0);
  780. rotated.mutable_theta() = Pose2d::vector2yaw(vecSpace.x(), vecSpace.y());
  781. bool isFront = isFront_.Get();
  782. if (rotated.theta() < 0.)
  783. isFront = !isFront;
  784. // 后进车,且单车,且先进车已过后进车的目标点
  785. Pose2d target(new_target.x(),new_target.y(),0);
  786. if (isFront == false && move_mode_ == eSingle) {
  787. while(true) {
  788. if (cancel_) {
  789. return false;
  790. }
  791. Pose2d current=timedPose_.Get();
  792. Pose2d brother_pose = timedBrotherPose_.Get();
  793. Pose2d vecCurent2T=current-target;
  794. Pose2d vecBrother2T=brother_pose-target;
  795. double dot=vecCurent2T.x()*vecBrother2T.x()+vecCurent2T.y()*vecBrother2T.y();
  796. if (timedBrotherNavStatu_.Get().in_space() == true && dot<0.) {
  797. printf("先进车已经过后进车目标点,后进车停止等待 dot=%f\n",dot);
  798. break;
  799. }
  800. printf(" 后车 等待 先车先入库。。。\n");
  801. usleep(1000 * 500);
  802. continue;
  803. }
  804. }
  805. isInSpace_ = true;
  806. printf("Enter space beg...\n");
  807. std::thread *thread_clamp = nullptr;
  808. thread_clamp = new std::thread(&Navigation::singleClamp_fullyOpen_until_inspaceBegin, this);
  809. bool retMove=MoveToTarget(new_target, limit_v, limit_w, true, false);
  810. thread_clamp->join();
  811. delete thread_clamp;
  812. if(retMove==false){
  813. printf(" Enter space:%s failed. type:%d\n", action.spacenode().id().data(), action.type());
  814. return false;
  815. }
  816. } else if (action.type() == 2) {
  817. // LogWriter("Out space beg-");
  818. // 计算当前位置,在车位点到马路点的连线方向上,与车位点的相对位姿
  819. Pose2d vec(action.streetnode().x() - action.spacenode().x(),
  820. action.streetnode().y() - action.spacenode().y(), 0);
  821. float theta = Pose2d::vector2yaw(vec.x(), vec.y());
  822. Pose2d space(action.spacenode().x(), action.spacenode().y(), theta);
  823. Pose2d current = timedPose_.Get();
  824. Pose2d diff = Pose2d::abs(Pose2d::relativePose(Pose2d(current.x(), current.y(), 0), space));
  825. if (diff.x() < 0.05 || diff.y() < 0.10) {
  826. //出库,移动到马路点,允许自由方向,不允许中途旋转
  827. action.mutable_streetnode()->set_theta(theta);
  828. action.mutable_streetnode()->set_l(0.03);
  829. action.mutable_streetnode()->set_w(0.2);
  830. std::cout << " Out space target street node:" << space << std::endl;
  831. if (MoveToTarget(action.streetnode(), limit_v, limit_w, true, false) == false) {
  832. printf(" out space failed type:%d: MoveTo StreetNode failed\n", action.type());
  833. return false;
  834. }
  835. } else {
  836. std::cout << " Out space failed: current pose too far from space node:" << space << ",diff:" << diff
  837. << std::endl;
  838. return false;
  839. }
  840. isInSpace_ = false;
  841. //从入口出库旋转180
  842. if (move_mode_ == eDouble && action.spacenode().id().find("S1101") != -1) {
  843. Pose2d current_pose = timedPose_.Get();
  844. double current_theta = current_pose.theta();
  845. if (RotateAfterOutSpace() != eMpcSuccess) {
  846. printf("Rotate after out entrance failed\n");
  847. return false;
  848. }
  849. }
  850. }
  851. return true;
  852. }
  853. /* current_to_target: current_to_target.theta()为所需旋转的角度
  854. * */
  855. bool Navigation::Rotation_mpc_once(Pose2d current_to_target, Navigation::stLimit limit_wmg, std::vector<double> &out,
  856. bool all_direct) {
  857. if (PoseTimeout() == true) {
  858. printf(" Rotation_mpc_once Error:Pose is timeout \n");
  859. return false;
  860. }
  861. if (timedV_.timeout() == true || timedA_.timeout() == true) {
  862. printf(" Rotation_mpc_once Error:V/A is timeout \n");
  863. return false;
  864. }
  865. Pose2d pose = timedPose_.Get();
  866. double line_velocity = timedV_.Get(); //从plc获取状态
  867. double angular_velocity = timedA_.Get();
  868. Eigen::VectorXd statu = Eigen::VectorXd::Zero(5);//agv状态
  869. statu[0] = pose.x();
  870. statu[1] = pose.y();
  871. statu[2] = pose.theta();
  872. statu[3] = line_velocity;
  873. statu[4] = angular_velocity;
  874. NavParameter::MPC_parameter mpc_parameter = parameter_.x_mpc_parameter();
  875. double obs_w = 0.95;//0.85;
  876. double obs_h = 1.55;//1.45;
  877. MpcError ret = failed;
  878. Pose2d brother = timedBrotherPose_.Get();
  879. Pose2d brother_in_self = Pose2d::relativePose(brother, pose);
  880. // std::cout<<" brother_in_self: "<<brother_in_self<<std::endl;
  881. if (move_mode_ == eDouble) {
  882. brother_in_self = Pose2d(pose.x() + 100, pose.y() + 100, 0);
  883. }
  884. RotateMPC MPC(brother_in_self, obs_w, obs_h, limit_wmg.min, limit_wmg.max);
  885. RotateMPC::MPC_parameter parameter = {mpc_parameter.shortest_radius(), mpc_parameter.dt(),
  886. mpc_parameter.acc_velocity(), mpc_parameter.acc_angular()};
  887. ret = MPC.solve(current_to_target, statu, parameter, out);
  888. if (ret == no_solution) {
  889. printf(" Rotation_mpc solve no solution set v/w = 0\n");
  890. out.clear();
  891. out.push_back(0);
  892. out.push_back(0);
  893. out.push_back(0);
  894. } else {
  895. // double min_angular_velocity = 1.0 / 180 * M_PI;
  896. double min_angular_velocity = 0.01;
  897. const int down_count = 3;
  898. for (int i = 0; i < down_count; ++i) {
  899. if (fabs(out[i]) < min_angular_velocity) {
  900. if (out[i] > 0)
  901. out[i] = min_angular_velocity;
  902. else if (out[i] < 0)
  903. out[i] = -min_angular_velocity;
  904. else {}
  905. }
  906. }
  907. }
  908. return ret == success || ret == no_solution;
  909. }
  910. bool Navigation::mpc_once(Trajectory traj, stLimit limit_v, std::vector<double> &out, bool directY) {
  911. if (PoseTimeout() == true) {
  912. printf(" MPC once Error:Pose is timeout \n");
  913. return false;
  914. }
  915. if (timedV_.timeout() == true || timedA_.timeout() == true) {
  916. printf(" MPC once Error:V/A is timeout \n");
  917. return false;
  918. }
  919. if (traj.size() == 0) {
  920. printf("traj size ==0\n");
  921. return false;
  922. }
  923. Pose2d pose = timedPose_.Get();
  924. double velocity = timedV_.Get(); //从plc获取状态
  925. double angular = timedA_.Get();
  926. // float diffYaw1=timedPose_.Get().m_diffYaw1;
  927. // float diffYaw2=timedPose_.Get().m_diffYaw2;
  928. Eigen::VectorXd statu = Eigen::VectorXd::Zero(5);//agv状态
  929. statu[0] = pose.x();
  930. statu[1] = pose.y();
  931. statu[2] = pose.theta();
  932. statu[3] = velocity;
  933. statu[4] = angular;
  934. Trajectory optimize_trajectory;
  935. Trajectory selected_trajectory;
  936. NavParameter::MPC_parameter mpc_parameter = parameter_.x_mpc_parameter();
  937. double obs_w = obs_w_;// 0.95;//0.85;
  938. double obs_h = obs_h_;// 1.55;//1.45;
  939. if (directY == true) {
  940. //将车身朝向旋转90°,车身朝向在(-pi,pi]
  941. statu[2] += M_PI / 2;
  942. if (statu[2] > M_PI)
  943. statu[2] -= 2 * M_PI;
  944. mpc_parameter = parameter_.y_mpc_parameter();
  945. obs_w = obs_h_;// 0.95;//0.85;
  946. obs_h = obs_w_;//1.55;//1.45;
  947. }
  948. Pose2d brother = timedBrotherPose_.Get();
  949. Pose2d relative = Pose2d::relativePose(brother, pose);
  950. if (directY)
  951. relative = Pose2d::relativePose(brother.rotate(brother.x(), brother.y(), M_PI / 2),
  952. pose.rotate(pose.x(), pose.y(), M_PI / 2));//计算另一节在当前小车坐标系下的坐标
  953. std::cout << "pose:" << pose << ", brother:" << brother << ", relative:" << relative << std::endl;
  954. if (move_mode_ == eDouble)
  955. relative = Pose2d(-1e8, -1e8, 0);
  956. MpcError ret = failed;
  957. LoadedMPC MPC(relative, obs_w, obs_h, limit_v.min, limit_v.max);
  958. LoadedMPC::MPC_parameter parameter = {mpc_parameter.shortest_radius(), mpc_parameter.dt(),
  959. mpc_parameter.acc_velocity(), mpc_parameter.acc_angular()};
  960. //printf(" r:%f dt:%f acc:%f acc_a:%f\n",mpc_parameter.shortest_radius(),
  961. // mpc_parameter.dt(),mpc_parameter.acc_velocity(),mpc_parameter.acc_angular());
  962. ret = MPC.solve(traj, traj[traj.size() - 1], statu, parameter,
  963. out, selected_trajectory, optimize_trajectory, directY);
  964. //std::cout<<" traj size %d %d -------- "<<selected_trajectory.size()<<","<<optimize_trajectory.size()<<std::endl;
  965. if (ret == no_solution) {
  966. printf(" mpc solve no solution set v/w = 0\n");
  967. out.clear();
  968. out.push_back(0);
  969. out.push_back(0);
  970. out.push_back(0);
  971. out.push_back(0);
  972. out.push_back(0);
  973. out.push_back(0);
  974. }
  975. //
  976. // diff_yaw.push_back(0);
  977. // diff_yaw.push_back(0);
  978. predict_traj_.reset(optimize_trajectory, 1);
  979. selected_traj_.reset(selected_trajectory, 1);
  980. return ret == success || ret == no_solution;
  981. }
  982. bool Navigation::IsArrived(NavMessage::PathNode targetNode) {
  983. if (timedPose_.timeout() || timedV_.timeout() || timedA_.timeout()) {
  984. printf(" pose / v / w timeout,IsArrived return false\n");
  985. return false;
  986. }
  987. Pose2d current = timedPose_.Get();
  988. double x = current.x();
  989. double y = current.y();
  990. double tx = targetNode.x();
  991. double ty = targetNode.y();
  992. double l = fabs(targetNode.l());
  993. double w = fabs(targetNode.w());
  994. double theta = -targetNode.theta();
  995. if (newUnfinished_cations_.front().type() == 1 && targetNode.id().find('S') != -1) {//入库只判断前后方向上是否到达
  996. tx = x;
  997. }
  998. if (l < 1e-10 || w < 1e-10) {
  999. printf("IsArrived: Error target l or w == 0\n");
  1000. return false;
  1001. }
  1002. double a = (x - tx) * cos(theta) - (y - ty) * sin(theta);
  1003. double b = (x - tx) * sin(theta) + (y - ty) * cos(theta);
  1004. if (pow(a / l, 8) + pow(b / w, 8) <= 1) {
  1005. if (fabs(timedV_.Get()) < 0.05 && fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  1006. printf(" Arrived target: %f %f l:%f w:%f theta:%f\n", tx, ty, l, w, theta);
  1007. return true;
  1008. }
  1009. }
  1010. return false;
  1011. }
  1012. void Navigation::SendMoveCmd(int mode, ActionType type,
  1013. double v, double angular) {
  1014. if (monitor_) {
  1015. monitor_->set_speed(mode, type, v, angular);
  1016. if (type == eRotation)
  1017. RWheel_position_ = eR;
  1018. if (type == eVertical)
  1019. RWheel_position_ = eX;
  1020. if (type == eHorizontal)
  1021. RWheel_position_ = eY;
  1022. }
  1023. }
  1024. void Navigation::SendMoveCmd(int mode, ActionType type,
  1025. double v[], double angular[]) {
  1026. if (monitor_) {
  1027. monitor_->set_ToAgvCmd(mode, type, v, angular);
  1028. if (type == eRotation)
  1029. RWheel_position_ = eR;
  1030. if (type == eVertical)
  1031. RWheel_position_ = eX;
  1032. if (type == eHorizontal)
  1033. RWheel_position_ = eY;
  1034. }
  1035. }
  1036. void Navigation::SendMoveCmd(int mode, ActionType type, double v[], double angular[], int space_id, double distance) {
  1037. if (monitor_) {
  1038. monitor_->set_ToAgvCmd(mode, type, v, angular, 0, space_id, distance);
  1039. if (type == eRotation)
  1040. RWheel_position_ = eR;
  1041. if (type == eVertical)
  1042. RWheel_position_ = eX;
  1043. if (type == eHorizontal)
  1044. RWheel_position_ = eY;
  1045. }
  1046. }
  1047. //void Navigation::SendMoveCmd(int mode, ActionType type, double v[], double angular[], double yaw_diff[] ,int space_id, double distance) {
  1048. // if (monitor_) {
  1049. // monitor_->set_ToAgvCmd(mode, type, v, angular, yaw_diff ,0,space_id, distance);
  1050. // if (type == eRotation)
  1051. // RWheel_position_ = eR;
  1052. // if (type == eVertical)
  1053. // RWheel_position_ = eX;
  1054. // if (type == eHorizontal)
  1055. // RWheel_position_ = eY;
  1056. // }
  1057. //}
  1058. bool Navigation::clamp_close() {
  1059. if (monitor_) {
  1060. printf("Clamp closing...\n");
  1061. monitor_->clamp_close(move_mode_);
  1062. actionType_ = eClampClose;
  1063. while (cancel_ == false) {
  1064. if (timed_clamp_.timeout()) {
  1065. printf("timed clamp is timeout\n");
  1066. return false;
  1067. }
  1068. if (timed_clamp_.Get() == eClosed)
  1069. return true;
  1070. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1071. monitor_->clamp_close(move_mode_);
  1072. actionType_ = eClampClose;
  1073. }
  1074. return false;
  1075. }
  1076. return false;
  1077. }
  1078. bool Navigation::clamp_half_open() {
  1079. if (monitor_) {
  1080. printf("Clamp openning...\n");
  1081. monitor_->clamp_half_open(move_mode_);
  1082. actionType_ = eClampHalfOpen;
  1083. while (cancel_ == false) {
  1084. if (timed_clamp_.timeout()) {
  1085. printf("timed clamp is timeout\n");
  1086. return false;
  1087. }
  1088. if (timed_clamp_.Get() == eHalfOpened)
  1089. return true;
  1090. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1091. monitor_->clamp_half_open(move_mode_);
  1092. actionType_ = eClampHalfOpen;
  1093. }
  1094. return false;
  1095. }
  1096. return false;
  1097. }
  1098. bool Navigation::IsUperSpace(NavMessage::PathNode spaceNode) {
  1099. if(spaceNode.id().find("S")<0)
  1100. return false;
  1101. std::string id = spaceNode.id().substr(1, spaceNode.id().length() - 1);
  1102. int space_id = stoi(id);
  1103. if (space_id > 99 && space_id < 1000) {
  1104. return true;
  1105. }
  1106. return false;
  1107. }
  1108. bool Navigation::singleClamp_fullyOpen_until_inspaceBegin(){
  1109. if(move_mode_==eDouble){
  1110. return true;
  1111. }
  1112. while(cancel_==false){
  1113. if(timedV_.timeout()){
  1114. return false;
  1115. }
  1116. if(fabs(timedV_.Get())<0.02){
  1117. usleep(1000*300);
  1118. continue;
  1119. }
  1120. break;
  1121. }
  1122. return clamp_fully_open();
  1123. };
  1124. bool Navigation::clamp_fully_open() {
  1125. if (monitor_) {
  1126. if (timed_clamp_.Get() == eFullyOpened)
  1127. return true;
  1128. printf("Clamp fully openning...\n");
  1129. monitor_->clamp_fully_open(move_mode_);
  1130. actionType_ = eClampFullyOpen;
  1131. while (cancel_ == false) {
  1132. if (timed_clamp_.timeout()) {
  1133. printf("timed clamp is timeout\n");
  1134. return false;
  1135. }
  1136. if (timed_clamp_.Get() == eFullyOpened)
  1137. return true;
  1138. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1139. monitor_->clamp_fully_open(move_mode_);
  1140. actionType_ = eClampFullyOpen;
  1141. }
  1142. return false;
  1143. }
  1144. return false;
  1145. }
  1146. bool Navigation::lifter_rise() {
  1147. if (monitor_) {
  1148. printf("Lifter upping...\n");
  1149. actionType_ = eLifterRise;
  1150. if (timed_lifter_.Get() == eRose)
  1151. return true;
  1152. if (timed_lifter_.Get() != eRose) {
  1153. if (timed_clamp_.Get() != eHalfOpened && timed_clamp_.Get() != eClosed) {
  1154. printf(" clamp statu !=eHalfOpened or eClosed, clamp_half_open...\n ");
  1155. if (!clamp_half_open()) {
  1156. printf(" clamp half open failed\n");
  1157. return false;
  1158. }
  1159. }
  1160. }
  1161. while (cancel_ == false) {
  1162. if (timed_lifter_.timeout()) {
  1163. printf("timed lifter is timeout\n");
  1164. return false;
  1165. }
  1166. if (timed_lifter_.timeout()) {
  1167. return false;
  1168. }
  1169. if (timed_lifter_.Get() == eRose)
  1170. return true;
  1171. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1172. monitor_->lifter_rise(move_mode_);
  1173. actionType_ = eLifterRise;
  1174. }
  1175. return false;
  1176. }
  1177. return false;
  1178. }
  1179. bool Navigation::lifter_down() {
  1180. if (monitor_) {
  1181. printf("Lifter downing...\n");
  1182. if (timed_lifter_.Get() == eDowned)
  1183. return true;
  1184. actionType_ = eLifterDown;
  1185. if (timed_lifter_.Get() != eDowned) {
  1186. if (timed_clamp_.Get() != eHalfOpened && timed_clamp_.Get() != eClosed) {
  1187. printf(" clamp statu !=eHalfOpened or eClosed, clamp_half_open...\n ");
  1188. if (!clamp_half_open()) {
  1189. printf(" clamp half open failed\n");
  1190. return false;
  1191. }
  1192. }
  1193. }
  1194. while (cancel_ == false) {
  1195. if (timed_lifter_.timeout()) {
  1196. printf("timed lifter is timeout\n");
  1197. return false;
  1198. }
  1199. if (timed_lifter_.timeout()) {
  1200. return false;
  1201. }
  1202. if (timed_lifter_.Get() == eDowned)
  1203. return true;
  1204. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1205. monitor_->lifter_down(move_mode_);
  1206. actionType_ = eLifterDown;
  1207. }
  1208. return false;
  1209. }
  1210. return false;
  1211. }
  1212. Navigation::MpcResult Navigation::MpcToTarget(NavMessage::PathNode node, stLimit limit_v, bool autoDirect) {
  1213. // LogWriter("MpcToTarget beg");
  1214. if (IsArrived(node)) {
  1215. printf(" current already in target completed !!!\n");
  1216. return eMpcSuccess;
  1217. }
  1218. if (inited_ == false) {
  1219. printf(" navigation has not inited\n");
  1220. return eMpcFailed;
  1221. }
  1222. if (PoseTimeout()) {
  1223. printf(" navigation Error:Pose is timeout \n");
  1224. return eMpcFailed;
  1225. }
  1226. Pose2d current = timedPose_.Get();
  1227. Pose2d target(node.x(), node.y(), 0);
  1228. //生成轨迹
  1229. Trajectory traj = Trajectory::create_line_trajectory(current, target, 0.1);
  1230. if (traj.size() == 0)
  1231. return eMpcSuccess;
  1232. //判断 巡线方向
  1233. bool directY = false;
  1234. if (autoDirect) {
  1235. Pose2d target_relative = Pose2d::relativePose(target, timedPose_.Get());
  1236. if (fabs(target_relative.y()) > fabs(target_relative.x())) { //目标轨迹点在当前点Y轴上
  1237. std::cout << " MPC Y axis target_relative:" << target_relative << std::endl;
  1238. directY = true;
  1239. } else {
  1240. std::cout << " MPC X axis target_relative:" << target_relative << std::endl;
  1241. }
  1242. }
  1243. printf(" exec along autoDirect:%d\n", autoDirect);
  1244. //文件log
  1245. std::ofstream ofs; //创建流对象
  1246. std::string log_file_dir = "../data/";
  1247. time_t t = time(0);
  1248. char tmp[32] = {NULL};
  1249. strftime(tmp, sizeof(tmp), "%Y_%m_%d_%H_%M_%S.txt", localtime(&t));
  1250. std::string log_file_name = tmp;
  1251. ofs.open(log_file_dir + log_file_name, std::ios::app); //打开的地址和方式
  1252. auto beg_time = std::chrono::steady_clock::now();
  1253. while (cancel_ == false) {
  1254. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  1255. if (pause_ == true) {
  1256. //发送暂停消息
  1257. continue;
  1258. }
  1259. if (PoseTimeout()) {
  1260. printf(" navigation Error:Pose is timeout \n");
  1261. ofs.close();//关闭文件
  1262. return eMpcFailed;
  1263. }
  1264. if (timedV_.timeout() || timedA_.timeout()) {
  1265. printf(" navigation Error:v/a is timeout | __LINE__:%d \n", __LINE__);
  1266. ofs.close();//关闭文件
  1267. return eMpcFailed;
  1268. }
  1269. //判断是否到达终点
  1270. if (IsArrived(node)) {
  1271. if (Stop()) {
  1272. printf(" exec along completed !!!\n");
  1273. ofs.close();//关闭文件
  1274. return eMpcSuccess;
  1275. }
  1276. }
  1277. //一次变速
  1278. std::vector<double> out;
  1279. // std::vector<double> diff_yaw; //两车分别与整车的相对角度
  1280. bool ret;
  1281. TimerRecord::Execute([&, this]() {
  1282. ret = mpc_once(traj, limit_v, out, directY);
  1283. }, "mpc_once");
  1284. if (ret == false) {
  1285. Stop();
  1286. ofs.close();//关闭文件
  1287. return eMpcFailed;
  1288. }
  1289. const int down_count = 3;//下发前多少步
  1290. double down_v[down_count] = {out[0], out[2], out[4]};//下发线速度
  1291. double down_w[down_count] = {out[1], out[3], out[5]};//下发角速度
  1292. /*
  1293. * AGV 在终点附近低速巡航时,设置最小速度0.05
  1294. */
  1295. Pose2d target_in_agv = Pose2d::relativePose(target, timedPose_.Get());
  1296. if (directY) {
  1297. target_in_agv = target_in_agv.rotate(M_PI / 2.0);
  1298. }
  1299. if (Pose2d::abs(target_in_agv) < Pose2d(0.2, 2, M_PI * 2)) {
  1300. for (int i = 0; i < down_count; ++i) {
  1301. if (down_v[i] >= 0 && down_v[i] < limit_v.min)
  1302. down_v[i] = limit_v.min;
  1303. if (down_v[i] < 0 && down_v[i] > -limit_v.min)
  1304. down_v[i] = -limit_v.min;
  1305. }
  1306. }
  1307. //放大角速度
  1308. // out[1] *= 10;
  1309. //入库,行进方向上最后一米不纠偏
  1310. if (newUnfinished_cations_.front().type() == 1 && node.id().find('S') != -1) {//入库
  1311. if (fabs(target_in_agv.x()) < 0.5) {
  1312. printf("target_in_agv: %f", target_in_agv.x());
  1313. for (double &i: down_w) {
  1314. i = 0.0;
  1315. }
  1316. }
  1317. } else if (newUnfinished_cations_.front().type() == 2) {//出库,行进方向上开始一米不纠偏
  1318. Pose2d agv_in_space =
  1319. Pose2d::relativePose(
  1320. Pose2d(newUnfinished_cations_.front().spacenode().x(),
  1321. newUnfinished_cations_.front().spacenode().y(), 0),
  1322. timedPose_.Get());
  1323. if (fabs(agv_in_space.x()) < 0.3) {
  1324. printf("agv_in_space: %f", agv_in_space.x());
  1325. for (double &i: down_w) {
  1326. i = 0.0;
  1327. }
  1328. }
  1329. }
  1330. //下发速度
  1331. //printf(" nav input :%f out:%f\n",timedV_.Get(),out[0]);
  1332. //添加车位号,距目标点距离信息
  1333. double distance = Pose2d::distance(target_in_agv, Pose2d(0, 0, 0));
  1334. int space_id = 0;
  1335. if (node.id().find('S') != -1) {
  1336. std::string id = node.id().substr(1, node.id().length() - 1);
  1337. space_id = stoi(id);
  1338. }
  1339. // double diff_yaw_[2] = {diff_yaw[0], diff_yaw[1]};
  1340. if (directY == false)
  1341. SendMoveCmd(move_mode_, eVertical, down_v, down_w, space_id, distance);
  1342. else
  1343. SendMoveCmd(move_mode_, eHorizontal, down_v, down_w, space_id, distance);
  1344. actionType_ = directY ? eHorizontal : eVertical;
  1345. //日志打印
  1346. std::string log_inf_line = std::to_string(move_mode_);
  1347. log_inf_line += " ";
  1348. log_inf_line += std::to_string(parameter_.x_mpc_parameter().shortest_radius()) + " " +
  1349. std::to_string(parameter_.x_mpc_parameter().acc_angular());
  1350. log_inf_line += " ";
  1351. Pose2d cur_pose = timedPose_.Get();//自身x,y,theta
  1352. log_inf_line += std::to_string(cur_pose.x()) + " " + std::to_string(cur_pose.y()) + " " +
  1353. std::to_string(cur_pose.theta());
  1354. log_inf_line += " ";
  1355. Pose2d cur_Bro_pose = timedBrotherPose_.Get();//另一节x,y,theta
  1356. log_inf_line += std::to_string(cur_Bro_pose.x()) + " " + std::to_string(cur_Bro_pose.y()) + " " +
  1357. std::to_string(cur_Bro_pose.theta());
  1358. log_inf_line += " ";
  1359. log_inf_line += std::to_string(out[0]) + " " + std::to_string(out[1]);//下发速度
  1360. log_inf_line += " ";
  1361. log_inf_line += std::to_string(out[2]) + " " + std::to_string(out[3]);//下发速度
  1362. log_inf_line += " ";
  1363. log_inf_line += std::to_string(out[4]) + " " + std::to_string(out[5]);//下发速度
  1364. log_inf_line += " ";
  1365. auto cur_time = std::chrono::steady_clock::now();
  1366. auto duration = std::chrono::duration_cast<std::chrono::microseconds>(cur_time - beg_time);
  1367. double time =
  1368. double(duration.count()) * std::chrono::microseconds::period::num /
  1369. std::chrono::microseconds::period::den;
  1370. log_inf_line += std::to_string(time);
  1371. ofs << log_inf_line << std::endl; //一行日志的内容
  1372. /*
  1373. * 判断车辆是否在终点附近徘徊,无法到达终点
  1374. */
  1375. if (PossibleToTarget(node, directY) == false) {
  1376. printf(" --------------MPC imposible to target -------------------------------------------\n");
  1377. if (fabs(timedV_.Get()) > 0.1 || fabs(timedA_.Get()) > 10 * M_PI / 180.0)
  1378. SlowlyStop();
  1379. else
  1380. Stop();
  1381. ofs.close();//关闭文件
  1382. return eImpossibleToTarget;
  1383. }
  1384. }
  1385. ofs.close();//关闭文件
  1386. return eMpcFailed;
  1387. }
  1388. bool Navigation::PossibleToTarget(NavMessage::PathNode targetNode, bool directY) {
  1389. if (timedPose_.timeout()) {
  1390. return false;
  1391. }
  1392. Pose2d current = timedPose_.Get();
  1393. if (targetNode.id().find('S') != -1) {
  1394. //车位点强制可到达
  1395. return true;
  1396. }
  1397. double tx = targetNode.x();
  1398. double ty = targetNode.y();
  1399. double l = fabs(targetNode.l());
  1400. double w = fabs(targetNode.w());
  1401. double theta = -targetNode.theta();
  1402. // double W = 2.45;
  1403. // double L = 1.3;
  1404. // double minYaw = 3 * M_PI / 180.0;
  1405. // if (move_mode_ == eDouble) {
  1406. // L = 1.3 + 2.7;
  1407. //
  1408. // }
  1409. double W = 2.5;
  1410. double L = 1.565;
  1411. double minYaw = 5 * M_PI / 180.0;
  1412. if (move_mode_ == eDouble) {
  1413. L = 1.565 + 2.78;
  1414. }
  1415. if (directY) {
  1416. current = current.rotate(current.x(), current.y(), M_PI / 2);
  1417. double t = W;
  1418. W = L;
  1419. L = t;
  1420. }
  1421. double minR = W / 2 + L / tan(minYaw);
  1422. //printf("l:%f,w:%f\n",l,w);
  1423. std::vector<Pose2d> poses = Pose2d::generate_rectangle_vertexs(Pose2d(tx, ty, 0), l * 2, w * 2);
  1424. bool nagY = false;
  1425. bool posiY = false;
  1426. for (int i = 0; i < poses.size(); ++i) {
  1427. Pose2d rpos = poses[i].rotate(tx, ty, theta);
  1428. Pose2d relative = Pose2d::relativePose(rpos, current);
  1429. double ax = fabs(relative.x());
  1430. double ay = fabs(relative.y());
  1431. if (relative.y() > 0) posiY = true;
  1432. if (relative.y() < 0) nagY = true;
  1433. if (ax * ax + pow(ay - minR, 2) > minR * minR) {
  1434. /*printf(" possible to target:%f %f l:%f,w:%f theta:%f minR:%f ax:%f,ay:%f\n",
  1435. targetNode.x(),targetNode.y(),targetNode.l(),targetNode.w(),targetNode.theta(),
  1436. minR,ax,ay);*/
  1437. return true;
  1438. } else if (nagY && posiY) {
  1439. // std::cout << "nagY && posiY" << std::endl;
  1440. return true;
  1441. }
  1442. // printf("directY:%d targetInPose:%f %f l:%f,w:%f theta:%f minR:%f ax:%f,ay:%f\n", directY,
  1443. // relative.x(), relative.y(), targetNode.l(), targetNode.w(), targetNode.theta(),
  1444. // minR, ax, ay);
  1445. }
  1446. printf(" impossible to target:%f %f l:%f,w:%f theta:%f, ",
  1447. targetNode.x(), targetNode.y(), targetNode.l(), targetNode.w(), targetNode.theta());
  1448. printf(" current:%f, %f, %f\n",
  1449. current.x(), current.y(), current.theta());
  1450. return false;
  1451. }
  1452. void Navigation::Start(const NavMessage::NavCmd &cmd, NavMessage::NavResponse &response) {
  1453. if (inited_ == false) {
  1454. response.set_ret(-1);
  1455. response.set_info("navigation has not inited");
  1456. printf(" navigation has not inited\n");
  1457. return;
  1458. }
  1459. if (newUnfinished_cations_.empty() == false) //正在运行中,上一次指令未完成
  1460. {
  1461. response.set_ret(-2);
  1462. response.set_info("navigation is running pls cancel before");
  1463. printf(" navigation is running pls cancel before\n");
  1464. return;
  1465. }
  1466. //add 先检查当前点与起点的距离
  1467. global_navCmd_ = cmd;
  1468. for (int i = 0; i < cmd.newactions_size(); ++i)
  1469. newUnfinished_cations_.push(cmd.newactions(i));
  1470. pause_ = false;
  1471. cancel_ = false;
  1472. running_ = true;
  1473. actionType_ = eReady;
  1474. printf("Navigation beg...\n");
  1475. while (newUnfinished_cations_.empty() == false && cancel_ == false) {
  1476. std::cout << "unfinished size:" << newUnfinished_cations_.size() << std::endl;
  1477. NavMessage::NewAction act = newUnfinished_cations_.front();
  1478. NavMessage::NewAction last_act = newUnfinished_cations_.back();
  1479. if (act.type() == 1) { //入库
  1480. space_id_ = act.spacenode().id();
  1481. obs_w_ = 1.25;
  1482. obs_h_ = 1.87;
  1483. if (!execute_InOut_space(act)) {
  1484. printf(" In space failed\n");
  1485. isInSpace_ = false;
  1486. break;
  1487. }
  1488. } else if (act.type() == 2) { //出库
  1489. obs_w_ = 1.25;
  1490. obs_h_ = 1.87;
  1491. if (!execute_InOut_space(act)) {
  1492. printf(" out space failed\n");
  1493. break;
  1494. } else {
  1495. isInSpace_ = false;
  1496. }
  1497. } else if (act.type() == 3 || act.type() == 4) { //马路导航
  1498. obs_w_ = 1.25;
  1499. obs_h_ = 1.87;
  1500. int space_id = -1;
  1501. if (last_act.type() == 1) {
  1502. std::string id = last_act.spacenode().id().substr(1, last_act.spacenode().id().length() - 1);
  1503. space_id = stoi(id);
  1504. }
  1505. if (!execute_nodes(act, space_id)) {
  1506. printf(" street nav failed\n");
  1507. break;
  1508. }
  1509. } else if (act.type() == 5) {
  1510. printf(" 汽车模型导航....\n");
  1511. } else if (act.type() == 6) {//夹持
  1512. if (this->clamp_close() == false) {
  1513. printf("夹持failed ...\n");
  1514. break;
  1515. }
  1516. } else if (act.type() == 7) {
  1517. if (this->clamp_fully_open() == false) {
  1518. printf("打开夹持 failed...\n");
  1519. break;
  1520. }
  1521. } else if (act.type() == 8) { //切换模式
  1522. SwitchMode(act.changedmode(), act.wheelbase());
  1523. } else if (act.type() == 9) { //提升机构提升
  1524. if (this->lifter_rise() == false) {
  1525. printf("提升failed ...\n");
  1526. break;
  1527. }
  1528. } else if (act.type() == 10) { //提升机构下降
  1529. if (this->lifter_down() == false) {
  1530. printf("下降failed ...\n");
  1531. break;
  1532. }
  1533. } else {
  1534. printf(" action type invalid not handled !!\n");
  1535. break;
  1536. }
  1537. newUnfinished_cations_.pop();
  1538. }
  1539. actionType_ = eReady;
  1540. Stop();
  1541. if (cancel_ == true) {
  1542. response.set_ret(-3);
  1543. response.set_info("navigation canceled");
  1544. printf(" navigation canceled\n");
  1545. while (newUnfinished_cations_.empty() == false)
  1546. newUnfinished_cations_.pop();
  1547. } else {
  1548. if (newUnfinished_cations_.empty()) {
  1549. response.set_ret(0);
  1550. response.set_info("navigation completed!!!");
  1551. printf("navigation completed!!!\n");
  1552. } else {
  1553. response.set_ret(-4);
  1554. response.set_info("navigation Failed!!!!");
  1555. printf(" navigation Failed\n");
  1556. while (newUnfinished_cations_.empty() == false)
  1557. newUnfinished_cations_.pop();
  1558. }
  1559. }
  1560. running_ = false;
  1561. }
  1562. void Navigation::SwitchMode(int mode, float wheelBase) {
  1563. wheelBase_ = wheelBase;
  1564. printf("Child AGV can not Switch Mode\n");
  1565. }
  1566. float Navigation::compute_cuv(const Pose2d &target) {
  1567. float x = fabs(target.x());
  1568. float y = fabs(target.y());
  1569. float cuv = atan(y / (x + 1e-8));
  1570. //printf(" ---------------------- cuv:%f\n",cuv);
  1571. return cuv;
  1572. }
  1573. void Navigation::ManualOperation(const NavMessage::ManualCmd &cmd, NavMessage::NavResponse &response) {
  1574. return;
  1575. // pause_ = false;
  1576. // cancel_ = false;
  1577. // running_ = true;
  1578. // actionType_ = eReady;
  1579. // printf("ManualOperation: %d | start...\n", cmd.operation_type());
  1580. //
  1581. // float symbol = cmd.velocity() < 0 ? -1 : 1; // 判断为正方向or负方向
  1582. // double velocity;
  1583. // std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1584. // switch (cmd.operation_type()) {
  1585. // case 1: // 旋转
  1586. // velocity = 2.0 * M_PI / 180.0 * symbol;
  1587. // SendMoveCmd(move_mode_, eRotation, 0, velocity);
  1588. // actionType_ = eRotation;
  1589. // printf(" ManualOperation: %d | input angular_v: %f, down: %f\n",
  1590. // cmd.operation_type(), timedA_.Get(), velocity);
  1591. // break;
  1592. // case 2: // X平移
  1593. // velocity = 1.0 * symbol;
  1594. // SendMoveCmd(move_mode_, eVertical, velocity, 0);
  1595. // actionType_ = eVertical;
  1596. // printf(" ManualOperation: %d | input line_v : %f, down: %f\n",
  1597. // cmd.operation_type(), timedV_.Get(), velocity);
  1598. // break;
  1599. // case 3: // Y平移
  1600. // velocity = 1.0 * symbol;
  1601. // SendMoveCmd(move_mode_, eHorizontal, velocity, 0);
  1602. // actionType_ = eHorizontal;
  1603. // printf(" ManualOperation: %d | input line_v: %f, down: %f\n",
  1604. // cmd.operation_type(), timedV_.Get(), velocity);
  1605. // break;
  1606. // default:
  1607. // break;
  1608. // }
  1609. //
  1610. // actionType_ = eReady;
  1611. // response.set_ret(-3);
  1612. // response.set_info("ManualOperation: %d, canceled!!!", cmd.operation_type());
  1613. // printf("ManualOperation: %d | canceled!!!\n", cmd.operation_type());
  1614. // running_ = false;
  1615. }