navigation.cpp 85 KB

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