navigation.cpp 90 KB

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