navigation.cpp 90 KB

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