navigation.cpp 87 KB

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