navigation.cpp 96 KB

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