navigation.cpp 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485
  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 (IsMasterAGV()) {
  120. if (msg.toProtoMessage(speed)) {
  121. ResetStatu(speed.v(), speed.w());
  122. ResetClamp((ClampStatu) speed.clamp());
  123. // ResetOtherClamp((ClampStatu) speed.clamp_other());
  124. ResetLifter((LifterStatus) speed.lifter());
  125. // ResetOtherLifter((LifterStatus) speed.lifter_other());
  126. //printf(" clamp:%d other:%d\n",speed.clamp(),speed.clamp_other());
  127. }
  128. } else {
  129. if (msg.toProtoMessage(speed)) {
  130. ResetStatu(speed.v(), speed.w());
  131. ResetClamp((ClampStatu) speed.clamp());
  132. ResetLifter((LifterStatus) speed.lifter());
  133. }
  134. }
  135. ResetDoor(speed.door());
  136. std::vector<int32_t> vecStatus;
  137. for (int i = 0; i < speed.zcb_size(); ++i) {
  138. vecStatus.push_back(speed.zcb(i));
  139. }
  140. ResetCarrier(vecStatus);
  141. }
  142. void Navigation::RobotSpeedCallback(const MqttMsg &msg, void *context) {
  143. Navigation *navigator = (Navigation *) context;
  144. navigator->HandleAgvStatu(msg);
  145. }
  146. void Navigation::pubStatuThreadFuc(void *p) {
  147. Navigation *navogator = (Navigation *) p;
  148. if (navogator) {
  149. while (navogator->exit_ == false) {
  150. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  151. NavMessage::NavStatu statu;
  152. statu.set_main_agv(false);
  153. navogator->publish_statu(statu);
  154. }
  155. }
  156. }
  157. void Navigation::publish_statu(NavMessage::NavStatu &statu) {
  158. if (timedPose_.timeout() == false) {
  159. NavMessage::LidarOdomStatu odom;
  160. odom.set_x(timedPose_.Get().x());
  161. odom.set_y(timedPose_.Get().y());
  162. odom.set_theta(timedPose_.Get().theta());
  163. if (timedV_.timeout() == false)
  164. odom.set_v(timedV_.Get());
  165. if (timedA_.timeout() == false)
  166. odom.set_vth(timedA_.Get());
  167. statu.mutable_odom()->CopyFrom(odom);
  168. }
  169. statu.set_in_space(isInSpace_);
  170. if (isInSpace_) statu.set_space_id(space_id_);
  171. //发布nav状态
  172. statu.set_statu(actionType_); //
  173. statu.set_move_mode(move_mode_);
  174. if (running_) {
  175. statu.set_key(global_navCmd_.key());
  176. }
  177. //发布MPC信息
  178. //发布mpc 预选点
  179. if (selected_traj_.timeout() == false) {
  180. for (int i = 0; i < selected_traj_.Get().size(); ++i) {
  181. Pose2d pt = selected_traj_.Get()[i];
  182. NavMessage::Pose2d *pose = statu.mutable_selected_traj()->add_poses();
  183. pose->set_x(pt.x());
  184. pose->set_y(pt.y());
  185. pose->set_theta(pt.theta());
  186. }
  187. }
  188. //发布 mpc 预测点
  189. if (predict_traj_.timeout() == false) {
  190. for (int i = 0; i < predict_traj_.Get().size(); ++i) {
  191. Pose2d pt = predict_traj_.Get()[i];
  192. NavMessage::Pose2d *pose = statu.mutable_predict_traj()->add_poses();
  193. pose->set_x(pt.x());
  194. pose->set_y(pt.y());
  195. pose->set_theta(pt.theta());
  196. }
  197. }
  198. // std::cout<<"nav statu:"<<statu.DebugString()<<std::endl;
  199. MqttMsg msg;
  200. msg.fromProtoMessage(statu);
  201. if (terminator_)
  202. terminator_->Publish(parameter_.terminal_emqx().pubnavstatutopic(), msg);
  203. //发布位姿 ------robot状态--------------------------
  204. NavMessage::RobotStatu robot;
  205. if (CreateRobotStatuMsg(robot)) {
  206. if (terminator_) {
  207. MqttMsg msg;
  208. msg.fromProtoMessage(robot);
  209. terminator_->Publish(parameter_.terminal_emqx().pubstatutopic(), msg);
  210. }
  211. }
  212. }
  213. bool Navigation::CreateRobotStatuMsg(NavMessage::RobotStatu &robotStatu) {
  214. //printf(" %d %d %d \n",timedPose_.timeout(),timedV_.timeout(),timedA_.timeout());
  215. if (timedPose_.timeout() == false) {
  216. Pose2d pose = timedPose_.Get();
  217. robotStatu.set_x(pose.x());
  218. robotStatu.set_y(pose.y());
  219. robotStatu.set_theta(pose.theta());
  220. if ((timedV_.timeout() == false && timedA_.timeout() == false)) {
  221. NavMessage::AgvStatu plc;
  222. plc.set_v(timedV_.Get());
  223. plc.set_w(timedA_.Get());
  224. plc.set_clamp(timed_clamp_.Get());
  225. plc.set_lifter(timed_lifter_.Get());
  226. robotStatu.mutable_agvstatu()->CopyFrom(plc);
  227. }
  228. return true;
  229. }
  230. return false;
  231. }
  232. void Navigation::ResetStatu(double v, double a) {
  233. timedV_.reset(v, 0.5);
  234. timedA_.reset(a, 0.5);
  235. }
  236. void Navigation::ResetClamp(ClampStatu statu) {
  237. timed_clamp_.reset(statu, 1);
  238. }
  239. void Navigation::ResetLifter(LifterStatus status) {
  240. timed_lifter_.reset(status, 1);
  241. }
  242. void Navigation::ResetPose(const Pose2d &pose) {
  243. timedPose_.reset(pose, 1.2);
  244. if (pose.theta() > 0) {
  245. if (parameter_.main_agv()) {
  246. isFront_.reset(true, 1.0);
  247. } else {
  248. isFront_.reset(false, 1.0);
  249. }
  250. } else {
  251. if (parameter_.main_agv()) {
  252. isFront_.reset(false, 1.0);
  253. } else {
  254. isFront_.reset(true, 1.0);
  255. }
  256. }
  257. }
  258. void Navigation::Cancel(const NavMessage::NavCmd &cmd, NavMessage::NavResponse &response) {
  259. cancel_ = true;
  260. response.set_ret(0);
  261. }
  262. bool Navigation::Stop() {
  263. if (monitor_) {
  264. monitor_->stop();
  265. while (cancel_ == false) {
  266. if (timedV_.timeout() == false && timedA_.timeout() == false) {
  267. if (fabs(timedV_.Get()) < 1e-2 && fabs(timedA_.Get()) < 1e-3)
  268. return true;
  269. else
  270. monitor_->stop();
  271. printf("Stoped wait V/A ==0(1e-4,1e-4),V:%f,A:%f\n", fabs(timedV_.Get()), fabs(timedA_.Get()));
  272. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  273. } else {
  274. printf("Stop failed V/A timeout\n");
  275. return false;
  276. }
  277. }
  278. }
  279. printf("stoped ret false.\n");
  280. return false;
  281. }
  282. bool Navigation::SlowlyStop() {
  283. double acc = 3.0;
  284. double dt = 0.1;
  285. while (cancel_ == false) {
  286. if (timedV_.timeout() == false) {
  287. double v = timedV_.Get();
  288. if (fabs(v < 1e-2 && fabs(timedA_.Get()) < 1e-3))
  289. return true;
  290. if (v > 0) {
  291. double new_v = v - acc * dt;
  292. new_v = new_v > 0 ? new_v : 0;
  293. SendMoveCmd(move_mode_, actionType_, new_v, 0);
  294. } else {
  295. double new_v = v + acc * dt;
  296. new_v = new_v < 0 ? new_v : 0;
  297. SendMoveCmd(move_mode_, actionType_, new_v, 0);
  298. }
  299. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  300. } else {
  301. printf("Stop failed V/A timeout\n");
  302. return false;
  303. }
  304. }
  305. printf("stoped ret false.\n");
  306. return false;
  307. }
  308. Navigation::Navigation() {
  309. is_master_AGV = false;
  310. wheelBase_ = 0;
  311. isInSpace_ = false; //是否在车位或者正在进入车位
  312. RWheel_position_ = eUnknow;
  313. move_mode_ = eSingle;
  314. monitor_ = nullptr;
  315. terminator_ = nullptr;
  316. obs_h_ = 4.0;
  317. obs_w_ = 2.0;
  318. timedBrotherPose_.reset(Pose2d(-100, 0, 0), 0.5);
  319. LoadSpaceNo2CarrierNo();
  320. }
  321. void Navigation::BrotherAgvStatuCallback(const MqttMsg &msg, void *context) {
  322. Navigation *navigator = (Navigation *) context;
  323. NavMessage::NavStatu brother_statu;
  324. if (msg.toProtoMessage(brother_statu) == false) {
  325. std::cout << " msg transform to AGVStatu failed,msg:" << msg.data() << std::endl;
  326. return;
  327. }
  328. //std::cout<<brother_nav.DebugString()<<std::endl<<std::endl;
  329. if (brother_statu.has_odom()) {
  330. NavMessage::LidarOdomStatu odom = brother_statu.odom();
  331. Pose2d pose(odom.x(), odom.y(), odom.theta());
  332. navigator->timedBrotherPose_.reset(pose, 1);
  333. navigator->timedBrotherV_.reset(odom.v(), 1);
  334. navigator->timedBrotherA_.reset(odom.vth(), 1);
  335. navigator->timedBrotherNavStatu_.reset(brother_statu, 0.1);
  336. }
  337. }
  338. //未使用
  339. /*
  340. bool Navigation::RotateReferToTarget(const Pose2d &target, stLimit limit_rotate, bool anyDirect) {
  341. while (cancel_ == false) {
  342. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  343. if (timedPose_.timeout()) {
  344. printf(" RotateBytarget failed pose timeout\n");
  345. return false;
  346. }
  347. if (timedA_.timeout()) {
  348. printf(" RotateBytarget failed wmg timeout\n");
  349. return false;
  350. }
  351. Pose2d targetInPose = Pose2d::relativePose(target, timedPose_.Get());
  352. float yawDiff = Pose2d::vector2yaw(targetInPose.x(), targetInPose.y());
  353. float minYawdiff = yawDiff;
  354. if (anyDirect) {
  355. Pose2d p0 = timedPose_.Get();
  356. float yawdiff[4] = {0};
  357. yawdiff[0] = yawDiff;
  358. Pose2d relativePose;
  359. relativePose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, M_PI / 2));
  360. yawdiff[1] = Pose2d::vector2yaw(relativePose.x(), relativePose.y()); ////使用减法,保证角度在【-pi pi】
  361. relativePose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, M_PI));
  362. yawdiff[2] = Pose2d::vector2yaw(relativePose.x(), relativePose.y());
  363. relativePose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, 3 * M_PI / 2));
  364. yawdiff[3] = Pose2d::vector2yaw(relativePose.x(), relativePose.y());
  365. for (int i = 1; i < 4; ++i) {
  366. if (fabs(yawdiff[i]) < fabs(minYawdiff)) {
  367. minYawdiff = yawdiff[i];
  368. targetInPose = Pose2d::relativePose(target, p0 - Pose2d(0, 0, i * M_PI / 2.0));
  369. }
  370. }
  371. }
  372. //std::cout<<" Rotate refer to target:"<<target<<",targetInPose:"
  373. //<<targetInPose<<",anyDirect:"<<anyDirect<<std::endl;
  374. //以当前点为原点,想方向经过目标点的二次曲线曲率>0.25,则需要调整 y=a x*x
  375. float cuv = compute_cuv(targetInPose);
  376. float dt = 0.1;
  377. float acc_angular = 15 * M_PI / 180.0;
  378. if (cuv > 2 * M_PI / 180.0) {
  379. double theta = limit_gause(minYawdiff, limit_rotate.min, limit_rotate.max);
  380. double angular = next_speed(timedA_.Get(), theta, acc_angular, dt);
  381. double limit_angular = limit(angular, limit_rotate.min, limit_rotate.max);
  382. SendMoveCmd(move_mode_, eRotation, 0, limit_angular);
  383. actionType_ = eRotation;
  384. printf(" Rotate | input angular:%f,next angular:%f,down:%f diff:%f anyDirect:%d\n",
  385. timedA_.Get(), angular, limit_angular, minYawdiff, anyDirect);
  386. continue;
  387. } else {
  388. if (fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  389. printf(" Rotate refer target completed,cuv:%f\n", cuv);
  390. return true;
  391. }
  392. continue;
  393. }
  394. }
  395. return false;
  396. }
  397. */
  398. bool Navigation::AdjustReferToTarget(const Pose2d &target, stLimit limit_rotate, int directions) {
  399. std::cout << "Adjust to : " << target << std::endl;
  400. if (inited_ == false) {
  401. printf(" MPC_rotate has not inited\n");
  402. return false;
  403. }
  404. if (PoseTimeout()) {
  405. printf(" MPC_rotate Error:Pose is timeout \n");
  406. return false;
  407. }
  408. Pose2d current = timedPose_.Get();
  409. NavMessage::PathNode yawTarget;
  410. yawTarget.set_x(current.x() + 100.);
  411. yawTarget.set_y(current.y());
  412. std::cout << "Adjust RotateRefer : " << Pose2d(yawTarget.x(), yawTarget.y(), 0) << std::endl;
  413. RotateReferToTarget(yawTarget, limit_rotate, directions);
  414. current = timedPose_.Get();
  415. Pose2d diff = target - current;
  416. Pose2d newTarget;
  417. NavMessage::PathNode node;
  418. if (fabs(diff.x()) > fabs(diff.y())) {
  419. newTarget = Pose2d(current.x(), target.y(), current.theta());
  420. node.set_theta(M_PI / 2.0);
  421. } else {
  422. newTarget = Pose2d(target.x(), current.y(), current.theta());
  423. node.set_theta(0);
  424. }
  425. node.set_x(newTarget.x());
  426. node.set_y(newTarget.y());
  427. node.set_l(0.03);
  428. node.set_w(0.2);
  429. stLimit limitV = {parameter_.inoutvlimit().min(), parameter_.inoutvlimit().max()};
  430. stLimit limitW = {0.03, 0.1};
  431. std::cout << " Adjust MoveTarget:" << Pose2d(node.x(), node.y(), node.theta()) << std::endl;
  432. return MoveToTarget(node, limitV, limitW, true, true);
  433. }
  434. Navigation::MpcResult Navigation::RotateReferToTarget(NavMessage::PathNode node, stLimit limit_rotate, int directions) {
  435. if (inited_ == false) {
  436. printf(" MPC_rotate has not inited\n");
  437. return eMpcFailed;
  438. }
  439. if (PoseTimeout()) {
  440. printf(" MPC_rotate Error:Pose is timeout \n");
  441. return eMpcFailed;
  442. }
  443. printf(" exec MPC_rotate autoDirect:%d\n", directions);
  444. while (cancel_ == false) {
  445. std::this_thread::sleep_for(std::chrono::milliseconds(30));
  446. if (pause_ == true) {
  447. //发送暂停消息
  448. continue;
  449. }
  450. if (PoseTimeout()) {
  451. printf(" MPC_rotate Error:Pose is timeout \n");
  452. return eMpcFailed;
  453. }
  454. if (timedA_.timeout()) {
  455. printf(" MPC_rotate Error:v/a is timeout \n");
  456. return eMpcFailed;
  457. }
  458. Pose2d current = timedPose_.Get();
  459. Pose2d target(node.x(), node.y(), node.theta());
  460. Pose2d targetInPose = Pose2d::relativePose(target, current);
  461. // 需要旋转的角度
  462. float target_yaw_diff = Pose2d::vector2yaw(targetInPose.x(), targetInPose.y());
  463. // 自由方向
  464. if (directions) {
  465. std::vector<double> yaw_diffs;
  466. if (directions & Direction::eForward) {
  467. yaw_diffs.push_back(target_yaw_diff);
  468. }
  469. if (directions & Direction::eBackward) {
  470. Pose2d relative_pose = Pose2d::relativePose(targetInPose, Pose2d(0, 0, M_PI));
  471. yaw_diffs.push_back(Pose2d::vector2yaw(relative_pose.x(), relative_pose.y()));
  472. }
  473. if (directions & Direction::eLeft) {
  474. Pose2d relative_pose = Pose2d::relativePose(targetInPose, Pose2d(0, 0, 1.0 / 2 * M_PI));
  475. yaw_diffs.push_back(Pose2d::vector2yaw(relative_pose.x(), relative_pose.y()));
  476. }
  477. if (directions & Direction::eRight) {
  478. Pose2d relative_pose = Pose2d::relativePose(targetInPose, Pose2d(0, 0, 3.0 / 2 * M_PI));
  479. yaw_diffs.push_back(Pose2d::vector2yaw(relative_pose.x(), relative_pose.y()));
  480. }
  481. for (auto i = 0; i < yaw_diffs.size(); ++i) {
  482. if (fabs(yaw_diffs[i]) < fabs(target_yaw_diff))
  483. target_yaw_diff = yaw_diffs[i];
  484. }
  485. // std::cout << std::endl;
  486. // std::cout << std::endl << " min_diff: " << current_to_target.theta() << std::endl;
  487. }
  488. //一次变速
  489. std::vector<double> out;
  490. bool ret;
  491. TimerRecord::Execute([&, this]() {
  492. ret = Rotation_mpc_once(Pose2d(0, 0, target_yaw_diff), limit_rotate, out);
  493. }, "Rotation_mpc_once");
  494. if (ret == false) {
  495. Stop();
  496. return eMpcFailed;
  497. }
  498. //下发速度
  499. if (fabs(target_yaw_diff) < 0.2 * M_PI / 180.0 && fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  500. printf(" MPC_rotate | refer target completed\\n,cuv:%f\n", target_yaw_diff);
  501. Stop();
  502. return eMpcSuccess;
  503. } else {
  504. const int down_count = 3;
  505. double v[down_count] = {0, 0, 0};
  506. double w[down_count] = {out[0], out[1], out[2]};
  507. SendMoveCmd(0, move_mode_, eRotation, v, w);
  508. actionType_ = eRotation;
  509. double input_w = timedA_.Get();
  510. /*
  511. for (int i = 0; i < down_count; ++i) {
  512. printf(" MPC_rotate |P[%d], input anguar:%f, down:%f(%f), diff:%f anyDirect:%d\n",
  513. i, input_w, w[i], w[i] / M_PI * 180, target_yaw_diff, directions);
  514. }*/
  515. }
  516. continue;
  517. }
  518. return eMpcFailed;
  519. }
  520. bool Navigation::MoveToTarget(NavMessage::PathNode node, Navigation::stLimit limit_v, Navigation::stLimit limit_w,
  521. bool anyDirect, bool enable_rotate, int clampLifterAction) {
  522. if (IsArrived(node)) {
  523. return true;
  524. }
  525. bool already_in_mpc = false;
  526. while (cancel_ == false) {
  527. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  528. if (PoseTimeout()) {
  529. printf(" navigation Error:Pose is timeout \n");
  530. break;
  531. }
  532. Pose2d current = timedPose_.Get();
  533. if (IsArrived(node)) {
  534. break;
  535. }
  536. //两个方向都无法到达目标点,旋转 朝向目标点
  537. bool x_enable = PossibleToTarget(node, false);
  538. bool y_enable = PossibleToTarget(node, true);
  539. bool enableTotarget = x_enable || y_enable;
  540. if (anyDirect == false) {
  541. enableTotarget = x_enable;
  542. }
  543. //巡线无法到达目标点
  544. Pose2d target(node.x(), node.y(), 0);
  545. Pose2d targetInCurrent = Pose2d::relativePose(target, current);
  546. if (GetCurrentAction().type() != 1 && GetCurrentAction().type() != 2) {
  547. if (enableTotarget == false) {
  548. int directions = Direction::eForward;
  549. if (anyDirect)
  550. directions = Direction::eForward | Direction::eRight | Direction::eLeft | Direction::eBackward;
  551. bool adjustRet = AdjustReferToTarget(target, limit_w, directions);
  552. if (adjustRet == false)
  553. return false;
  554. }
  555. }
  556. already_in_mpc = true;
  557. MpcResult ret = MpcToTarget(node, limit_v, anyDirect, clampLifterAction);
  558. if (ret == eMpcSuccess) {
  559. printf(" MPC to target:%f %f l:%f,w:%f theta:%f completed\n",
  560. node.x(), node.y(), node.l(), node.w(), node.theta());
  561. break;
  562. } else if (ret == eImpossibleToTarget) {
  563. printf(" MPC to target:%f %f l:%f,w:%f theta:%f impossible ,retry ...\n",
  564. node.x(), node.y(), node.l(), node.w(), node.theta());
  565. } else {
  566. }
  567. }
  568. if (cancel_) {
  569. return false;
  570. }
  571. return true;
  572. }
  573. bool Navigation::execute_nodes(NavMessage::NewAction action) {
  574. if (action.type() == 3 || action.type() == 4) //最优动作导航 or 导航中保证朝向严格一致
  575. {
  576. if (!parameter_.has_nodeangularlimit() || !parameter_.has_nodevelocitylimit() || action.pathnodes_size() == 0) {
  577. std::cout << "execute pathNodes failed ,Action invalid:" << action.DebugString() << std::endl;
  578. return false;
  579. }
  580. bool anyDirect = (action.type() == 3);
  581. //速度限制
  582. stLimit wmg_limit = {parameter_.nodeangularlimit().min(), parameter_.nodeangularlimit().max()};
  583. stLimit mpc_velocity = {parameter_.nodevelocitylimit().min(), parameter_.nodevelocitylimit().max()};
  584. /////////////////////////////////////////
  585. int clampLifterAction = 0;
  586. if (move_mode_ == eSingle) {
  587. clampLifterAction |= eByteClampHalfOpen;
  588. }
  589. ////////////////////////////////////////////////////////////
  590. for (int i = 0; i < action.pathnodes_size(); ++i) {
  591. NavMessage::PathNode node = action.pathnodes(i);
  592. if (i < action.pathnodes_size() - 1) {
  593. NavMessage::PathNode next = action.pathnodes(i + 1);
  594. Pose2d vec(next.x() - node.x(), next.y() - node.y(), 0);
  595. node.set_theta(Pose2d::vector2yaw(vec.x(), vec.y()) + M_PI / 2.0);
  596. node.set_l(0.03);
  597. node.set_w(0.25);
  598. } else {
  599. NavMessage::PathNode befor = action.pathnodes(i - 1);
  600. Pose2d vec(node.x() - befor.x(), node.y() - befor.y(), 0);
  601. node.set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  602. node.set_l(0.02);
  603. node.set_w(0.25);
  604. }
  605. int directions = Direction::eForward;
  606. if (anyDirect)
  607. directions = Direction::eForward | Direction::eBackward |
  608. Direction::eLeft | Direction::eRight;
  609. /*if(i>=1 && move_mode_==eSingle){
  610. //马路Y巡航,需要判断等待
  611. Pose2d targetInAGV = Pose2d::relativePose(Pose2d(node.x(), node.y(), 0), timedPose_.Get());
  612. double distance=Pose2d::distance(Pose2d(0,0,0),targetInAGV);
  613. double thresh=0.5*obs_w_*distance;
  614. while(cancel_==false) {
  615. usleep(1000*500);
  616. if(timedPose_.timeout() || timedBrotherPose_.timeout()){
  617. return false;
  618. }
  619. Pose2d otherInAGV = Pose2d::relativePose(timedBrotherPose_.Get(), timedPose_.Get());
  620. double dot = targetInAGV.x() * otherInAGV.x() + targetInAGV.y() * otherInAGV.y();
  621. if (dot > thresh) { //目标点与other在当前车的同一朝向上,需要等待other点到位
  622. printf(" need to wait other,dot:%f,thresh:%f\n",dot,thresh);
  623. if(fabs(otherInAGV.x())>obs_w_*3 && fabs(otherInAGV.y())<0.2){
  624. std::cout<<"Wait other agv completed otherInCurrent:"<<otherInAGV<<std::endl;
  625. break;
  626. }else{
  627. std::cout<<"Wait other agv ,otherInCurrent:"<<otherInAGV<<std::endl;
  628. }
  629. }else{
  630. printf(" not need wait other,dot:%f,thresh:%f\n",dot,thresh);
  631. break;
  632. }
  633. }
  634. }*/
  635. //提升机构提前动作
  636. if (GetRemainActionsCount() > 1){
  637. NavMessage::NewAction last_action = GetLastAction();
  638. if (IsUperSpace(last_action.spacenode())){
  639. if ((i+1) == action.pathnodes_size()){
  640. clampLifterAction |= eByteLifterUp;
  641. }
  642. } else{
  643. clampLifterAction |= eByteLifterDown;
  644. }
  645. }
  646. if (MoveToTarget(node, mpc_velocity, wmg_limit, anyDirect, true, clampLifterAction) == false)
  647. return false;
  648. else
  649. isInSpace_ = false;
  650. }
  651. if (cancel_ == true) {
  652. return false;
  653. }
  654. return true;
  655. }
  656. printf("execute PathNode failed ,action type is not 3/4 :%d\n", action.type());
  657. return false;
  658. }
  659. Navigation::MpcResult Navigation::DoubleOutSpaceCorrectTheta() {
  660. if (move_mode_ != eDouble)
  661. return eMpcSuccess;
  662. int clampLifterAction = 0;
  663. if (move_mode_ == eDouble) {
  664. clampLifterAction |= eLifterDown;
  665. }
  666. Pose2d init = timedPose_.Get();
  667. double diff1 = fabs(M_PI / 2.0 - init.theta());
  668. double diff2 = fabs(-M_PI / 2.0 - init.theta());
  669. double target = diff1 < diff2 ? M_PI / 2.0 : -M_PI / 2.0;
  670. stLimit limit_rotate = {3 * M_PI / 180.0, 15 * M_PI / 180.0};
  671. while (cancel_ == false) {
  672. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  673. Pose2d current = timedPose_.Get();
  674. double yawDiff = (target - current.theta());
  675. //一次变速
  676. std::vector<double> out;
  677. bool ret;
  678. TimerRecord::Execute([&, this]() {
  679. ret = Rotation_mpc_once(Pose2d(0, 0, yawDiff), limit_rotate, out);
  680. }, "Rotation_mpc_once");
  681. if (ret == false) {
  682. Stop();
  683. return eMpcFailed;
  684. }
  685. //下发速度
  686. if (fabs(yawDiff) < 0.2 * M_PI / 180.0 && fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  687. printf(" DoubleOutSpaceCorrectTheta refer target completed\\n,cuv:%f\n", yawDiff);
  688. Stop();
  689. if (WaitClampLifterStatu(clampLifterAction) == false) {
  690. return eMpcFailed;
  691. }
  692. return eMpcSuccess;
  693. } else {
  694. const int down_count = 3;
  695. double v[down_count] = {0, 0, 0};
  696. double w[down_count] = {out[0], out[1], out[2]};
  697. SendMoveCmd(clampLifterAction, move_mode_, eRotation, v, w);
  698. actionType_ = eRotation;
  699. printf(" DoubleOutSpaceCorrectTheta | input anguar:%f, down:%f(%f), diff:%f anyDirect:false\n",
  700. timedA_.Get(), out[0], out[0] / M_PI * 180, yawDiff);
  701. }
  702. continue;
  703. }
  704. return eMpcFailed;
  705. }
  706. Navigation::MpcResult Navigation::RotateAfterOutExport() {
  707. printf("RotateAfterOutExport...\n");
  708. if (move_mode_ != eDouble)
  709. return eMpcSuccess;
  710. Pose2d init = timedPose_.Get();
  711. double diff1 = fabs(M_PI / 2.0 - init.theta());
  712. double diff2 = fabs(-M_PI / 2.0 - init.theta());
  713. double target = diff1 > diff2 ? M_PI / 2.0 : -M_PI / 2.0;
  714. stLimit limit_rotate = {3 * M_PI / 180.0, 15 * M_PI / 180.0};
  715. while (cancel_ == false) {
  716. std::this_thread::sleep_for(std::chrono::milliseconds(80));
  717. Pose2d current = timedPose_.Get();
  718. double yawDiff = (target - current.theta());
  719. //一次变速
  720. std::vector<double> out;
  721. bool ret;
  722. TimerRecord::Execute([&, this]() {
  723. ret = Rotation_mpc_once(Pose2d(0, 0, yawDiff), limit_rotate, out);
  724. }, "Rotation_mpc_once");
  725. if (ret == false) {
  726. Stop();
  727. return eMpcFailed;
  728. }
  729. //下发速度
  730. if (fabs(yawDiff) < 0.5 * M_PI / 180.0 && fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  731. printf(" RotateBeforeEnterSpace refer target completed\\n,cuv:%f\n", yawDiff);
  732. Stop();
  733. return eMpcSuccess;
  734. } else {
  735. const int down_count = 3;
  736. double v[down_count] = {0, 0, 0};
  737. double w[down_count] = {out[0], out[1], out[2]};
  738. SendMoveCmd(0, move_mode_, eRotation, v, w);
  739. actionType_ = eRotation;
  740. // printf(" RotateBeforeEnterSpace | input anguar:%f, down:%f(%f), diff:%f anyDirect:false\n",
  741. // timedA_.Get(), out[0], out[0] / M_PI * 180, yawDiff);
  742. }
  743. continue;
  744. }
  745. return eMpcFailed;
  746. }
  747. Navigation::MpcResult Navigation::RotateBeforeIntoExport() {
  748. if (move_mode_ != eDouble)
  749. return eMpcSuccess;
  750. Pose2d init = timedPose_.Get();
  751. double diff1 = fabs(M_PI / 2.0 - init.theta());
  752. double diff2 = fabs(-M_PI / 2.0 - init.theta());
  753. double target = diff1 > diff2 ? M_PI / 2.0 : -M_PI / 2.0;
  754. stLimit limit_rotate = {3 * M_PI / 180.0, 15 * M_PI / 180.0};
  755. while (cancel_ == false) {
  756. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  757. Pose2d current = timedPose_.Get();
  758. double yawDiff = (target - current.theta());
  759. //一次变速
  760. std::vector<double> out;
  761. bool ret;
  762. TimerRecord::Execute([&, this]() {
  763. ret = Rotation_mpc_once(Pose2d(0, 0, yawDiff), limit_rotate, out);
  764. }, "Rotation_mpc_once");
  765. if (ret == false) {
  766. Stop();
  767. return eMpcFailed;
  768. }
  769. //下发速度
  770. if (fabs(yawDiff) < 0.5 * M_PI / 180.0 && fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  771. printf(" RotateBeforeEnterSpace refer target completed\\n,cuv:%f\n", yawDiff);
  772. Stop();
  773. return eMpcSuccess;
  774. } else {
  775. const int down_count = 3;
  776. double v[down_count] = {0, 0, 0};
  777. double w[down_count] = {out[0], out[1], out[2]};
  778. SendMoveCmd(0, move_mode_, eRotation, v, w);
  779. actionType_ = eRotation;
  780. // printf(" RotateBeforeEnterSpace | input anguar:%f, down:%f(%f), diff:%f anyDirect:false\n",
  781. // timedA_.Get(), out[0], out[0] / M_PI * 180, yawDiff);
  782. }
  783. continue;
  784. }
  785. return eMpcFailed;
  786. }
  787. Navigation::MpcResult
  788. Navigation::RotateBeforeEnterSpace(NavMessage::PathNode space, double wheelbase,
  789. NavMessage::PathNode &target, int clampLifterAction) {
  790. // if (timedBrotherNavStatu_.timeout() || timedPose_.timeout()) {
  791. if (timedPose_.timeout()) {
  792. printf(" rotate failed : timedBrotherNavStatu_ or pose timeout\n");
  793. return eMpcFailed;
  794. }
  795. NavMessage::NavStatu brother = timedBrotherNavStatu_.Get();
  796. stLimit limit_rotate = {2 * M_PI / 180.0, 15 * M_PI / 180.0};
  797. double acc_angular = 20 * M_PI / 180.0;
  798. double dt = 0.1;
  799. Pose2d current = timedPose_.Get();
  800. double x = space.x();
  801. double y = space.y();
  802. Pose2d vec(x - current.x(), y - current.y(), 0);
  803. double vecTheta = Pose2d::vector2yaw(vec.x(), vec.y());
  804. bool isFront = isFront_.Get();
  805. printf(" front__:%d theta:%f\n", isFront, vecTheta);
  806. if (vecTheta < 0.)
  807. isFront = !isFront;
  808. //如果是后车,计算目标点(车位点-轴距)
  809. if (isFront == false) {
  810. printf("后车 RotateBeforeEnterSpace | , __LINE__ = %d\n", __LINE__);
  811. if (move_mode_ == eSingle) {
  812. x -= wheelbase * cos(vecTheta);
  813. y -= wheelbase * sin(vecTheta);
  814. printf("确定车位点:eSingle\n");
  815. }
  816. } else { //当后车先到,倒车入库
  817. printf("前车RotateBeforeEnterSpace | __LINE__ = %d\n", __LINE__);
  818. //rotated.mutable_theta() = space.theta();
  819. //rotated = rotated.rotate(rotated.x(), rotated.y(), M_PI);
  820. }
  821. Pose2d spaceInCurrent = Pose2d::relativePose(Pose2d(space.x(), space.y(), 0), current);
  822. target.set_x(x);
  823. target.set_y(y);
  824. target.set_theta(current.theta());
  825. target.set_l(0.02);
  826. target.set_w(0.5);
  827. target.set_id(space.id());
  828. printf("RotateBeforeEnterSpace | target:[x:%f,y:%f,theta:%f]\n", x, y, target.theta());
  829. // //整车协调的时候,保持前后与车位一致即可
  830. // if (move_mode_ == eDouble) {
  831. // double yawDiff1 = (rotated - timedPose_.Get()).theta();
  832. // double yawDiff2 = (rotated + Pose2d(0, 0, M_PI) - timedPose_.Get()).theta();
  833. // if (fabs(yawDiff1) < fabs(yawDiff2)) {
  834. // rotated = rotated + Pose2d(0, 0, M_PI);
  835. // }
  836. // }
  837. while (cancel_ == false) {
  838. std::this_thread::sleep_for(std::chrono::milliseconds(30));
  839. Pose2d current_now = timedPose_.Get();
  840. if (spaceInCurrent.x() < 0.)
  841. current_now = current_now.rotate(current_now.x(), current_now.y(), M_PI);
  842. double yawDiff = vecTheta - current_now.theta();
  843. //一次变速
  844. std::vector<double> out;
  845. bool ret;
  846. TimerRecord::Execute([&, this]() {
  847. ret = Rotation_mpc_once(Pose2d(0, 0, yawDiff), limit_rotate, out);
  848. }, "Rotation_mpc_once");
  849. if (ret == false) {
  850. Stop();
  851. return eMpcFailed;
  852. }
  853. //下发速度
  854. if (fabs(yawDiff) < 0.5 * M_PI / 180.0 && fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  855. printf(" RotateBeforeEnterSpace refer target completed\\n,cuv:%f\n", yawDiff);
  856. Stop();
  857. return eMpcSuccess;
  858. } else {
  859. const int down_count = 3;
  860. double v[down_count] = {0, 0, 0};
  861. double w[down_count] = {out[0], out[1], out[2]};
  862. SendMoveCmd(clampLifterAction, move_mode_, eRotation, v, w);
  863. actionType_ = eRotation;
  864. // printf(" RotateBeforeEnterSpace | input anguar:%f, down:%f(%f), diff:%f anyDirect:false\n",
  865. // timedA_.Get(), out[0], out[0] / M_PI * 180, yawDiff);
  866. }
  867. continue;
  868. }
  869. return eMpcFailed;
  870. }
  871. bool Navigation::IsUperSpace(NavMessage::PathNode spaceNode) {
  872. int space_id = GetSpaceId(spaceNode);
  873. if (space_id < 0)
  874. return false;
  875. if (space_id > 99 && space_id < 1000) {
  876. return true;
  877. }
  878. return false;
  879. }
  880. int Navigation::GetSpaceId(NavMessage::PathNode spaceNode) {
  881. if (spaceNode.has_id() == false) {
  882. return -1;
  883. }
  884. std::string space_flag = "S_";
  885. if (spaceNode.id().find(space_flag) >= 0 && spaceNode.id().size() > 2) {
  886. std::string id = spaceNode.id().substr(space_flag.size(), spaceNode.id().length() - 1);
  887. int space_id = stoi(id);
  888. return space_id;
  889. }
  890. return -1;
  891. }
  892. bool Navigation::TargetIsEntrance(NavMessage::PathNode node) {
  893. int space_id = GetSpaceId(node);
  894. return space_id == 1101 || space_id == 1102;
  895. }
  896. bool Navigation::TargetIsExport(NavMessage::PathNode node) {
  897. int space_id = GetSpaceId(node);
  898. return space_id == 1101 || space_id == 1102;
  899. }
  900. bool Navigation::execute_InOut_space(NavMessage::NewAction action) {
  901. printf("execute_InOut_space\n");
  902. if (action.type() != 1 && action.type() != 2) {
  903. printf(" Inout_space failed : msg action type must ==1\n ");
  904. return false;
  905. }
  906. if (!parameter_.has_inoutvlimit() || !action.has_spacenode() ||
  907. !action.has_streetnode()) {
  908. std::cout << "execute enter_space failed ,Action miss some infos:" << action.DebugString() << std::endl;
  909. return false;
  910. }
  911. if (PoseTimeout() == true) {
  912. printf(" inout_space failed type:%d : current pose is timeout\n", action.type());
  913. return false;
  914. }
  915. stLimit limit_v = {parameter_.inoutvlimit().min(), parameter_.inoutvlimit().max()};
  916. stLimit limit_w = {2 * M_PI / 180.0, 20 * M_PI / 180.0};
  917. //入库,起点为streetNode
  918. if (action.type() == 1) {
  919. Pose2d vec(action.spacenode().x() - action.streetnode().x(),
  920. action.spacenode().y() - action.streetnode().y(),
  921. 0);
  922. action.mutable_streetnode()->set_l(0.02);
  923. action.mutable_streetnode()->set_w(0.2);
  924. action.mutable_streetnode()->set_theta(Pose2d::vector2yaw(vec.x(), vec.y()) + M_PI / 2.0);
  925. /*
  926. * 是否需要添加判断,距离较远才先运动到马路点=============================
  927. */
  928. int clampLifterAction = 0;
  929. printf("IsUperSpace\n");
  930. if (IsUperSpace(action.spacenode())) { //进载车板库前提升机构上升
  931. clampLifterAction |= eByteLifterUp;
  932. } else { //否则下降
  933. clampLifterAction |= eByteLifterDown;
  934. }
  935. if (move_mode_ == eSingle)
  936. clampLifterAction |= eByteClampHalfOpen;
  937. if (MoveToTarget(action.streetnode(), limit_v, limit_w, true, true, clampLifterAction) == false) {
  938. printf(" Enter space failed type:%d: MoveTo StreetNode failed\n", action.type());
  939. return false;
  940. }
  941. //移动到库位点, 禁止任意方向// 不允许巡线中停下旋转(当无法到达目标点时,返回false)
  942. printf("inout ----------------------------------------\n");
  943. //取车流程,送车到出口前旋转180
  944. // if (move_mode_ == eDouble && TargetIsExport(action.spacenode()) && GetSpaceId(action.spacenode()) != 1102) {
  945. // Pose2d current_pose = timedPose_.Get();
  946. // double current_theta = current_pose.theta();
  947. // if (RotateBeforeIntoExport() != eMpcSuccess) {
  948. // printf("Rotate before in entrance failed\n");
  949. // return false;
  950. // }
  951. // }
  952. //计算车位朝向
  953. action.mutable_spacenode()->set_theta(Pose2d::vector2yaw(vec.x(), vec.y()));
  954. //计算当前车是进入车位1点还是2点,
  955. NavMessage::PathNode new_target;
  956. bool retRotate = RotateBeforeEnterSpace(action.spacenode(), action.wheelbase(),
  957. new_target, clampLifterAction) == eMpcSuccess;
  958. if (retRotate == false) {
  959. return false;
  960. }
  961. //去出入口,等内门打开
  962. if (TargetIsExport(action.spacenode()) || TargetIsEntrance(action.spacenode())) {
  963. printf(" Wait Inside door opened.......\n");
  964. int port_id = GetPortIDBySpace(action.spacenode());
  965. if (WaitInsideDoorCompleted(port_id, eDoorOpened) == false) {
  966. return false;
  967. }
  968. printf(" Wait Inside door opened completed!!!\n");
  969. } else {
  970. //去车位点
  971. if (IsUperSpace(action.spacenode())) {
  972. printf(" Wait Carrier down.......\n");
  973. if (WaitCarrierCompleted(GetSpaceId(action.spacenode()), eCarrierDown) == false) {
  974. return false;
  975. }
  976. printf(" Wait Carrier down completed!!!\n");
  977. } else {
  978. if (!TargetIsExport(action.spacenode()) && !TargetIsEntrance(action.spacenode())) {
  979. printf(" Wait Carrier up.......\n");
  980. if (WaitCarrierCompleted(GetSpaceId(action.spacenode()), eCarrierUp) == false) {
  981. return false;
  982. }
  983. printf(" Wait Carrier up completed!!!\n");
  984. } else {
  985. printf(" Wait inside door open.......\n");
  986. if (WaitInsideDoorCompleted(GetSpaceId(action.spacenode()), eDoorOpened) == false)
  987. return false;
  988. printf("inside door opened\n");
  989. }
  990. }
  991. }
  992. if (IsUperSpace(action.spacenode())) {
  993. if (lifter_rise() == false) {
  994. return false;
  995. }
  996. }
  997. // 单车进库必须全打开(先半开,行走时全开)
  998. if (move_mode_ == eSingle) {
  999. if (clamp_half_open() == false) {
  1000. return false;
  1001. }
  1002. }
  1003. //入库
  1004. Pose2d rotated = timedPose_.Get();
  1005. double x = new_target.x();
  1006. double y = new_target.y();
  1007. Pose2d vecSpace(x - rotated.x(), y - rotated.y(), 0);
  1008. rotated.mutable_theta() = Pose2d::vector2yaw(vecSpace.x(), vecSpace.y());
  1009. bool isFront = isFront_.Get();
  1010. if (rotated.theta() < 0.)
  1011. isFront = !isFront;
  1012. // 后进车,且单车,且先进车已过后进车的目标点
  1013. Pose2d target(new_target.x(), new_target.y(), 0);
  1014. if (isFront == false && move_mode_ == eSingle) {
  1015. while (true) {
  1016. if (cancel_) {
  1017. return false;
  1018. }
  1019. if (move_mode_ == eDouble) {
  1020. clampLifterAction |= eLifterDown;
  1021. }
  1022. Pose2d current = timedPose_.Get();
  1023. Pose2d brother_pose = timedBrotherPose_.Get();
  1024. Pose2d vecCurent2T = current - target;
  1025. Pose2d vecBrother2T = brother_pose - target;
  1026. double dot = vecCurent2T.x() * vecBrother2T.x() + vecCurent2T.y() * vecBrother2T.y();
  1027. if (timedBrotherNavStatu_.Get().in_space() == true && dot < 0.) {
  1028. printf("先进车已经过后进车目标点,后进车停止等待 dot=%f\n", dot);
  1029. break;
  1030. }
  1031. printf(" 后车 等待 先车先入库。。。\n");
  1032. usleep(1000 * 500);
  1033. continue;
  1034. }
  1035. }
  1036. isInSpace_ = true;
  1037. printf("Enter space beg...\n");
  1038. clampLifterAction = 0;
  1039. if (IsUperSpace(action.spacenode())) { //进载车板库前提升机构上升
  1040. clampLifterAction |= eByteLifterUp;
  1041. } else { //否则下降
  1042. clampLifterAction |= eByteLifterDown;
  1043. }
  1044. printf(" clampLifter_statu1 :%d\n", clampLifterAction);
  1045. if (move_mode_ == eSingle)
  1046. clampLifterAction |= eByteClampFullyOpen; //////// 后续再改为全打开位
  1047. else
  1048. clampLifterAction |= eByteCLampClose;
  1049. printf(" clampLifter_statu2 :%d\n", clampLifterAction);
  1050. if (!TargetIsExport(action.spacenode()) && !TargetIsEntrance(action.spacenode()))
  1051. limit_w = {0.01, 0.05}; //进库纠偏角速度限制
  1052. else {
  1053. // 整车进 出入口速度调整为与巡线一致
  1054. if (move_mode_ == eDouble) {
  1055. limit_v = {parameter_.nodevelocitylimit().min(), parameter_.nodevelocitylimit().max()};
  1056. limit_w = {parameter_.nodeangularlimit().min(), parameter_.nodeangularlimit().max()};
  1057. }
  1058. }
  1059. bool retMove = MoveToTarget(new_target, limit_v, limit_w, true, false, clampLifterAction);
  1060. if (retMove == false) {
  1061. printf(" Enter space:%s failed. type:%d\n", action.spacenode().id().data(), action.type());
  1062. return false;
  1063. }
  1064. } else if (action.type() == 2) {
  1065. //出库,起点为spaceNode
  1066. // 计算当前位置,在车位点到马路点的连线方向上,与车位点的相对位姿
  1067. Pose2d vec(action.streetnode().x() - action.spacenode().x(),
  1068. action.streetnode().y() - action.spacenode().y(), 0);
  1069. float theta = Pose2d::vector2yaw(vec.x(), vec.y());
  1070. Pose2d space(action.spacenode().x(), action.spacenode().y(), theta);
  1071. Pose2d current = timedPose_.Get();
  1072. Pose2d diff = Pose2d::abs(Pose2d::relativePose(Pose2d(current.x(), current.y(), 0), space));
  1073. // 整车从出入口出库速度调整为与巡线一致
  1074. if (move_mode_ == eDouble && (TargetIsExport(action.spacenode()) || TargetIsExport(action.spacenode()))) {
  1075. limit_v = {parameter_.nodevelocitylimit().min(), parameter_.nodevelocitylimit().max()};
  1076. limit_w = {parameter_.nodeangularlimit().min(), parameter_.nodeangularlimit().max()};
  1077. }
  1078. if (fabs(diff.x()) < 0.15 || fabs(diff.y()) < 0.10) {
  1079. //出库,移动到马路点,允许自由方向,不允许中途旋转
  1080. action.mutable_streetnode()->set_theta(theta);
  1081. action.mutable_streetnode()->set_l(0.03);
  1082. action.mutable_streetnode()->set_w(0.2);
  1083. std::cout << " Out space target street node:" << space << std::endl;
  1084. if (MoveToTarget(action.streetnode(), limit_v, limit_w, true, false) == false) {
  1085. printf(" out space failed type:%d: MoveTo StreetNode failed\n", action.type());
  1086. return false;
  1087. }
  1088. } else {
  1089. std::cout << " Out space failed: current pose too far from space node:" << space << ",diff:" << diff
  1090. << std::endl;
  1091. return false;
  1092. }
  1093. isInSpace_ = false;
  1094. // 存车流程离开入口,掉头
  1095. if (GetSequenceType() == eSequencePark) {
  1096. if (move_mode_ == eDouble && TargetIsExport(action.spacenode()) && GetSpaceId(action.spacenode()) != 1102) {
  1097. Pose2d current_pose = timedPose_.Get();
  1098. double current_theta = current_pose.theta();
  1099. if (RotateAfterOutExport() != eMpcSuccess) {
  1100. printf("Rotate before in entrance failed\n");
  1101. return false;
  1102. }
  1103. }
  1104. }
  1105. //摆正
  1106. if (GetRemainActionsCount() > 1) {
  1107. if (DoubleOutSpaceCorrectTheta() != eMpcSuccess)
  1108. return false;
  1109. }
  1110. }
  1111. return true;
  1112. }
  1113. /* current_to_target: current_to_target.theta()为所需旋转的角度
  1114. * */
  1115. bool Navigation::Rotation_mpc_once(Pose2d current_to_target, Navigation::stLimit limit_wmg, std::vector<double> &out,
  1116. bool all_direct) {
  1117. if (PoseTimeout() == true) {
  1118. printf(" Rotation_mpc_once Error:Pose is timeout \n");
  1119. return false;
  1120. }
  1121. if (timedV_.timeout() == true || timedA_.timeout() == true) {
  1122. printf(" Rotation_mpc_once Error:V/A is timeout \n");
  1123. return false;
  1124. }
  1125. Pose2d pose = timedPose_.Get();
  1126. double line_velocity = timedV_.Get(); //从plc获取状态
  1127. double angular_velocity = timedA_.Get();
  1128. Eigen::VectorXd statu = Eigen::VectorXd::Zero(5);//agv状态
  1129. statu[0] = pose.x();
  1130. statu[1] = pose.y();
  1131. statu[2] = pose.theta();
  1132. statu[3] = line_velocity;
  1133. statu[4] = angular_velocity;
  1134. NavParameter::MPC_parameter mpc_parameter = parameter_.x_mpc_parameter();
  1135. double obs_w = 0.95;//0.85;
  1136. double obs_h = 1.55;//1.45;
  1137. MpcError ret = failed;
  1138. Pose2d brother = timedBrotherPose_.Get();
  1139. Pose2d brother_in_self = Pose2d::relativePose(brother, pose);
  1140. // std::cout<<" brother_in_self: "<<brother_in_self<<std::endl;
  1141. if (move_mode_ == eDouble) {
  1142. brother_in_self = Pose2d(pose.x() + 100, pose.y() + 100, 0);
  1143. }
  1144. RotateMPC MPC(brother_in_self, obs_w, obs_h, limit_wmg.min, limit_wmg.max);
  1145. RotateMPC::MPC_parameter parameter = {mpc_parameter.shortest_radius(), mpc_parameter.dt(),
  1146. mpc_parameter.acc_velocity(), mpc_parameter.acc_angular()};
  1147. ret = MPC.solve(current_to_target, statu, parameter, out);
  1148. if (ret == no_solution) {
  1149. printf(" Rotation_mpc solve no solution set v/w = 0\n");
  1150. out.clear();
  1151. out.push_back(0);
  1152. out.push_back(0);
  1153. out.push_back(0);
  1154. } else {
  1155. // double min_angular_velocity = 1.0 / 180 * M_PI;
  1156. double min_angular_velocity = 0.01;
  1157. const int down_count = 3;
  1158. for (int i = 0; i < down_count; ++i) {
  1159. if (fabs(out[i]) < min_angular_velocity) {
  1160. if (out[i] > 0)
  1161. out[i] = min_angular_velocity;
  1162. else if (out[i] < 0)
  1163. out[i] = -min_angular_velocity;
  1164. else {}
  1165. }
  1166. }
  1167. }
  1168. return ret == success || ret == no_solution;
  1169. }
  1170. bool Navigation::mpc_once(Trajectory traj, stLimit limit_v, std::vector<double> &out, int& mpc_result, bool directY) {
  1171. if (PoseTimeout() == true) {
  1172. printf(" MPC once Error:Pose is timeout \n");
  1173. return false;
  1174. }
  1175. if (timedV_.timeout() == true || timedA_.timeout() == true) {
  1176. printf(" MPC once Error:V/A is timeout \n");
  1177. return false;
  1178. }
  1179. if (traj.size() == 0) {
  1180. printf("traj size ==0\n");
  1181. return false;
  1182. }
  1183. Pose2d pose = timedPose_.Get();
  1184. double velocity = timedV_.Get(); //从plc获取状态
  1185. double angular = timedA_.Get();
  1186. // float diffYaw1=timedPose_.Get().m_diffYaw1;
  1187. // float diffYaw2=timedPose_.Get().m_diffYaw2;
  1188. Eigen::VectorXd statu = Eigen::VectorXd::Zero(5);//agv状态
  1189. statu[0] = pose.x();
  1190. statu[1] = pose.y();
  1191. statu[2] = pose.theta();
  1192. statu[3] = velocity;
  1193. statu[4] = angular;
  1194. Trajectory optimize_trajectory;
  1195. Trajectory selected_trajectory;
  1196. NavParameter::MPC_parameter mpc_parameter = parameter_.x_mpc_parameter();
  1197. double obs_w = obs_w_;// 0.95;//0.85;
  1198. double obs_h = obs_h_;// 1.55;//1.45;
  1199. if (directY == true) {
  1200. //将车身朝向旋转90°,车身朝向在(-pi,pi]
  1201. statu[2] += M_PI / 2;
  1202. if (statu[2] > M_PI)
  1203. statu[2] -= 2 * M_PI;
  1204. mpc_parameter = parameter_.y_mpc_parameter();
  1205. obs_w = obs_h_;// 0.95;//0.85;
  1206. obs_h = obs_w_;//1.55;//1.45;
  1207. }
  1208. Pose2d brother = timedBrotherPose_.Get();
  1209. Pose2d relative = Pose2d::relativePose(brother, pose);
  1210. if (directY)
  1211. relative = Pose2d::relativePose(brother.rotate(brother.x(), brother.y(), M_PI / 2),
  1212. pose.rotate(pose.x(), pose.y(), M_PI / 2));//计算另一节在当前小车坐标系下的坐标
  1213. std::cout << "pose:" << pose << ", brother:" << brother << ", relative:" << relative << std::endl;
  1214. if (move_mode_ == eDouble)
  1215. relative = Pose2d(-1e8, -1e8, 0);
  1216. MpcError ret = failed;
  1217. LoadedMPC MPC(relative, obs_w, obs_h, limit_v.min, limit_v.max);
  1218. // 巡线最大角加速度固定0.1745
  1219. LoadedMPC::MPC_parameter parameter = {mpc_parameter.shortest_radius(), mpc_parameter.dt(),
  1220. mpc_parameter.acc_velocity(), 0.1745};
  1221. //printf(" r:%f dt:%f acc:%f acc_a:%f\n",mpc_parameter.shortest_radius(),
  1222. // mpc_parameter.dt(),mpc_parameter.acc_velocity(),mpc_parameter.acc_angular());
  1223. ret = MPC.solve(traj, traj[traj.size() - 1], statu, parameter,
  1224. out, selected_trajectory, optimize_trajectory, directY);
  1225. mpc_result = ret;
  1226. //std::cout<<" traj size %d %d -------- "<<selected_trajectory.size()<<","<<optimize_trajectory.size()<<std::endl;
  1227. if (ret == no_solution) {
  1228. printf(" mpc solve no solution set v/w = 0\n");
  1229. out.clear();
  1230. out.push_back(0);
  1231. out.push_back(0);
  1232. out.push_back(0);
  1233. out.push_back(0);
  1234. out.push_back(0);
  1235. out.push_back(0);
  1236. }
  1237. if (ret == unknown) {
  1238. printf(" mpc solve unknown set v/w = current\n");
  1239. double current_v = timedV_.Get(), current_w = timedA_.Get();
  1240. out.clear();
  1241. out.push_back(current_v);
  1242. out.push_back(current_w);
  1243. out.push_back(current_v);
  1244. out.push_back(current_w);
  1245. out.push_back(current_v);
  1246. out.push_back(current_w);
  1247. }
  1248. //
  1249. // diff_yaw.push_back(0);
  1250. // diff_yaw.push_back(0);
  1251. predict_traj_.reset(optimize_trajectory, 1);
  1252. selected_traj_.reset(selected_trajectory, 1);
  1253. return ret == success || ret == no_solution;
  1254. }
  1255. bool Navigation::IsArrived(NavMessage::PathNode targetNode) {
  1256. if (timedPose_.timeout() || timedV_.timeout() || timedA_.timeout()) {
  1257. printf(" pose / v / w timeout,IsArrived return false\n");
  1258. return false;
  1259. }
  1260. Pose2d current = timedPose_.Get();
  1261. double x = current.x();
  1262. double y = current.y();
  1263. double tx = targetNode.x();
  1264. double ty = targetNode.y();
  1265. double l = fabs(targetNode.l());
  1266. double w = fabs(targetNode.w());
  1267. double theta = -targetNode.theta();
  1268. /*if (newUnfinished_cations_.front().type() == 1 && GetSpaceId(targetNode) > 0) {//入库只判断前后方向上是否到达
  1269. tx = x;
  1270. }*/
  1271. if (l < 1e-10 || w < 1e-10) {
  1272. printf("IsArrived: Error target l or w == 0\n");
  1273. return false;
  1274. }
  1275. double a = (x - tx) * cos(theta) - (y - ty) * sin(theta);
  1276. double b = (x - tx) * sin(theta) + (y - ty) * cos(theta);
  1277. if (pow(a / l, 8) + pow(b / w, 8) <= 1) {
  1278. if (fabs(timedV_.Get()) < 0.06 && fabs(timedA_.Get()) < 5 * M_PI / 180.0) {
  1279. printf(" Arrived target: %f %f l:%f w:%f theta:%f\n", tx, ty, l, w, theta);
  1280. return true;
  1281. }
  1282. }
  1283. return false;
  1284. }
  1285. void Navigation::SendMoveCmd(int mode, ActionType type,
  1286. double v, double angular) {
  1287. if (monitor_) {
  1288. monitor_->set_speed(mode, type, v, angular);
  1289. if (type == eRotation)
  1290. RWheel_position_ = eR;
  1291. if (type == eVertical)
  1292. RWheel_position_ = eX;
  1293. if (type == eHorizontal)
  1294. RWheel_position_ = eY;
  1295. }
  1296. }
  1297. void Navigation::SendMoveCmd(int clampLifterAction, int mode, ActionType type,
  1298. double v[], double angular[]) {
  1299. if (monitor_) {
  1300. monitor_->set_ToAgvCmd(clampLifterAction, mode, type, v, angular);
  1301. if (type == eRotation)
  1302. RWheel_position_ = eR;
  1303. if (type == eVertical)
  1304. RWheel_position_ = eX;
  1305. if (type == eHorizontal)
  1306. RWheel_position_ = eY;
  1307. }
  1308. }
  1309. /*void Navigation::SendMoveCmd(int mode, ActionType type, double v[], double angular[],
  1310. int space_id, double distance,double Y1,double Y2) {
  1311. if (monitor_) {
  1312. monitor_->set_ToAgvCmd(mode, type, v, angular, 0, space_id, distance,Y1,Y2);
  1313. if (type == eRotation)
  1314. RWheel_position_ = eR;
  1315. if (type == eVertical)
  1316. RWheel_position_ = eX;
  1317. if (type == eHorizontal)
  1318. RWheel_position_ = eY;
  1319. }
  1320. }*/
  1321. void Navigation::SendMoveCmd(int clampLifterAction, int mode, ActionType type, double v[], double angular[],
  1322. int space_id, double distance, double Y1, double Y2) {
  1323. if (monitor_) {
  1324. monitor_->set_ToAgvCmd(clampLifterAction, mode, type, v, angular, 0, space_id, distance, Y1, Y2);
  1325. if (type == eRotation)
  1326. RWheel_position_ = eR;
  1327. if (type == eVertical)
  1328. RWheel_position_ = eX;
  1329. if (type == eHorizontal)
  1330. RWheel_position_ = eY;
  1331. }
  1332. }
  1333. //void Navigation::SendMoveCmd(int mode, ActionType type, double v[], double angular[], double yaw_diff[] ,int space_id, double distance) {
  1334. // if (monitor_) {
  1335. // monitor_->set_ToAgvCmd(mode, type, v, angular, yaw_diff ,0,space_id, distance);
  1336. // if (type == eRotation)
  1337. // RWheel_position_ = eR;
  1338. // if (type == eVertical)
  1339. // RWheel_position_ = eX;
  1340. // if (type == eHorizontal)
  1341. // RWheel_position_ = eY;
  1342. // }
  1343. //}
  1344. bool Navigation::clamp_close() {
  1345. if (monitor_) {
  1346. printf("Clamp closing...\n");
  1347. monitor_->clamp_close(move_mode_);
  1348. actionType_ = eClampClose;
  1349. while (cancel_ == false) {
  1350. if (timed_clamp_.timeout()) {
  1351. printf("timed clamp is timeout\n");
  1352. return false;
  1353. }
  1354. if (timed_clamp_.Get() == eClosed)
  1355. return true;
  1356. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1357. monitor_->clamp_close(move_mode_);
  1358. actionType_ = eClampClose;
  1359. }
  1360. return false;
  1361. }
  1362. return false;
  1363. }
  1364. bool Navigation::clamp_half_open() {
  1365. if (monitor_) {
  1366. printf("Clamp openning...\n");
  1367. monitor_->clamp_half_open(move_mode_);
  1368. actionType_ = eClampHalfOpen;
  1369. while (cancel_ == false) {
  1370. if (timed_clamp_.timeout()) {
  1371. printf("timed clamp is timeout\n");
  1372. return false;
  1373. }
  1374. if (timed_clamp_.Get() == eHalfOpened)
  1375. return true;
  1376. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1377. monitor_->clamp_half_open(move_mode_);
  1378. actionType_ = eClampHalfOpen;
  1379. }
  1380. return false;
  1381. }
  1382. return false;
  1383. }
  1384. bool Navigation::singleClamp_fullyOpen_until_inspaceBegin() {
  1385. if (move_mode_ == eDouble) {
  1386. return true;
  1387. }
  1388. while (cancel_ == false) {
  1389. if (timedV_.timeout()) {
  1390. return false;
  1391. }
  1392. if (fabs(timedV_.Get()) < 0.02) {
  1393. usleep(1000 * 300);
  1394. continue;
  1395. }
  1396. break;
  1397. }
  1398. return clamp_fully_open();
  1399. };
  1400. bool Navigation::clamp_fully_open() {
  1401. if (monitor_) {
  1402. if (timed_clamp_.Get() == eFullyOpened)
  1403. return true;
  1404. printf("Clamp fully openning...\n");
  1405. monitor_->clamp_fully_open(move_mode_);
  1406. actionType_ = eClampFullyOpen;
  1407. while (cancel_ == false) {
  1408. if (timed_clamp_.timeout()) {
  1409. printf("timed clamp is timeout\n");
  1410. return false;
  1411. }
  1412. if (timed_clamp_.Get() == eFullyOpened)
  1413. return true;
  1414. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1415. monitor_->clamp_fully_open(move_mode_);
  1416. actionType_ = eClampFullyOpen;
  1417. }
  1418. return false;
  1419. }
  1420. return false;
  1421. }
  1422. bool Navigation::lifter_rise() {
  1423. if (monitor_) {
  1424. printf("Lifter upping...\n");
  1425. actionType_ = eLifterRise;
  1426. if (timed_lifter_.Get() == eRose)
  1427. return true;
  1428. if (timed_lifter_.Get() != eRose) {
  1429. if (timed_clamp_.Get() != eHalfOpened && timed_clamp_.Get() != eClosed) {
  1430. printf(" clamp statu !=eHalfOpened or eClosed, clamp_half_open...\n ");
  1431. if (!clamp_half_open()) {
  1432. printf(" clamp half open failed\n");
  1433. return false;
  1434. }
  1435. }
  1436. }
  1437. while (cancel_ == false) {
  1438. if (timed_lifter_.timeout()) {
  1439. printf("timed lifter is timeout\n");
  1440. return false;
  1441. }
  1442. if (timed_lifter_.timeout()) {
  1443. return false;
  1444. }
  1445. if (timed_lifter_.Get() == eRose)
  1446. return true;
  1447. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1448. monitor_->lifter_rise(move_mode_);
  1449. actionType_ = eLifterRise;
  1450. }
  1451. return false;
  1452. }
  1453. return false;
  1454. }
  1455. bool Navigation::lifter_down() {
  1456. if (monitor_) {
  1457. printf("Lifter downing...\n");
  1458. if (timed_lifter_.Get() == eDowned)
  1459. return true;
  1460. actionType_ = eLifterDown;
  1461. if (timed_lifter_.Get() != eDowned) {
  1462. if (timed_clamp_.Get() != eHalfOpened && timed_clamp_.Get() != eClosed) {
  1463. printf(" clamp statu !=eHalfOpened or eClosed, clamp_half_open...\n ");
  1464. if (!clamp_half_open()) {
  1465. printf(" clamp half open failed\n");
  1466. return false;
  1467. }
  1468. }
  1469. }
  1470. while (cancel_ == false) {
  1471. if (timed_lifter_.timeout()) {
  1472. printf("timed lifter is timeout\n");
  1473. return false;
  1474. }
  1475. if (timed_lifter_.timeout()) {
  1476. return false;
  1477. }
  1478. if (timed_lifter_.Get() == eDowned)
  1479. return true;
  1480. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1481. monitor_->lifter_down(move_mode_);
  1482. actionType_ = eLifterDown;
  1483. }
  1484. return false;
  1485. }
  1486. return false;
  1487. }
  1488. bool Navigation::WaitInsideDoorCompleted(int doorID, DoorStatu status) {
  1489. while (cancel_ == false) {
  1490. if (timed_Door_.timeout()) {
  1491. return false;
  1492. }
  1493. if (timed_Door_.Get()[doorID].second == status) {
  1494. return true;
  1495. }
  1496. usleep(1000 * 100);
  1497. printf("waiting door_id(ins):%d, to:%d...\n", doorID, status);
  1498. }
  1499. if (cancel_ == true) {
  1500. return false;
  1501. }
  1502. return false;
  1503. }
  1504. bool Navigation::WaitCarrierCompleted(int spaceID, CarrierStatu statu) {
  1505. while (cancel_ == false) {
  1506. int region_id = 0, carrier_no = 0;
  1507. SpaceNo2CarrierNo(spaceID, region_id, carrier_no);
  1508. if (region_id < 0) {
  1509. return true;
  1510. }
  1511. if (timed_Carrier_[region_id].timeout()) {
  1512. printf("spaceID:%d, timed_Carrier_[%d].timeout carrier_no id:%d\n", spaceID, region_id, carrier_no);
  1513. return false;
  1514. }
  1515. CarrierStatu cur_ = GetCarrierStatusBySpaceID(spaceID);
  1516. if (cur_ == statu) {
  1517. return true;
  1518. }
  1519. usleep(1000 * 100);
  1520. printf("waiting space_id:%d, carrier_id[%d,%d] to:%d, cur:%d...\n", spaceID, region_id, carrier_no, statu,
  1521. cur_);
  1522. }
  1523. if (cancel_ == true) {
  1524. return false;
  1525. }
  1526. return false;
  1527. }
  1528. bool Navigation::WaitClampLifterStatu(int clampLifterAction) {
  1529. int currentStatu = 0;
  1530. if (move_mode_ == eSingle) {
  1531. while (cancel_ == false) {
  1532. if (timed_clamp_.timeout() || timed_lifter_.timeout()) {
  1533. return false;
  1534. }
  1535. if (timed_clamp_.Get() == eClosed) {
  1536. currentStatu |= eByteCLampClose;
  1537. }
  1538. if (timed_clamp_.Get() == eHalfOpened) {
  1539. currentStatu |= eByteClampHalfOpen;
  1540. }
  1541. if (timed_clamp_.Get() == eFullyOpened) {
  1542. currentStatu |= eByteClampFullyOpen;
  1543. }
  1544. if (timed_lifter_.Get() == eRose) {
  1545. currentStatu |= eByteLifterUp;
  1546. }
  1547. if (timed_lifter_.Get() == eDowned) {
  1548. currentStatu |= eByteLifterDown;
  1549. }
  1550. printf(" current statu:%d action status:%d last:%d\n",
  1551. currentStatu, clampLifterAction, currentStatu & clampLifterAction);
  1552. if ((currentStatu & clampLifterAction) == clampLifterAction)
  1553. return true;
  1554. double down_v[3] = {0, 0, 0};//下发线速度0
  1555. double down_w[3] = {0, 0, 0};//下发角速度0
  1556. SendMoveCmd(clampLifterAction, move_mode_, actionType_, down_v, down_w);
  1557. usleep(1000 * 100);
  1558. }
  1559. } else if (move_mode_ == eDouble) {
  1560. while (cancel_ == false) {
  1561. if (timed_clamp_.timeout() || timed_lifter_.timeout() ||
  1562. timed_other_clamp_.timeout() || timed_other_lifter_.timeout()) {
  1563. return false;
  1564. }
  1565. if (timed_clamp_.Get() == eClosed && timed_other_clamp_.Get() == eClosed) {
  1566. currentStatu |= eByteCLampClose;
  1567. }
  1568. if (timed_clamp_.Get() == eHalfOpened && timed_other_clamp_.Get() == eHalfOpened) {
  1569. currentStatu |= eByteClampHalfOpen;
  1570. }
  1571. if (timed_clamp_.Get() == eFullyOpened && timed_other_clamp_.Get() == eFullyOpened) {
  1572. currentStatu |= eByteClampFullyOpen;
  1573. }
  1574. if (timed_lifter_.Get() == eRose && timed_other_lifter_.Get() == eRose) {
  1575. currentStatu |= eByteLifterUp;
  1576. }
  1577. if (timed_lifter_.Get() == eDowned && timed_other_lifter_.Get() == eDowned) {
  1578. currentStatu |= eByteLifterDown;
  1579. }
  1580. printf(" current statu:%d action status:%d last:%d\n",
  1581. currentStatu, clampLifterAction, currentStatu & clampLifterAction);
  1582. if ((currentStatu & clampLifterAction) == clampLifterAction)
  1583. return true;
  1584. double down_v[3] = {0, 0, 0};//下发线速度0
  1585. double down_w[3] = {0, 0, 0};//下发角速度0
  1586. SendMoveCmd(clampLifterAction, move_mode_, actionType_, down_v, down_w);
  1587. usleep(1000 * 100);
  1588. }
  1589. }
  1590. if (cancel_ == true) {
  1591. return false;
  1592. }
  1593. return false;
  1594. }
  1595. Navigation::MpcResult Navigation::MpcToTarget(NavMessage::PathNode node, stLimit limit_v,
  1596. bool autoDirect, int clampLifterAction) {
  1597. if (IsArrived(node)) {
  1598. printf(" current already in target completed !!!\n");
  1599. return eMpcSuccess;
  1600. }
  1601. if (inited_ == false) {
  1602. printf(" navigation has not inited\n");
  1603. return eMpcFailed;
  1604. }
  1605. if (PoseTimeout()) {
  1606. printf(" navigation Error:Pose is timeout \n");
  1607. return eMpcFailed;
  1608. }
  1609. Pose2d current = timedPose_.Get();
  1610. Pose2d target(node.x(), node.y(), 0);
  1611. //生成轨迹
  1612. Trajectory traj = Trajectory::create_line_trajectory(current, target, 0.1);
  1613. if (traj.size() == 0)
  1614. return eMpcSuccess;
  1615. //判断 巡线方向
  1616. bool directY = false;
  1617. if (autoDirect) {
  1618. Pose2d target_relative = Pose2d::relativePose(target, timedPose_.Get());
  1619. if (fabs(target_relative.y()) > fabs(target_relative.x())) { //目标轨迹点在当前点Y轴上
  1620. std::cout << " MPC Y axis target_relative:" << target_relative << std::endl;
  1621. directY = true;
  1622. } else {
  1623. std::cout << " MPC X axis target_relative:" << target_relative << std::endl;
  1624. }
  1625. if (!PossibleToTarget(node, directY)) {
  1626. directY = !directY;
  1627. }
  1628. }
  1629. printf(" exec along autoDirect:%d\n", autoDirect);
  1630. //文件log
  1631. std::ofstream ofs; //创建流对象
  1632. std::string log_file_dir = "../data/";
  1633. time_t t = time(0);
  1634. char tmp[32] = {NULL};
  1635. strftime(tmp, sizeof(tmp), "%Y_%m_%d_%H_%M_%S.txt", localtime(&t));
  1636. std::string log_file_name = tmp;
  1637. ofs.open(log_file_dir + log_file_name, std::ios::app); //打开的地址和方式
  1638. auto beg_time = std::chrono::steady_clock::now();
  1639. int retry_count = 0;
  1640. int retry_count_limit = 3;
  1641. while (cancel_ == false) {
  1642. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  1643. if (pause_ == true) {
  1644. //发送暂停消息
  1645. continue;
  1646. }
  1647. if (PoseTimeout()) {
  1648. printf(" navigation Error:Pose is timeout \n");
  1649. ofs.close();//关闭文件
  1650. return eMpcFailed;
  1651. }
  1652. if (timedV_.timeout() || timedA_.timeout()) {
  1653. printf(" navigation Error:v/a is timeout | __LINE__:%d \n", __LINE__);
  1654. ofs.close();//关闭文件
  1655. return eMpcFailed;
  1656. }
  1657. // //出入库实时判断门控或者载车板
  1658. // float door_no_1_y = -5;
  1659. // NavMessage::NewAction current_action = GetCurrentAction();
  1660. // if (current_action.type() == 1 || current_action.type() == 2) {
  1661. // //去出入口,判断内门是否打开
  1662. // if (TargetIsExport(current_action.spacenode()) || TargetIsEntrance(current_action.spacenode())) {
  1663. // int port_id = GetPortIDBySpace(current_action.spacenode());
  1664. // if (timed_Door_.timeout() || timed_Door_.Get()[port_id].second != eDoorOpened) {
  1665. // printf(" Inside door is not opened.......| line: %d\n", __LINE__);
  1666. // return eMpcFailed;
  1667. // }
  1668. // } else {
  1669. // //去车位点
  1670. // if (IsUperSpace(current_action.spacenode())) {
  1671. // if (GetCarrierStatusBySpaceID(GetSpaceId(current_action.spacenode())) != eCarrierDown) {
  1672. // printf(" Carrier is not downed.......| line: %d\n", __LINE__);
  1673. // return eMpcFailed;
  1674. // }
  1675. // } else {
  1676. // int region_id = 0, carrier_no = 0;
  1677. // SpaceNo2CarrierNo(GetSpaceId(current_action.spacenode()), region_id, carrier_no);
  1678. // if (region_id < 0) {// 子母车位,且不在载车板下方的车位
  1679. //
  1680. // } else {
  1681. // if (GetCarrierStatusBySpaceID(GetSpaceId(current_action.spacenode())) != eCarrierUp) {
  1682. // printf(" Carrier is not up.......| line: %d\n", __LINE__);
  1683. // return eMpcFailed;
  1684. // }
  1685. // }
  1686. // }
  1687. // }
  1688. // }
  1689. //判断是否到达终点
  1690. if (IsArrived(node)) {
  1691. if (Stop()) {
  1692. printf(" exec along completed !!!\n");
  1693. ofs.close();//关闭文件
  1694. bool waited = WaitClampLifterStatu(clampLifterAction);
  1695. if (waited) return eMpcSuccess;
  1696. else return eMpcFailed;
  1697. }
  1698. }
  1699. float v_before_compute = timedV_.Get();
  1700. float a_before_compute = timedA_.Get();
  1701. //一次变速
  1702. std::vector<double> out;
  1703. // std::vector<double> diff_yaw; //两车分别与整车的相对角度
  1704. bool ret;
  1705. int mpc_result = 0;
  1706. TimerRecord::Execute([&, this]() {
  1707. ret = mpc_once(traj, limit_v, out, mpc_result, directY);
  1708. }, "mpc_once");
  1709. if (ret == false) {
  1710. if (mpc_result == unknown){
  1711. retry_count++;
  1712. if (retry_count > retry_count_limit) {
  1713. printf("MpcToTarget failed,ret:%d\n", ret);
  1714. SlowlyStop();
  1715. ofs.close();//关闭文件
  1716. return eMpcFailed;
  1717. }
  1718. printf("MpcToTarget failed,mpc_result:%d, retry...\n", mpc_result);
  1719. } else {
  1720. printf("MpcToTarget failed,ret:%d\n", ret);
  1721. SlowlyStop();
  1722. ofs.close();//关闭文件
  1723. return eMpcFailed;
  1724. }
  1725. }
  1726. const int down_count = 3;//下发前多少步
  1727. double down_v[down_count] = {out[0], out[2], out[4]};//下发线速度
  1728. double down_w[down_count] = {out[1], out[3], out[5]};//下发角速度
  1729. /*
  1730. * AGV 在终点附近低速巡航时,设置最小速度0.05
  1731. */
  1732. Pose2d target_in_agv = Pose2d::relativePose(target, timedPose_.Get());
  1733. if (directY) {
  1734. target_in_agv = target_in_agv.rotate(M_PI / 2.0);
  1735. }
  1736. for (int i = 0; i < down_count; ++i) {
  1737. if (down_v[i] >= 0 && down_v[i] < limit_v.min)
  1738. down_v[i] = limit_v.min;
  1739. if (down_v[i] < 0 && down_v[i] > -limit_v.min)
  1740. down_v[i] = -limit_v.min;
  1741. }
  1742. //放大角速度
  1743. // out[1] *= 10;
  1744. //入库,行进方向上最后一米不纠偏
  1745. if (newUnfinished_cations_.front().type() == 1 && GetSpaceId(node) > 0) {//入库
  1746. if (fabs(target_in_agv.x()) < 0.8) {
  1747. printf("target_in_agv: %f", target_in_agv.x());
  1748. for (double &i: down_w) {
  1749. i = 0.0;
  1750. }
  1751. }
  1752. } else if (newUnfinished_cations_.front().type() == 2) {//出库,行进方向上开始一米不纠偏
  1753. Pose2d agv_in_space =
  1754. Pose2d::relativePose(
  1755. Pose2d(newUnfinished_cations_.front().spacenode().x(),
  1756. newUnfinished_cations_.front().spacenode().y(), 0),
  1757. timedPose_.Get());
  1758. if (fabs(agv_in_space.x()) < 1.4) {
  1759. printf("agv_in_space: %f", agv_in_space.x());
  1760. for (double &i: down_w) {
  1761. i = 0.0;
  1762. }
  1763. }
  1764. }
  1765. //下发速度
  1766. //printf(" nav input :%f out:%f\n",timedV_.Get(),out[0]);
  1767. //添加车位号,距目标点距离信息
  1768. double distance = 0;
  1769. int space_id = -1;
  1770. if (GetCurrentAction().type() == 1 || GetCurrentAction().type() == 2) {
  1771. space_id = GetSpaceId(GetCurrentAction().spacenode());
  1772. }
  1773. if (space_id > 0) {
  1774. distance = Pose2d::distance(target_in_agv, Pose2d(0, 0, 0));
  1775. }
  1776. double Y1 = 0.0, Y2 = 0.0;
  1777. if (move_mode_ == eDouble) {
  1778. double dy = -timeYawDiff1_.Get();
  1779. Y1 = 0.2 * (1.0 / (1 + exp(-16. * dy)) - 0.5) * 1.0;
  1780. Y2 = timeYawDiff2_.Get();
  1781. if (directY == false) {
  1782. Y1 = 0;
  1783. }
  1784. }
  1785. if (directY == false)
  1786. SendMoveCmd(clampLifterAction, move_mode_, eVertical, down_v, down_w, space_id, distance, Y1, Y2);
  1787. else
  1788. SendMoveCmd(clampLifterAction, move_mode_, eHorizontal, down_v, down_w, space_id, distance, Y1, Y2);
  1789. actionType_ = directY ? eHorizontal : eVertical;
  1790. //日志打印
  1791. std::string log_inf_line = std::to_string(move_mode_);
  1792. log_inf_line += " ";
  1793. log_inf_line += std::to_string(parameter_.x_mpc_parameter().shortest_radius()) + " " +
  1794. std::to_string(parameter_.x_mpc_parameter().acc_angular());
  1795. log_inf_line += " ";
  1796. Pose2d cur_pose = timedPose_.Get();//自身x,y,theta
  1797. log_inf_line += std::to_string(cur_pose.x()) + " " + std::to_string(cur_pose.y()) + " " +
  1798. std::to_string(cur_pose.theta());
  1799. log_inf_line += " ";
  1800. Pose2d cur_Bro_pose = timedBrotherPose_.Get();//另一节x,y,theta
  1801. log_inf_line += std::to_string(cur_Bro_pose.x()) + " " + std::to_string(cur_Bro_pose.y()) + " " +
  1802. std::to_string(cur_Bro_pose.theta());
  1803. log_inf_line += " ";
  1804. log_inf_line += std::to_string(v_before_compute) + " " + std::to_string(a_before_compute);//计算时反馈速度
  1805. log_inf_line += " ";
  1806. log_inf_line += std::to_string(timedV_.Get()) + " " + std::to_string(timedA_.Get());//下发时反馈速度
  1807. log_inf_line += " ";
  1808. log_inf_line += std::to_string(out[0]) + " " + std::to_string(out[1]);//下发速度
  1809. log_inf_line += " ";
  1810. log_inf_line += std::to_string(out[2]) + " " + std::to_string(out[3]);//下发速度
  1811. log_inf_line += " ";
  1812. log_inf_line += std::to_string(out[4]) + " " + std::to_string(out[5]);//下发速度
  1813. log_inf_line += " ";
  1814. log_inf_line += std::to_string(Y1) + " " + std::to_string(Y2);//下发速度
  1815. log_inf_line += " ";
  1816. auto cur_time = std::chrono::steady_clock::now();
  1817. auto duration = std::chrono::duration_cast<std::chrono::microseconds>(cur_time - beg_time);
  1818. double time =
  1819. double(duration.count()) * std::chrono::microseconds::period::num /
  1820. std::chrono::microseconds::period::den;
  1821. log_inf_line += std::to_string(time);
  1822. ofs << log_inf_line << std::endl; //一行日志的内容
  1823. /*
  1824. * 判断车辆是否在终点附近徘徊,无法到达终点
  1825. */
  1826. if (PossibleToTarget(node, directY) == false) {
  1827. printf(" --------------MPC imposible to target -------------------------------------------\n");
  1828. if (fabs(timedV_.Get()) > 0.1 || fabs(timedA_.Get()) > 10 * M_PI / 180.0)
  1829. SlowlyStop();
  1830. else
  1831. Stop();
  1832. ofs.close();//关闭文件
  1833. return eImpossibleToTarget;
  1834. }
  1835. }
  1836. ofs.close();//关闭文件
  1837. return eMpcFailed;
  1838. }
  1839. bool Navigation::PossibleToTarget(NavMessage::PathNode targetNode, bool directY) {
  1840. if (timedPose_.timeout()) {
  1841. return false;
  1842. }
  1843. Pose2d current = timedPose_.Get();
  1844. // if (GetSpaceId(targetNode) > 0) {
  1845. // printf("车位点强制可到达\n");
  1846. // //车位点强制可到达
  1847. // return true;
  1848. // }
  1849. double tx = targetNode.x();
  1850. double ty = targetNode.y();
  1851. double l = fabs(targetNode.l());
  1852. double w = fabs(targetNode.w());
  1853. double theta = -targetNode.theta();
  1854. // double W = 2.45;
  1855. // double L = 1.3;
  1856. // double minYaw = 3 * M_PI / 180.0;
  1857. // if (move_mode_ == eDouble) {
  1858. // L = 1.3 + 2.7;
  1859. //
  1860. // }
  1861. double W = 2.5;
  1862. double L = 1.565;
  1863. double minYaw = 5 * M_PI / 180.0;
  1864. if (move_mode_ == eDouble) {
  1865. L = 1.565 + 2.78;
  1866. }
  1867. if (directY) {
  1868. current = current.rotate(current.x(), current.y(), M_PI / 2);
  1869. double t = W;
  1870. W = L;
  1871. L = t;
  1872. }
  1873. double minR = W / 2 + L / tan(minYaw);
  1874. //printf("l:%f,w:%f\n",l,w);
  1875. std::vector<Pose2d> poses = Pose2d::generate_rectangle_vertexs(Pose2d(tx, ty, 0), l * 2, w * 2);
  1876. bool nagY = false;
  1877. bool posiY = false;
  1878. for (int i = 0; i < poses.size(); ++i) {
  1879. Pose2d rpos = poses[i].rotate(tx, ty, theta);
  1880. Pose2d relative = Pose2d::relativePose(rpos, current);
  1881. double ax = fabs(relative.x());
  1882. double ay = fabs(relative.y());
  1883. if (relative.y() > 0) posiY = true;
  1884. if (relative.y() < 0) nagY = true;
  1885. if (ax * ax + pow(ay - minR, 2) > minR * minR) {
  1886. /*printf(" possible to target:%f %f l:%f,w:%f theta:%f minR:%f ax:%f,ay:%f\n",
  1887. targetNode.x(),targetNode.y(),targetNode.l(),targetNode.w(),targetNode.theta(),
  1888. minR,ax,ay);*/
  1889. return true;
  1890. } else if (nagY && posiY) {
  1891. // std::cout << "nagY && posiY" << std::endl;
  1892. return true;
  1893. }
  1894. // printf("directY:%d targetInPose:%f %f l:%f,w:%f theta:%f minR:%f ax:%f,ay:%f\n", directY,
  1895. // relative.x(), relative.y(), targetNode.l(), targetNode.w(), targetNode.theta(),
  1896. // minR, ax, ay);
  1897. }
  1898. printf(" impossible to target:%f %f l:%f,w:%f theta:%f, ",
  1899. targetNode.x(), targetNode.y(), targetNode.l(), targetNode.w(), targetNode.theta());
  1900. printf(" current:%f, %f, %f\n",
  1901. current.x(), current.y(), current.theta());
  1902. return false;
  1903. }
  1904. void Navigation::Start(const NavMessage::NavCmd &cmd, NavMessage::NavResponse &response) {
  1905. if (inited_ == false) {
  1906. response.set_ret(-1);
  1907. response.set_info("navigation has not inited");
  1908. printf(" navigation has not inited\n");
  1909. return;
  1910. }
  1911. if (newUnfinished_cations_.empty() == false) //正在运行中,上一次指令未完成
  1912. {
  1913. response.set_ret(-2);
  1914. response.set_info("navigation is running pls cancel before");
  1915. printf(" navigation is running pls cancel before\n");
  1916. return;
  1917. }
  1918. //add 先检查当前点与起点的距离
  1919. global_navCmd_ = cmd;
  1920. for (int i = 0; i < cmd.newactions_size(); ++i)
  1921. newUnfinished_cations_.push(cmd.newactions(i));
  1922. pause_ = false;
  1923. cancel_ = false;
  1924. running_ = true;
  1925. actionType_ = eReady;
  1926. printf("Navigation beg...\n");
  1927. bool ret = false;
  1928. while (newUnfinished_cations_.empty() == false && cancel_ == false) {
  1929. std::cout << "unfinished size:" << newUnfinished_cations_.size() << std::endl;
  1930. NavMessage::NewAction act = newUnfinished_cations_.front();
  1931. NavMessage::NewAction last_act = newUnfinished_cations_.back();
  1932. if (act.type() == 1) { //入库
  1933. printf("入库\n");
  1934. space_id_ = act.spacenode().id();
  1935. obs_w_ = 1.1;
  1936. obs_h_ = 1.87;
  1937. ret = execute_InOut_space(act);
  1938. if (!ret) {
  1939. printf(" In space failed\n");
  1940. isInSpace_ = false;
  1941. break;
  1942. }
  1943. } else if (act.type() == 2) { //出库
  1944. printf("出库\n");
  1945. obs_w_ = 1.25;
  1946. obs_h_ = 1.87;
  1947. ret = execute_InOut_space(act);
  1948. if (!ret) {
  1949. printf(" out space failed\n");
  1950. break;
  1951. } else {
  1952. isInSpace_ = false;
  1953. }
  1954. } else if (act.type() == 3 || act.type() == 4) { //马路导航
  1955. printf("马路导航\n");
  1956. obs_w_ = 1.1;
  1957. obs_h_ = 1.87;
  1958. ret = execute_nodes(act);
  1959. if (!ret) {
  1960. printf(" street nav failed\n");
  1961. break;
  1962. }
  1963. } else if (act.type() == 5) {
  1964. printf(" 汽车模型导航....\n");
  1965. } else if (act.type() == 6) {//夹持
  1966. ret = clamp_close();
  1967. if (ret == false) {
  1968. printf("夹持failed ...\n");
  1969. break;
  1970. }
  1971. } else if (act.type() == 7) {
  1972. if (this->clamp_fully_open() == false) {
  1973. printf("打开夹持 failed...\n");
  1974. break;
  1975. }
  1976. } else if (act.type() == 8) { //切换模式
  1977. SwitchMode(act.changedmode(), act.wheelbase());
  1978. ret = true;
  1979. } else if (act.type() == 9) { //提升机构提升
  1980. ret = lifter_rise();
  1981. if (ret == false) {
  1982. printf("提升failed ...\n");
  1983. break;
  1984. }
  1985. } else if (act.type() == 10) { //提升机构下降
  1986. ret = lifter_down();
  1987. if (ret == false) {
  1988. printf("下降failed ...\n");
  1989. break;
  1990. }
  1991. } else {
  1992. printf(" action type invalid not handled !!\n");
  1993. break;
  1994. }
  1995. newUnfinished_cations_.pop();
  1996. }
  1997. actionType_ = eReady;
  1998. Stop();
  1999. if (ret == false) {
  2000. response.set_ret(-4);
  2001. response.set_info("navigation ret false");
  2002. printf(" navigation ret false\n");
  2003. while (newUnfinished_cations_.empty() == false)
  2004. newUnfinished_cations_.pop();
  2005. } else if (cancel_ == true) {
  2006. response.set_ret(-3);
  2007. response.set_info("navigation canceled");
  2008. printf(" navigation canceled\n");
  2009. while (newUnfinished_cations_.empty() == false)
  2010. newUnfinished_cations_.pop();
  2011. } else {
  2012. if (newUnfinished_cations_.empty()) {
  2013. response.set_ret(0);
  2014. response.set_info("navigation completed!!!");
  2015. printf("navigation completed!!!\n");
  2016. } else {
  2017. response.set_ret(-4);
  2018. response.set_info("navigation Failed!!!!");
  2019. printf(" navigation Failed\n");
  2020. while (newUnfinished_cations_.empty() == false)
  2021. newUnfinished_cations_.pop();
  2022. }
  2023. }
  2024. running_ = false;
  2025. }
  2026. bool Navigation::SwitchMode(int mode, float wheelBase) {
  2027. wheelBase_ = wheelBase;
  2028. printf("Child AGV can not Switch Mode\n");
  2029. return true;
  2030. }
  2031. float Navigation::compute_cuv(const Pose2d &target) {
  2032. float x = fabs(target.x());
  2033. float y = fabs(target.y());
  2034. float cuv = atan(y / (x + 1e-8));
  2035. //printf(" ---------------------- cuv:%f\n",cuv);
  2036. return cuv;
  2037. }
  2038. void Navigation::ManualOperation(const NavMessage::ManualCmd &cmd, NavMessage::NavResponse &response) {
  2039. return;
  2040. // pause_ = false;
  2041. // cancel_ = false;
  2042. // running_ = true;
  2043. // actionType_ = eReady;
  2044. // printf("ManualOperation: %d | start...\n", cmd.operation_type());
  2045. //
  2046. // float symbol = cmd.velocity() < 0 ? -1 : 1; // 判断为正方向or负方向
  2047. // double velocity;
  2048. // std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2049. // switch (cmd.operation_type()) {
  2050. // case 1: // 旋转
  2051. // velocity = 2.0 * M_PI / 180.0 * symbol;
  2052. // SendMoveCmd(move_mode_, eRotation, 0, velocity);
  2053. // actionType_ = eRotation;
  2054. // printf(" ManualOperation: %d | input angular_v: %f, down: %f\n",
  2055. // cmd.operation_type(), timedA_.Get(), velocity);
  2056. // break;
  2057. // case 2: // X平移
  2058. // velocity = 1.0 * symbol;
  2059. // SendMoveCmd(move_mode_, eVertical, velocity, 0);
  2060. // actionType_ = eVertical;
  2061. // printf(" ManualOperation: %d | input line_v : %f, down: %f\n",
  2062. // cmd.operation_type(), timedV_.Get(), velocity);
  2063. // break;
  2064. // case 3: // Y平移
  2065. // velocity = 1.0 * symbol;
  2066. // SendMoveCmd(move_mode_, eHorizontal, velocity, 0);
  2067. // actionType_ = eHorizontal;
  2068. // printf(" ManualOperation: %d | input line_v: %f, down: %f\n",
  2069. // cmd.operation_type(), timedV_.Get(), velocity);
  2070. // break;
  2071. // default:
  2072. // break;
  2073. // }
  2074. //
  2075. // actionType_ = eReady;
  2076. // response.set_ret(-3);
  2077. // response.set_info("ManualOperation: %d, canceled!!!", cmd.operation_type());
  2078. // printf("ManualOperation: %d | canceled!!!\n", cmd.operation_type());
  2079. // running_ = false;
  2080. }
  2081. bool Navigation::IsMasterAGV() {
  2082. return is_master_AGV;
  2083. }
  2084. void Navigation::ResetDoor(int32_t status) {
  2085. // printf("---------------receive status:%d\n",status);
  2086. DoorStatusMap doorStatusMap;
  2087. anasisDoorStatu(status, doorStatusMap);
  2088. // for (auto it = doorStatusMap.begin() ; it != doorStatusMap.end() ; ++it) {
  2089. // printf("doorID:%d, out:%d, ins:%d\n",it->first, it->second.first, it->second.second);
  2090. // }
  2091. timed_Door_.reset(doorStatusMap, 3);
  2092. }
  2093. void Navigation::anasisDoorStatu(int32_t i_door_status, DoorStatusMap &m_door_status) {
  2094. // int bytesize = sizeof(int32_t)*8;
  2095. m_door_status.clear();
  2096. for (int i = 1; i >= 0; --i) {
  2097. int statu = i_door_status >> (i * 16);
  2098. int door_id = (statu & 0xFF00) >> 8;
  2099. int outside_door_status = statu & 0x00FF;
  2100. int inside_door_status = outside_door_status >> 2;
  2101. if ((outside_door_status & eDoorOpened) == eDoorOpened) {
  2102. outside_door_status = eDoorOpened;
  2103. } else if ((outside_door_status & eDoorClosed) == eDoorClosed) {
  2104. outside_door_status = eDoorClosed;
  2105. } else {
  2106. outside_door_status = eDoorInvalid;
  2107. }
  2108. if ((inside_door_status & eDoorOpened) == eDoorOpened) {
  2109. inside_door_status = eDoorOpened;
  2110. } else if ((inside_door_status & eDoorClosed) == eDoorClosed) {
  2111. inside_door_status = eDoorClosed;
  2112. } else {
  2113. inside_door_status = eDoorInvalid;
  2114. }
  2115. m_door_status[door_id] = DoorStatusInOnePort((DoorStatu) outside_door_status, (DoorStatu) inside_door_status);
  2116. }
  2117. }
  2118. #define SWAP_BYTES 0
  2119. void Navigation::anasisCarierStatu(int &regionID, CarrierStatuRegionMap &status, int32_t bytes) {
  2120. int32_t reverseBytes = bytes;
  2121. if (SWAP_BYTES) {
  2122. reverseBytes = (bytes >> 24) | ((bytes & 0xFF0000) >> 8) | ((bytes & 0xFF00) << 8) | ((bytes & 0xFF) << 24);
  2123. }
  2124. int bytesize = sizeof(int32_t) * 8;
  2125. regionID = (bytes >> ((bytesize - 1) * 8));
  2126. for (int i = 0; i < (bytesize - 8) / 2; ++i) {
  2127. int statu = (reverseBytes >> (i * 2) & 0x03);
  2128. if ((statu & eCarrierUp) == eCarrierUp) {
  2129. status[i + 1] = eCarrierUp;
  2130. } else if ((statu & eCarrierDown) == eCarrierDown) {
  2131. status[i + 1] = eCarrierDown;
  2132. } else {
  2133. status[i + 1] = eCarrierInvalid;
  2134. }
  2135. }
  2136. }
  2137. void Navigation::ResetCarrier(std::vector<int32_t> status) {
  2138. for (int32_t statu: status) {
  2139. int regionID;
  2140. CarrierStatuRegionMap region;
  2141. anasisCarierStatu(regionID, region, statu);
  2142. timed_Carrier_[regionID].reset(region, 5);
  2143. }
  2144. /*printf("---------------------------------------\n");
  2145. for(std::map<int,TimedLockData<CarrierStatuRegionMap>>::iterator it=timed_Carrier_.begin();
  2146. it!=timed_Carrier_.end();it++){
  2147. int regionID=it->first;
  2148. if(it->second.timeout())
  2149. continue;
  2150. printf(">>>>>>> Region ID :%d\n",regionID);
  2151. std::map<int,CarrierStatu> region=it->second.Get();
  2152. for(std::map<int,CarrierStatu>::iterator it1=region.begin();
  2153. it1!=region.end();++it1){
  2154. int id=it1->first;
  2155. CarrierStatu sta=it1->second;
  2156. printf("\t \tcarrier id :%d statu:%d\n",id,sta);
  2157. }
  2158. }*/
  2159. }
  2160. bool Navigation::Stringsplit(const std::string &str, const std::string splits, std::vector<std::string> &res) {
  2161. res.clear();
  2162. if (str.empty()) {
  2163. return false;
  2164. }
  2165. std::string strs = str + splits;
  2166. size_t pos = strs.find(splits);
  2167. int step = splits.size();
  2168. while (pos != std::string::npos) {
  2169. std::string temp = strs.substr(0, pos);
  2170. if (temp.size() > 0)
  2171. res.push_back(temp);
  2172. strs = strs.substr(pos + step, strs.size());
  2173. pos = strs.find(splits);
  2174. }
  2175. // for (int i = 0; i < res.size(); ++i) {
  2176. // printf("%d: %s[%zu]\n",i, res[i].c_str(),res[i].size());
  2177. // }
  2178. return true;
  2179. }
  2180. bool Navigation::LoadSpaceNo2CarrierNo() {
  2181. std::string file_name = "../config/SpaceNO2CarrarierNO.txt";
  2182. std::ifstream in(file_name);
  2183. std::string line;
  2184. std::vector<std::string> data_in_one_line;
  2185. if (in) {
  2186. int space_id, region_id, carrier_no;
  2187. while (std::getline(in, line)) {
  2188. if (!Stringsplit(line, " ", data_in_one_line) || line.find("//") != std::string::npos)
  2189. continue;
  2190. if (data_in_one_line.size() == 3) {
  2191. space_id = std::stoi(data_in_one_line[0]);
  2192. region_id = std::stoi(data_in_one_line[1]);
  2193. carrier_no = std::stoi(data_in_one_line[2]);
  2194. spaceNo_2_region_carrier_excel_[space_id] = Region_Carry(region_id, carrier_no);
  2195. }
  2196. }
  2197. //打印
  2198. for (auto &i: spaceNo_2_region_carrier_excel_) {
  2199. printf("space_id: %d, region_id: %d, carrier_no: %d\n", i.first, i.second.first, i.second.second);
  2200. }
  2201. return true;
  2202. } else {
  2203. printf("no SpaceNO2CarrarierNO.txt in config!\n");
  2204. }
  2205. return false;
  2206. }
  2207. bool Navigation::SpaceNo2CarrierNo(int space_no, int &region_id, int &carrier_no) {
  2208. Region_Carry region_carry = spaceNo_2_region_carrier_excel_[space_no];
  2209. region_id = region_carry.first;
  2210. carrier_no = region_carry.second;
  2211. return true;
  2212. }
  2213. Navigation::CarrierStatu Navigation::GetCarrierStatusBySpaceID(int space_id) {
  2214. int region_id;
  2215. int carrier_no;
  2216. if (SpaceNo2CarrierNo(space_id, region_id, carrier_no) == false) {
  2217. printf("no matched carrier!\n");
  2218. return eCarrierInvalid;
  2219. }
  2220. printf("space_id:%d, region_id:%d, carrier_no:%d\n", space_id, region_id, carrier_no);
  2221. if (timed_Carrier_[region_id].timeout()) {
  2222. printf("carrier status is timeout!\n");
  2223. return eCarrierInvalid;
  2224. } else {
  2225. return timed_Carrier_[region_id].Get()[carrier_no];
  2226. }
  2227. return eCarrierInvalid;
  2228. }
  2229. int Navigation::GetPortIDBySpace(NavMessage::PathNode node) {
  2230. int port_id = GetSpaceId(node);
  2231. if (port_id == 1101) {
  2232. return 1;
  2233. } else if (port_id == 1102) {
  2234. return 2;
  2235. }
  2236. return -1;
  2237. }
  2238. int Navigation::GetRemainActionsCount() {
  2239. return newUnfinished_cations_.size();
  2240. }
  2241. NavMessage::NewAction Navigation::GetCurrentAction() {
  2242. return newUnfinished_cations_.front();
  2243. }
  2244. NavMessage::NewAction Navigation::GetLastAction() {
  2245. return newUnfinished_cations_.back();
  2246. }
  2247. int Navigation::GetSequenceType() {
  2248. if (global_navCmd_.has_sequence()){
  2249. return eSequenceDefault;
  2250. }
  2251. else{
  2252. return global_navCmd_.sequence();
  2253. }
  2254. }