navigation.cpp 87 KB

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