navigation.cpp 90 KB

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