GCS_Common.cpp 150 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797
  1. /*
  2. Common GCS MAVLink functions for all vehicle types
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. #include "GCS.h"
  15. #include <AP_AHRS/AP_AHRS.h>
  16. #include <AP_HAL/AP_HAL.h>
  17. #include <AP_Arming/AP_Arming.h>
  18. #include <AP_InternalError/AP_InternalError.h>
  19. #include <AP_Logger/AP_Logger.h>
  20. #include <AP_OpticalFlow/AP_OpticalFlow.h>
  21. #include <AP_Vehicle/AP_Vehicle.h>
  22. #include <AP_RangeFinder/RangeFinder_Backend.h>
  23. #include <AP_Airspeed/AP_Airspeed.h>
  24. #include <AP_Camera/AP_Camera.h>
  25. #include <AP_Gripper/AP_Gripper.h>
  26. #include <AP_BLHeli/AP_BLHeli.h>
  27. #include <AP_RSSI/AP_RSSI.h>
  28. #include <AP_RTC/AP_RTC.h>
  29. #include <AP_Scheduler/AP_Scheduler.h>
  30. #include <AP_SerialManager/AP_SerialManager.h>
  31. #include <AP_Mount/AP_Mount.h>
  32. #include <AP_Common/AP_FWVersion.h>
  33. #include <AP_VisualOdom/AP_VisualOdom.h>
  34. #include <AP_OpticalFlow/OpticalFlow.h>
  35. #include <AP_Baro/AP_Baro.h>
  36. #include <stdio.h>
  37. #if HAL_RCINPUT_WITH_AP_RADIO
  38. #include <AP_Radio/AP_Radio.h>
  39. #include <AP_BoardConfig/AP_BoardConfig.h>
  40. #endif
  41. #if CONFIG_HAL_BOARD == HAL_BOARD_SITL
  42. #include <SITL/SITL.h>
  43. #endif
  44. #if HAL_WITH_UAVCAN
  45. #include <AP_BoardConfig/AP_BoardConfig_CAN.h>
  46. #include <AP_Common/AP_Common.h>
  47. // To be replaced with macro saying if KDECAN library is included
  48. #if APM_BUILD_TYPE(APM_BUILD_ArduCopter) || APM_BUILD_TYPE(APM_BUILD_ArduPlane) || APM_BUILD_TYPE(APM_BUILD_ArduSub)
  49. #include <AP_KDECAN/AP_KDECAN.h>
  50. #endif
  51. #include <AP_ToshibaCAN/AP_ToshibaCAN.h>
  52. #endif
  53. #include <AP_BattMonitor/AP_BattMonitor.h>
  54. #include <AP_GPS/AP_GPS.h>
  55. #include <AP_UAVCAN/AP_UAVCAN.h>
  56. #include "../../ArduSub/Sub.h"
  57. extern const AP_HAL::HAL& hal;
  58. uint32_t GCS_MAVLINK::last_radio_status_remrssi_ms;
  59. uint8_t GCS_MAVLINK::mavlink_active = 0;
  60. uint8_t GCS_MAVLINK::chan_is_streaming = 0;
  61. uint32_t GCS_MAVLINK::reserve_param_space_start_ms;
  62. // private channels are ones used for point-to-point protocols, and
  63. // don't get broadcasts or fwded packets
  64. uint8_t GCS_MAVLINK::mavlink_private = 0;
  65. GCS *GCS::_singleton = nullptr;
  66. GCS_MAVLINK::GCS_MAVLINK(GCS_MAVLINK_Parameters &parameters,
  67. AP_HAL::UARTDriver &uart)
  68. {
  69. _port = &uart;
  70. streamRates = parameters.streamRates;
  71. }
  72. bool GCS_MAVLINK::init(uint8_t instance)
  73. {
  74. // search for serial port
  75. const AP_SerialManager& serial_manager = AP::serialmanager();
  76. const AP_SerialManager::SerialProtocol protocol = AP_SerialManager::SerialProtocol_MAVLink;
  77. // get associated mavlink channel
  78. if (!serial_manager.get_mavlink_channel(protocol, instance, chan)) {
  79. // return immediately in unlikely case mavlink channel cannot be found
  80. return false;
  81. }
  82. // and init the gcs instance
  83. if (!valid_channel(chan)) {
  84. return false;
  85. }
  86. /*
  87. Now try to cope with SiK radios that may be stuck in bootloader
  88. mode because CTS was held while powering on. This tells the
  89. bootloader to wait for a firmware. It affects any SiK radio with
  90. CTS connected that is externally powered. To cope we send 0x30
  91. 0x20 at 115200 on startup, which tells the bootloader to reset
  92. and boot normally
  93. */
  94. _port->begin(115200);
  95. AP_HAL::UARTDriver::flow_control old_flow_control = _port->get_flow_control();
  96. _port->set_flow_control(AP_HAL::UARTDriver::FLOW_CONTROL_DISABLE);
  97. for (uint8_t i=0; i<3; i++) {
  98. hal.scheduler->delay(1);
  99. _port->write(0x30);
  100. _port->write(0x20);
  101. }
  102. // since tcdrain() and TCSADRAIN may not be implemented...
  103. hal.scheduler->delay(1);
  104. _port->set_flow_control(old_flow_control);
  105. // now change back to desired baudrate
  106. _port->begin(serial_manager.find_baudrate(protocol, instance));
  107. mavlink_comm_port[chan] = _port;
  108. // create performance counters
  109. snprintf(_perf_packet_name, sizeof(_perf_packet_name), "GCS_Packet_%u", chan);
  110. _perf_packet = hal.util->perf_alloc(AP_HAL::Util::PC_ELAPSED, _perf_packet_name);
  111. snprintf(_perf_update_name, sizeof(_perf_update_name), "GCS_Update_%u", chan);
  112. _perf_update = hal.util->perf_alloc(AP_HAL::Util::PC_ELAPSED, _perf_update_name);
  113. AP_SerialManager::SerialProtocol mavlink_protocol = serial_manager.get_mavlink_protocol(chan);
  114. mavlink_status_t *status = mavlink_get_channel_status(chan);
  115. if (status == nullptr) {
  116. return false;
  117. }
  118. if (mavlink_protocol == AP_SerialManager::SerialProtocol_MAVLink2) {
  119. // load signing key
  120. load_signing_key();
  121. if (status->signing == nullptr) {
  122. // if signing is off start by sending MAVLink1.
  123. status->flags |= MAVLINK_STATUS_FLAG_OUT_MAVLINK1;
  124. }
  125. } else if (status) {
  126. // user has asked to only send MAVLink1
  127. status->flags |= MAVLINK_STATUS_FLAG_OUT_MAVLINK1;
  128. }
  129. if (chan == MAVLINK_COMM_0) {
  130. // Always start with MAVLink1 on first port for now, to allow for recovery
  131. // after experiments with MAVLink2
  132. status->flags |= MAVLINK_STATUS_FLAG_OUT_MAVLINK1;
  133. }
  134. return true;
  135. }
  136. void GCS_MAVLINK::send_meminfo(void)
  137. {
  138. unsigned __brkval = 0;
  139. uint32_t memory = hal.util->available_memory();
  140. mavlink_msg_meminfo_send(chan, __brkval, MIN(memory, 0xFFFFU), memory);
  141. }
  142. // report power supply status
  143. void GCS_MAVLINK::send_power_status(void)
  144. {
  145. if (!gcs().vehicle_initialised()) {
  146. // avoid unnecessary errors being reported to user
  147. return;
  148. }
  149. mavlink_msg_power_status_send(chan,
  150. hal.analogin->board_voltage() * 1000,
  151. hal.analogin->servorail_voltage() * 1000,
  152. hal.analogin->power_status_flags());
  153. }
  154. void GCS_MAVLINK::send_battery_status(const uint8_t instance) const
  155. {
  156. // catch the battery backend not supporting the required number of cells
  157. static_assert(sizeof(AP_BattMonitor::cells) >= (sizeof(uint16_t) * MAVLINK_MSG_BATTERY_STATUS_FIELD_VOLTAGES_LEN),
  158. "Not enough battery cells for the MAVLink message");
  159. const AP_BattMonitor &battery = AP::battery();
  160. float temp;
  161. bool got_temperature = battery.get_temperature(temp, instance);
  162. // ensure we always send a voltage estimate to the GCS, because not all battery monitors monitor individual cells
  163. // as a work around for this we create a set of fake cells to be used if the backend doesn't provide direct monitoring
  164. // the GCS can then recover the pack voltage by summing all non ignored cell values. Because this is looped we can
  165. // report a pack up to 655.34 V with this method
  166. AP_BattMonitor::cells fake_cells;
  167. if (!battery.has_cell_voltages(instance)) {
  168. float voltage = battery.voltage(instance) * 1e3f;
  169. for (uint8_t i = 0; i < MAVLINK_MSG_BATTERY_STATUS_FIELD_VOLTAGES_LEN; i++) {
  170. if (voltage < 0.001f) {
  171. // too small to send to the GCS, set it to the no cell value
  172. fake_cells.cells[i] = UINT16_MAX;
  173. } else {
  174. fake_cells.cells[i] = MIN(voltage, 65534.0f); // Can't send more then UINT16_MAX - 1 in a cell
  175. voltage -= 65534.0f;
  176. }
  177. }
  178. }
  179. float current, consumed_mah, consumed_wh;
  180. if (battery.current_amps(current, instance)) {
  181. current *= 100;
  182. } else {
  183. current = -1;
  184. }
  185. if (!battery.consumed_mah(consumed_mah, instance)) {
  186. consumed_mah = -1;
  187. }
  188. if (battery.consumed_wh(consumed_wh, instance)) {
  189. consumed_wh *= 36;
  190. } else {
  191. consumed_wh = -1;
  192. }
  193. mavlink_msg_battery_status_send(chan,
  194. instance, // id
  195. MAV_BATTERY_FUNCTION_UNKNOWN, // function
  196. MAV_BATTERY_TYPE_UNKNOWN, // type
  197. got_temperature ? ((int16_t) (temp * 100)) : INT16_MAX, // temperature. INT16_MAX if unknown
  198. battery.has_cell_voltages(instance) ? battery.get_cell_voltages(instance).cells : fake_cells.cells, // cell voltages
  199. current, // current in centiampere
  200. consumed_mah, // total consumed current in milliampere.hour
  201. consumed_wh, // consumed energy in hJ (hecto-Joules)
  202. get_battery_remaining_percentage(instance),
  203. 0, // time remaining, seconds (not provided)
  204. MAV_BATTERY_CHARGE_STATE_UNDEFINED);
  205. }
  206. // returns true if all battery instances were reported
  207. bool GCS_MAVLINK::send_battery_status() const
  208. {
  209. const AP_BattMonitor &battery = AP::battery();
  210. for(uint8_t i = 0; i < battery.num_instances(); i++) {
  211. if (battery.get_type(i) != AP_BattMonitor_Params::BattMonitor_Type::BattMonitor_TYPE_NONE) {
  212. CHECK_PAYLOAD_SIZE(BATTERY_STATUS);
  213. send_battery_status(i);
  214. }
  215. }
  216. return true;
  217. }
  218. void GCS_MAVLINK::send_distance_sensor(const AP_RangeFinder_Backend *sensor, const uint8_t instance) const
  219. {
  220. if (!sensor->has_data()) {
  221. return;
  222. }
  223. mavlink_msg_distance_sensor_send(
  224. chan,
  225. AP_HAL::millis(), // time since system boot TODO: take time of measurement
  226. sensor->min_distance_cm(), // minimum distance the sensor can measure in centimeters
  227. sensor->max_distance_cm(), // maximum distance the sensor can measure in centimeters
  228. sensor->distance_cm(), // current distance reading
  229. sensor->get_mav_distance_sensor_type(), // type from MAV_DISTANCE_SENSOR enum
  230. instance, // onboard ID of the sensor == instance
  231. sensor->orientation(), // direction the sensor faces from MAV_SENSOR_ORIENTATION enum
  232. 0, // Measurement covariance in centimeters, 0 for unknown / invalid readings
  233. 0, // horizontal FOV
  234. 0, // vertical FOV
  235. (const float *)nullptr); // quaternion of sensor orientation for MAV_SENSOR_ROTATION_CUSTOM
  236. }
  237. // send any and all distance_sensor messages. This starts by sending
  238. // any distance sensors not used by a Proximity sensor, then sends the
  239. // proximity sensor ones.
  240. void GCS_MAVLINK::send_distance_sensor() const
  241. {
  242. RangeFinder *rangefinder = RangeFinder::get_singleton();
  243. if (rangefinder == nullptr) {
  244. return;
  245. }
  246. // if we have a proximity backend that utilizes rangefinders cull
  247. // sending them here, and allow the later proximity code to manage
  248. // them
  249. bool filter_possible_proximity_sensors = false;
  250. AP_Proximity *proximity = AP_Proximity::get_singleton();
  251. if (proximity != nullptr) {
  252. for (uint8_t i = 0; i < proximity->num_sensors(); i++) {
  253. if (proximity->get_type(i) == AP_Proximity::Proximity_Type_RangeFinder) {
  254. filter_possible_proximity_sensors = true;
  255. }
  256. }
  257. }
  258. for (uint8_t i = 0; i < RANGEFINDER_MAX_INSTANCES; i++) {
  259. if (!HAVE_PAYLOAD_SPACE(chan, DISTANCE_SENSOR)) {
  260. return;
  261. }
  262. AP_RangeFinder_Backend *sensor = rangefinder->get_backend(i);
  263. if (sensor == nullptr) {
  264. continue;
  265. }
  266. enum Rotation orient = sensor->orientation();
  267. if (!filter_possible_proximity_sensors ||
  268. (orient > ROTATION_YAW_315 && orient != ROTATION_PITCH_90)) {
  269. send_distance_sensor(sensor, i);
  270. }
  271. }
  272. send_proximity();
  273. }
  274. void GCS_MAVLINK::send_rangefinder() const
  275. {
  276. RangeFinder *rangefinder = RangeFinder::get_singleton();
  277. if (rangefinder == nullptr) {
  278. return;
  279. }
  280. AP_RangeFinder_Backend *s = rangefinder->find_instance(ROTATION_PITCH_270);
  281. if (s == nullptr) {
  282. return;
  283. }
  284. mavlink_msg_rangefinder_send(
  285. chan,
  286. s->distance_cm() * 0.01f,
  287. s->voltage_mv() * 0.001f);
  288. }
  289. void GCS_MAVLINK::send_proximity() const
  290. {
  291. AP_Proximity *proximity = AP_Proximity::get_singleton();
  292. if (proximity == nullptr || proximity->get_status() == AP_Proximity::Proximity_NotConnected) {
  293. return; // this is wrong, but pretend we sent data and don't requeue
  294. }
  295. const uint16_t dist_min = (uint16_t)(proximity->distance_min() * 100.0f); // minimum distance the sensor can measure in centimeters
  296. const uint16_t dist_max = (uint16_t)(proximity->distance_max() * 100.0f); // maximum distance the sensor can measure in centimeters
  297. // send horizontal distances
  298. AP_Proximity::Proximity_Distance_Array dist_array;
  299. if (proximity->get_horizontal_distances(dist_array)) {
  300. for (uint8_t i = 0; i < PROXIMITY_MAX_DIRECTION; i++) {
  301. if (!HAVE_PAYLOAD_SPACE(chan, DISTANCE_SENSOR)) {
  302. return;
  303. }
  304. mavlink_msg_distance_sensor_send(
  305. chan,
  306. AP_HAL::millis(), // time since system boot
  307. dist_min, // minimum distance the sensor can measure in centimeters
  308. dist_max, // maximum distance the sensor can measure in centimeters
  309. (uint16_t)(dist_array.distance[i] * 100.0f), // current distance reading
  310. MAV_DISTANCE_SENSOR_LASER, // type from MAV_DISTANCE_SENSOR enum
  311. PROXIMITY_SENSOR_ID_START + i, // onboard ID of the sensor
  312. dist_array.orientation[i], // direction the sensor faces from MAV_SENSOR_ORIENTATION enum
  313. 0, // Measurement covariance in centimeters, 0 for unknown / invalid readings
  314. 0, 0, nullptr);
  315. }
  316. }
  317. // send upward distance
  318. float dist_up;
  319. if (proximity->get_upward_distance(dist_up)) {
  320. if (!HAVE_PAYLOAD_SPACE(chan, DISTANCE_SENSOR)) {
  321. return;
  322. }
  323. mavlink_msg_distance_sensor_send(
  324. chan,
  325. AP_HAL::millis(), // time since system boot
  326. dist_min, // minimum distance the sensor can measure in centimeters
  327. dist_max, // maximum distance the sensor can measure in centimeters
  328. (uint16_t)(dist_up * 100.0f), // current distance reading
  329. MAV_DISTANCE_SENSOR_LASER, // type from MAV_DISTANCE_SENSOR enum
  330. PROXIMITY_SENSOR_ID_START + PROXIMITY_MAX_DIRECTION + 1, // onboard ID of the sensor
  331. MAV_SENSOR_ROTATION_PITCH_90, // direction upwards
  332. 0, // Measurement covariance in centimeters, 0 for unknown / invalid readings
  333. 0, 0, nullptr);
  334. }
  335. }
  336. // report AHRS2 state
  337. void GCS_MAVLINK::send_ahrs2()
  338. {
  339. #if AP_AHRS_NAVEKF_AVAILABLE
  340. const AP_AHRS &ahrs = AP::ahrs();
  341. Vector3f euler;
  342. struct Location loc {};
  343. if (ahrs.get_secondary_attitude(euler) ||
  344. ahrs.get_secondary_position(loc)) {
  345. mavlink_msg_ahrs2_send(chan,
  346. euler.x,
  347. euler.y,
  348. euler.z,
  349. loc.alt*1.0e-2f,
  350. loc.lat,
  351. loc.lng);
  352. }
  353. #endif
  354. }
  355. void GCS_MAVLINK::send_ahrs3()
  356. {
  357. #if AP_AHRS_NAVEKF_AVAILABLE
  358. const NavEKF2 &ekf2 = AP::ahrs_navekf().get_NavEKF2_const();
  359. if (ekf2.activeCores() > 0 &&
  360. HAVE_PAYLOAD_SPACE(chan, AHRS3)) {
  361. struct Location loc {};
  362. ekf2.getLLH(loc);
  363. Vector3f euler;
  364. ekf2.getEulerAngles(-1,euler);
  365. mavlink_msg_ahrs3_send(chan,
  366. euler.x,
  367. euler.y,
  368. euler.z,
  369. loc.alt*1.0e-2f,
  370. loc.lat,
  371. loc.lng,
  372. 0, 0, 0, 0);
  373. }
  374. #endif
  375. }
  376. MissionItemProtocol *GCS::get_prot_for_mission_type(const MAV_MISSION_TYPE mission_type) const
  377. {
  378. switch (mission_type) {
  379. case MAV_MISSION_TYPE_MISSION:
  380. return _missionitemprotocol_waypoints;
  381. case MAV_MISSION_TYPE_RALLY:
  382. return _missionitemprotocol_rally;
  383. default:
  384. return nullptr;
  385. }
  386. }
  387. // handle a request for the number of items we have stored for a mission type:
  388. void GCS_MAVLINK::handle_mission_request_list(const mavlink_message_t &msg)
  389. {
  390. // decode
  391. mavlink_mission_request_list_t packet;
  392. mavlink_msg_mission_request_list_decode(&msg, &packet);
  393. MissionItemProtocol *prot = gcs().get_prot_for_mission_type((MAV_MISSION_TYPE)packet.mission_type);
  394. if (prot == nullptr) {
  395. mavlink_msg_mission_ack_send(chan,
  396. msg.sysid,
  397. msg.compid,
  398. MAV_MISSION_UNSUPPORTED,
  399. packet.mission_type);
  400. return;
  401. }
  402. prot->handle_mission_request_list(*this, packet, msg);
  403. }
  404. /*
  405. handle a MISSION_REQUEST mavlink packet
  406. */
  407. void GCS_MAVLINK::handle_mission_request_int(const mavlink_message_t &msg)
  408. {
  409. // decode
  410. mavlink_mission_request_int_t packet;
  411. mavlink_msg_mission_request_int_decode(&msg, &packet);
  412. MissionItemProtocol *prot = gcs().get_prot_for_mission_type((MAV_MISSION_TYPE)packet.mission_type);
  413. if (prot == nullptr) {
  414. return;
  415. }
  416. prot->handle_mission_request_int(*this, packet, msg);
  417. }
  418. void GCS_MAVLINK::handle_mission_request(const mavlink_message_t &msg)
  419. {
  420. // decode
  421. mavlink_mission_request_t packet;
  422. mavlink_msg_mission_request_decode(&msg, &packet);
  423. MissionItemProtocol *prot = gcs().get_prot_for_mission_type((MAV_MISSION_TYPE)packet.mission_type);
  424. if (prot == nullptr) {
  425. return;
  426. }
  427. prot->handle_mission_request(*this, packet, msg);
  428. }
  429. /*
  430. handle a MISSION_SET_CURRENT mavlink packet
  431. */
  432. void GCS_MAVLINK::handle_mission_set_current(AP_Mission &mission, const mavlink_message_t &msg)
  433. {
  434. // decode
  435. mavlink_mission_set_current_t packet;
  436. mavlink_msg_mission_set_current_decode(&msg, &packet);
  437. // set current command
  438. if (mission.set_current_cmd(packet.seq)) {
  439. mavlink_msg_mission_current_send(chan, packet.seq);
  440. }
  441. }
  442. /*
  443. handle a MISSION_COUNT mavlink packet
  444. */
  445. void GCS_MAVLINK::handle_mission_count(const mavlink_message_t &msg)
  446. {
  447. // decode
  448. mavlink_mission_count_t packet;
  449. mavlink_msg_mission_count_decode(&msg, &packet);
  450. MissionItemProtocol *prot = gcs().get_prot_for_mission_type((MAV_MISSION_TYPE)packet.mission_type);
  451. if (prot == nullptr) {
  452. mavlink_msg_mission_ack_send(chan,
  453. msg.sysid,
  454. msg.compid,
  455. MAV_MISSION_UNSUPPORTED,
  456. packet.mission_type);
  457. return;
  458. }
  459. prot->handle_mission_count(*this, packet, msg);
  460. }
  461. /*
  462. handle a MISSION_CLEAR_ALL mavlink packet
  463. */
  464. void GCS_MAVLINK::handle_mission_clear_all(const mavlink_message_t &msg)
  465. {
  466. // decode
  467. mavlink_mission_clear_all_t packet;
  468. mavlink_msg_mission_clear_all_decode(&msg, &packet);
  469. const MAV_MISSION_TYPE mission_type = (MAV_MISSION_TYPE)packet.mission_type;
  470. MissionItemProtocol *prot = gcs().get_prot_for_mission_type(mission_type);
  471. if (prot == nullptr) {
  472. send_mission_ack(msg, mission_type, MAV_MISSION_UNSUPPORTED);
  473. return;
  474. }
  475. prot->handle_mission_clear_all(*this, msg);
  476. }
  477. bool GCS_MAVLINK::requesting_mission_items() const
  478. {
  479. for (uint8_t i=0; i<ARRAY_SIZE(supported_mission_types); i++) {
  480. MissionItemProtocol *prot = gcs().get_prot_for_mission_type(supported_mission_types[i]);
  481. if (prot && prot->receiving && prot->active_link_is(this)) {
  482. return true;
  483. }
  484. }
  485. return false;
  486. }
  487. void GCS_MAVLINK::handle_mission_write_partial_list(const mavlink_message_t &msg)
  488. {
  489. // decode
  490. mavlink_mission_write_partial_list_t packet;
  491. mavlink_msg_mission_write_partial_list_decode(&msg, &packet);
  492. MissionItemProtocol *use_prot = gcs().get_prot_for_mission_type((MAV_MISSION_TYPE)packet.mission_type);
  493. if (use_prot == nullptr) {
  494. send_mission_ack(msg, (MAV_MISSION_TYPE)packet.mission_type, MAV_MISSION_UNSUPPORTED);
  495. return;
  496. }
  497. use_prot->handle_mission_write_partial_list(*this, msg, packet);
  498. }
  499. /*
  500. pass mavlink messages to the AP_Mount singleton
  501. */
  502. void GCS_MAVLINK::handle_mount_message(const mavlink_message_t &msg)
  503. {
  504. AP_Mount *mount = AP::mount();
  505. if (mount == nullptr) {
  506. return;
  507. }
  508. mount->handle_message(chan, msg);
  509. }
  510. /*
  511. pass parameter value messages through to mount library
  512. */
  513. void GCS_MAVLINK::handle_param_value(const mavlink_message_t &msg)
  514. {
  515. AP_Mount *mount = AP::mount();
  516. if (mount == nullptr) {
  517. return;
  518. }
  519. mount->handle_param_value(msg);
  520. }
  521. void GCS_MAVLINK::send_text(MAV_SEVERITY severity, const char *fmt, ...) const
  522. {
  523. char text[MAVLINK_MSG_STATUSTEXT_FIELD_TEXT_LEN+1];
  524. va_list arg_list;
  525. va_start(arg_list, fmt);
  526. hal.util->vsnprintf(text, sizeof(text), fmt, arg_list);
  527. va_end(arg_list);
  528. gcs().send_statustext(severity, (1<<chan), text);
  529. }
  530. void GCS_MAVLINK::handle_radio_status(const mavlink_message_t &msg, bool log_radio)
  531. {
  532. mavlink_radio_t packet;
  533. mavlink_msg_radio_decode(&msg, &packet);
  534. // record if the GCS has been receiving radio messages from
  535. // the aircraft
  536. if (packet.remrssi != 0) {
  537. last_radio_status_remrssi_ms = AP_HAL::millis();
  538. }
  539. // use the state of the transmit buffer in the radio to
  540. // control the stream rate, giving us adaptive software
  541. // flow control
  542. if (packet.txbuf < 20 && stream_slowdown_ms < 2000) {
  543. // we are very low on space - slow down a lot
  544. stream_slowdown_ms += 60;
  545. } else if (packet.txbuf < 50 && stream_slowdown_ms < 2000) {
  546. // we are a bit low on space, slow down slightly
  547. stream_slowdown_ms += 20;
  548. } else if (packet.txbuf > 95 && stream_slowdown_ms > 200) {
  549. // the buffer has plenty of space, speed up a lot
  550. stream_slowdown_ms -= 40;
  551. } else if (packet.txbuf > 90 && stream_slowdown_ms != 0) {
  552. // the buffer has enough space, speed up a bit
  553. stream_slowdown_ms -= 20;
  554. }
  555. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  556. if (stream_slowdown_ms > max_slowdown_ms) {
  557. max_slowdown_ms = stream_slowdown_ms;
  558. }
  559. #endif
  560. //log rssi, noise, etc if logging Performance monitoring data
  561. if (log_radio) {
  562. AP::logger().Write_Radio(packet);
  563. }
  564. }
  565. /*
  566. handle an incoming mission item
  567. return true if this is the last mission item, otherwise false
  568. */
  569. void GCS_MAVLINK::handle_mission_item(const mavlink_message_t &msg)
  570. {
  571. // TODO: rename packet to mission_item_int
  572. mavlink_mission_item_int_t packet;
  573. if (msg.msgid == MAVLINK_MSG_ID_MISSION_ITEM) {
  574. mavlink_mission_item_t mission_item;
  575. mavlink_msg_mission_item_decode(&msg, &mission_item);
  576. MAV_MISSION_RESULT ret = AP_Mission::convert_MISSION_ITEM_to_MISSION_ITEM_INT(mission_item, packet);
  577. if (ret != MAV_MISSION_ACCEPTED) {
  578. const MAV_MISSION_TYPE type = (MAV_MISSION_TYPE)packet.mission_type;
  579. send_mission_ack(msg, type, ret);
  580. return;
  581. }
  582. } else {
  583. mavlink_msg_mission_item_int_decode(&msg, &packet);
  584. }
  585. const uint8_t current = packet.current;
  586. const MAV_MISSION_TYPE type = (MAV_MISSION_TYPE)packet.mission_type;
  587. if (type == MAV_MISSION_TYPE_MISSION && (current == 2 || current == 3)) {
  588. struct AP_Mission::Mission_Command cmd = {};
  589. MAV_MISSION_RESULT result = AP_Mission::mavlink_int_to_mission_cmd(packet, cmd);
  590. if (result != MAV_MISSION_ACCEPTED) {
  591. //decode failed
  592. send_mission_ack(msg, MAV_MISSION_TYPE_MISSION, result);
  593. return;
  594. }
  595. // guided or change-alt
  596. if (current == 2) {
  597. // current = 2 is a flag to tell us this is a "guided mode"
  598. // waypoint and not for the mission
  599. result = (handle_guided_request(cmd) ? MAV_MISSION_ACCEPTED
  600. : MAV_MISSION_ERROR) ;
  601. } else if (current == 3) {
  602. //current = 3 is a flag to tell us this is a alt change only
  603. // add home alt if needed
  604. handle_change_alt_request(cmd);
  605. // verify we recevied the command
  606. result = MAV_MISSION_ACCEPTED;
  607. }
  608. send_mission_ack(msg, MAV_MISSION_TYPE_MISSION, result);
  609. return;
  610. }
  611. // not a guided-mode reqest
  612. MissionItemProtocol *prot = gcs().get_prot_for_mission_type(type);
  613. if (prot == nullptr) {
  614. send_mission_ack(msg, type, MAV_MISSION_UNSUPPORTED);
  615. return;
  616. }
  617. if (!prot->receiving) {
  618. send_mission_ack(msg, type, MAV_MISSION_ERROR);
  619. return;
  620. }
  621. prot->handle_mission_item(msg, packet);
  622. }
  623. ap_message GCS_MAVLINK::mavlink_id_to_ap_message_id(const uint32_t mavlink_id) const
  624. {
  625. // MSG_NEXT_MISSION_REQUEST doesn't correspond to a mavlink message directly.
  626. // It is used to request the next waypoint after receiving one.
  627. // MSG_NEXT_PARAM doesn't correspond to a mavlink message directly.
  628. // It is used to send the next parameter in a stream after sending one
  629. // MSG_NAMED_FLOAT messages can't really be "streamed"...
  630. static const struct {
  631. uint32_t mavlink_id;
  632. ap_message msg_id;
  633. } map[] {
  634. { MAVLINK_MSG_ID_HEARTBEAT, MSG_HEARTBEAT},
  635. { MAVLINK_MSG_ID_ATTITUDE, MSG_ATTITUDE},
  636. { MAVLINK_MSG_ID_GLOBAL_POSITION_INT, MSG_LOCATION},
  637. { MAVLINK_MSG_ID_HOME_POSITION, MSG_HOME},
  638. { MAVLINK_MSG_ID_GPS_GLOBAL_ORIGIN, MSG_ORIGIN},
  639. { MAVLINK_MSG_ID_SYS_STATUS, MSG_SYS_STATUS},
  640. { MAVLINK_MSG_ID_POWER_STATUS, MSG_POWER_STATUS},
  641. { MAVLINK_MSG_ID_MEMINFO, MSG_MEMINFO},
  642. { MAVLINK_MSG_ID_NAV_CONTROLLER_OUTPUT, MSG_NAV_CONTROLLER_OUTPUT},
  643. { MAVLINK_MSG_ID_MISSION_CURRENT, MSG_CURRENT_WAYPOINT},
  644. { MAVLINK_MSG_ID_VFR_HUD, MSG_VFR_HUD},
  645. { MAVLINK_MSG_ID_SERVO_OUTPUT_RAW, MSG_SERVO_OUTPUT_RAW},
  646. { MAVLINK_MSG_ID_RC_CHANNELS, MSG_RC_CHANNELS},
  647. { MAVLINK_MSG_ID_RC_CHANNELS_RAW, MSG_RC_CHANNELS_RAW},
  648. { MAVLINK_MSG_ID_RAW_IMU, MSG_RAW_IMU},
  649. { MAVLINK_MSG_ID_SCALED_IMU, MSG_SCALED_IMU},
  650. { MAVLINK_MSG_ID_SCALED_IMU2, MSG_SCALED_IMU2},
  651. { MAVLINK_MSG_ID_SCALED_IMU3, MSG_SCALED_IMU3},
  652. { MAVLINK_MSG_ID_SCALED_PRESSURE, MSG_SCALED_PRESSURE},
  653. { MAVLINK_MSG_ID_SCALED_PRESSURE2, MSG_SCALED_PRESSURE2},
  654. { MAVLINK_MSG_ID_SCALED_PRESSURE3, MSG_SCALED_PRESSURE3},
  655. { MAVLINK_MSG_ID_SENSOR_OFFSETS, MSG_SENSOR_OFFSETS},
  656. { MAVLINK_MSG_ID_GPS_RAW_INT, MSG_GPS_RAW},
  657. { MAVLINK_MSG_ID_GPS_RTK, MSG_GPS_RTK},
  658. { MAVLINK_MSG_ID_GPS2_RAW, MSG_GPS2_RAW},
  659. { MAVLINK_MSG_ID_GPS2_RTK, MSG_GPS2_RTK},
  660. { MAVLINK_MSG_ID_SYSTEM_TIME, MSG_SYSTEM_TIME},
  661. { MAVLINK_MSG_ID_RC_CHANNELS_SCALED, MSG_SERVO_OUT},
  662. { MAVLINK_MSG_ID_PARAM_VALUE, MSG_NEXT_PARAM},
  663. { MAVLINK_MSG_ID_FENCE_STATUS, MSG_FENCE_STATUS},
  664. { MAVLINK_MSG_ID_AHRS, MSG_AHRS},
  665. { MAVLINK_MSG_ID_SIMSTATE, MSG_SIMSTATE},
  666. { MAVLINK_MSG_ID_AHRS2, MSG_AHRS2},
  667. { MAVLINK_MSG_ID_AHRS3, MSG_AHRS3},
  668. { MAVLINK_MSG_ID_HWSTATUS, MSG_HWSTATUS},
  669. { MAVLINK_MSG_ID_WIND, MSG_WIND},
  670. { MAVLINK_MSG_ID_RANGEFINDER, MSG_RANGEFINDER},
  671. { MAVLINK_MSG_ID_DISTANCE_SENSOR, MSG_DISTANCE_SENSOR},
  672. // request also does report:
  673. { MAVLINK_MSG_ID_TERRAIN_REQUEST, MSG_TERRAIN},
  674. { MAVLINK_MSG_ID_BATTERY2, MSG_BATTERY2},
  675. { MAVLINK_MSG_ID_CAMERA_FEEDBACK, MSG_CAMERA_FEEDBACK},
  676. { MAVLINK_MSG_ID_MOUNT_STATUS, MSG_MOUNT_STATUS},
  677. { MAVLINK_MSG_ID_OPTICAL_FLOW, MSG_OPTICAL_FLOW},
  678. { MAVLINK_MSG_ID_GIMBAL_REPORT, MSG_GIMBAL_REPORT},
  679. { MAVLINK_MSG_ID_MAG_CAL_PROGRESS, MSG_MAG_CAL_PROGRESS},
  680. { MAVLINK_MSG_ID_MAG_CAL_REPORT, MSG_MAG_CAL_REPORT},
  681. { MAVLINK_MSG_ID_EKF_STATUS_REPORT, MSG_EKF_STATUS_REPORT},
  682. { MAVLINK_MSG_ID_LOCAL_POSITION_NED, MSG_LOCAL_POSITION},
  683. { MAVLINK_MSG_ID_PID_TUNING, MSG_PID_TUNING},
  684. { MAVLINK_MSG_ID_VIBRATION, MSG_VIBRATION},
  685. { MAVLINK_MSG_ID_RPM, MSG_RPM},
  686. { MAVLINK_MSG_ID_MISSION_ITEM_REACHED, MSG_MISSION_ITEM_REACHED},
  687. { MAVLINK_MSG_ID_POSITION_TARGET_GLOBAL_INT, MSG_POSITION_TARGET_GLOBAL_INT},
  688. { MAVLINK_MSG_ID_POSITION_TARGET_LOCAL_NED, MSG_POSITION_TARGET_LOCAL_NED},
  689. { MAVLINK_MSG_ID_ADSB_VEHICLE, MSG_ADSB_VEHICLE},
  690. { MAVLINK_MSG_ID_BATTERY_STATUS, MSG_BATTERY_STATUS},
  691. { MAVLINK_MSG_ID_AOA_SSA, MSG_AOA_SSA},
  692. { MAVLINK_MSG_ID_DEEPSTALL, MSG_LANDING},
  693. { MAVLINK_MSG_ID_EXTENDED_SYS_STATE, MSG_EXTENDED_SYS_STATE},
  694. { MAVLINK_MSG_ID_AUTOPILOT_VERSION, MSG_AUTOPILOT_VERSION},
  695. };
  696. for (uint8_t i=0; i<ARRAY_SIZE(map); i++) {
  697. if (map[i].mavlink_id == mavlink_id) {
  698. return map[i].msg_id;
  699. }
  700. }
  701. return MSG_LAST;
  702. }
  703. bool GCS_MAVLINK::set_mavlink_message_id_interval(const uint32_t mavlink_id,
  704. const uint16_t interval_ms)
  705. {
  706. const ap_message id = mavlink_id_to_ap_message_id(mavlink_id);
  707. if (id == MSG_LAST) {
  708. gcs().send_text(MAV_SEVERITY_INFO, "No ap_message for mavlink id (%u)", (unsigned int)mavlink_id);
  709. return false;
  710. }
  711. return set_ap_message_interval(id, interval_ms);
  712. }
  713. bool GCS_MAVLINK::should_send_message_in_delay_callback(const ap_message id) const
  714. {
  715. // No ID we return true for may take more than a few hundred
  716. // microseconds to return!
  717. if (id == MSG_HEARTBEAT || id == MSG_NEXT_PARAM) {
  718. return true;
  719. }
  720. if (in_hil_mode()) {
  721. // in HIL we need to keep sending servo values to ensure
  722. // the simulator doesn't pause, otherwise our sensor
  723. // calibration could stall
  724. if (id == MSG_SERVO_OUT ||
  725. id == MSG_SERVO_OUTPUT_RAW) {
  726. return true;
  727. }
  728. }
  729. return false;
  730. }
  731. uint16_t GCS_MAVLINK::get_reschedule_interval_ms(const deferred_message_bucket_t &deferred) const
  732. {
  733. uint32_t interval_ms = deferred.interval_ms;
  734. interval_ms += stream_slowdown_ms;
  735. // slow most messages down if we're transfering parameters or
  736. // waypoints:
  737. if (_queued_parameter) {
  738. // we are sending parameters, penalize streams:
  739. interval_ms *= 4;
  740. }
  741. if (requesting_mission_items()) {
  742. // we are sending requests for waypoints, penalize streams:
  743. interval_ms *= 4;
  744. }
  745. if (interval_ms > 60000) {
  746. return 60000;
  747. }
  748. return interval_ms;
  749. }
  750. // typical runtime on fmuv3: 5 microseconds for 3 buckets
  751. void GCS_MAVLINK::find_next_bucket_to_send()
  752. {
  753. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  754. void *data = hal.scheduler->disable_interrupts_save();
  755. uint32_t start_us = AP_HAL::micros();
  756. #endif
  757. const uint16_t now16_ms{AP_HAL::millis16()};
  758. // all done sending this bucket... find another bucket...
  759. sending_bucket_id = no_bucket_to_send;
  760. uint16_t ms_before_send_next_bucket_to_send = UINT16_MAX;
  761. for (uint8_t i=0; i<ARRAY_SIZE(deferred_message_bucket); i++) {
  762. if (deferred_message_bucket[i].ap_message_ids.count() == 0) {
  763. // no entries
  764. continue;
  765. }
  766. const uint16_t interval = get_reschedule_interval_ms(deferred_message_bucket[i]);
  767. const uint16_t ms_since_last_sent = now16_ms - deferred_message_bucket[i].last_sent_ms;
  768. uint16_t ms_before_send_this_bucket;
  769. if (ms_since_last_sent > interval) {
  770. // should already have sent this bucket!
  771. ms_before_send_this_bucket = 0;
  772. } else {
  773. ms_before_send_this_bucket = interval - ms_since_last_sent;
  774. }
  775. if (ms_before_send_this_bucket < ms_before_send_next_bucket_to_send) {
  776. sending_bucket_id = i;
  777. ms_before_send_next_bucket_to_send = ms_before_send_this_bucket;
  778. }
  779. }
  780. if (sending_bucket_id != no_bucket_to_send) {
  781. bucket_message_ids_to_send = deferred_message_bucket[sending_bucket_id].ap_message_ids;
  782. } else {
  783. bucket_message_ids_to_send.clearall();
  784. }
  785. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  786. uint32_t delta_us = AP_HAL::micros() - start_us;
  787. hal.scheduler->restore_interrupts(data);
  788. if (delta_us > try_send_message_stats.fnbts_maxtime) {
  789. try_send_message_stats.fnbts_maxtime = delta_us;
  790. }
  791. #endif
  792. }
  793. ap_message GCS_MAVLINK::next_deferred_bucket_message_to_send()
  794. {
  795. if (sending_bucket_id == no_bucket_to_send) {
  796. // could happen if all streamrates are zero?
  797. return no_message_to_send;
  798. }
  799. const uint16_t now16_ms = AP_HAL::millis16();
  800. const uint16_t ms_since_last_sent = now16_ms - deferred_message_bucket[sending_bucket_id].last_sent_ms;
  801. if (ms_since_last_sent < get_reschedule_interval_ms(deferred_message_bucket[sending_bucket_id])) {
  802. // not time to send this bucket
  803. return no_message_to_send;
  804. }
  805. const int16_t next = bucket_message_ids_to_send.first_set();
  806. if (next == -1) {
  807. // should not happen
  808. #if CONFIG_HAL_BOARD == HAL_BOARD_SITL
  809. AP_HAL::panic("next_deferred_bucket_message_to_send called on empty bucket");
  810. #endif
  811. find_next_bucket_to_send();
  812. return no_message_to_send;
  813. }
  814. return (ap_message)next;
  815. }
  816. // call try_send_message if appropriate. Incorporates debug code to
  817. // record how long it takes to send a message. try_send_message is
  818. // expected to be overridden, not this function.
  819. bool GCS_MAVLINK::do_try_send_message(const ap_message id)
  820. {
  821. const bool in_delay_callback = hal.scheduler->in_delay_callback();
  822. if (in_delay_callback && !should_send_message_in_delay_callback(id)) {
  823. return true;
  824. }
  825. if (telemetry_delayed()) {
  826. return false;
  827. }
  828. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  829. void *data = hal.scheduler->disable_interrupts_save();
  830. uint32_t start_send_message_us = AP_HAL::micros();
  831. #endif
  832. if (!try_send_message(id)) {
  833. // didn't fit in buffer...
  834. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  835. try_send_message_stats.no_space_for_message++;
  836. hal.scheduler->restore_interrupts(data);
  837. #endif
  838. return false;
  839. }
  840. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  841. const uint32_t delta_us = AP_HAL::micros() - start_send_message_us;
  842. hal.scheduler->restore_interrupts(data);
  843. if (delta_us > try_send_message_stats.longest_time_us) {
  844. try_send_message_stats.longest_time_us = delta_us;
  845. try_send_message_stats.longest_id = id;
  846. }
  847. #endif
  848. return true;
  849. }
  850. int8_t GCS_MAVLINK::get_deferred_message_index(const ap_message id) const
  851. {
  852. for (uint8_t i=0; i<ARRAY_SIZE(deferred_message); i++) {
  853. if (deferred_message[i].id == id) {
  854. return i;
  855. }
  856. }
  857. return -1;
  858. }
  859. int8_t GCS_MAVLINK::deferred_message_to_send_index()
  860. {
  861. const uint16_t now16_ms = AP_HAL::millis16();
  862. if (next_deferred_message_to_send_cache == -1) {
  863. uint16_t ms_before_next_message_to_send = UINT16_MAX;
  864. for (uint8_t i=0; i<ARRAY_SIZE(deferred_message); i++) {
  865. const uint16_t interval_ms = deferred_message[i].interval_ms;
  866. if (interval_ms == 0) {
  867. continue;
  868. }
  869. const uint16_t ms_since_last_sent = now16_ms - deferred_message[i].last_sent_ms;
  870. uint16_t ms_before_send_this_message;
  871. if (ms_since_last_sent > interval_ms) {
  872. // should already have sent this one!
  873. ms_before_send_this_message = 0;
  874. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  875. try_send_message_stats.behind++;
  876. #endif
  877. } else {
  878. ms_before_send_this_message = interval_ms - ms_since_last_sent;
  879. }
  880. if (ms_before_send_this_message < ms_before_next_message_to_send) {
  881. next_deferred_message_to_send_cache = i;
  882. ms_before_next_message_to_send = ms_before_send_this_message;
  883. }
  884. }
  885. }
  886. if (next_deferred_message_to_send_cache == -1) {
  887. // this really shouldn't happen; we force parameter rates, for example.
  888. return -1;
  889. }
  890. const uint16_t ms_since_last_sent = now16_ms - deferred_message[next_deferred_message_to_send_cache].last_sent_ms;
  891. if (ms_since_last_sent < deferred_message[next_deferred_message_to_send_cache].interval_ms) {
  892. return -1;
  893. }
  894. return next_deferred_message_to_send_cache;
  895. }
  896. extern mavlink_rov_state_monitoring_t rov_message;
  897. //extern mavlink_motor_speed_t mav_motor_speed;
  898. extern mavlink_motor_speed_t mav_motor_speed_back;
  899. mavlink_data64_t rov_message3;
  900. extern mavlink_set_slave_parameter_t get_stm32_param;
  901. extern mavlink_hv_reg_get_t hv_reg_get;
  902. extern uint8_t get_stm32_param_buf[7];
  903. int countper = 0;
  904. void GCS_MAVLINK::update_send()
  905. {
  906. // const AP_UAVCAN &uavcan = AP::uavcan();//6自由度电机计算出来的PWM
  907. mav_motor_speed_back.motorTest = 0;
  908. mav_motor_speed_back.Ltrack = 0;
  909. mav_motor_speed_back.Rtrack =0;
  910. mav_motor_speed_back.motor1 =(float)sub._telemetry[0].rpm/7;//uint32 rpm
  911. mav_motor_speed_back.motor2 =(float)sub._telemetry[1].rpm/7;
  912. mav_motor_speed_back.motor3 =(float)sub._telemetry[2].rpm/7;
  913. mav_motor_speed_back.motor4 =(float)sub._telemetry[3].rpm/7;
  914. mav_motor_speed_back.motor5 =(float)sub._telemetry[4].rpm/7;
  915. mav_motor_speed_back.motor6 =(float)sub._telemetry[5].rpm/7;
  916. mav_motor_speed_back.motor7 =0;
  917. mav_motor_speed_back.motor8 =0;
  918. rov_message.floodlight = sub.lights;
  919. //pressure_level 在各个模式中已经赋值
  920. rov_message.low_voltage = (float)sub._telemetry[0].voltage/10;
  921. rov_message.high_voltage = (float)sub._telemetry[1].voltage/10;//sub._telemetry[0].voltage;//电压
  922. rov_message.deep =fabsf(sub.barometer.get_altitude());//深度
  923. //rov_message.temp = 0;
  924. rov_message.motor_block_flag = 0;
  925. rov_message.motor_twine_flag[0] = 0;//(uint16_t)uavcan.thruster[0].error_count;//故障码?
  926. rov_message.motor_twine_flag[1] = 0;//(uint16_t)uavcan.thruster[1].error_count;
  927. rov_message.motor_twine_flag[2] = 0;//(uint16_t)uavcan.thruster[2].error_count;
  928. rov_message.motor_twine_flag[3] = 0;//(uint16_t)uavcan.thruster[3].error_count;
  929. rov_message.motor_twine_flag[4] = 0;//(uint16_t)uavcan.thruster[4].error_count;
  930. rov_message.motor_twine_flag[5] = 0;//(uint16_t)uavcan.thruster[5].error_count;
  931. rov_message.motor_twine_flag[6] = 0;
  932. rov_message.motor_twine_flag[7] = 0;
  933. rov_message.motor_power[0] = (int16_t)sub._telemetry[0].totalcurrent;//float current
  934. rov_message.motor_power[1] = (int16_t)sub._telemetry[1].totalcurrent;
  935. rov_message.motor_power[2] = (int16_t)sub._telemetry[2].totalcurrent;
  936. rov_message.motor_power[3] = (int16_t)sub._telemetry[3].totalcurrent;
  937. rov_message.motor_power[4] = (int16_t)sub._telemetry[4].totalcurrent;
  938. rov_message.motor_power[5] = (int16_t)sub._telemetry[5].totalcurrent;
  939. get_stm32_param.number = 0;
  940. get_stm32_param.flag = 0;
  941. get_stm32_param.XX1 = 0;
  942. get_stm32_param.XX2 =0;
  943. get_stm32_param.XX3 = 0;
  944. get_stm32_param.XX4 = 0;
  945. get_stm32_param.YY = 0;
  946. const NavEKF2 &ekf2 = AP::ahrs_navekf().get_NavEKF2_const();
  947. Matrix3f mat;
  948. ekf2.getRotationBodyToNED(mat);
  949. countper++;
  950. if (countper>30)
  951. {
  952. countper = 0;
  953. mavlink_msg_rotation_matrix_array_send(chan,
  954. mat.c.x,mat.c.z,mat.c.y,
  955. mat.b.x,mat.b.z,mat.b.y,
  956. mat.a.x,mat.a.z,mat.a.y);
  957. }
  958. /*const NavEKF2 &ekf2 = AP::ahrs_navekf().get_NavEKF2_const();
  959. Matrix3f mat;
  960. ekf2.getRotationBodyToNED(mat);
  961. countper++;
  962. if (countper>50)
  963. {
  964. countper = 0;
  965. mavlink_msg_rotation_matrix_array_send(chan,
  966. mat.c.x,mat.c.z,mat.c.y,
  967. mat.b.x,mat.b.z,mat.b.y,
  968. mat.a.x,mat.a.z,mat.a.y);
  969. mavlink_msg_rov_state_monitoring_send_struct(chan,&rov_message);
  970. mavlink_msg_set_slave_parameter_send_struct(chan,&get_stm32_param);
  971. //mavlink_msg_motor_speed_send_struct(chan,&mav_motor_speed_back);
  972. //mavlink_msg_hv_reg_get_send_struct(chan,&hv_reg_get);
  973. }*/
  974. if (!hal.scheduler->in_delay_callback()) {
  975. // AP_Logger will not send log data if we are armed.
  976. AP::logger().handle_log_send();
  977. }
  978. if (!deferred_messages_initialised) {
  979. initialise_message_intervals_from_streamrates();
  980. deferred_messages_initialised = true;
  981. }
  982. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  983. uint32_t retry_deferred_body_start = AP_HAL::micros();
  984. #endif
  985. const uint32_t start = AP_HAL::millis();
  986. while (AP_HAL::millis() - start < 5) { // spend a max of 5ms sending messages. This should never trigger - out_of_time() should become true
  987. if (gcs().out_of_time()) {
  988. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  989. try_send_message_stats.out_of_time++;
  990. #endif
  991. break;
  992. }
  993. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  994. retry_deferred_body_start = AP_HAL::micros();
  995. #endif
  996. // check if any "specially handled" messages should be sent out
  997. {
  998. const int8_t next = deferred_message_to_send_index();
  999. if (next != -1) {
  1000. if (!do_try_send_message(deferred_message[next].id)) {
  1001. break;
  1002. }
  1003. deferred_message[next].last_sent_ms += deferred_message[next].interval_ms;
  1004. next_deferred_message_to_send_cache = -1; // deferred_message_to_send will recalculate
  1005. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  1006. const uint32_t stop = AP_HAL::micros();
  1007. const uint32_t delta = stop - retry_deferred_body_start;
  1008. if (delta > try_send_message_stats.max_retry_deferred_body_us) {
  1009. try_send_message_stats.max_retry_deferred_body_us = delta;
  1010. try_send_message_stats.max_retry_deferred_body_type = 1;
  1011. }
  1012. #endif
  1013. continue;
  1014. }
  1015. }
  1016. // check for any messages that the code has explicitly sent
  1017. const int16_t fs = pushed_ap_message_ids.first_set();
  1018. if (fs != -1) {
  1019. ap_message next = (ap_message)fs;
  1020. if (!do_try_send_message(next)) {
  1021. break;
  1022. }
  1023. pushed_ap_message_ids.clear(next);
  1024. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  1025. const uint32_t stop = AP_HAL::micros();
  1026. const uint32_t delta = stop - retry_deferred_body_start;
  1027. if (delta > try_send_message_stats.max_retry_deferred_body_us) {
  1028. try_send_message_stats.max_retry_deferred_body_us = delta;
  1029. try_send_message_stats.max_retry_deferred_body_type = 2;
  1030. }
  1031. #endif
  1032. continue;
  1033. }
  1034. ap_message next = next_deferred_bucket_message_to_send();
  1035. if (next != no_message_to_send) {
  1036. if (!do_try_send_message(next)) {
  1037. break;
  1038. }
  1039. bucket_message_ids_to_send.clear(next);
  1040. if (bucket_message_ids_to_send.count() == 0) {
  1041. // we sent everything in the bucket. Reschedule it.
  1042. deferred_message_bucket[sending_bucket_id].last_sent_ms +=
  1043. get_reschedule_interval_ms(deferred_message_bucket[sending_bucket_id]);
  1044. find_next_bucket_to_send();
  1045. }
  1046. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  1047. const uint32_t stop = AP_HAL::micros();
  1048. const uint32_t delta = stop - retry_deferred_body_start;
  1049. if (delta > try_send_message_stats.max_retry_deferred_body_us) {
  1050. try_send_message_stats.max_retry_deferred_body_us = delta;
  1051. try_send_message_stats.max_retry_deferred_body_type = 3;
  1052. }
  1053. #endif
  1054. continue;
  1055. }
  1056. break;
  1057. }
  1058. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  1059. const uint32_t stop = AP_HAL::micros();
  1060. const uint32_t delta = stop - retry_deferred_body_start;
  1061. if (delta > try_send_message_stats.max_retry_deferred_body_us) {
  1062. try_send_message_stats.max_retry_deferred_body_us = delta;
  1063. try_send_message_stats.max_retry_deferred_body_type = 4;
  1064. }
  1065. #endif
  1066. // update the number of packets transmitted base on seqno, making
  1067. // the assumption that we don't send more than 256 messages
  1068. // between the last pass through here
  1069. mavlink_status_t *status = mavlink_get_channel_status(chan);
  1070. if (status != nullptr) {
  1071. send_packet_count += uint8_t(status->current_tx_seq - last_tx_seq);
  1072. last_tx_seq = status->current_tx_seq;
  1073. }
  1074. }
  1075. void GCS_MAVLINK::remove_message_from_bucket(int8_t bucket, ap_message id)
  1076. {
  1077. deferred_message_bucket[bucket].ap_message_ids.clear(id);
  1078. if (bucket == sending_bucket_id) {
  1079. bucket_message_ids_to_send.clear(id);
  1080. }
  1081. if (deferred_message_bucket[bucket].ap_message_ids.count() == 0) {
  1082. // bucket empty. Free it:
  1083. deferred_message_bucket[bucket].interval_ms = 0;
  1084. deferred_message_bucket[bucket].last_sent_ms = 0;
  1085. if (sending_bucket_id == bucket) {
  1086. find_next_bucket_to_send();
  1087. }
  1088. }
  1089. }
  1090. bool GCS_MAVLINK::set_ap_message_interval(enum ap_message id, uint16_t interval_ms)
  1091. {
  1092. if (id == MSG_NEXT_PARAM) {
  1093. // force parameters to *always* get streamed so a vehicle is
  1094. // recoverable from bad configuration:
  1095. if (interval_ms == 0) {
  1096. interval_ms = 100;
  1097. } else if (interval_ms > 1000) {
  1098. interval_ms = 1000;
  1099. }
  1100. }
  1101. // send messages out at most 80% of main loop rate
  1102. if (interval_ms != 0 &&
  1103. interval_ms*800 < AP::scheduler().get_loop_period_us()) {
  1104. interval_ms = AP::scheduler().get_loop_period_us()/800.0f;
  1105. }
  1106. // check if it's a specially-handled message:
  1107. const int8_t deferred_offset = get_deferred_message_index(id);
  1108. if (deferred_offset != -1) {
  1109. deferred_message[deferred_offset].interval_ms = interval_ms;
  1110. deferred_message[deferred_offset].last_sent_ms = AP_HAL::millis16();
  1111. return true;
  1112. }
  1113. // see which bucket has the closest interval:
  1114. int8_t closest_bucket = -1;
  1115. uint16_t closest_bucket_interval_delta = UINT16_MAX;
  1116. int8_t in_bucket = -1;
  1117. int8_t empty_bucket_id = -1;
  1118. for (uint8_t i=0; i<ARRAY_SIZE(deferred_message_bucket); i++) {
  1119. const deferred_message_bucket_t &bucket = deferred_message_bucket[i];
  1120. if (bucket.interval_ms == 0) {
  1121. // unused bucket
  1122. if (empty_bucket_id == -1) {
  1123. empty_bucket_id = i;
  1124. }
  1125. #if CONFIG_HAL_BOARD == HAL_BOARD_SITL
  1126. if (bucket.ap_message_ids.count() != 0) {
  1127. AP_HAL::panic("Bucket %u has zero interval but with ids set", i);
  1128. }
  1129. #endif
  1130. continue;
  1131. }
  1132. if (bucket.ap_message_ids.get(id)) {
  1133. in_bucket = i;
  1134. }
  1135. const uint16_t interval_delta = abs(bucket.interval_ms - interval_ms);
  1136. if (interval_delta < closest_bucket_interval_delta) {
  1137. closest_bucket = i;
  1138. closest_bucket_interval_delta = interval_delta;
  1139. }
  1140. }
  1141. if (in_bucket == -1 && interval_ms == 0) {
  1142. // not in a bucket and told to remove from scheduling
  1143. return true;
  1144. }
  1145. if (in_bucket != -1) {
  1146. if (interval_ms == 0) {
  1147. // remove it
  1148. remove_message_from_bucket(in_bucket, id);
  1149. return true;
  1150. }
  1151. if (closest_bucket_interval_delta == 0 &&
  1152. in_bucket == closest_bucket) {
  1153. // don't need to move it
  1154. return true;
  1155. }
  1156. // remove from existing bucket
  1157. remove_message_from_bucket(in_bucket, id);
  1158. if (empty_bucket_id == -1 &&
  1159. deferred_message_bucket[in_bucket].ap_message_ids.count() == 0) {
  1160. empty_bucket_id = in_bucket;
  1161. }
  1162. }
  1163. if (closest_bucket == -1 && empty_bucket_id == -1) {
  1164. // gah?!
  1165. #if CONFIG_HAL_BOARD == HAL_BOARD_SITL
  1166. ::fprintf(stderr, "no buckets?!\n");
  1167. abort();
  1168. #endif
  1169. return false;
  1170. }
  1171. if (closest_bucket_interval_delta != 0 &&
  1172. empty_bucket_id != -1) {
  1173. // allocate a bucket for this interval
  1174. deferred_message_bucket[empty_bucket_id].interval_ms = interval_ms;
  1175. deferred_message_bucket[empty_bucket_id].last_sent_ms = AP_HAL::millis16();
  1176. closest_bucket = empty_bucket_id;
  1177. closest_bucket_interval_delta = 0;
  1178. }
  1179. deferred_message_bucket[closest_bucket].ap_message_ids.set(id);
  1180. if (sending_bucket_id == no_bucket_to_send) {
  1181. sending_bucket_id = closest_bucket;
  1182. bucket_message_ids_to_send = deferred_message_bucket[closest_bucket].ap_message_ids;
  1183. }
  1184. return true;
  1185. }
  1186. // queue a message to be sent (try_send_message does the *actual*
  1187. // mavlink work!)
  1188. void GCS_MAVLINK::send_message(enum ap_message id)
  1189. {
  1190. if (id == MSG_HEARTBEAT) {
  1191. save_signing_timestamp(false);
  1192. // update the mask of all streaming channels
  1193. if (is_streaming()) {
  1194. GCS_MAVLINK::chan_is_streaming |= (1U<<(chan-MAVLINK_COMM_0));
  1195. } else {
  1196. GCS_MAVLINK::chan_is_streaming &= ~(1U<<(chan-MAVLINK_COMM_0));
  1197. }
  1198. }
  1199. pushed_ap_message_ids.set(id);
  1200. }
  1201. void GCS_MAVLINK::packetReceived(const mavlink_status_t &status,
  1202. const mavlink_message_t &msg)
  1203. {
  1204. // we exclude radio packets because we historically used this to
  1205. // make it possible to use the CLI over the radio
  1206. if (msg.msgid != MAVLINK_MSG_ID_RADIO && msg.msgid != MAVLINK_MSG_ID_RADIO_STATUS) {
  1207. const uint8_t mask = (1U<<(chan-MAVLINK_COMM_0));
  1208. if (!(mask & mavlink_private)) {
  1209. mavlink_active |= mask;
  1210. }
  1211. }
  1212. if (!(status.flags & MAVLINK_STATUS_FLAG_IN_MAVLINK1) &&
  1213. (status.flags & MAVLINK_STATUS_FLAG_OUT_MAVLINK1) &&
  1214. AP::serialmanager().get_mavlink_protocol(chan) == AP_SerialManager::SerialProtocol_MAVLink2) {
  1215. // if we receive any MAVLink2 packets on a connection
  1216. // currently sending MAVLink1 then switch to sending
  1217. // MAVLink2
  1218. mavlink_status_t *cstatus = mavlink_get_channel_status(chan);
  1219. if (cstatus != nullptr) {
  1220. cstatus->flags &= ~MAVLINK_STATUS_FLAG_OUT_MAVLINK1;
  1221. }
  1222. }
  1223. if (!routing.check_and_forward(chan, msg)) {
  1224. // the routing code has indicated we should not handle this packet locally
  1225. return;
  1226. }
  1227. if (!accept_packet(status, msg)) {
  1228. // e.g. enforce-sysid says we shouldn't look at this packet
  1229. return;
  1230. }
  1231. handleMessage(msg);
  1232. }
  1233. void
  1234. GCS_MAVLINK::update_receive(uint32_t max_time_us)
  1235. {
  1236. // do absolutely nothing if we are locked
  1237. if (locked()) {
  1238. return;
  1239. }
  1240. // receive new packets
  1241. mavlink_message_t msg;
  1242. mavlink_status_t status;
  1243. uint32_t tstart_us = AP_HAL::micros();
  1244. uint32_t now_ms = AP_HAL::millis();
  1245. hal.util->perf_begin(_perf_update);
  1246. status.packet_rx_drop_count = 0;
  1247. const uint16_t nbytes = _port->available();
  1248. for (uint16_t i=0; i<nbytes; i++)
  1249. {
  1250. const uint8_t c = (uint8_t)_port->read();
  1251. const uint32_t protocol_timeout = 4000;
  1252. if (alternative.handler &&
  1253. now_ms - alternative.last_mavlink_ms > protocol_timeout) {
  1254. /*
  1255. we have an alternative protocol handler installed and we
  1256. haven't parsed a MAVLink packet for 4 seconds. Try
  1257. parsing using alternative handler
  1258. */
  1259. if (alternative.handler(c, mavlink_comm_port[chan])) {
  1260. alternative.last_alternate_ms = now_ms;
  1261. gcs_alternative_active[chan] = true;
  1262. }
  1263. /*
  1264. we may also try parsing as MAVLink if we haven't had a
  1265. successful parse on the alternative protocol for 4s
  1266. */
  1267. if (now_ms - alternative.last_alternate_ms <= protocol_timeout) {
  1268. continue;
  1269. }
  1270. }
  1271. bool parsed_packet = false;
  1272. // Try to get a new message
  1273. if (mavlink_parse_char(chan, c, &msg, &status)) {
  1274. hal.util->persistent_data.last_mavlink_msgid = msg.msgid;
  1275. hal.util->perf_begin(_perf_packet);
  1276. packetReceived(status, msg);
  1277. hal.util->perf_end(_perf_packet);
  1278. parsed_packet = true;
  1279. gcs_alternative_active[chan] = false;
  1280. alternative.last_mavlink_ms = now_ms;
  1281. hal.util->persistent_data.last_mavlink_msgid = 0;
  1282. }
  1283. if (parsed_packet || i % 100 == 0) {
  1284. // make sure we don't spend too much time parsing mavlink messages
  1285. if (AP_HAL::micros() - tstart_us > max_time_us) {
  1286. break;
  1287. }
  1288. }
  1289. }
  1290. const uint32_t tnow = AP_HAL::millis();
  1291. // send a timesync message every 10 seconds; this is for data
  1292. // collection purposes
  1293. if (tnow - _timesync_request.last_sent_ms > _timesync_request.interval_ms && !is_private()) {
  1294. if (HAVE_PAYLOAD_SPACE(chan, TIMESYNC)) {
  1295. send_timesync();
  1296. _timesync_request.last_sent_ms = tnow;
  1297. }
  1298. }
  1299. // consider logging mavlink stats:
  1300. if (is_active() || is_streaming()) {
  1301. if (tnow - last_mavlink_stats_logged > 1000) {
  1302. log_mavlink_stats();
  1303. last_mavlink_stats_logged = tnow;
  1304. }
  1305. }
  1306. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  1307. const uint16_t now16_ms{AP_HAL::millis16()};
  1308. if (uint16_t(now16_ms - try_send_message_stats.statustext_last_sent_ms) > 10000U) {
  1309. if (try_send_message_stats.longest_time_us) {
  1310. gcs().send_text(MAV_SEVERITY_INFO,
  1311. "GCS.chan(%u): ap_msg=%u took %uus to send",
  1312. chan,
  1313. try_send_message_stats.longest_id,
  1314. try_send_message_stats.longest_time_us);
  1315. try_send_message_stats.longest_time_us = 0;
  1316. }
  1317. if (try_send_message_stats.no_space_for_message &&
  1318. (is_active() || is_streaming())) {
  1319. gcs().send_text(MAV_SEVERITY_INFO,
  1320. "GCS.chan(%u): out-of-space: %u",
  1321. chan,
  1322. try_send_message_stats.no_space_for_message);
  1323. try_send_message_stats.no_space_for_message = 0;
  1324. }
  1325. if (try_send_message_stats.out_of_time) {
  1326. gcs().send_text(MAV_SEVERITY_INFO,
  1327. "GCS.chan(%u): out-of-time=%u",
  1328. chan,
  1329. try_send_message_stats.out_of_time);
  1330. try_send_message_stats.out_of_time = 0;
  1331. }
  1332. if (max_slowdown_ms) {
  1333. gcs().send_text(MAV_SEVERITY_INFO,
  1334. "GCS.chan(%u): max slowdown=%u",
  1335. chan,
  1336. max_slowdown_ms);
  1337. max_slowdown_ms = 0;
  1338. }
  1339. if (try_send_message_stats.behind) {
  1340. gcs().send_text(MAV_SEVERITY_INFO,
  1341. "GCS.chan(%u): behind=%u",
  1342. chan,
  1343. try_send_message_stats.behind);
  1344. try_send_message_stats.behind = 0;
  1345. }
  1346. if (try_send_message_stats.fnbts_maxtime) {
  1347. gcs().send_text(MAV_SEVERITY_INFO,
  1348. "GCS.chan(%u): fnbts_maxtime=%uus",
  1349. chan,
  1350. try_send_message_stats.fnbts_maxtime);
  1351. try_send_message_stats.fnbts_maxtime = 0;
  1352. }
  1353. if (try_send_message_stats.max_retry_deferred_body_us) {
  1354. gcs().send_text(MAV_SEVERITY_INFO,
  1355. "GCS.chan(%u): retry_body_maxtime=%uus (%u)",
  1356. chan,
  1357. try_send_message_stats.max_retry_deferred_body_us,
  1358. try_send_message_stats.max_retry_deferred_body_type
  1359. );
  1360. try_send_message_stats.max_retry_deferred_body_us = 0;
  1361. }
  1362. for (uint8_t i=0; i<ARRAY_SIZE(deferred_message_bucket); i++) {
  1363. gcs().send_text(MAV_SEVERITY_INFO,
  1364. "B. intvl. (%u): %u %u %u %u %u",
  1365. chan,
  1366. deferred_message_bucket[0].interval_ms,
  1367. deferred_message_bucket[1].interval_ms,
  1368. deferred_message_bucket[2].interval_ms,
  1369. deferred_message_bucket[3].interval_ms,
  1370. deferred_message_bucket[4].interval_ms);
  1371. }
  1372. try_send_message_stats.statustext_last_sent_ms = now16_ms;
  1373. }
  1374. #endif
  1375. hal.util->perf_end(_perf_update);
  1376. }
  1377. /*
  1378. record stats about this link to logger
  1379. */
  1380. void GCS_MAVLINK::log_mavlink_stats()
  1381. {
  1382. mavlink_status_t *status = mavlink_get_channel_status(chan);
  1383. if (status == nullptr) {
  1384. return;
  1385. }
  1386. const struct log_MAV pkt = {
  1387. LOG_PACKET_HEADER_INIT(LOG_MAV_MSG),
  1388. time_us : AP_HAL::micros64(),
  1389. chan : (uint8_t)chan,
  1390. packet_tx_count : send_packet_count,
  1391. packet_rx_success_count: status->packet_rx_success_count,
  1392. packet_rx_drop_count : status->packet_rx_drop_count
  1393. };
  1394. AP::logger().WriteBlock(&pkt, sizeof(pkt));
  1395. }
  1396. /*
  1397. send the SYSTEM_TIME message
  1398. */
  1399. void GCS_MAVLINK::send_system_time()
  1400. {
  1401. uint64_t time_unix = 0;
  1402. AP::rtc().get_utc_usec(time_unix); // may fail, leaving time_unix at 0
  1403. mavlink_msg_system_time_send(
  1404. chan,
  1405. time_unix,
  1406. AP_HAL::millis());
  1407. }
  1408. /*
  1409. send RC_CHANNELS messages
  1410. */
  1411. void GCS_MAVLINK::send_rc_channels() const
  1412. {
  1413. AP_RSSI *rssi = AP::rssi();
  1414. uint8_t receiver_rssi = 0;
  1415. if (rssi != nullptr) {
  1416. receiver_rssi = rssi->read_receiver_rssi_uint8();
  1417. }
  1418. uint16_t values[18] = {};
  1419. rc().get_radio_in(values, ARRAY_SIZE(values));
  1420. mavlink_msg_rc_channels_send(
  1421. chan,
  1422. AP_HAL::millis(),
  1423. RC_Channels::get_valid_channel_count(),
  1424. values[0],
  1425. values[1],
  1426. values[2],
  1427. values[3],
  1428. values[4],
  1429. values[5],
  1430. values[6],
  1431. values[7],
  1432. values[8],
  1433. values[9],
  1434. values[10],
  1435. values[11],
  1436. values[12],
  1437. values[13],
  1438. values[14],
  1439. values[15],
  1440. values[16],
  1441. values[17],
  1442. receiver_rssi);
  1443. }
  1444. bool GCS_MAVLINK::sending_mavlink1() const
  1445. {
  1446. const mavlink_status_t *status = mavlink_get_channel_status(chan);
  1447. if (status == nullptr) {
  1448. // should not happen
  1449. return true;
  1450. }
  1451. return ((status->flags & MAVLINK_STATUS_FLAG_OUT_MAVLINK1) != 0);
  1452. }
  1453. void GCS_MAVLINK::send_rc_channels_raw() const
  1454. {
  1455. // for mavlink1 send RC_CHANNELS_RAW, for compatibility with OSD
  1456. // implementations
  1457. if (!sending_mavlink1()) {
  1458. return;
  1459. }
  1460. AP_RSSI *rssi = AP::rssi();
  1461. uint8_t receiver_rssi = 0;
  1462. if (rssi != nullptr) {
  1463. receiver_rssi = rssi->read_receiver_rssi_uint8();
  1464. }
  1465. uint16_t values[8] = {};
  1466. rc().get_radio_in(values, ARRAY_SIZE(values));
  1467. mavlink_msg_rc_channels_raw_send(
  1468. chan,
  1469. AP_HAL::millis(),
  1470. 0,
  1471. values[0],
  1472. values[1],
  1473. values[2],
  1474. values[3],
  1475. values[4],
  1476. values[5],
  1477. values[6],
  1478. values[7],
  1479. receiver_rssi);
  1480. }
  1481. void GCS_MAVLINK::send_raw_imu()
  1482. {
  1483. const AP_InertialSensor &ins = AP::ins();
  1484. const Compass &compass = AP::compass();
  1485. const Vector3f &accel = ins.get_accel(0);
  1486. const Vector3f &gyro = ins.get_gyro(0);
  1487. Vector3f mag;
  1488. if (compass.get_count() >= 1) {
  1489. mag = compass.get_field(0);
  1490. } else {
  1491. mag.zero();
  1492. }
  1493. mavlink_msg_raw_imu_send(
  1494. chan,
  1495. AP_HAL::micros(),
  1496. accel.x * 1000.0f / GRAVITY_MSS,
  1497. accel.y * 1000.0f / GRAVITY_MSS,
  1498. accel.z * 1000.0f / GRAVITY_MSS,
  1499. gyro.x * 1000.0f,
  1500. gyro.y * 1000.0f,
  1501. gyro.z * 1000.0f,
  1502. mag.x,
  1503. mag.y,
  1504. mag.z);
  1505. }
  1506. void GCS_MAVLINK::send_scaled_imu(uint8_t instance, void (*send_fn)(mavlink_channel_t chan, uint32_t time_ms, int16_t xacc, int16_t yacc, int16_t zacc, int16_t xgyro, int16_t ygyro, int16_t zgyro, int16_t xmag, int16_t ymag, int16_t zmag))
  1507. {
  1508. const AP_InertialSensor &ins = AP::ins();
  1509. const Compass &compass = AP::compass();
  1510. bool have_data = false;
  1511. Vector3f accel{};
  1512. if (ins.get_accel_count() > instance) {
  1513. accel = ins.get_accel(instance);
  1514. have_data = true;
  1515. }
  1516. Vector3f gyro{};
  1517. if (ins.get_accel_count() > instance) {
  1518. gyro = ins.get_gyro(instance);
  1519. have_data = true;
  1520. }
  1521. Vector3f mag{};
  1522. if (compass.get_count() > instance) {
  1523. mag = compass.get_field(instance);
  1524. have_data = true;
  1525. }
  1526. if (!have_data) {
  1527. return;
  1528. }
  1529. send_fn(
  1530. chan,
  1531. AP_HAL::millis(),
  1532. accel.x * 1000.0f / GRAVITY_MSS,
  1533. accel.y * 1000.0f / GRAVITY_MSS,
  1534. accel.z * 1000.0f / GRAVITY_MSS,
  1535. gyro.x * 1000.0f,
  1536. gyro.y * 1000.0f,
  1537. gyro.z * 1000.0f,
  1538. mag.x,
  1539. mag.y,
  1540. mag.z);
  1541. }
  1542. // send data for barometer and airspeed sensors instances. In the
  1543. // case that we run out of instances of one before the other we send
  1544. // the relevant fields as 0.
  1545. void GCS_MAVLINK::send_scaled_pressure_instance(uint8_t instance, void (*send_fn)(mavlink_channel_t chan, uint32_t time_boot_ms, float press_abs, float press_diff, int16_t temperature))
  1546. {
  1547. const AP_Baro &barometer = AP::baro();
  1548. bool have_data = false;
  1549. float press_abs = 0.0f;
  1550. float temperature = 0.0f;
  1551. if (instance < barometer.num_instances()) {
  1552. press_abs = barometer.get_pressure(instance) * 0.01f;
  1553. temperature = barometer.get_temperature(instance)*100;
  1554. have_data = true;
  1555. }
  1556. float press_diff = 0; // pascal
  1557. AP_Airspeed *airspeed = AP_Airspeed::get_singleton();
  1558. if (airspeed != nullptr &&
  1559. airspeed->enabled(instance)) {
  1560. press_diff = airspeed->get_differential_pressure(instance) * 0.01f;
  1561. have_data = true;
  1562. }
  1563. if (!have_data) {
  1564. return;
  1565. }
  1566. send_fn(
  1567. chan,
  1568. AP_HAL::millis(),
  1569. press_abs, // hectopascal
  1570. press_diff, // hectopascal
  1571. temperature); // 0.01 degrees C
  1572. }
  1573. void GCS_MAVLINK::send_scaled_pressure()
  1574. {
  1575. send_scaled_pressure_instance(0, mavlink_msg_scaled_pressure_send);
  1576. }
  1577. void GCS_MAVLINK::send_scaled_pressure2()
  1578. {
  1579. send_scaled_pressure_instance(1, mavlink_msg_scaled_pressure2_send);
  1580. }
  1581. void GCS_MAVLINK::send_scaled_pressure3()
  1582. {
  1583. send_scaled_pressure_instance(2, mavlink_msg_scaled_pressure3_send);
  1584. }
  1585. void GCS_MAVLINK::send_sensor_offsets()
  1586. {
  1587. const AP_InertialSensor &ins = AP::ins();
  1588. const Compass &compass = AP::compass();
  1589. // run this message at a much lower rate - otherwise it
  1590. // pointlessly wastes quite a lot of bandwidth
  1591. static uint8_t counter;
  1592. if (counter++ < 10) {
  1593. return;
  1594. }
  1595. counter = 0;
  1596. const Vector3f &mag_offsets = compass.get_offsets(0);
  1597. const Vector3f &accel_offsets = ins.get_accel_offsets(0);
  1598. const Vector3f &gyro_offsets = ins.get_gyro_offsets(0);
  1599. const AP_Baro &barometer = AP::baro();
  1600. mavlink_msg_sensor_offsets_send(chan,
  1601. mag_offsets.x,
  1602. mag_offsets.y,
  1603. mag_offsets.z,
  1604. compass.get_declination(),
  1605. barometer.get_pressure(),
  1606. barometer.get_temperature()*100,
  1607. gyro_offsets.x,
  1608. gyro_offsets.y,
  1609. gyro_offsets.z,
  1610. accel_offsets.x,
  1611. accel_offsets.y,
  1612. accel_offsets.z);
  1613. }
  1614. void GCS_MAVLINK::send_ahrs()
  1615. {
  1616. const AP_AHRS &ahrs = AP::ahrs();
  1617. const Vector3f &omega_I = ahrs.get_gyro_drift();
  1618. mavlink_msg_ahrs_send(
  1619. chan,
  1620. omega_I.x,
  1621. omega_I.y,
  1622. omega_I.z,
  1623. 0,
  1624. 0,
  1625. ahrs.get_error_rp(),
  1626. ahrs.get_error_yaw());
  1627. }
  1628. /*
  1629. send a statustext text string to specific MAVLink bitmask
  1630. */
  1631. void GCS::send_statustext(MAV_SEVERITY severity, uint8_t dest_bitmask, const char *text)
  1632. {
  1633. #if CONFIG_HAL_BOARD == HAL_BOARD_SITL
  1634. if (strlen(text) > MAVLINK_MSG_STATUSTEXT_FIELD_TEXT_LEN) {
  1635. AP_HAL::panic("Statustext (%s) too long", text);
  1636. }
  1637. #endif
  1638. AP_Logger *logger = AP_Logger::get_singleton();
  1639. if (logger != nullptr) {
  1640. logger->Write_Message(text);
  1641. }
  1642. if (frsky != nullptr) {
  1643. frsky->queue_message(severity, text);
  1644. }
  1645. AP_Notify *notify = AP_Notify::get_singleton();
  1646. if (notify) {
  1647. notify->send_text(text);
  1648. }
  1649. // filter destination ports to only allow active ports.
  1650. statustext_t statustext{};
  1651. statustext.bitmask = (GCS_MAVLINK::active_channel_mask() | GCS_MAVLINK::streaming_channel_mask() ) & dest_bitmask;
  1652. if (!statustext.bitmask) {
  1653. // nowhere to send
  1654. return;
  1655. }
  1656. statustext.msg.severity = severity;
  1657. strncpy(statustext.msg.text, text, sizeof(statustext.msg.text));
  1658. WITH_SEMAPHORE(_statustext_sem);
  1659. // The force push will ensure comm links do not block other comm links forever if they fail.
  1660. // If we push to a full buffer then we overwrite the oldest entry, effectively removing the
  1661. // block but not until the buffer fills up.
  1662. _statustext_queue.push_force(statustext);
  1663. // try and send immediately if possible
  1664. service_statustext();
  1665. }
  1666. /*
  1667. send a statustext message to specific MAVLink connections in a bitmask
  1668. */
  1669. void GCS::service_statustext(void)
  1670. {
  1671. // create bitmask of what mavlink ports we should send this text to.
  1672. // note, if sending to all ports, we only need to store the bitmask for each and the string only once.
  1673. // once we send over a link, clear the port but other busy ports bit may stay allowing for faster links
  1674. // to clear the bit and send quickly but slower links to still store the string. Regardless of mixed
  1675. // bitrates of ports, a maximum of _status_capacity strings can be buffered. Downside
  1676. // is if you have a super slow link mixed with a faster port, if there are _status_capacity
  1677. // strings in the slow queue then the next item can not be queued for the faster link
  1678. if (_statustext_queue.empty()) {
  1679. // nothing to do
  1680. return;
  1681. }
  1682. for (uint8_t idx=0; idx<_status_capacity; ) {
  1683. statustext_t *statustext = _statustext_queue[idx];
  1684. if (statustext == nullptr) {
  1685. break;
  1686. }
  1687. // try and send to all active mavlink ports listed in the statustext.bitmask
  1688. for (uint8_t i=0; i<MAVLINK_COMM_NUM_BUFFERS; i++) {
  1689. uint8_t chan_bit = (1U<<i);
  1690. // logical AND (&) to mask them together
  1691. if (statustext->bitmask & chan_bit) {
  1692. // something is queued on a port and that's the port index we're looped at
  1693. mavlink_channel_t chan_index = (mavlink_channel_t)(MAVLINK_COMM_0+i);
  1694. if (HAVE_PAYLOAD_SPACE(chan_index, STATUSTEXT)) {
  1695. // we have space so send then clear that channel bit on the mask
  1696. mavlink_msg_statustext_send(chan_index, statustext->msg.severity, statustext->msg.text);
  1697. statustext->bitmask &= ~chan_bit;
  1698. }
  1699. }
  1700. }
  1701. if (statustext->bitmask == 0) {
  1702. _statustext_queue.remove(idx);
  1703. } else {
  1704. // move to next index
  1705. idx++;
  1706. }
  1707. }
  1708. }
  1709. void GCS::send_message(enum ap_message id)
  1710. {
  1711. for (uint8_t i=0; i<num_gcs(); i++) {
  1712. chan(i)->send_message(id);
  1713. }
  1714. }
  1715. void GCS::update_send()
  1716. {
  1717. if (!initialised_missionitemprotocol_objects) {
  1718. initialised_missionitemprotocol_objects = true;
  1719. // once-only initialisation of MissionItemProtocol objects:
  1720. AP_Mission *mission = AP::mission();
  1721. if (mission != nullptr) {
  1722. _missionitemprotocol_waypoints = new MissionItemProtocol_Waypoints(*mission);
  1723. }
  1724. AP_Rally *rally = AP::rally();
  1725. if (rally != nullptr) {
  1726. _missionitemprotocol_rally = new MissionItemProtocol_Rally(*rally);
  1727. }
  1728. }
  1729. if (_missionitemprotocol_waypoints != nullptr) {
  1730. _missionitemprotocol_waypoints->update();
  1731. }
  1732. if (_missionitemprotocol_rally != nullptr) {
  1733. _missionitemprotocol_rally->update();
  1734. }
  1735. for (uint8_t i=0; i<num_gcs(); i++) {
  1736. chan(i)->update_send();
  1737. }
  1738. WITH_SEMAPHORE(_statustext_sem);
  1739. service_statustext();
  1740. }
  1741. void GCS::update_receive(void)
  1742. {
  1743. for (uint8_t i=0; i<num_gcs(); i++) {
  1744. chan(i)->update_receive();
  1745. }
  1746. // also update UART pass-thru, if enabled
  1747. update_passthru();
  1748. }
  1749. void GCS::send_mission_item_reached_message(uint16_t mission_index)
  1750. {
  1751. for (uint8_t i=0; i<num_gcs(); i++) {
  1752. chan(i)->mission_item_reached_index = mission_index;
  1753. chan(i)->send_message(MSG_MISSION_ITEM_REACHED);
  1754. }
  1755. }
  1756. void GCS::setup_console()
  1757. {
  1758. AP_HAL::UARTDriver *uart = AP::serialmanager().find_serial(AP_SerialManager::SerialProtocol_MAVLink, 0);
  1759. if (uart == nullptr) {
  1760. // this is probably not going to end well.
  1761. return;
  1762. }
  1763. if (ARRAY_SIZE(chan_parameters) == 0) {
  1764. return;
  1765. }
  1766. create_gcs_mavlink_backend(chan_parameters[0], *uart);
  1767. }
  1768. GCS_MAVLINK_Parameters::GCS_MAVLINK_Parameters()
  1769. {
  1770. AP_Param::setup_object_defaults(this, var_info);
  1771. }
  1772. void GCS::create_gcs_mavlink_backend(GCS_MAVLINK_Parameters &params, AP_HAL::UARTDriver &uart)
  1773. {
  1774. if (_num_gcs >= ARRAY_SIZE(chan_parameters)) {
  1775. return;
  1776. }
  1777. _chan[_num_gcs] = new_gcs_mavlink_backend(params, uart);
  1778. if (_chan[_num_gcs] == nullptr) {
  1779. return;
  1780. }
  1781. if (!_chan[_num_gcs]->init(_num_gcs)) {
  1782. delete _chan[_num_gcs];
  1783. _chan[_num_gcs] = nullptr;
  1784. return;
  1785. }
  1786. _num_gcs++;
  1787. }
  1788. void GCS::setup_uarts()
  1789. {
  1790. for (uint8_t i = 1; i < MAVLINK_COMM_NUM_BUFFERS; i++) {
  1791. if (i >= ARRAY_SIZE(chan_parameters)) {
  1792. // should not happen
  1793. break;
  1794. }
  1795. AP_HAL::UARTDriver *uart = AP::serialmanager().find_serial(AP_SerialManager::SerialProtocol_MAVLink, i);
  1796. if (uart == nullptr) {
  1797. // no more mavlink uarts
  1798. break;
  1799. }
  1800. create_gcs_mavlink_backend(chan_parameters[i], *uart);
  1801. }
  1802. if (frsky == nullptr) {
  1803. frsky = new AP_Frsky_Telem();
  1804. if (frsky == nullptr || !frsky->init()) {
  1805. delete frsky;
  1806. frsky = nullptr;
  1807. }
  1808. }
  1809. #if !HAL_MINIMIZE_FEATURES
  1810. devo_telemetry.init();
  1811. #endif
  1812. }
  1813. // report battery2 state
  1814. void GCS_MAVLINK::send_battery2()
  1815. {
  1816. const AP_BattMonitor &battery = AP::battery();
  1817. if (battery.num_instances() > 1) {
  1818. float current;
  1819. if (battery.current_amps(current, 1)) {
  1820. current *= 100; // 10*mA
  1821. } else {
  1822. current = -1;
  1823. }
  1824. mavlink_msg_battery2_send(chan, battery.voltage(1)*1000, current);
  1825. }
  1826. }
  1827. /*
  1828. handle a SET_MODE MAVLink message
  1829. */
  1830. void GCS_MAVLINK::handle_set_mode(const mavlink_message_t &msg)
  1831. {
  1832. mavlink_set_mode_t packet;
  1833. mavlink_msg_set_mode_decode(&msg, &packet);
  1834. const MAV_MODE _base_mode = (MAV_MODE)packet.base_mode;
  1835. const uint32_t _custom_mode = packet.custom_mode;
  1836. const MAV_RESULT result = _set_mode_common(_base_mode, _custom_mode);
  1837. // send ACK or NAK. Note that this is extraodinarily improper -
  1838. // we are sending a command-ack for a message which is not a
  1839. // command. The command we are acking (ID=11) doesn't actually
  1840. // exist, but if it did we'd probably be acking something
  1841. // completely unrelated to setting modes.
  1842. if (HAVE_PAYLOAD_SPACE(chan, MAVLINK_MSG_ID_COMMAND_ACK)) {
  1843. mavlink_msg_command_ack_send(chan, MAVLINK_MSG_ID_SET_MODE, result);
  1844. }
  1845. }
  1846. /*
  1847. code common to both SET_MODE mavlink message and command long set_mode msg
  1848. */
  1849. MAV_RESULT GCS_MAVLINK::_set_mode_common(const MAV_MODE _base_mode, const uint32_t _custom_mode)
  1850. {
  1851. MAV_RESULT result = MAV_RESULT_UNSUPPORTED;
  1852. // only accept custom modes because there is no easy mapping from Mavlink flight modes to AC flight modes
  1853. if (_base_mode & MAV_MODE_FLAG_CUSTOM_MODE_ENABLED) {
  1854. if (set_mode(_custom_mode)) {
  1855. result = MAV_RESULT_ACCEPTED;
  1856. }
  1857. } else if (_base_mode == (MAV_MODE)MAV_MODE_FLAG_DECODE_POSITION_SAFETY) {
  1858. // set the safety switch position. Must be in a command by itself
  1859. if (_custom_mode == 0) {
  1860. // turn safety off (pwm outputs flow to the motors)
  1861. hal.rcout->force_safety_off();
  1862. result = MAV_RESULT_ACCEPTED;
  1863. } else if (_custom_mode == 1) {
  1864. // turn safety on (no pwm outputs to the motors)
  1865. if (hal.rcout->force_safety_on()) {
  1866. result = MAV_RESULT_ACCEPTED;
  1867. }
  1868. }
  1869. }
  1870. return result;
  1871. }
  1872. /*
  1873. send OPTICAL_FLOW message
  1874. */
  1875. void GCS_MAVLINK::send_opticalflow()
  1876. {
  1877. #if AP_AHRS_NAVEKF_AVAILABLE
  1878. const OpticalFlow *optflow = AP::opticalflow();
  1879. // exit immediately if no optical flow sensor or not healthy
  1880. if (optflow == nullptr ||
  1881. !optflow->healthy()) {
  1882. return;
  1883. }
  1884. // get rates from sensor
  1885. const Vector2f &flowRate = optflow->flowRate();
  1886. const Vector2f &bodyRate = optflow->bodyRate();
  1887. const AP_AHRS &ahrs = AP::ahrs();
  1888. float hagl = 0;
  1889. if (ahrs.have_inertial_nav()) {
  1890. if (!ahrs.get_hagl(hagl)) {
  1891. return;
  1892. }
  1893. }
  1894. // populate and send message
  1895. mavlink_msg_optical_flow_send(
  1896. chan,
  1897. AP_HAL::millis(),
  1898. 0, // sensor id is zero
  1899. flowRate.x,
  1900. flowRate.y,
  1901. flowRate.x - bodyRate.x,
  1902. flowRate.y - bodyRate.y,
  1903. optflow->quality(),
  1904. hagl, // ground distance (in meters) set to zero
  1905. flowRate.x,
  1906. flowRate.y);
  1907. #endif
  1908. }
  1909. /*
  1910. send AUTOPILOT_VERSION packet
  1911. */
  1912. void GCS_MAVLINK::send_autopilot_version() const
  1913. {
  1914. uint32_t flight_sw_version;
  1915. uint32_t middleware_sw_version = 0;
  1916. uint32_t board_version = 0;
  1917. char flight_custom_version[MAVLINK_MSG_AUTOPILOT_VERSION_FIELD_FLIGHT_CUSTOM_VERSION_LEN]{};
  1918. char middleware_custom_version[MAVLINK_MSG_AUTOPILOT_VERSION_FIELD_MIDDLEWARE_CUSTOM_VERSION_LEN]{};
  1919. char os_custom_version[MAVLINK_MSG_AUTOPILOT_VERSION_FIELD_OS_CUSTOM_VERSION_LEN]{};
  1920. uint16_t vendor_id = 0;
  1921. uint16_t product_id = 0;
  1922. uint64_t uid = 0;
  1923. uint8_t uid2[MAVLINK_MSG_AUTOPILOT_VERSION_FIELD_UID2_LEN] = {0};
  1924. const AP_FWVersion &version = AP::fwversion();
  1925. flight_sw_version = version.major << (8 * 3) | \
  1926. version.minor << (8 * 2) | \
  1927. version.patch << (8 * 1) | \
  1928. (uint32_t)(version.fw_type) << (8 * 0);
  1929. if (version.fw_hash_str) {
  1930. strncpy(flight_custom_version, version.fw_hash_str, sizeof(flight_custom_version) - 1);
  1931. flight_custom_version[sizeof(flight_custom_version) - 1] = '\0';
  1932. }
  1933. if (version.middleware_hash_str) {
  1934. strncpy(middleware_custom_version, version.middleware_hash_str, sizeof(middleware_custom_version) - 1);
  1935. middleware_custom_version[sizeof(middleware_custom_version) - 1] = '\0';
  1936. }
  1937. if (version.os_hash_str) {
  1938. strncpy(os_custom_version, version.os_hash_str, sizeof(os_custom_version) - 1);
  1939. os_custom_version[sizeof(os_custom_version) - 1] = '\0';
  1940. }
  1941. mavlink_msg_autopilot_version_send(
  1942. chan,
  1943. capabilities(),
  1944. flight_sw_version,
  1945. middleware_sw_version,
  1946. version.os_sw_version,
  1947. board_version,
  1948. (uint8_t *)flight_custom_version,
  1949. (uint8_t *)middleware_custom_version,
  1950. (uint8_t *)os_custom_version,
  1951. vendor_id,
  1952. product_id,
  1953. uid,
  1954. uid2
  1955. );
  1956. }
  1957. /*
  1958. send LOCAL_POSITION_NED message
  1959. */
  1960. void GCS_MAVLINK::send_local_position() const
  1961. {
  1962. const AP_AHRS &ahrs = AP::ahrs();
  1963. Vector3f local_position, velocity;
  1964. if (!ahrs.get_relative_position_NED_home(local_position) ||
  1965. !ahrs.get_velocity_NED(velocity)) {
  1966. // we don't know the position and velocity
  1967. return;
  1968. }
  1969. mavlink_msg_local_position_ned_send(
  1970. chan,
  1971. AP_HAL::millis(),
  1972. local_position.x,
  1973. local_position.y,
  1974. local_position.z,
  1975. velocity.x,
  1976. velocity.y,
  1977. velocity.z);
  1978. }
  1979. /*
  1980. send VIBRATION message
  1981. */
  1982. void GCS_MAVLINK::send_vibration() const
  1983. {
  1984. const AP_InertialSensor &ins = AP::ins();
  1985. Vector3f vibration = ins.get_vibration_levels();
  1986. mavlink_msg_vibration_send(
  1987. chan,
  1988. AP_HAL::micros64(),
  1989. vibration.x,
  1990. vibration.y,
  1991. vibration.z,
  1992. ins.get_accel_clip_count(0),
  1993. ins.get_accel_clip_count(1),
  1994. ins.get_accel_clip_count(2));
  1995. }
  1996. void GCS_MAVLINK::send_named_float(const char *name, float value) const
  1997. {
  1998. char float_name[MAVLINK_MSG_NAMED_VALUE_FLOAT_FIELD_NAME_LEN+1] {};
  1999. strncpy(float_name, name, MAVLINK_MSG_NAMED_VALUE_FLOAT_FIELD_NAME_LEN);
  2000. mavlink_msg_named_value_float_send(chan, AP_HAL::millis(), float_name, value);
  2001. }
  2002. void GCS_MAVLINK::send_home_position() const
  2003. {
  2004. if (!AP::ahrs().home_is_set()) {
  2005. return;
  2006. }
  2007. const Location &home = AP::ahrs().get_home();
  2008. const float q[4] = {1.0f, 0.0f, 0.0f, 0.0f};
  2009. mavlink_msg_home_position_send(
  2010. chan,
  2011. home.lat,
  2012. home.lng,
  2013. home.alt * 10,
  2014. 0.0f, 0.0f, 0.0f,
  2015. q,
  2016. 0.0f, 0.0f, 0.0f,
  2017. AP_HAL::micros64());
  2018. }
  2019. void GCS_MAVLINK::send_gps_global_origin() const
  2020. {
  2021. Location ekf_origin;
  2022. if (!AP::ahrs().get_origin(ekf_origin)) {
  2023. return;
  2024. }
  2025. mavlink_msg_gps_global_origin_send(
  2026. chan,
  2027. ekf_origin.lat,
  2028. ekf_origin.lng,
  2029. ekf_origin.alt * 10,
  2030. AP_HAL::micros64());
  2031. }
  2032. /*
  2033. Send MAVLink heartbeat
  2034. */
  2035. void GCS_MAVLINK::send_heartbeat() const
  2036. {
  2037. mavlink_msg_heartbeat_send(
  2038. chan,
  2039. gcs().frame_type(),
  2040. MAV_AUTOPILOT_ARDUPILOTMEGA,
  2041. base_mode(),
  2042. gcs().custom_mode(),
  2043. system_status());
  2044. }
  2045. MAV_RESULT GCS_MAVLINK::handle_command_set_message_interval(const mavlink_command_long_t &packet)
  2046. {
  2047. const uint32_t msg_id = (uint32_t)packet.param1;
  2048. const int32_t interval_us = (int32_t)packet.param2;
  2049. uint16_t interval_ms;
  2050. if (interval_us == 0) {
  2051. // zero is "reset to default rate"
  2052. if (!get_default_interval_for_mavlink_message_id(msg_id, interval_ms)) {
  2053. return MAV_RESULT_FAILED;
  2054. }
  2055. } else if (interval_us == -1) {
  2056. // minus-one is "stop sending"
  2057. interval_ms = 0;
  2058. } else if (interval_us < 1000) {
  2059. // don't squash sub-ms times to zero
  2060. interval_ms = 1;
  2061. } else if (interval_us > 60000000) {
  2062. interval_ms = 60000;
  2063. } else {
  2064. interval_ms = interval_us / 1000;
  2065. }
  2066. if (set_mavlink_message_id_interval(msg_id, interval_ms)) {
  2067. return MAV_RESULT_ACCEPTED;
  2068. }
  2069. return MAV_RESULT_FAILED;
  2070. }
  2071. MAV_RESULT GCS_MAVLINK::handle_command_request_message(const mavlink_command_long_t &packet)
  2072. {
  2073. const uint32_t mavlink_id = (uint32_t)packet.param1;
  2074. const ap_message id = mavlink_id_to_ap_message_id(mavlink_id);
  2075. if (id == MSG_LAST) {
  2076. return MAV_RESULT_FAILED;
  2077. }
  2078. send_message(id);
  2079. return MAV_RESULT_ACCEPTED;
  2080. }
  2081. bool GCS_MAVLINK::get_ap_message_interval(ap_message id, uint16_t &interval_ms) const
  2082. {
  2083. // check if it's a specially-handled message:
  2084. const int8_t deferred_offset = get_deferred_message_index(id);
  2085. if (deferred_offset != -1) {
  2086. interval_ms = deferred_message[deferred_offset].interval_ms;
  2087. return true;
  2088. }
  2089. // check the deferred message buckets:
  2090. for (uint8_t i=0; i<ARRAY_SIZE(deferred_message_bucket); i++) {
  2091. const deferred_message_bucket_t &bucket = deferred_message_bucket[i];
  2092. if (bucket.ap_message_ids.get(id)) {
  2093. interval_ms = bucket.interval_ms;
  2094. return true;
  2095. }
  2096. }
  2097. return false;
  2098. }
  2099. MAV_RESULT GCS_MAVLINK::handle_command_get_message_interval(const mavlink_command_long_t &packet)
  2100. {
  2101. if (comm_get_txspace(chan) < PAYLOAD_SIZE(chan, MESSAGE_INTERVAL) + PAYLOAD_SIZE(chan, COMMAND_ACK)) {
  2102. return MAV_RESULT_TEMPORARILY_REJECTED;
  2103. }
  2104. const uint32_t mavlink_id = (uint32_t)packet.param1;
  2105. if (mavlink_id >= 2 << 15) {
  2106. // response packet limits range this works against!
  2107. mavlink_msg_message_interval_send(chan, mavlink_id, 0); // not available
  2108. return MAV_RESULT_FAILED;
  2109. }
  2110. const ap_message id = mavlink_id_to_ap_message_id(mavlink_id);
  2111. if (id == MSG_LAST) {
  2112. mavlink_msg_message_interval_send(chan, mavlink_id, 0); // not available
  2113. return MAV_RESULT_FAILED;
  2114. }
  2115. uint16_t interval_ms = 0;
  2116. if (!get_ap_message_interval(id, interval_ms)) {
  2117. // not streaming this message at the moment...
  2118. mavlink_msg_message_interval_send(chan, mavlink_id, -1); // disabled
  2119. return MAV_RESULT_ACCEPTED;
  2120. }
  2121. if (interval_ms == 0) {
  2122. mavlink_msg_message_interval_send(chan, mavlink_id, -1); // disabled
  2123. return MAV_RESULT_ACCEPTED;
  2124. }
  2125. mavlink_msg_message_interval_send(chan, mavlink_id, interval_ms * 1000);
  2126. return MAV_RESULT_ACCEPTED;
  2127. }
  2128. // are we still delaying telemetry to try to avoid Xbee bricking?
  2129. bool GCS_MAVLINK::telemetry_delayed() const
  2130. {
  2131. uint32_t tnow = AP_HAL::millis() >> 10;
  2132. if (tnow > telem_delay()) {
  2133. return false;
  2134. }
  2135. if (chan == MAVLINK_COMM_0 && hal.gpio->usb_connected()) {
  2136. // this is USB telemetry, so won't be an Xbee
  2137. return false;
  2138. }
  2139. // we're either on the 2nd UART, or no USB cable is connected
  2140. // we need to delay telemetry by the TELEM_DELAY time
  2141. return true;
  2142. }
  2143. /*
  2144. send SERVO_OUTPUT_RAW
  2145. */
  2146. void GCS_MAVLINK::send_servo_output_raw()
  2147. {
  2148. uint16_t values[16] {};
  2149. if (in_hil_mode()) {
  2150. for (uint8_t i=0; i<16; i++) {
  2151. values[i] = SRV_Channels::srv_channel(i)->get_output_pwm();
  2152. }
  2153. } else {
  2154. hal.rcout->read(values, 16);
  2155. }
  2156. for (uint8_t i=0; i<16; i++) {
  2157. if (values[i] == 65535) {
  2158. values[i] = 0;
  2159. }
  2160. }
  2161. mavlink_msg_servo_output_raw_send(
  2162. chan,
  2163. AP_HAL::micros(),
  2164. 0, // port
  2165. values[0], values[1], values[2], values[3],
  2166. values[4], values[5], values[6], values[7],
  2167. values[8], values[9], values[10], values[11],
  2168. values[12], values[13], values[14], values[15]);
  2169. }
  2170. void GCS_MAVLINK::send_accelcal_vehicle_position(uint32_t position)
  2171. {
  2172. if (HAVE_PAYLOAD_SPACE(chan, COMMAND_LONG)) {
  2173. mavlink_msg_command_long_send(
  2174. chan,
  2175. 0,
  2176. 0,
  2177. MAV_CMD_ACCELCAL_VEHICLE_POS,
  2178. 0,
  2179. (float) position,
  2180. 0, 0, 0, 0, 0, 0);
  2181. }
  2182. }
  2183. float GCS_MAVLINK::vfr_hud_airspeed() const
  2184. {
  2185. AP_Airspeed *airspeed = AP_Airspeed::get_singleton();
  2186. if (airspeed != nullptr && airspeed->healthy()) {
  2187. return airspeed->get_airspeed();
  2188. }
  2189. // because most vehicles don't have airspeed sensors, we return a
  2190. // different sort of speed estimate in the relevant field for
  2191. // comparison's sake.
  2192. return AP::gps().ground_speed();
  2193. }
  2194. float GCS_MAVLINK::vfr_hud_climbrate() const
  2195. {
  2196. Vector3f velned;
  2197. if (!AP::ahrs().get_velocity_NED(velned)) {
  2198. velned.zero();
  2199. }
  2200. return -velned.z;
  2201. }
  2202. float GCS_MAVLINK::vfr_hud_alt() const
  2203. {
  2204. return global_position_current_loc.alt * 0.01f; // cm -> m
  2205. }
  2206. void GCS_MAVLINK::send_vfr_hud()
  2207. {
  2208. AP_AHRS &ahrs = AP::ahrs();
  2209. // return values ignored; we send stale data
  2210. ahrs.get_position(global_position_current_loc);
  2211. mavlink_msg_vfr_hud_send(
  2212. chan,
  2213. vfr_hud_airspeed(),
  2214. ahrs.groundspeed(),
  2215. (ahrs.yaw_sensor / 100) % 360,
  2216. vfr_hud_throttle(),
  2217. vfr_hud_alt(),
  2218. vfr_hud_climbrate());
  2219. }
  2220. void GCS_MAVLINK::zero_rc_outputs()
  2221. {
  2222. // Send an invalid signal to the motors to prevent spinning due to neutral (1500) pwm pulse being cut short
  2223. // For that matter, send an invalid signal to all channels to prevent undesired/unexpected behavior
  2224. SRV_Channels::cork();
  2225. for (int i=0; i<NUM_RC_CHANNELS; i++) {
  2226. hal.rcout->write(i, 0);
  2227. }
  2228. SRV_Channels::push();
  2229. }
  2230. /*
  2231. handle a MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN command
  2232. Optionally disable PX4IO overrides. This is done for quadplanes to
  2233. prevent the mixer running while rebooting which can start the VTOL
  2234. motors. That can be dangerous when a preflight reboot is done with
  2235. the pilot close to the aircraft and can also damage the aircraft
  2236. */
  2237. MAV_RESULT GCS_MAVLINK::handle_preflight_reboot(const mavlink_command_long_t &packet)
  2238. {
  2239. if (is_equal(packet.param1, 42.0f) &&
  2240. is_equal(packet.param2, 24.0f) &&
  2241. is_equal(packet.param3, 71.0f) &&
  2242. is_equal(packet.param4, 93.0f)) {
  2243. // this is a magic sequence to force the main loop to
  2244. // lockup. This is for testing the stm32 watchdog
  2245. // functionality
  2246. while (true) {
  2247. send_text(MAV_SEVERITY_WARNING,"entering lockup");
  2248. hal.scheduler->delay(250);
  2249. }
  2250. }
  2251. if (hal.util->get_soft_armed()) {
  2252. // refuse reboot when armed
  2253. return MAV_RESULT_FAILED;
  2254. }
  2255. if (!(is_equal(packet.param1, 1.0f) || is_equal(packet.param1, 3.0f))) {
  2256. // param1 must be 1 or 3 - 1 being reboot, 3 being reboot-to-bootloader
  2257. return MAV_RESULT_UNSUPPORTED;
  2258. }
  2259. if (should_zero_rc_outputs_on_reboot()) {
  2260. zero_rc_outputs();
  2261. }
  2262. // send ack before we reboot
  2263. mavlink_msg_command_ack_send(chan, packet.command, MAV_RESULT_ACCEPTED);
  2264. // Notify might want to blink some LEDs:
  2265. AP_Notify *notify = AP_Notify::get_singleton();
  2266. if (notify) {
  2267. AP_Notify::flags.firmware_update = 1;
  2268. notify->update();
  2269. }
  2270. // force safety on
  2271. hal.rcout->force_safety_on();
  2272. // flush pending parameter writes
  2273. AP_Param::flush();
  2274. hal.scheduler->delay(200);
  2275. // when packet.param1 == 3 we reboot to hold in bootloader
  2276. const bool hold_in_bootloader = is_equal(packet.param1, 3.0f);
  2277. hal.scheduler->reboot(hold_in_bootloader);
  2278. return MAV_RESULT_FAILED;
  2279. }
  2280. /*
  2281. handle a flight termination request
  2282. */
  2283. MAV_RESULT GCS_MAVLINK::handle_flight_termination(const mavlink_command_long_t &packet)
  2284. {
  2285. AP_AdvancedFailsafe *failsafe = get_advanced_failsafe();
  2286. if (failsafe == nullptr) {
  2287. return MAV_RESULT_UNSUPPORTED;
  2288. }
  2289. bool should_terminate = packet.param1 > 0.5f;
  2290. if (failsafe->gcs_terminate(should_terminate, "GCS request")) {
  2291. return MAV_RESULT_ACCEPTED;
  2292. }
  2293. return MAV_RESULT_FAILED;
  2294. }
  2295. /*
  2296. handle a R/C bind request (for spektrum)
  2297. */
  2298. MAV_RESULT GCS_MAVLINK::handle_rc_bind(const mavlink_command_long_t &packet)
  2299. {
  2300. // initiate bind procedure. We accept the DSM type from either
  2301. // param1 or param2 due to a past mixup with what parameter is the
  2302. // right one
  2303. if (!RC_Channels::receiver_bind(packet.param2>0?packet.param2:packet.param1)) {
  2304. return MAV_RESULT_FAILED;
  2305. }
  2306. return MAV_RESULT_ACCEPTED;
  2307. }
  2308. uint64_t GCS_MAVLINK::timesync_receive_timestamp_ns() const
  2309. {
  2310. uint64_t ret = _port->receive_time_constraint_us(PAYLOAD_SIZE(chan, TIMESYNC));
  2311. if (ret == 0) {
  2312. ret = AP_HAL::micros64();
  2313. }
  2314. return ret*1000LL;
  2315. }
  2316. uint64_t GCS_MAVLINK::timesync_timestamp_ns() const
  2317. {
  2318. // we add in our own system id try to ensure we only consider
  2319. // responses to our own timesync request messages
  2320. return AP_HAL::micros64()*1000LL + mavlink_system.sysid;
  2321. }
  2322. /*
  2323. return a timesync request
  2324. Sends back ts1 as received, and tc1 is the local timestamp in usec
  2325. */
  2326. void GCS_MAVLINK::handle_timesync(const mavlink_message_t &msg)
  2327. {
  2328. // decode incoming timesync message
  2329. mavlink_timesync_t tsync;
  2330. mavlink_msg_timesync_decode(&msg, &tsync);
  2331. if (tsync.tc1 != 0) {
  2332. // this is a response to a timesync request
  2333. if (tsync.ts1 != _timesync_request.sent_ts1) {
  2334. // we didn't actually send the request.... or it's a
  2335. // response to an ancient request...
  2336. return;
  2337. }
  2338. const uint64_t round_trip_time_us = (timesync_receive_timestamp_ns() - _timesync_request.sent_ts1)*0.001f;
  2339. #if 0
  2340. gcs().send_text(MAV_SEVERITY_INFO,
  2341. "timesync response sysid=%u (latency=%fms)",
  2342. msg.sysid,
  2343. round_trip_time_us*0.001f);
  2344. #endif
  2345. AP_Logger *logger = AP_Logger::get_singleton();
  2346. if (logger != nullptr) {
  2347. AP::logger().Write(
  2348. "TSYN",
  2349. "TimeUS,SysID,RTT",
  2350. "s-s",
  2351. "F-F",
  2352. "QBQ",
  2353. AP_HAL::micros64(),
  2354. msg.sysid,
  2355. round_trip_time_us
  2356. );
  2357. }
  2358. return;
  2359. }
  2360. if (!HAVE_PAYLOAD_SPACE(chan, TIMESYNC)) {
  2361. // drop this timesync request entirely
  2362. return;
  2363. }
  2364. // create new timesync struct with tc1 field as system time in
  2365. // nanoseconds. The client timestamp is as close as possible to
  2366. // the time we received the TIMESYNC message.
  2367. mavlink_timesync_t rsync;
  2368. rsync.tc1 = timesync_receive_timestamp_ns();
  2369. rsync.ts1 = tsync.ts1;
  2370. // respond with a timesync message
  2371. mavlink_msg_timesync_send(
  2372. chan,
  2373. rsync.tc1,
  2374. rsync.ts1
  2375. );
  2376. }
  2377. /*
  2378. * broadcast a timesync message. We may get multiple responses to this request.
  2379. */
  2380. void GCS_MAVLINK::send_timesync()
  2381. {
  2382. _timesync_request.sent_ts1 = timesync_timestamp_ns();
  2383. mavlink_msg_timesync_send(
  2384. chan,
  2385. 0,
  2386. _timesync_request.sent_ts1
  2387. );
  2388. }
  2389. void GCS_MAVLINK::handle_statustext(const mavlink_message_t &msg)
  2390. {
  2391. AP_Logger *logger = AP_Logger::get_singleton();
  2392. if (logger == nullptr) {
  2393. return;
  2394. }
  2395. mavlink_statustext_t packet;
  2396. mavlink_msg_statustext_decode(&msg, &packet);
  2397. const uint8_t max_prefix_len = 20;
  2398. const uint8_t text_len = MAVLINK_MSG_STATUSTEXT_FIELD_TEXT_LEN+1+max_prefix_len;
  2399. char text[text_len] = { 'G','C','S',':'};
  2400. uint8_t offset = strlen(text);
  2401. if (msg.sysid != sysid_my_gcs()) {
  2402. offset = hal.util->snprintf(text,
  2403. max_prefix_len,
  2404. "SRC=%u/%u:",
  2405. msg.sysid,
  2406. msg.compid);
  2407. offset = MIN(offset, max_prefix_len);
  2408. }
  2409. memcpy(&text[offset], packet.text, MAVLINK_MSG_STATUSTEXT_FIELD_TEXT_LEN);
  2410. logger->Write_Message(text);
  2411. }
  2412. void GCS_MAVLINK::handle_system_time_message(const mavlink_message_t &msg)
  2413. {
  2414. mavlink_system_time_t packet;
  2415. mavlink_msg_system_time_decode(&msg, &packet);
  2416. AP::rtc().set_utc_usec(packet.time_unix_usec, AP_RTC::SOURCE_MAVLINK_SYSTEM_TIME);
  2417. }
  2418. MAV_RESULT GCS_MAVLINK::handle_command_camera(const mavlink_command_long_t &packet)
  2419. {
  2420. AP_Camera *camera = AP::camera();
  2421. if (camera == nullptr) {
  2422. return MAV_RESULT_UNSUPPORTED;
  2423. }
  2424. MAV_RESULT result = MAV_RESULT_FAILED;
  2425. switch (packet.command) {
  2426. case MAV_CMD_DO_DIGICAM_CONFIGURE:
  2427. camera->configure(packet.param1,
  2428. packet.param2,
  2429. packet.param3,
  2430. packet.param4,
  2431. packet.param5,
  2432. packet.param6,
  2433. packet.param7);
  2434. result = MAV_RESULT_ACCEPTED;
  2435. break;
  2436. case MAV_CMD_DO_DIGICAM_CONTROL:
  2437. camera->control(packet.param1,
  2438. packet.param2,
  2439. packet.param3,
  2440. packet.param4,
  2441. packet.param5,
  2442. packet.param6);
  2443. result = MAV_RESULT_ACCEPTED;
  2444. break;
  2445. case MAV_CMD_DO_SET_CAM_TRIGG_DIST:
  2446. camera->set_trigger_distance(packet.param1);
  2447. result = MAV_RESULT_ACCEPTED;
  2448. break;
  2449. default:
  2450. result = MAV_RESULT_UNSUPPORTED;
  2451. break;
  2452. }
  2453. return result;
  2454. }
  2455. // sets ekf_origin if it has not been set.
  2456. // should only be used when there is no GPS to provide an absolute position
  2457. void GCS_MAVLINK::set_ekf_origin(const Location& loc)
  2458. {
  2459. // check location is valid
  2460. if (!loc.check_latlng()) {
  2461. return;
  2462. }
  2463. AP_AHRS &ahrs = AP::ahrs();
  2464. // check if EKF origin has already been set
  2465. Location ekf_origin;
  2466. if (ahrs.get_origin(ekf_origin)) {
  2467. return;
  2468. }
  2469. if (!ahrs.set_origin(loc)) {
  2470. return;
  2471. }
  2472. ahrs.Log_Write_Home_And_Origin();
  2473. // send ekf origin to GCS
  2474. if (!try_send_message(MSG_ORIGIN)) {
  2475. // try again later
  2476. send_message(MSG_ORIGIN);
  2477. }
  2478. }
  2479. void GCS_MAVLINK::handle_set_gps_global_origin(const mavlink_message_t &msg)
  2480. {
  2481. mavlink_set_gps_global_origin_t packet;
  2482. mavlink_msg_set_gps_global_origin_decode(&msg, &packet);
  2483. // sanity check location
  2484. if (!check_latlng(packet.latitude, packet.longitude)) {
  2485. // silently drop the request
  2486. return;
  2487. }
  2488. Location ekf_origin {};
  2489. ekf_origin.lat = packet.latitude;
  2490. ekf_origin.lng = packet.longitude;
  2491. ekf_origin.alt = packet.altitude / 10;
  2492. set_ekf_origin(ekf_origin);
  2493. }
  2494. /*
  2495. handle a DATA96 message
  2496. */
  2497. void GCS_MAVLINK::handle_data_packet(const mavlink_message_t &msg)
  2498. {
  2499. #if HAL_RCINPUT_WITH_AP_RADIO
  2500. mavlink_data96_t m;
  2501. mavlink_msg_data96_decode(&msg, &m);
  2502. switch (m.type) {
  2503. case 42:
  2504. case 43: {
  2505. // pass to AP_Radio (for firmware upload and playing test tunes)
  2506. AP_Radio *radio = AP_Radio::get_singleton();
  2507. if (radio != nullptr) {
  2508. radio->handle_data_packet(chan, m);
  2509. }
  2510. break;
  2511. }
  2512. default:
  2513. // unknown
  2514. break;
  2515. }
  2516. #endif
  2517. }
  2518. void GCS_MAVLINK::handle_vision_position_delta(const mavlink_message_t &msg)
  2519. {
  2520. AP_VisualOdom *visual_odom = AP::visualodom();
  2521. if (visual_odom == nullptr) {
  2522. return;
  2523. }
  2524. visual_odom->handle_msg(msg);
  2525. }
  2526. void GCS_MAVLINK::handle_vision_position_estimate(const mavlink_message_t &msg)
  2527. {
  2528. mavlink_vision_position_estimate_t m;
  2529. mavlink_msg_vision_position_estimate_decode(&msg, &m);
  2530. handle_common_vision_position_estimate_data(m.usec, m.x, m.y, m.z, m.roll, m.pitch, m.yaw,
  2531. PAYLOAD_SIZE(chan, VISION_POSITION_ESTIMATE));
  2532. }
  2533. void GCS_MAVLINK::handle_global_vision_position_estimate(const mavlink_message_t &msg)
  2534. {
  2535. mavlink_global_vision_position_estimate_t m;
  2536. mavlink_msg_global_vision_position_estimate_decode(&msg, &m);
  2537. handle_common_vision_position_estimate_data(m.usec, m.x, m.y, m.z, m.roll, m.pitch, m.yaw,
  2538. PAYLOAD_SIZE(chan, GLOBAL_VISION_POSITION_ESTIMATE));
  2539. }
  2540. void GCS_MAVLINK::handle_vicon_position_estimate(const mavlink_message_t &msg)
  2541. {
  2542. mavlink_vicon_position_estimate_t m;
  2543. mavlink_msg_vicon_position_estimate_decode(&msg, &m);
  2544. handle_common_vision_position_estimate_data(m.usec, m.x, m.y, m.z, m.roll, m.pitch, m.yaw,
  2545. PAYLOAD_SIZE(chan, VICON_POSITION_ESTIMATE));
  2546. }
  2547. // there are several messages which all have identical fields in them.
  2548. // This function provides common handling for the data contained in
  2549. // these packets
  2550. void GCS_MAVLINK::handle_common_vision_position_estimate_data(const uint64_t usec,
  2551. const float x,
  2552. const float y,
  2553. const float z,
  2554. const float roll,
  2555. const float pitch,
  2556. const float yaw,
  2557. const uint16_t payload_size)
  2558. {
  2559. // correct offboard timestamp to be in local ms since boot
  2560. uint32_t timestamp_ms = correct_offboard_timestamp_usec_to_ms(usec, payload_size);
  2561. // sensor assumed to be at 0,0,0 body-frame; need parameters for this?
  2562. // or a new message
  2563. const Vector3f sensor_offset = {};
  2564. const Vector3f pos = {
  2565. x,
  2566. y,
  2567. z
  2568. };
  2569. Quaternion attitude;
  2570. attitude.from_euler(roll, pitch, yaw); // from_vector312?
  2571. const float posErr = 0; // parameter required?
  2572. const float angErr = 0; // parameter required?
  2573. const uint32_t reset_timestamp_ms = 0; // no data available
  2574. AP::ahrs().writeExtNavData(sensor_offset,
  2575. pos,
  2576. attitude,
  2577. posErr,
  2578. angErr,
  2579. timestamp_ms,
  2580. reset_timestamp_ms);
  2581. log_vision_position_estimate_data(usec, timestamp_ms, x, y, z, roll, pitch, yaw);
  2582. }
  2583. void GCS_MAVLINK::log_vision_position_estimate_data(const uint64_t usec,
  2584. const uint32_t corrected_msec,
  2585. const float x,
  2586. const float y,
  2587. const float z,
  2588. const float roll,
  2589. const float pitch,
  2590. const float yaw)
  2591. {
  2592. AP::logger().Write("VISP", "TimeUS,RemTimeUS,CTimeMS,PX,PY,PZ,Roll,Pitch,Yaw",
  2593. "sssmmmddh", "FFC000000", "QQIffffff",
  2594. (uint64_t)AP_HAL::micros64(),
  2595. (uint64_t)usec,
  2596. corrected_msec,
  2597. (double)x,
  2598. (double)y,
  2599. (double)z,
  2600. (double)(roll * RAD_TO_DEG),
  2601. (double)(pitch * RAD_TO_DEG),
  2602. (double)(yaw * RAD_TO_DEG));
  2603. }
  2604. void GCS_MAVLINK::handle_att_pos_mocap(const mavlink_message_t &msg)
  2605. {
  2606. mavlink_att_pos_mocap_t m;
  2607. mavlink_msg_att_pos_mocap_decode(&msg, &m);
  2608. // sensor assumed to be at 0,0,0 body-frame; need parameters for this?
  2609. const Vector3f sensor_offset = {};
  2610. const Vector3f pos = {
  2611. m.x,
  2612. m.y,
  2613. m.z
  2614. };
  2615. Quaternion attitude = Quaternion(m.q);
  2616. const float posErr = 0; // parameter required?
  2617. const float angErr = 0; // parameter required?
  2618. // correct offboard timestamp to be in local ms since boot
  2619. uint32_t timestamp_ms = correct_offboard_timestamp_usec_to_ms(m.time_usec, PAYLOAD_SIZE(chan, ATT_POS_MOCAP));
  2620. const uint32_t reset_timestamp_ms = 0; // no data available
  2621. AP::ahrs().writeExtNavData(sensor_offset,
  2622. pos,
  2623. attitude,
  2624. posErr,
  2625. angErr,
  2626. timestamp_ms,
  2627. reset_timestamp_ms);
  2628. // calculate euler orientation for logging
  2629. float roll;
  2630. float pitch;
  2631. float yaw;
  2632. attitude.to_euler(roll, pitch, yaw);
  2633. log_vision_position_estimate_data(m.time_usec, timestamp_ms, m.x, m.y, m.z, roll, pitch, yaw);
  2634. }
  2635. void GCS_MAVLINK::handle_command_ack(const mavlink_message_t &msg)
  2636. {
  2637. AP_AccelCal *accelcal = AP::ins().get_acal();
  2638. if (accelcal != nullptr) {
  2639. accelcal->handleMessage(msg);
  2640. }
  2641. }
  2642. // allow override of RC channel values for HIL or for complete GCS
  2643. // control of switch position and RC PWM values.
  2644. void GCS_MAVLINK::handle_rc_channels_override(const mavlink_message_t &msg)
  2645. {
  2646. if(msg.sysid != sysid_my_gcs()) {
  2647. return; // Only accept control from our gcs
  2648. }
  2649. const uint32_t tnow = AP_HAL::millis();
  2650. mavlink_rc_channels_override_t packet;
  2651. mavlink_msg_rc_channels_override_decode(&msg, &packet);
  2652. const uint16_t override_data[] = {
  2653. packet.chan1_raw,
  2654. packet.chan2_raw,
  2655. packet.chan3_raw,
  2656. packet.chan4_raw,
  2657. packet.chan5_raw,
  2658. packet.chan6_raw,
  2659. packet.chan7_raw,
  2660. packet.chan8_raw,
  2661. packet.chan9_raw,
  2662. packet.chan10_raw,
  2663. packet.chan11_raw,
  2664. packet.chan12_raw,
  2665. packet.chan13_raw,
  2666. packet.chan14_raw,
  2667. packet.chan15_raw,
  2668. packet.chan16_raw
  2669. };
  2670. for (uint8_t i=0; i<ARRAY_SIZE(override_data); i++) {
  2671. // Per MAVLink spec a value of UINT16_MAX means to ignore this field.
  2672. if (override_data[i] != UINT16_MAX) {
  2673. RC_Channels::set_override(i, override_data[i], tnow);
  2674. }
  2675. }
  2676. }
  2677. // allow override of RC channel values for HIL or for complete GCS
  2678. // control of switch position and RC PWM values.
  2679. void GCS_MAVLINK::handle_optical_flow(const mavlink_message_t &msg)
  2680. {
  2681. OpticalFlow *optflow = AP::opticalflow();
  2682. if (optflow == nullptr) {
  2683. return;
  2684. }
  2685. optflow->handle_msg(msg);
  2686. }
  2687. /*
  2688. handle messages which don't require vehicle specific data
  2689. */
  2690. void GCS_MAVLINK::handle_common_message(const mavlink_message_t &msg)
  2691. {
  2692. switch (msg.msgid) {
  2693. case MAVLINK_MSG_ID_COMMAND_ACK: {
  2694. handle_command_ack(msg);
  2695. break;
  2696. }
  2697. case MAVLINK_MSG_ID_SETUP_SIGNING:
  2698. handle_setup_signing(msg);
  2699. break;
  2700. case MAVLINK_MSG_ID_PARAM_REQUEST_LIST:
  2701. case MAVLINK_MSG_ID_PARAM_SET:
  2702. case MAVLINK_MSG_ID_PARAM_REQUEST_READ:
  2703. handle_common_param_message(msg);
  2704. break;
  2705. case MAVLINK_MSG_ID_SET_GPS_GLOBAL_ORIGIN:
  2706. handle_set_gps_global_origin(msg);
  2707. break;
  2708. case MAVLINK_MSG_ID_DEVICE_OP_READ:
  2709. handle_device_op_read(msg);
  2710. break;
  2711. case MAVLINK_MSG_ID_DEVICE_OP_WRITE:
  2712. handle_device_op_write(msg);
  2713. break;
  2714. case MAVLINK_MSG_ID_TIMESYNC:
  2715. handle_timesync(msg);
  2716. break;
  2717. case MAVLINK_MSG_ID_LOG_REQUEST_LIST:
  2718. case MAVLINK_MSG_ID_LOG_REQUEST_DATA:
  2719. case MAVLINK_MSG_ID_LOG_ERASE:
  2720. case MAVLINK_MSG_ID_LOG_REQUEST_END:
  2721. case MAVLINK_MSG_ID_REMOTE_LOG_BLOCK_STATUS:
  2722. AP::logger().handle_mavlink_msg(*this, msg);
  2723. break;
  2724. case MAVLINK_MSG_ID_DIGICAM_CONTROL:
  2725. {
  2726. AP_Camera *camera = AP::camera();
  2727. if (camera == nullptr) {
  2728. return;
  2729. }
  2730. camera->control_msg(msg);
  2731. }
  2732. break;
  2733. case MAVLINK_MSG_ID_SET_MODE:
  2734. handle_set_mode(msg);
  2735. break;
  2736. case MAVLINK_MSG_ID_AUTOPILOT_VERSION_REQUEST:
  2737. handle_send_autopilot_version(msg);
  2738. break;
  2739. case MAVLINK_MSG_ID_MISSION_WRITE_PARTIAL_LIST:
  2740. case MAVLINK_MSG_ID_MISSION_REQUEST_LIST:
  2741. case MAVLINK_MSG_ID_MISSION_COUNT:
  2742. case MAVLINK_MSG_ID_MISSION_CLEAR_ALL:
  2743. case MAVLINK_MSG_ID_MISSION_ITEM:
  2744. case MAVLINK_MSG_ID_MISSION_ITEM_INT:
  2745. case MAVLINK_MSG_ID_MISSION_REQUEST_INT:
  2746. case MAVLINK_MSG_ID_MISSION_REQUEST:
  2747. case MAVLINK_MSG_ID_MISSION_ACK:
  2748. case MAVLINK_MSG_ID_MISSION_SET_CURRENT:
  2749. handle_common_mission_message(msg);
  2750. break;
  2751. case MAVLINK_MSG_ID_COMMAND_LONG:
  2752. handle_command_long(msg);
  2753. break;
  2754. case MAVLINK_MSG_ID_COMMAND_INT:
  2755. handle_command_int(msg);
  2756. break;
  2757. case MAVLINK_MSG_ID_FENCE_POINT:
  2758. case MAVLINK_MSG_ID_FENCE_FETCH_POINT:
  2759. handle_fence_message(msg);
  2760. break;
  2761. case MAVLINK_MSG_ID_GIMBAL_REPORT:
  2762. handle_mount_message(msg);
  2763. break;
  2764. case MAVLINK_MSG_ID_PARAM_VALUE:
  2765. handle_param_value(msg);
  2766. break;
  2767. case MAVLINK_MSG_ID_SERIAL_CONTROL:
  2768. handle_serial_control(msg);
  2769. break;
  2770. case MAVLINK_MSG_ID_GPS_RTCM_DATA:
  2771. case MAVLINK_MSG_ID_GPS_INPUT:
  2772. case MAVLINK_MSG_ID_HIL_GPS:
  2773. case MAVLINK_MSG_ID_GPS_INJECT_DATA:
  2774. AP::gps().handle_msg(msg);
  2775. break;
  2776. case MAVLINK_MSG_ID_STATUSTEXT:
  2777. handle_statustext(msg);
  2778. break;
  2779. case MAVLINK_MSG_ID_LED_CONTROL:
  2780. // send message to Notify
  2781. AP_Notify::handle_led_control(msg);
  2782. break;
  2783. case MAVLINK_MSG_ID_MOUNT_CONFIGURE: // deprecated. Use MAV_CMD_DO_MOUNT_CONFIGURE
  2784. case MAVLINK_MSG_ID_MOUNT_CONTROL: // deprecated. Use MAV_CMD_DO_MOUNT_CONTROL
  2785. handle_mount_message(msg);
  2786. break;
  2787. case MAVLINK_MSG_ID_PLAY_TUNE:
  2788. // send message to Notify
  2789. AP_Notify::handle_play_tune(msg);
  2790. break;
  2791. case MAVLINK_MSG_ID_RALLY_POINT:
  2792. case MAVLINK_MSG_ID_RALLY_FETCH_POINT:
  2793. handle_common_rally_message(msg);
  2794. break;
  2795. case MAVLINK_MSG_ID_REQUEST_DATA_STREAM:
  2796. handle_request_data_stream(msg);
  2797. break;
  2798. case MAVLINK_MSG_ID_DATA96:
  2799. handle_data_packet(msg);
  2800. break;
  2801. case MAVLINK_MSG_ID_VISION_POSITION_DELTA:
  2802. handle_vision_position_delta(msg);
  2803. break;
  2804. case MAVLINK_MSG_ID_VISION_POSITION_ESTIMATE:
  2805. handle_vision_position_estimate(msg);
  2806. break;
  2807. case MAVLINK_MSG_ID_GLOBAL_VISION_POSITION_ESTIMATE:
  2808. handle_global_vision_position_estimate(msg);
  2809. break;
  2810. case MAVLINK_MSG_ID_VICON_POSITION_ESTIMATE:
  2811. handle_vicon_position_estimate(msg);
  2812. break;
  2813. case MAVLINK_MSG_ID_ATT_POS_MOCAP:
  2814. handle_att_pos_mocap(msg);
  2815. break;
  2816. case MAVLINK_MSG_ID_SYSTEM_TIME:
  2817. handle_system_time_message(msg);
  2818. break;
  2819. case MAVLINK_MSG_ID_RC_CHANNELS_OVERRIDE:
  2820. handle_rc_channels_override(msg);
  2821. break;
  2822. case MAVLINK_MSG_ID_OPTICAL_FLOW:
  2823. handle_optical_flow(msg);
  2824. break;
  2825. }
  2826. }
  2827. void GCS_MAVLINK::handle_common_mission_message(const mavlink_message_t &msg)
  2828. {
  2829. AP_Mission *_mission = AP::mission();
  2830. if (_mission == nullptr) {
  2831. return;
  2832. }
  2833. switch (msg.msgid) {
  2834. case MAVLINK_MSG_ID_MISSION_WRITE_PARTIAL_LIST: // MAV ID: 38
  2835. {
  2836. handle_mission_write_partial_list(msg);
  2837. break;
  2838. }
  2839. // GCS has sent us a mission item, store to EEPROM
  2840. case MAVLINK_MSG_ID_MISSION_ITEM: // MAV ID: 39
  2841. case MAVLINK_MSG_ID_MISSION_ITEM_INT:
  2842. handle_mission_item(msg);
  2843. break;
  2844. // read an individual command from EEPROM and send it to the GCS
  2845. case MAVLINK_MSG_ID_MISSION_REQUEST_INT:
  2846. handle_mission_request_int(msg);
  2847. break;
  2848. case MAVLINK_MSG_ID_MISSION_REQUEST:
  2849. handle_mission_request(msg);
  2850. break;
  2851. case MAVLINK_MSG_ID_MISSION_SET_CURRENT: // MAV ID: 41
  2852. {
  2853. handle_mission_set_current(*_mission, msg);
  2854. break;
  2855. }
  2856. // GCS request the full list of commands, we return just the number and leave the GCS to then request each command individually
  2857. case MAVLINK_MSG_ID_MISSION_REQUEST_LIST: // MAV ID: 43
  2858. {
  2859. handle_mission_request_list(msg);
  2860. break;
  2861. }
  2862. // GCS provides the full number of commands it wishes to upload
  2863. // individual commands will then be sent from the GCS using the MAVLINK_MSG_ID_MISSION_ITEM message
  2864. case MAVLINK_MSG_ID_MISSION_COUNT: // MAV ID: 44
  2865. {
  2866. handle_mission_count(msg);
  2867. break;
  2868. }
  2869. case MAVLINK_MSG_ID_MISSION_CLEAR_ALL: // MAV ID: 45
  2870. {
  2871. handle_mission_clear_all(msg);
  2872. break;
  2873. }
  2874. case MAVLINK_MSG_ID_MISSION_ACK:
  2875. /* not used */
  2876. break;
  2877. }
  2878. }
  2879. void GCS_MAVLINK::handle_send_autopilot_version(const mavlink_message_t &msg)
  2880. {
  2881. send_message(MSG_AUTOPILOT_VERSION);
  2882. }
  2883. void GCS_MAVLINK::send_banner()
  2884. {
  2885. // mark the firmware version in the tlog
  2886. const AP_FWVersion &fwver = AP::fwversion();
  2887. send_text(MAV_SEVERITY_INFO, "%s", fwver.fw_string);
  2888. if (fwver.middleware_name && fwver.os_name) {
  2889. send_text(MAV_SEVERITY_INFO, "%s: %s %s: %s",
  2890. fwver.middleware_name, fwver.middleware_hash_str,
  2891. fwver.os_name, fwver.os_hash_str);
  2892. } else if (fwver.os_name) {
  2893. send_text(MAV_SEVERITY_INFO, "%s: %s",
  2894. fwver.os_name, fwver.os_hash_str);
  2895. }
  2896. // send system ID if we can
  2897. char sysid[40];
  2898. if (hal.util->get_system_id(sysid)) {
  2899. send_text(MAV_SEVERITY_INFO, "%s", sysid);
  2900. }
  2901. }
  2902. void GCS_MAVLINK::send_simstate() const
  2903. {
  2904. #if CONFIG_HAL_BOARD == HAL_BOARD_SITL
  2905. SITL::SITL *sitl = AP::sitl();
  2906. if (sitl == nullptr) {
  2907. return;
  2908. }
  2909. sitl->simstate_send(get_chan());
  2910. #endif
  2911. }
  2912. MAV_RESULT GCS_MAVLINK::handle_command_flash_bootloader(const mavlink_command_long_t &packet)
  2913. {
  2914. if (uint32_t(packet.param5) != 290876) {
  2915. gcs().send_text(MAV_SEVERITY_INFO, "Magic not set");
  2916. return MAV_RESULT_FAILED;
  2917. }
  2918. if (!hal.util->flash_bootloader()) {
  2919. return MAV_RESULT_FAILED;
  2920. }
  2921. return MAV_RESULT_ACCEPTED;
  2922. }
  2923. MAV_RESULT GCS_MAVLINK::handle_command_preflight_set_sensor_offsets(const mavlink_command_long_t &packet)
  2924. {
  2925. Compass &compass = AP::compass();
  2926. uint8_t compassNumber = -1;
  2927. if (is_equal(packet.param1, 2.0f)) {
  2928. compassNumber = 0;
  2929. } else if (is_equal(packet.param1, 5.0f)) {
  2930. compassNumber = 1;
  2931. } else if (is_equal(packet.param1, 6.0f)) {
  2932. compassNumber = 2;
  2933. }
  2934. if (compassNumber == (uint8_t) -1) {
  2935. return MAV_RESULT_FAILED;
  2936. }
  2937. compass.set_and_save_offsets(compassNumber, Vector3f(packet.param2, packet.param3, packet.param4));
  2938. return MAV_RESULT_ACCEPTED;
  2939. }
  2940. bool GCS_MAVLINK::calibrate_gyros()
  2941. {
  2942. AP::ins().init_gyro();
  2943. if (!AP::ins().gyro_calibrated_ok_all()) {
  2944. return false;
  2945. }
  2946. AP::ahrs().reset_gyro_drift();
  2947. return true;
  2948. }
  2949. MAV_RESULT GCS_MAVLINK::_handle_command_preflight_calibration_baro()
  2950. {
  2951. // fast barometer calibration
  2952. gcs().send_text(MAV_SEVERITY_INFO, "Updating barometer calibration");
  2953. AP::baro().update_calibration();
  2954. gcs().send_text(MAV_SEVERITY_INFO, "Barometer calibration complete");
  2955. AP_Airspeed *airspeed = AP_Airspeed::get_singleton();
  2956. if (airspeed != nullptr) {
  2957. airspeed->calibrate(false);
  2958. }
  2959. return MAV_RESULT_ACCEPTED;
  2960. }
  2961. MAV_RESULT GCS_MAVLINK::_handle_command_preflight_calibration(const mavlink_command_long_t &packet)
  2962. {
  2963. EXPECT_DELAY_MS(30000);
  2964. if (is_equal(packet.param1,1.0f)) {
  2965. if (!calibrate_gyros()) {
  2966. return MAV_RESULT_FAILED;
  2967. }
  2968. return MAV_RESULT_ACCEPTED;
  2969. }
  2970. if (is_equal(packet.param3,1.0f)) {
  2971. return _handle_command_preflight_calibration_baro();
  2972. }
  2973. if (is_equal(packet.param5,1.0f)) {
  2974. // start with gyro calibration
  2975. if (!calibrate_gyros()) {
  2976. return MAV_RESULT_FAILED;
  2977. }
  2978. // start accel cal
  2979. AP::ins().acal_init();
  2980. AP::ins().get_acal()->start(this);
  2981. return MAV_RESULT_ACCEPTED;
  2982. }
  2983. if (is_equal(packet.param5,2.0f)) {
  2984. if (!calibrate_gyros()) {
  2985. return MAV_RESULT_FAILED;
  2986. }
  2987. float trim_roll, trim_pitch;
  2988. if (!AP::ins().calibrate_trim(trim_roll, trim_pitch)) {
  2989. return MAV_RESULT_FAILED;
  2990. }
  2991. // reset ahrs's trim to suggested values from calibration routine
  2992. AP::ahrs().set_trim(Vector3f(trim_roll, trim_pitch, 0));
  2993. return MAV_RESULT_ACCEPTED;
  2994. }
  2995. if (is_equal(packet.param5,4.0f)) {
  2996. // simple accel calibration
  2997. return AP::ins().simple_accel_cal();
  2998. }
  2999. return MAV_RESULT_UNSUPPORTED;
  3000. }
  3001. MAV_RESULT GCS_MAVLINK::handle_command_preflight_calibration(const mavlink_command_long_t &packet)
  3002. {
  3003. if (hal.util->get_soft_armed()) {
  3004. // *preflight*, remember?
  3005. return MAV_RESULT_FAILED;
  3006. }
  3007. // now call subclass methods:
  3008. return _handle_command_preflight_calibration(packet);
  3009. }
  3010. MAV_RESULT GCS_MAVLINK::handle_command_preflight_can(const mavlink_command_long_t &packet)
  3011. {
  3012. #if HAL_WITH_UAVCAN
  3013. if (hal.util->get_soft_armed()) {
  3014. // *preflight*, remember?
  3015. return MAV_RESULT_TEMPORARILY_REJECTED;
  3016. }
  3017. bool start_stop = is_equal(packet.param1,1.0f) ? true : false;
  3018. bool result = true;
  3019. bool can_exists = false;
  3020. uint8_t num_drivers = AP::can().get_num_drivers();
  3021. for (uint8_t i = 0; i < num_drivers; i++) {
  3022. switch (AP::can().get_protocol_type(i)) {
  3023. case AP_BoardConfig_CAN::Protocol_Type_KDECAN: {
  3024. // To be replaced with macro saying if KDECAN library is included
  3025. #if APM_BUILD_TYPE(APM_BUILD_ArduCopter) || APM_BUILD_TYPE(APM_BUILD_ArduPlane) || APM_BUILD_TYPE(APM_BUILD_ArduSub)
  3026. AP_KDECAN *ap_kdecan = AP_KDECAN::get_kdecan(i);
  3027. if (ap_kdecan != nullptr) {
  3028. can_exists = true;
  3029. result = ap_kdecan->run_enumeration(start_stop) && result;
  3030. }
  3031. break;
  3032. #else
  3033. UNUSED_RESULT(start_stop); // prevent unused variable error
  3034. #endif
  3035. }
  3036. case AP_BoardConfig_CAN::Protocol_Type_UAVCAN:
  3037. case AP_BoardConfig_CAN::Protocol_Type_None:
  3038. default:
  3039. break;
  3040. }
  3041. }
  3042. MAV_RESULT ack = MAV_RESULT_DENIED;
  3043. if (can_exists) {
  3044. ack = result ? MAV_RESULT_ACCEPTED : MAV_RESULT_FAILED;
  3045. }
  3046. return ack;
  3047. #else
  3048. return MAV_RESULT_UNSUPPORTED;
  3049. #endif
  3050. }
  3051. MAV_RESULT GCS_MAVLINK::handle_command_battery_reset(const mavlink_command_long_t &packet)
  3052. {
  3053. const uint16_t battery_mask = packet.param1;
  3054. const float percentage = packet.param2;
  3055. if (AP::battery().reset_remaining(battery_mask, percentage)) {
  3056. return MAV_RESULT_ACCEPTED;
  3057. }
  3058. return MAV_RESULT_FAILED;
  3059. }
  3060. MAV_RESULT GCS_MAVLINK::handle_command_mag_cal(const mavlink_command_long_t &packet)
  3061. {
  3062. return AP::compass().handle_mag_cal_command(packet);
  3063. }
  3064. MAV_RESULT GCS_MAVLINK::handle_command_request_autopilot_capabilities(const mavlink_command_long_t &packet)
  3065. {
  3066. if (!is_equal(packet.param1,1.0f)) {
  3067. return MAV_RESULT_FAILED;
  3068. }
  3069. send_message(MSG_AUTOPILOT_VERSION);
  3070. return MAV_RESULT_ACCEPTED;
  3071. }
  3072. MAV_RESULT GCS_MAVLINK::handle_command_do_send_banner(const mavlink_command_long_t &packet)
  3073. {
  3074. send_banner();
  3075. return MAV_RESULT_ACCEPTED;
  3076. }
  3077. MAV_RESULT GCS_MAVLINK::handle_command_do_set_mode(const mavlink_command_long_t &packet)
  3078. {
  3079. const MAV_MODE _base_mode = (MAV_MODE)packet.param1;
  3080. const uint32_t _custom_mode = (uint32_t)packet.param2;
  3081. return _set_mode_common(_base_mode, _custom_mode);
  3082. }
  3083. MAV_RESULT GCS_MAVLINK::handle_command_get_home_position(const mavlink_command_long_t &packet)
  3084. {
  3085. if (!AP::ahrs().home_is_set()) {
  3086. return MAV_RESULT_FAILED;
  3087. }
  3088. if (!try_send_message(MSG_HOME)) {
  3089. // try again later
  3090. send_message(MSG_HOME);
  3091. }
  3092. if (!try_send_message(MSG_ORIGIN)) {
  3093. // try again later
  3094. send_message(MSG_ORIGIN);
  3095. }
  3096. return MAV_RESULT_ACCEPTED;
  3097. }
  3098. MAV_RESULT GCS_MAVLINK::handle_command_do_gripper(const mavlink_command_long_t &packet)
  3099. {
  3100. AP_Gripper *gripper = AP::gripper();
  3101. if (gripper == nullptr) {
  3102. return MAV_RESULT_FAILED;
  3103. }
  3104. // param1 : gripper number (ignored)
  3105. // param2 : action (0=release, 1=grab). See GRIPPER_ACTIONS enum.
  3106. if(!gripper->enabled()) {
  3107. return MAV_RESULT_FAILED;
  3108. }
  3109. MAV_RESULT result = MAV_RESULT_ACCEPTED;
  3110. switch ((uint8_t)packet.param2) {
  3111. case GRIPPER_ACTION_RELEASE:
  3112. gripper->release();
  3113. break;
  3114. case GRIPPER_ACTION_GRAB:
  3115. gripper->grab();
  3116. break;
  3117. default:
  3118. result = MAV_RESULT_FAILED;
  3119. break;
  3120. }
  3121. return result;
  3122. }
  3123. MAV_RESULT GCS_MAVLINK::handle_command_accelcal_vehicle_pos(const mavlink_command_long_t &packet)
  3124. {
  3125. if (!AP::ins().get_acal()->gcs_vehicle_position(packet.param1)) {
  3126. return MAV_RESULT_FAILED;
  3127. }
  3128. return MAV_RESULT_ACCEPTED;
  3129. }
  3130. MAV_RESULT GCS_MAVLINK::handle_command_mount(const mavlink_command_long_t &packet)
  3131. {
  3132. AP_Mount *mount = AP::mount();
  3133. if (mount == nullptr) {
  3134. return MAV_RESULT_UNSUPPORTED;
  3135. }
  3136. return mount->handle_command_long(packet);
  3137. }
  3138. MAV_RESULT GCS_MAVLINK::handle_command_do_set_home(const mavlink_command_long_t &packet)
  3139. {
  3140. if (is_equal(packet.param1, 1.0f) || (is_zero(packet.param5) && is_zero(packet.param6))) {
  3141. // param1 is 1 (or both lat and lon are zero); use current location
  3142. if (!set_home_to_current_location(true)) {
  3143. return MAV_RESULT_FAILED;
  3144. }
  3145. return MAV_RESULT_ACCEPTED;
  3146. }
  3147. // ensure param1 is zero
  3148. if (!is_zero(packet.param1)) {
  3149. return MAV_RESULT_FAILED;
  3150. }
  3151. Location new_home_loc;
  3152. new_home_loc.lat = (int32_t)(packet.param5 * 1.0e7f);
  3153. new_home_loc.lng = (int32_t)(packet.param6 * 1.0e7f);
  3154. new_home_loc.alt = (int32_t)(packet.param7 * 100.0f);
  3155. if (!set_home(new_home_loc, true)) {
  3156. return MAV_RESULT_FAILED;
  3157. }
  3158. return MAV_RESULT_ACCEPTED;
  3159. }
  3160. MAV_RESULT GCS_MAVLINK::handle_command_long_packet(const mavlink_command_long_t &packet)
  3161. {
  3162. MAV_RESULT result = MAV_RESULT_FAILED;
  3163. switch (packet.command) {
  3164. case MAV_CMD_ACCELCAL_VEHICLE_POS:
  3165. result = handle_command_accelcal_vehicle_pos(packet);
  3166. break;
  3167. case MAV_CMD_DO_SET_MODE:
  3168. result = handle_command_do_set_mode(packet);
  3169. break;
  3170. case MAV_CMD_DO_SEND_BANNER:
  3171. result = handle_command_do_send_banner(packet);
  3172. break;
  3173. case MAV_CMD_DO_SET_HOME:
  3174. result = handle_command_do_set_home(packet);
  3175. break;
  3176. case MAV_CMD_DO_FENCE_ENABLE:
  3177. result = handle_command_do_fence_enable(packet);
  3178. break;
  3179. case MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN:
  3180. result = handle_preflight_reboot(packet);
  3181. break;
  3182. case MAV_CMD_DO_START_MAG_CAL:
  3183. case MAV_CMD_DO_ACCEPT_MAG_CAL:
  3184. case MAV_CMD_DO_CANCEL_MAG_CAL: {
  3185. result = handle_command_mag_cal(packet);
  3186. break;
  3187. }
  3188. case MAV_CMD_START_RX_PAIR:
  3189. result = handle_rc_bind(packet);
  3190. break;
  3191. case MAV_CMD_DO_DIGICAM_CONFIGURE:
  3192. case MAV_CMD_DO_DIGICAM_CONTROL:
  3193. case MAV_CMD_DO_SET_CAM_TRIGG_DIST:
  3194. result = handle_command_camera(packet);
  3195. break;
  3196. case MAV_CMD_DO_GRIPPER:
  3197. result = handle_command_do_gripper(packet);
  3198. break;
  3199. case MAV_CMD_DO_MOUNT_CONFIGURE:
  3200. case MAV_CMD_DO_MOUNT_CONTROL:
  3201. result = handle_command_mount(packet);
  3202. break;
  3203. case MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES: {
  3204. result = handle_command_request_autopilot_capabilities(packet);
  3205. break;
  3206. }
  3207. case MAV_CMD_DO_SET_ROI_LOCATION:
  3208. case MAV_CMD_DO_SET_ROI:
  3209. result = handle_command_do_set_roi(packet);
  3210. break;
  3211. case MAV_CMD_PREFLIGHT_CALIBRATION:
  3212. result = handle_command_preflight_calibration(packet);
  3213. break;
  3214. case MAV_CMD_BATTERY_RESET:
  3215. result = handle_command_battery_reset(packet);
  3216. break;
  3217. case MAV_CMD_PREFLIGHT_UAVCAN:
  3218. result = handle_command_preflight_can(packet);
  3219. break;
  3220. case MAV_CMD_FLASH_BOOTLOADER:
  3221. result = handle_command_flash_bootloader(packet);
  3222. break;
  3223. case MAV_CMD_PREFLIGHT_SET_SENSOR_OFFSETS: {
  3224. result = handle_command_preflight_set_sensor_offsets(packet);
  3225. break;
  3226. }
  3227. case MAV_CMD_GET_HOME_POSITION:
  3228. result = handle_command_get_home_position(packet);
  3229. break;
  3230. case MAV_CMD_PREFLIGHT_STORAGE:
  3231. if (is_equal(packet.param1, 2.0f)) {
  3232. AP_Param::erase_all();
  3233. send_text(MAV_SEVERITY_WARNING, "All parameters reset, reboot board");
  3234. result= MAV_RESULT_ACCEPTED;
  3235. }
  3236. break;
  3237. case MAV_CMD_SET_MESSAGE_INTERVAL:
  3238. result = handle_command_set_message_interval(packet);
  3239. break;
  3240. case MAV_CMD_GET_MESSAGE_INTERVAL:
  3241. result = handle_command_get_message_interval(packet);
  3242. break;
  3243. case MAV_CMD_REQUEST_MESSAGE:
  3244. result = handle_command_request_message(packet);
  3245. break;
  3246. case MAV_CMD_DO_SET_SERVO:
  3247. case MAV_CMD_DO_REPEAT_SERVO:
  3248. case MAV_CMD_DO_SET_RELAY:
  3249. case MAV_CMD_DO_REPEAT_RELAY:
  3250. result = handle_servorelay_message(packet);
  3251. break;
  3252. case MAV_CMD_DO_FLIGHTTERMINATION:
  3253. result = handle_flight_termination(packet);
  3254. break;
  3255. case MAV_CMD_COMPONENT_ARM_DISARM:
  3256. if (is_equal(packet.param1,1.0f)) {
  3257. // run pre_arm_checks and arm_checks and display failures
  3258. const bool do_arming_checks = !is_equal(packet.param2,magic_force_arm_value);
  3259. if (AP::arming().is_armed() ||
  3260. AP::arming().arm(AP_Arming::Method::MAVLINK, do_arming_checks)) {
  3261. return MAV_RESULT_ACCEPTED;
  3262. }
  3263. return MAV_RESULT_FAILED;
  3264. }
  3265. if (is_zero(packet.param1)) {
  3266. if (!AP::arming().is_armed()) {
  3267. return MAV_RESULT_ACCEPTED;
  3268. }
  3269. // allow vehicle to disallow disarm. Copter does this if
  3270. // the vehicle isn't considered landed.
  3271. if (!allow_disarm() &&
  3272. !is_equal(packet.param2, magic_force_disarm_value)) {
  3273. return MAV_RESULT_FAILED;
  3274. }
  3275. if (AP::arming().disarm()) {
  3276. return MAV_RESULT_ACCEPTED;
  3277. }
  3278. return MAV_RESULT_FAILED;
  3279. }
  3280. return MAV_RESULT_UNSUPPORTED;
  3281. default:
  3282. result = MAV_RESULT_UNSUPPORTED;
  3283. break;
  3284. }
  3285. return result;
  3286. }
  3287. bool GCS_MAVLINK::command_long_stores_location(const MAV_CMD command)
  3288. {
  3289. switch(command) {
  3290. case MAV_CMD_DO_SET_HOME:
  3291. case MAV_CMD_DO_SET_ROI:
  3292. case MAV_CMD_NAV_TAKEOFF:
  3293. return true;
  3294. default:
  3295. return false;
  3296. }
  3297. return false;
  3298. }
  3299. void GCS_MAVLINK::convert_COMMAND_LONG_to_COMMAND_INT(const mavlink_command_long_t &in, mavlink_command_int_t &out)
  3300. {
  3301. out.target_system = in.target_system;
  3302. out.target_component = in.target_component;
  3303. out.frame = MAV_FRAME_GLOBAL_RELATIVE_ALT; // FIXME?
  3304. out.command = in.command;
  3305. out.current = 0;
  3306. out.autocontinue = 0;
  3307. out.param1 = in.param1;
  3308. out.param2 = in.param2;
  3309. out.param3 = in.param3;
  3310. out.param4 = in.param4;
  3311. if (command_long_stores_location((MAV_CMD)in.command)) {
  3312. out.x = in.param5 *1e7;
  3313. out.y = in.param6 *1e7;
  3314. } else {
  3315. out.x = in.param5;
  3316. out.y = in.param6;
  3317. }
  3318. out.z = in.param7;
  3319. }
  3320. void GCS_MAVLINK::handle_command_long(const mavlink_message_t &msg)
  3321. {
  3322. // decode packet
  3323. mavlink_command_long_t packet;
  3324. mavlink_msg_command_long_decode(&msg, &packet);
  3325. hal.util->persistent_data.last_mavlink_cmd = packet.command;
  3326. const MAV_RESULT result = handle_command_long_packet(packet);
  3327. // send ACK or NAK
  3328. mavlink_msg_command_ack_send(chan, packet.command, result);
  3329. // log the packet:
  3330. mavlink_command_int_t packet_int;
  3331. convert_COMMAND_LONG_to_COMMAND_INT(packet, packet_int);
  3332. AP::logger().Write_Command(packet_int, result, true);
  3333. hal.util->persistent_data.last_mavlink_cmd = 0;
  3334. }
  3335. MAV_RESULT GCS_MAVLINK::handle_command_do_set_roi(const Location &roi_loc)
  3336. {
  3337. AP_Mount *mount = AP::mount();
  3338. if (mount == nullptr) {
  3339. return MAV_RESULT_UNSUPPORTED;
  3340. }
  3341. // sanity check location
  3342. if (!roi_loc.check_latlng()) {
  3343. return MAV_RESULT_FAILED;
  3344. }
  3345. if (roi_loc.lat == 0 && roi_loc.lng == 0 && roi_loc.alt == 0) {
  3346. // switch off the camera tracking if enabled
  3347. if (mount->get_mode() == MAV_MOUNT_MODE_GPS_POINT) {
  3348. mount->set_mode_to_default();
  3349. }
  3350. } else {
  3351. // send the command to the camera mount
  3352. mount->set_roi_target(roi_loc);
  3353. }
  3354. return MAV_RESULT_ACCEPTED;
  3355. }
  3356. MAV_RESULT GCS_MAVLINK::handle_command_int_do_set_home(const mavlink_command_int_t &packet)
  3357. {
  3358. if (is_equal(packet.param1, 1.0f) || (packet.x == 0 && packet.y == 0)) {
  3359. // param1 is 1 (or both lat and lon are zero); use current location
  3360. if (!set_home_to_current_location(true)) {
  3361. return MAV_RESULT_FAILED;
  3362. }
  3363. return MAV_RESULT_ACCEPTED;
  3364. }
  3365. // ensure param1 is zero
  3366. if (!is_zero(packet.param1)) {
  3367. return MAV_RESULT_FAILED;
  3368. }
  3369. Location::AltFrame frame;
  3370. if (!mavlink_coordinate_frame_to_location_alt_frame((MAV_FRAME)packet.frame, frame)) {
  3371. // unknown coordinate frame
  3372. return MAV_RESULT_UNSUPPORTED;
  3373. }
  3374. const Location new_home_loc{
  3375. packet.x,
  3376. packet.y,
  3377. int32_t(packet.z * 100),
  3378. frame,
  3379. };
  3380. if (!set_home(new_home_loc, true)) {
  3381. return MAV_RESULT_FAILED;
  3382. }
  3383. return MAV_RESULT_ACCEPTED;
  3384. }
  3385. MAV_RESULT GCS_MAVLINK::handle_command_do_set_roi(const mavlink_command_int_t &packet)
  3386. {
  3387. // be aware that this method is called for both MAV_CMD_DO_SET_ROI
  3388. // and MAV_CMD_DO_SET_ROI_LOCATION. If you intend to support any
  3389. // of the extra fields in the former then you will need to split
  3390. // off support for MAV_CMD_DO_SET_ROI_LOCATION (which doesn't
  3391. // support the extra fields).
  3392. // param1 : /* Region of interest mode (not used)*/
  3393. // param2 : /* MISSION index/ target ID (not used)*/
  3394. // param3 : /* ROI index (not used)*/
  3395. // param4 : /* empty */
  3396. // x : lat
  3397. // y : lon
  3398. // z : alt
  3399. Location roi_loc;
  3400. roi_loc.lat = packet.x;
  3401. roi_loc.lng = packet.y;
  3402. roi_loc.alt = (int32_t)(packet.z * 100.0f);
  3403. return handle_command_do_set_roi(roi_loc);
  3404. }
  3405. MAV_RESULT GCS_MAVLINK::handle_command_do_set_roi(const mavlink_command_long_t &packet)
  3406. {
  3407. // be aware that this method is called for both MAV_CMD_DO_SET_ROI
  3408. // and MAV_CMD_DO_SET_ROI_LOCATION. If you intend to support any
  3409. // of the extra fields in the former then you will need to split
  3410. // off support for MAV_CMD_DO_SET_ROI_LOCATION (which doesn't
  3411. // support the extra fields).
  3412. Location roi_loc;
  3413. roi_loc.lat = (int32_t)(packet.param5 * 1.0e7f);
  3414. roi_loc.lng = (int32_t)(packet.param6 * 1.0e7f);
  3415. roi_loc.alt = (int32_t)(packet.param7 * 100.0f);
  3416. return handle_command_do_set_roi(roi_loc);
  3417. }
  3418. MAV_RESULT GCS_MAVLINK::handle_command_int_packet(const mavlink_command_int_t &packet)
  3419. {
  3420. switch (packet.command) {
  3421. case MAV_CMD_DO_SET_ROI:
  3422. case MAV_CMD_DO_SET_ROI_LOCATION:
  3423. return handle_command_do_set_roi(packet);
  3424. case MAV_CMD_DO_SET_HOME:
  3425. return handle_command_int_do_set_home(packet);
  3426. default:
  3427. break;
  3428. }
  3429. return MAV_RESULT_UNSUPPORTED;
  3430. }
  3431. void GCS_MAVLINK::handle_command_int(const mavlink_message_t &msg)
  3432. {
  3433. // decode packet
  3434. mavlink_command_int_t packet;
  3435. mavlink_msg_command_int_decode(&msg, &packet);
  3436. hal.util->persistent_data.last_mavlink_cmd = packet.command;
  3437. const MAV_RESULT result = handle_command_int_packet(packet);
  3438. // send ACK or NAK
  3439. mavlink_msg_command_ack_send(chan, packet.command, result);
  3440. AP::logger().Write_Command(packet, result);
  3441. hal.util->persistent_data.last_mavlink_cmd = 0;
  3442. }
  3443. void GCS::try_send_queued_message_for_type(MAV_MISSION_TYPE type) {
  3444. MissionItemProtocol *prot = get_prot_for_mission_type(type);
  3445. if (prot == nullptr) {
  3446. return;
  3447. }
  3448. prot->queued_request_send();
  3449. }
  3450. bool GCS_MAVLINK::try_send_mission_message(const enum ap_message id)
  3451. {
  3452. AP_Mission *mission = AP::mission();
  3453. if (mission == nullptr) {
  3454. return true;
  3455. }
  3456. bool ret = true;
  3457. switch (id) {
  3458. case MSG_CURRENT_WAYPOINT:
  3459. CHECK_PAYLOAD_SIZE(MISSION_CURRENT);
  3460. mavlink_msg_mission_current_send(chan, mission->get_current_nav_index());
  3461. ret = true;
  3462. break;
  3463. case MSG_MISSION_ITEM_REACHED:
  3464. CHECK_PAYLOAD_SIZE(MISSION_ITEM_REACHED);
  3465. mavlink_msg_mission_item_reached_send(chan, mission_item_reached_index);
  3466. ret = true;
  3467. break;
  3468. case MSG_NEXT_MISSION_REQUEST_WAYPOINTS:
  3469. CHECK_PAYLOAD_SIZE(MISSION_REQUEST);
  3470. gcs().try_send_queued_message_for_type(MAV_MISSION_TYPE_MISSION);
  3471. ret = true;
  3472. break;
  3473. case MSG_NEXT_MISSION_REQUEST_RALLY:
  3474. CHECK_PAYLOAD_SIZE(MISSION_REQUEST);
  3475. gcs().try_send_queued_message_for_type(MAV_MISSION_TYPE_RALLY);
  3476. ret = true;
  3477. break;
  3478. default:
  3479. ret = true;
  3480. break;
  3481. }
  3482. return ret;
  3483. }
  3484. void GCS_MAVLINK::send_hwstatus()
  3485. {
  3486. mavlink_msg_hwstatus_send(
  3487. chan,
  3488. hal.analogin->board_voltage()*1000,
  3489. 0);
  3490. }
  3491. void GCS_MAVLINK::send_rpm() const
  3492. {
  3493. AP_RPM *rpm = AP::rpm();
  3494. if (rpm == nullptr) {
  3495. return;
  3496. }
  3497. if (!rpm->enabled(0) && !rpm->enabled(1)) {
  3498. return;
  3499. }
  3500. mavlink_msg_rpm_send(
  3501. chan,
  3502. rpm->get_rpm(0),
  3503. rpm->get_rpm(1));
  3504. }
  3505. void GCS_MAVLINK::send_sys_status()
  3506. {
  3507. // send extended status only once vehicle has been initialised
  3508. // to avoid unnecessary errors being reported to user
  3509. if (!gcs().vehicle_initialised()) {
  3510. return;
  3511. }
  3512. const AP_BattMonitor &battery = AP::battery();
  3513. float battery_current;
  3514. int8_t battery_remaining;
  3515. if (battery.healthy() && battery.current_amps(battery_current)) {
  3516. battery_remaining = get_battery_remaining_percentage();
  3517. battery_current *= 100;
  3518. } else {
  3519. battery_current = -1;
  3520. battery_remaining = -1;
  3521. }
  3522. uint32_t control_sensors_present;
  3523. uint32_t control_sensors_enabled;
  3524. uint32_t control_sensors_health;
  3525. gcs().get_sensor_status_flags(control_sensors_present, control_sensors_enabled, control_sensors_health);
  3526. const uint32_t errors = AP::internalerror().errors();
  3527. const uint16_t errors1 = errors & 0xffff;
  3528. const uint16_t errors2 = (errors>>16) & 0xffff;
  3529. const uint16_t errors4 = AP::internalerror().count() & 0xffff;
  3530. mavlink_msg_sys_status_send(
  3531. chan,
  3532. control_sensors_present,
  3533. control_sensors_enabled,
  3534. control_sensors_health,
  3535. static_cast<uint16_t>(AP::scheduler().load_average() * 1000),
  3536. battery.voltage() * 1000, // mV
  3537. battery_current, // in 10mA units
  3538. battery_remaining, // in %
  3539. 0, // comm drops %,
  3540. 0, // comm drops in pkts,
  3541. errors1,
  3542. errors2,
  3543. 0, // errors3
  3544. errors4); // errors4
  3545. }
  3546. void GCS_MAVLINK::send_extended_sys_state() const
  3547. {
  3548. mavlink_msg_extended_sys_state_send(chan, vtol_state(), landed_state());
  3549. }
  3550. void GCS_MAVLINK::send_attitude() const
  3551. {
  3552. const AP_AHRS &ahrs = AP::ahrs();
  3553. const Vector3f omega = ahrs.get_gyro();
  3554. mavlink_msg_attitude_send(
  3555. chan,
  3556. AP_HAL::millis(),
  3557. ahrs.roll,
  3558. ahrs.pitch,
  3559. ahrs.yaw,
  3560. omega.x,
  3561. omega.y,
  3562. omega.z);
  3563. }
  3564. int32_t GCS_MAVLINK::global_position_int_alt() const {
  3565. return global_position_current_loc.alt * 10UL;
  3566. }
  3567. int32_t GCS_MAVLINK::global_position_int_relative_alt() const {
  3568. float posD;
  3569. AP::ahrs().get_relative_position_D_home(posD);
  3570. posD *= -1000.0f; // change from down to up and metres to millimeters
  3571. return posD;
  3572. }
  3573. void GCS_MAVLINK::send_global_position_int()
  3574. {
  3575. AP_AHRS &ahrs = AP::ahrs();
  3576. ahrs.get_position(global_position_current_loc); // return value ignored; we send stale data
  3577. Vector3f vel;
  3578. if (!ahrs.get_velocity_NED(vel)) {
  3579. vel.zero();
  3580. }
  3581. mavlink_msg_global_position_int_send(
  3582. chan,
  3583. AP_HAL::millis(),
  3584. global_position_current_loc.lat, // in 1E7 degrees
  3585. global_position_current_loc.lng, // in 1E7 degrees
  3586. global_position_int_alt(), // millimeters above ground/sea level
  3587. global_position_int_relative_alt(), // millimeters above home
  3588. vel.x * 100, // X speed cm/s (+ve North)
  3589. vel.y * 100, // Y speed cm/s (+ve East)
  3590. vel.z * 100, // Z speed cm/s (+ve Down)
  3591. ahrs.yaw_sensor); // compass heading in 1/100 degree
  3592. }
  3593. void GCS_MAVLINK::send_gimbal_report() const
  3594. {
  3595. AP_Mount *mount = AP::mount();
  3596. if (mount == nullptr) {
  3597. return;
  3598. }
  3599. mount->send_gimbal_report(chan);
  3600. }
  3601. void GCS_MAVLINK::send_mount_status() const
  3602. {
  3603. AP_Mount *mount = AP::mount();
  3604. if (mount == nullptr) {
  3605. return;
  3606. }
  3607. mount->send_mount_status(chan);
  3608. }
  3609. void GCS_MAVLINK::send_set_position_target_global_int(uint8_t target_system, uint8_t target_component, const Location& loc)
  3610. {
  3611. const uint16_t type_mask = POSITION_TARGET_TYPEMASK_VX_IGNORE | POSITION_TARGET_TYPEMASK_VY_IGNORE | POSITION_TARGET_TYPEMASK_VZ_IGNORE | \
  3612. POSITION_TARGET_TYPEMASK_AX_IGNORE | POSITION_TARGET_TYPEMASK_AY_IGNORE | POSITION_TARGET_TYPEMASK_AZ_IGNORE | \
  3613. POSITION_TARGET_TYPEMASK_YAW_IGNORE | POSITION_TARGET_TYPEMASK_YAW_RATE_IGNORE;
  3614. // convert altitude to relative to home
  3615. int32_t rel_alt;
  3616. if (!loc.get_alt_cm(Location::AltFrame::ABOVE_HOME, rel_alt)) {
  3617. return;
  3618. }
  3619. mavlink_msg_set_position_target_global_int_send(
  3620. chan,
  3621. AP_HAL::millis(),
  3622. target_system,
  3623. target_component,
  3624. MAV_FRAME_GLOBAL_RELATIVE_ALT_INT,
  3625. type_mask,
  3626. loc.lat,
  3627. loc.lng,
  3628. rel_alt,
  3629. 0,0,0, // vx, vy, vz
  3630. 0,0,0, // ax, ay, az
  3631. 0,0); // yaw, yaw_rate
  3632. }
  3633. bool GCS_MAVLINK::try_send_message(const enum ap_message id)
  3634. {
  3635. bool ret = true;
  3636. switch(id) {
  3637. case MSG_ROV_STATE_MONITORING:
  3638. mavlink_msg_rov_state_monitoring_send_struct(chan,&rov_message);
  3639. break;
  3640. case MSG_SET_SLAVE_PARAMETER:
  3641. mavlink_msg_set_slave_parameter_send_struct(chan,&get_stm32_param);
  3642. break;
  3643. case MSG_MOTOR_SPEED:
  3644. mavlink_msg_motor_speed_send_struct(chan,&mav_motor_speed_back);
  3645. break;
  3646. case MSG_HV_REG_GET:
  3647. mavlink_msg_hv_reg_get_send_struct(chan,&hv_reg_get);
  3648. break;
  3649. case MSG_ATTITUDE:
  3650. CHECK_PAYLOAD_SIZE(ATTITUDE);
  3651. send_attitude();
  3652. break;
  3653. case MSG_NEXT_PARAM:
  3654. CHECK_PAYLOAD_SIZE(PARAM_VALUE);
  3655. queued_param_send();
  3656. break;
  3657. case MSG_GIMBAL_REPORT:
  3658. CHECK_PAYLOAD_SIZE(GIMBAL_REPORT);
  3659. send_gimbal_report();
  3660. break;
  3661. case MSG_HEARTBEAT:
  3662. CHECK_PAYLOAD_SIZE(HEARTBEAT);
  3663. last_heartbeat_time = AP_HAL::millis();
  3664. send_heartbeat();
  3665. break;
  3666. case MSG_HWSTATUS:
  3667. CHECK_PAYLOAD_SIZE(HWSTATUS);
  3668. send_hwstatus();
  3669. break;
  3670. case MSG_LOCATION:
  3671. CHECK_PAYLOAD_SIZE(GLOBAL_POSITION_INT);
  3672. send_global_position_int();
  3673. break;
  3674. case MSG_HOME:
  3675. CHECK_PAYLOAD_SIZE(HOME_POSITION);
  3676. send_home_position();
  3677. break;
  3678. case MSG_ORIGIN:
  3679. CHECK_PAYLOAD_SIZE(GPS_GLOBAL_ORIGIN);
  3680. send_gps_global_origin();
  3681. break;
  3682. case MSG_RPM:
  3683. CHECK_PAYLOAD_SIZE(RPM);
  3684. send_rpm();
  3685. break;
  3686. case MSG_CURRENT_WAYPOINT:
  3687. case MSG_MISSION_ITEM_REACHED:
  3688. case MSG_NEXT_MISSION_REQUEST_WAYPOINTS:
  3689. case MSG_NEXT_MISSION_REQUEST_RALLY:
  3690. ret = try_send_mission_message(id);
  3691. break;
  3692. case MSG_MAG_CAL_PROGRESS:
  3693. ret = AP::compass().send_mag_cal_progress(*this);
  3694. break;
  3695. case MSG_MAG_CAL_REPORT:
  3696. ret = AP::compass().send_mag_cal_report(*this);
  3697. break;
  3698. case MSG_BATTERY_STATUS:
  3699. send_battery_status();
  3700. break;
  3701. case MSG_BATTERY2:
  3702. CHECK_PAYLOAD_SIZE(BATTERY2);
  3703. send_battery2();
  3704. break;
  3705. case MSG_EKF_STATUS_REPORT:
  3706. #if AP_AHRS_NAVEKF_AVAILABLE
  3707. CHECK_PAYLOAD_SIZE(EKF_STATUS_REPORT);
  3708. AP::ahrs_navekf().send_ekf_status_report(chan);
  3709. #endif
  3710. break;
  3711. case MSG_MEMINFO:
  3712. CHECK_PAYLOAD_SIZE(MEMINFO);
  3713. send_meminfo();
  3714. break;
  3715. case MSG_FENCE_STATUS:
  3716. CHECK_PAYLOAD_SIZE(FENCE_STATUS);
  3717. send_fence_status();
  3718. break;
  3719. case MSG_RANGEFINDER:
  3720. CHECK_PAYLOAD_SIZE(RANGEFINDER);
  3721. send_rangefinder();
  3722. break;
  3723. case MSG_DISTANCE_SENSOR:
  3724. send_distance_sensor();
  3725. break;
  3726. case MSG_CAMERA_FEEDBACK:
  3727. {
  3728. AP_Camera *camera = AP::camera();
  3729. if (camera == nullptr) {
  3730. break;
  3731. }
  3732. CHECK_PAYLOAD_SIZE(CAMERA_FEEDBACK);
  3733. camera->send_feedback(chan);
  3734. }
  3735. break;
  3736. case MSG_SYSTEM_TIME:
  3737. CHECK_PAYLOAD_SIZE(SYSTEM_TIME);
  3738. send_system_time();
  3739. break;
  3740. case MSG_GPS_RAW:
  3741. CHECK_PAYLOAD_SIZE(GPS_RAW_INT);
  3742. AP::gps().send_mavlink_gps_raw(chan);
  3743. break;
  3744. case MSG_GPS_RTK:
  3745. CHECK_PAYLOAD_SIZE(GPS_RTK);
  3746. AP::gps().send_mavlink_gps_rtk(chan, 0);
  3747. break;
  3748. case MSG_GPS2_RAW:
  3749. CHECK_PAYLOAD_SIZE(GPS2_RAW);
  3750. AP::gps().send_mavlink_gps2_raw(chan);
  3751. break;
  3752. case MSG_GPS2_RTK:
  3753. CHECK_PAYLOAD_SIZE(GPS2_RTK);
  3754. AP::gps().send_mavlink_gps_rtk(chan, 1);
  3755. break;
  3756. case MSG_LOCAL_POSITION:
  3757. CHECK_PAYLOAD_SIZE(LOCAL_POSITION_NED);
  3758. send_local_position();
  3759. break;
  3760. case MSG_MOUNT_STATUS:
  3761. CHECK_PAYLOAD_SIZE(MOUNT_STATUS);
  3762. send_mount_status();
  3763. break;
  3764. case MSG_OPTICAL_FLOW:
  3765. CHECK_PAYLOAD_SIZE(OPTICAL_FLOW);
  3766. send_opticalflow();
  3767. break;
  3768. case MSG_POSITION_TARGET_GLOBAL_INT:
  3769. CHECK_PAYLOAD_SIZE(POSITION_TARGET_GLOBAL_INT);
  3770. send_position_target_global_int();
  3771. break;
  3772. case MSG_POSITION_TARGET_LOCAL_NED:
  3773. CHECK_PAYLOAD_SIZE(POSITION_TARGET_LOCAL_NED);
  3774. send_position_target_local_ned();
  3775. break;
  3776. case MSG_POWER_STATUS:
  3777. CHECK_PAYLOAD_SIZE(POWER_STATUS);
  3778. send_power_status();
  3779. break;
  3780. case MSG_RC_CHANNELS:
  3781. CHECK_PAYLOAD_SIZE(RC_CHANNELS);
  3782. send_rc_channels();
  3783. break;
  3784. case MSG_RC_CHANNELS_RAW:
  3785. CHECK_PAYLOAD_SIZE(RC_CHANNELS_RAW);
  3786. send_rc_channels_raw();
  3787. break;
  3788. case MSG_RAW_IMU:
  3789. CHECK_PAYLOAD_SIZE(RAW_IMU);
  3790. send_raw_imu();
  3791. break;
  3792. case MSG_SCALED_IMU:
  3793. CHECK_PAYLOAD_SIZE(SCALED_IMU);
  3794. send_scaled_imu(0, mavlink_msg_scaled_imu_send);
  3795. break;
  3796. case MSG_SCALED_IMU2:
  3797. CHECK_PAYLOAD_SIZE(SCALED_IMU2);
  3798. send_scaled_imu(1, mavlink_msg_scaled_imu2_send);
  3799. break;
  3800. case MSG_SCALED_IMU3:
  3801. CHECK_PAYLOAD_SIZE(SCALED_IMU3);
  3802. send_scaled_imu(2, mavlink_msg_scaled_imu3_send);
  3803. break;
  3804. case MSG_SCALED_PRESSURE:
  3805. CHECK_PAYLOAD_SIZE(SCALED_PRESSURE);
  3806. send_scaled_pressure();
  3807. break;
  3808. case MSG_SCALED_PRESSURE2:
  3809. CHECK_PAYLOAD_SIZE(SCALED_PRESSURE2);
  3810. send_scaled_pressure2();
  3811. break;
  3812. case MSG_SCALED_PRESSURE3:
  3813. CHECK_PAYLOAD_SIZE(SCALED_PRESSURE3);
  3814. send_scaled_pressure3();
  3815. break;
  3816. case MSG_SENSOR_OFFSETS:
  3817. CHECK_PAYLOAD_SIZE(SENSOR_OFFSETS);
  3818. send_sensor_offsets();
  3819. break;
  3820. case MSG_SERVO_OUTPUT_RAW:
  3821. CHECK_PAYLOAD_SIZE(SERVO_OUTPUT_RAW);
  3822. send_servo_output_raw();
  3823. break;
  3824. case MSG_SIMSTATE:
  3825. CHECK_PAYLOAD_SIZE(SIMSTATE);
  3826. send_simstate();
  3827. break;
  3828. case MSG_SYS_STATUS:
  3829. CHECK_PAYLOAD_SIZE(SYS_STATUS);
  3830. send_sys_status();
  3831. break;
  3832. case MSG_AHRS2:
  3833. CHECK_PAYLOAD_SIZE(AHRS2);
  3834. send_ahrs2();
  3835. break;
  3836. case MSG_AHRS3:
  3837. CHECK_PAYLOAD_SIZE(AHRS3);
  3838. send_ahrs3();
  3839. break;
  3840. case MSG_PID_TUNING:
  3841. CHECK_PAYLOAD_SIZE(PID_TUNING);
  3842. send_pid_tuning();
  3843. break;
  3844. case MSG_NAV_CONTROLLER_OUTPUT:
  3845. CHECK_PAYLOAD_SIZE(NAV_CONTROLLER_OUTPUT);
  3846. send_nav_controller_output();
  3847. break;
  3848. case MSG_AHRS:
  3849. CHECK_PAYLOAD_SIZE(AHRS);
  3850. send_ahrs();
  3851. break;
  3852. case MSG_EXTENDED_SYS_STATE:
  3853. CHECK_PAYLOAD_SIZE(EXTENDED_SYS_STATE);
  3854. send_extended_sys_state();
  3855. break;
  3856. case MSG_VFR_HUD:
  3857. CHECK_PAYLOAD_SIZE(VFR_HUD);
  3858. send_vfr_hud();
  3859. break;
  3860. case MSG_VIBRATION:
  3861. CHECK_PAYLOAD_SIZE(VIBRATION);
  3862. send_vibration();
  3863. break;
  3864. case MSG_AUTOPILOT_VERSION:
  3865. CHECK_PAYLOAD_SIZE(AUTOPILOT_VERSION);
  3866. send_autopilot_version();
  3867. break;
  3868. case MSG_ESC_TELEMETRY: {
  3869. #ifdef HAVE_AP_BLHELI_SUPPORT
  3870. CHECK_PAYLOAD_SIZE(ESC_TELEMETRY_1_TO_4);
  3871. AP_BLHeli *blheli = AP_BLHeli::get_singleton();
  3872. if (blheli) {
  3873. blheli->send_esc_telemetry_mavlink(uint8_t(chan));
  3874. }
  3875. #endif
  3876. #if HAL_WITH_UAVCAN
  3877. uint8_t num_drivers = AP::can().get_num_drivers();
  3878. for (uint8_t i = 0; i < num_drivers; i++) {
  3879. switch (AP::can().get_protocol_type(i)) {
  3880. case AP_BoardConfig_CAN::Protocol_Type_KDECAN: {
  3881. // To be replaced with macro saying if KDECAN library is included
  3882. #if APM_BUILD_TYPE(APM_BUILD_ArduCopter) || APM_BUILD_TYPE(APM_BUILD_ArduPlane) || APM_BUILD_TYPE(APM_BUILD_ArduSub)
  3883. AP_KDECAN *ap_kdecan = AP_KDECAN::get_kdecan(i);
  3884. if (ap_kdecan != nullptr) {
  3885. ap_kdecan->send_mavlink(uint8_t(chan));
  3886. }
  3887. #endif
  3888. break;
  3889. }
  3890. case AP_BoardConfig_CAN::Protocol_Type_ToshibaCAN: {
  3891. AP_ToshibaCAN *ap_tcan = AP_ToshibaCAN::get_tcan(i);
  3892. if (ap_tcan != nullptr) {
  3893. ap_tcan->send_esc_telemetry_mavlink(uint8_t(chan));
  3894. }
  3895. break;
  3896. }
  3897. case AP_BoardConfig_CAN::Protocol_Type_UAVCAN:
  3898. case AP_BoardConfig_CAN::Protocol_Type_None:
  3899. default:
  3900. break;
  3901. }
  3902. }
  3903. #endif
  3904. break;
  3905. }
  3906. default:
  3907. // try_send_message must always at some stage return true for
  3908. // a message, or we will attempt to infinitely retry the
  3909. // message as part of send_message.
  3910. // This message will be sent out at the same rate as the
  3911. // unknown message, so should be safe.
  3912. gcs().send_text(MAV_SEVERITY_DEBUG, "Sending unknown message (%u)", id);
  3913. #if CONFIG_HAL_BOARD == HAL_BOARD_SITL
  3914. AP_HAL::panic("Sending unknown ap_message %u", id);
  3915. #endif
  3916. break;
  3917. }
  3918. return ret;
  3919. }
  3920. uint16_t GCS_MAVLINK::get_interval_for_stream(GCS_MAVLINK::streams id) const
  3921. {
  3922. const int16_t frate = streamRates[id].get();
  3923. if (frate == 0) {
  3924. return 0;
  3925. }
  3926. const uint32_t ret = 1000/frate;
  3927. if (ret > 60000) {
  3928. return 60000;
  3929. }
  3930. return ret;
  3931. }
  3932. void GCS_MAVLINK::initialise_message_intervals_for_stream(GCS_MAVLINK::streams id)
  3933. {
  3934. for (uint8_t i=0; all_stream_entries[i].ap_message_ids != nullptr; i++) {
  3935. const GCS_MAVLINK::stream_entries &entries = all_stream_entries[i];
  3936. if (entries.stream_id != id) {
  3937. continue;
  3938. }
  3939. // found it!
  3940. const uint16_t interval_ms = get_interval_for_stream(id);
  3941. for (uint8_t j=0; j<entries.num_ap_message_ids; j++) {
  3942. set_ap_message_interval(entries.ap_message_ids[j], interval_ms);
  3943. }
  3944. break;
  3945. }
  3946. }
  3947. void GCS_MAVLINK::initialise_message_intervals_from_streamrates()
  3948. {
  3949. // this is O(n^2), but it's once at boot and across a 10-entry list...
  3950. for (uint8_t i=0; all_stream_entries[i].ap_message_ids != nullptr; i++) {
  3951. initialise_message_intervals_for_stream(all_stream_entries[i].stream_id);
  3952. }
  3953. set_mavlink_message_id_interval(MAVLINK_MSG_ID_HEARTBEAT, 1000);
  3954. }
  3955. bool GCS_MAVLINK::get_default_interval_for_ap_message(const ap_message id, uint16_t &interval) const
  3956. {
  3957. if (id == MSG_HEARTBEAT) {
  3958. // handle heartbeat requests as a special case because heartbeat is not "streamed"
  3959. interval = 1000;
  3960. return true;
  3961. }
  3962. // find which stream this ap_message is in
  3963. for (uint8_t i=0; all_stream_entries[i].ap_message_ids != nullptr; i++) {
  3964. const GCS_MAVLINK::stream_entries &entries = all_stream_entries[i];
  3965. for (uint8_t j=0; j<entries.num_ap_message_ids; j++) {
  3966. if (entries.ap_message_ids[j] == id) {
  3967. interval = get_interval_for_stream(all_stream_entries[i].stream_id);
  3968. return true;
  3969. }
  3970. }
  3971. }
  3972. return false;
  3973. }
  3974. bool GCS_MAVLINK::get_default_interval_for_mavlink_message_id(const uint32_t mavlink_message_id, uint16_t &interval) const
  3975. {
  3976. const ap_message id = mavlink_id_to_ap_message_id(mavlink_message_id);
  3977. if (id == MSG_LAST) {
  3978. return false;
  3979. }
  3980. return get_default_interval_for_ap_message(id, interval);
  3981. }
  3982. /*
  3983. correct an offboard timestamp in microseconds into a local timestamp
  3984. since boot in milliseconds. See the JitterCorrection code for details
  3985. Return a value in milliseconds since boot (for use by the EKF)
  3986. */
  3987. uint32_t GCS_MAVLINK::correct_offboard_timestamp_usec_to_ms(uint64_t offboard_usec, uint16_t payload_size)
  3988. {
  3989. uint64_t local_us;
  3990. // if the HAL supports it then constrain the latest possible time
  3991. // the packet could have been sent by the uart receive time and
  3992. // the baudrate and packet size.
  3993. uint64_t uart_receive_time = _port->receive_time_constraint_us(payload_size);
  3994. if (uart_receive_time != 0) {
  3995. local_us = uart_receive_time;
  3996. } else {
  3997. local_us = AP_HAL::micros64();
  3998. }
  3999. uint64_t corrected_us = lag_correction.correct_offboard_timestamp_usec(offboard_usec, local_us);
  4000. return corrected_us / 1000U;
  4001. }
  4002. /*
  4003. return true if we will accept this packet. Used to implement SYSID_ENFORCE
  4004. */
  4005. bool GCS_MAVLINK::accept_packet(const mavlink_status_t &status,
  4006. const mavlink_message_t &msg)
  4007. {
  4008. if (msg.sysid == mavlink_system.sysid) {
  4009. // accept packets from our own components
  4010. // (e.g. mavlink-connected companion computers)
  4011. return true;
  4012. }
  4013. if (msg.sysid == sysid_my_gcs()) {
  4014. return true;
  4015. }
  4016. if (msg.msgid == MAVLINK_MSG_ID_RADIO ||
  4017. msg.msgid == MAVLINK_MSG_ID_RADIO_STATUS) {
  4018. return true;
  4019. }
  4020. if (!sysid_enforce()) {
  4021. return true;
  4022. }
  4023. return false;
  4024. }
  4025. /*
  4026. update UART pass-thru, if enabled
  4027. */
  4028. void GCS::update_passthru(void)
  4029. {
  4030. WITH_SEMAPHORE(_passthru.sem);
  4031. uint32_t now = AP_HAL::millis();
  4032. bool enabled = AP::serialmanager().get_passthru(_passthru.port1, _passthru.port2, _passthru.timeout_s);
  4033. if (enabled && !_passthru.enabled) {
  4034. _passthru.start_ms = now;
  4035. _passthru.last_ms = 0;
  4036. _passthru.enabled = true;
  4037. _passthru.last_port1_data_ms = now;
  4038. gcs().send_text(MAV_SEVERITY_INFO, "Passthru enabled");
  4039. if (!_passthru.timer_installed) {
  4040. _passthru.timer_installed = true;
  4041. hal.scheduler->register_timer_process(FUNCTOR_BIND_MEMBER(&GCS::passthru_timer, void));
  4042. }
  4043. } else if (!enabled && _passthru.enabled) {
  4044. _passthru.enabled = false;
  4045. _passthru.port1->lock_port(0, 0);
  4046. _passthru.port2->lock_port(0, 0);
  4047. gcs().send_text(MAV_SEVERITY_INFO, "Passthru disabled");
  4048. } else if (enabled &&
  4049. _passthru.timeout_s &&
  4050. now - _passthru.last_port1_data_ms > uint32_t(_passthru.timeout_s)*1000U) {
  4051. // timed out, disable
  4052. _passthru.enabled = false;
  4053. _passthru.port1->lock_port(0, 0);
  4054. _passthru.port2->lock_port(0, 0);
  4055. AP::serialmanager().disable_passthru();
  4056. gcs().send_text(MAV_SEVERITY_INFO, "Passthru timed out");
  4057. }
  4058. }
  4059. /*
  4060. called at 1kHz to handle pass-thru between SERIA0_PASSTHRU port and hal.console
  4061. */
  4062. void GCS::passthru_timer(void)
  4063. {
  4064. WITH_SEMAPHORE(_passthru.sem);
  4065. if (!_passthru.enabled) {
  4066. // it has been disabled after starting
  4067. return;
  4068. }
  4069. if (_passthru.start_ms != 0) {
  4070. uint32_t now = AP_HAL::millis();
  4071. if (now - _passthru.start_ms < 1000) {
  4072. // delay for 1s so the reply for the SERIAL0_PASSTHRU param set can be seen by GCS
  4073. return;
  4074. }
  4075. _passthru.start_ms = 0;
  4076. }
  4077. // while pass-thru is enabled lock both ports. They remain
  4078. // locked until disabled again, or reboot
  4079. const uint32_t lock_key = 0x3256AB9F;
  4080. _passthru.port1->lock_port(lock_key, lock_key);
  4081. _passthru.port2->lock_port(lock_key, lock_key);
  4082. int16_t b;
  4083. uint8_t buf[64];
  4084. uint8_t nbytes = 0;
  4085. // read from port1, and write to port2
  4086. while (nbytes < sizeof(buf) && (b = _passthru.port1->read_locked(lock_key)) >= 0) {
  4087. buf[nbytes++] = b;
  4088. }
  4089. if (nbytes > 0) {
  4090. _passthru.last_port1_data_ms = AP_HAL::millis();
  4091. _passthru.port2->write_locked(buf, nbytes, lock_key);
  4092. }
  4093. // read from port2, and write to port1
  4094. nbytes = 0;
  4095. while (nbytes < sizeof(buf) && (b = _passthru.port2->read_locked(lock_key)) >= 0) {
  4096. buf[nbytes++] = b;
  4097. }
  4098. if (nbytes > 0) {
  4099. _passthru.port1->write_locked(buf, nbytes, lock_key);
  4100. }
  4101. }
  4102. bool GCS_MAVLINK::mavlink_coordinate_frame_to_location_alt_frame(const MAV_FRAME coordinate_frame, Location::AltFrame &frame)
  4103. {
  4104. switch (coordinate_frame) {
  4105. case MAV_FRAME_GLOBAL_RELATIVE_ALT: // solo shot manager incorrectly sends RELATIVE_ALT instead of RELATIVE_ALT_INT
  4106. case MAV_FRAME_GLOBAL_RELATIVE_ALT_INT:
  4107. frame = Location::AltFrame::ABOVE_HOME;
  4108. return true;
  4109. case MAV_FRAME_GLOBAL_TERRAIN_ALT:
  4110. case MAV_FRAME_GLOBAL_TERRAIN_ALT_INT:
  4111. frame = Location::AltFrame::ABOVE_TERRAIN;
  4112. return true;
  4113. case MAV_FRAME_GLOBAL:
  4114. case MAV_FRAME_GLOBAL_INT:
  4115. frame = Location::AltFrame::ABSOLUTE;
  4116. return true;
  4117. default:
  4118. #if CONFIG_HAL_BOARD == HAL_BOARD_SITL
  4119. gcs().send_text(MAV_SEVERITY_INFO, "Unknown mavlink coordinate frame %u", coordinate_frame);
  4120. #endif
  4121. return false;
  4122. }
  4123. }
  4124. uint64_t GCS_MAVLINK::capabilities() const
  4125. {
  4126. uint64_t ret = 0;
  4127. AP_SerialManager::SerialProtocol mavlink_protocol = AP::serialmanager().get_mavlink_protocol(chan);
  4128. if (mavlink_protocol == AP_SerialManager::SerialProtocol_MAVLink2) {
  4129. ret |= MAV_PROTOCOL_CAPABILITY_MAVLINK2;
  4130. }
  4131. AP_AdvancedFailsafe *failsafe = get_advanced_failsafe();
  4132. if (failsafe != nullptr && failsafe->enabled()) {
  4133. // Copter and Sub may also set this bit as they can always terminate
  4134. ret |= MAV_PROTOCOL_CAPABILITY_FLIGHT_TERMINATION;
  4135. }
  4136. if (AP::rally()) {
  4137. ret |= MAV_PROTOCOL_CAPABILITY_MISSION_RALLY;
  4138. }
  4139. return ret;
  4140. }
  4141. void GCS_MAVLINK::manual_override(RC_Channel *c, int16_t value_in, const uint16_t offset, const float scaler, const uint32_t tnow, const bool reversed)
  4142. {
  4143. if (c == nullptr) {
  4144. return;
  4145. }
  4146. int16_t override_value = 0;
  4147. if (value_in != INT16_MAX) {
  4148. const int16_t radio_min = c->get_radio_min();
  4149. const int16_t radio_max = c->get_radio_max();
  4150. if (reversed) {
  4151. value_in *= -1;
  4152. }
  4153. override_value = radio_min + (radio_max - radio_min) * (value_in + offset) / scaler;
  4154. }
  4155. c->set_override(override_value, tnow);
  4156. }
  4157. uint8_t GCS_MAVLINK::get_battery_remaining_percentage(uint8_t instance) const {
  4158. const AP_BattMonitor &battery = AP::battery();
  4159. return battery.capacity_remaining_pct(instance);
  4160. }
  4161. GCS &gcs()
  4162. {
  4163. return *GCS::get_singleton();
  4164. }