GCS_Common.cpp 149 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781
  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. mavlink_rov_motor_temp_t rov_motor_temp = {0,0,0,0,0,0,0,0,0,0};
  904. int countper = 0;
  905. void GCS_MAVLINK::update_send()
  906. {
  907. // const AP_UAVCAN &uavcan = AP::uavcan();//6自由度电机计算出来的PWM
  908. mav_motor_speed_back.motorTest = 0;
  909. mav_motor_speed_back.Ltrack = 0;
  910. mav_motor_speed_back.Rtrack =0;
  911. mav_motor_speed_back.motor1 =(float)0.0;//sub._telemetry[0].rpm/7;//uint32 rpm
  912. mav_motor_speed_back.motor2 =(float)0.0;//sub._telemetry[1].rpm/7;
  913. mav_motor_speed_back.motor3 =(float)0.0;//sub._telemetry[2].rpm/7;
  914. mav_motor_speed_back.motor4 =(float)0.0;//sub._telemetry[3].rpm/7;
  915. mav_motor_speed_back.motor5 =(float)0.0;//sub._telemetry[4].rpm/7;
  916. mav_motor_speed_back.motor6 =(float)0.0;//sub._telemetry[5].rpm/7;
  917. mav_motor_speed_back.motor7 =0;
  918. mav_motor_speed_back.motor8 =0;
  919. rov_message.floodlight = sub.lights;
  920. //pressure_level 在各个模式中已经赋值
  921. rov_message.low_voltage = (float)sub._telemetry[0].voltage/10;
  922. rov_message.high_voltage = (float)sub._telemetry[1].voltage/10;
  923. rov_message.deep =fabsf(sub.barometer.get_altitude());//深度
  924. //rov_message.temp = 0;
  925. rov_message.motor_block_flag = 0;
  926. rov_message.track_fault_flag[0] = 0;
  927. rov_message.track_fault_flag[1] = 0;
  928. rov_message.motor_twine_flag[0] = 0;
  929. rov_message.motor_twine_flag[1] = 0;
  930. rov_message.motor_twine_flag[2] = 0;
  931. rov_message.motor_twine_flag[3] = 0;
  932. rov_message.motor_twine_flag[4] = 0;
  933. rov_message.motor_twine_flag[5] = 0;
  934. rov_message.motor_twine_flag[6] = 0;
  935. rov_message.motor_twine_flag[7] = 0;
  936. rov_message.track_power[0] = 0;
  937. rov_message.track_power[1] = 0;
  938. rov_message.motor_power[0] = 0;
  939. rov_message.motor_power[1] = 0;
  940. rov_message.motor_power[2] = 0;
  941. rov_message.motor_power[3] = 0;
  942. rov_message.motor_power[4] = 0;
  943. rov_message.motor_power[5] = 0;
  944. rov_message.motor_power[6] = 0;
  945. rov_message.motor_power[7] = 0;
  946. get_stm32_param.number = 0;
  947. get_stm32_param.flag = 0;
  948. get_stm32_param.XX1 = 0;
  949. get_stm32_param.XX2 =0;
  950. get_stm32_param.XX3 = 0;
  951. get_stm32_param.XX4 = 0;
  952. get_stm32_param.YY = 0;
  953. const NavEKF2 &ekf2 = AP::ahrs_navekf().get_NavEKF2_const();
  954. Matrix3f mat;
  955. ekf2.getRotationBodyToNED(mat);
  956. countper++;
  957. if (countper>30)
  958. {
  959. countper = 0;
  960. mavlink_msg_rotation_matrix_array_send(chan,
  961. mat.c.x,mat.c.z,mat.c.y,
  962. mat.b.x,mat.b.z,mat.b.y,
  963. mat.a.x,mat.a.z,mat.a.y);
  964. }
  965. if (!hal.scheduler->in_delay_callback()) {
  966. // AP_Logger will not send log data if we are armed.
  967. AP::logger().handle_log_send();
  968. }
  969. if (!deferred_messages_initialised) {
  970. initialise_message_intervals_from_streamrates();
  971. deferred_messages_initialised = true;
  972. }
  973. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  974. uint32_t retry_deferred_body_start = AP_HAL::micros();
  975. #endif
  976. const uint32_t start = AP_HAL::millis();
  977. while (AP_HAL::millis() - start < 5) { // spend a max of 5ms sending messages. This should never trigger - out_of_time() should become true
  978. if (gcs().out_of_time()) {
  979. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  980. try_send_message_stats.out_of_time++;
  981. #endif
  982. break;
  983. }
  984. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  985. retry_deferred_body_start = AP_HAL::micros();
  986. #endif
  987. // check if any "specially handled" messages should be sent out
  988. {
  989. const int8_t next = deferred_message_to_send_index();
  990. if (next != -1) {
  991. if (!do_try_send_message(deferred_message[next].id)) {
  992. break;
  993. }
  994. deferred_message[next].last_sent_ms += deferred_message[next].interval_ms;
  995. next_deferred_message_to_send_cache = -1; // deferred_message_to_send will recalculate
  996. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  997. const uint32_t stop = AP_HAL::micros();
  998. const uint32_t delta = stop - retry_deferred_body_start;
  999. if (delta > try_send_message_stats.max_retry_deferred_body_us) {
  1000. try_send_message_stats.max_retry_deferred_body_us = delta;
  1001. try_send_message_stats.max_retry_deferred_body_type = 1;
  1002. }
  1003. #endif
  1004. continue;
  1005. }
  1006. }
  1007. // check for any messages that the code has explicitly sent
  1008. const int16_t fs = pushed_ap_message_ids.first_set();
  1009. if (fs != -1) {
  1010. ap_message next = (ap_message)fs;
  1011. if (!do_try_send_message(next)) {
  1012. break;
  1013. }
  1014. pushed_ap_message_ids.clear(next);
  1015. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  1016. const uint32_t stop = AP_HAL::micros();
  1017. const uint32_t delta = stop - retry_deferred_body_start;
  1018. if (delta > try_send_message_stats.max_retry_deferred_body_us) {
  1019. try_send_message_stats.max_retry_deferred_body_us = delta;
  1020. try_send_message_stats.max_retry_deferred_body_type = 2;
  1021. }
  1022. #endif
  1023. continue;
  1024. }
  1025. ap_message next = next_deferred_bucket_message_to_send();
  1026. if (next != no_message_to_send) {
  1027. if (!do_try_send_message(next)) {
  1028. break;
  1029. }
  1030. bucket_message_ids_to_send.clear(next);
  1031. if (bucket_message_ids_to_send.count() == 0) {
  1032. // we sent everything in the bucket. Reschedule it.
  1033. deferred_message_bucket[sending_bucket_id].last_sent_ms +=
  1034. get_reschedule_interval_ms(deferred_message_bucket[sending_bucket_id]);
  1035. find_next_bucket_to_send();
  1036. }
  1037. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  1038. const uint32_t stop = AP_HAL::micros();
  1039. const uint32_t delta = stop - retry_deferred_body_start;
  1040. if (delta > try_send_message_stats.max_retry_deferred_body_us) {
  1041. try_send_message_stats.max_retry_deferred_body_us = delta;
  1042. try_send_message_stats.max_retry_deferred_body_type = 3;
  1043. }
  1044. #endif
  1045. continue;
  1046. }
  1047. break;
  1048. }
  1049. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  1050. const uint32_t stop = AP_HAL::micros();
  1051. const uint32_t delta = stop - retry_deferred_body_start;
  1052. if (delta > try_send_message_stats.max_retry_deferred_body_us) {
  1053. try_send_message_stats.max_retry_deferred_body_us = delta;
  1054. try_send_message_stats.max_retry_deferred_body_type = 4;
  1055. }
  1056. #endif
  1057. // update the number of packets transmitted base on seqno, making
  1058. // the assumption that we don't send more than 256 messages
  1059. // between the last pass through here
  1060. mavlink_status_t *status = mavlink_get_channel_status(chan);
  1061. if (status != nullptr) {
  1062. send_packet_count += uint8_t(status->current_tx_seq - last_tx_seq);
  1063. last_tx_seq = status->current_tx_seq;
  1064. }
  1065. }
  1066. void GCS_MAVLINK::remove_message_from_bucket(int8_t bucket, ap_message id)
  1067. {
  1068. deferred_message_bucket[bucket].ap_message_ids.clear(id);
  1069. if (bucket == sending_bucket_id) {
  1070. bucket_message_ids_to_send.clear(id);
  1071. }
  1072. if (deferred_message_bucket[bucket].ap_message_ids.count() == 0) {
  1073. // bucket empty. Free it:
  1074. deferred_message_bucket[bucket].interval_ms = 0;
  1075. deferred_message_bucket[bucket].last_sent_ms = 0;
  1076. if (sending_bucket_id == bucket) {
  1077. find_next_bucket_to_send();
  1078. }
  1079. }
  1080. }
  1081. bool GCS_MAVLINK::set_ap_message_interval(enum ap_message id, uint16_t interval_ms)
  1082. {
  1083. if (id == MSG_NEXT_PARAM) {
  1084. // force parameters to *always* get streamed so a vehicle is
  1085. // recoverable from bad configuration:
  1086. if (interval_ms == 0) {
  1087. interval_ms = 100;
  1088. } else if (interval_ms > 1000) {
  1089. interval_ms = 1000;
  1090. }
  1091. }
  1092. // send messages out at most 80% of main loop rate
  1093. if (interval_ms != 0 &&
  1094. interval_ms*800 < AP::scheduler().get_loop_period_us()) {
  1095. interval_ms = AP::scheduler().get_loop_period_us()/800.0f;
  1096. }
  1097. // check if it's a specially-handled message:
  1098. const int8_t deferred_offset = get_deferred_message_index(id);
  1099. if (deferred_offset != -1) {
  1100. deferred_message[deferred_offset].interval_ms = interval_ms;
  1101. deferred_message[deferred_offset].last_sent_ms = AP_HAL::millis16();
  1102. return true;
  1103. }
  1104. // see which bucket has the closest interval:
  1105. int8_t closest_bucket = -1;
  1106. uint16_t closest_bucket_interval_delta = UINT16_MAX;
  1107. int8_t in_bucket = -1;
  1108. int8_t empty_bucket_id = -1;
  1109. for (uint8_t i=0; i<ARRAY_SIZE(deferred_message_bucket); i++) {
  1110. const deferred_message_bucket_t &bucket = deferred_message_bucket[i];
  1111. if (bucket.interval_ms == 0) {
  1112. // unused bucket
  1113. if (empty_bucket_id == -1) {
  1114. empty_bucket_id = i;
  1115. }
  1116. #if CONFIG_HAL_BOARD == HAL_BOARD_SITL
  1117. if (bucket.ap_message_ids.count() != 0) {
  1118. AP_HAL::panic("Bucket %u has zero interval but with ids set", i);
  1119. }
  1120. #endif
  1121. continue;
  1122. }
  1123. if (bucket.ap_message_ids.get(id)) {
  1124. in_bucket = i;
  1125. }
  1126. const uint16_t interval_delta = abs(bucket.interval_ms - interval_ms);
  1127. if (interval_delta < closest_bucket_interval_delta) {
  1128. closest_bucket = i;
  1129. closest_bucket_interval_delta = interval_delta;
  1130. }
  1131. }
  1132. if (in_bucket == -1 && interval_ms == 0) {
  1133. // not in a bucket and told to remove from scheduling
  1134. return true;
  1135. }
  1136. if (in_bucket != -1) {
  1137. if (interval_ms == 0) {
  1138. // remove it
  1139. remove_message_from_bucket(in_bucket, id);
  1140. return true;
  1141. }
  1142. if (closest_bucket_interval_delta == 0 &&
  1143. in_bucket == closest_bucket) {
  1144. // don't need to move it
  1145. return true;
  1146. }
  1147. // remove from existing bucket
  1148. remove_message_from_bucket(in_bucket, id);
  1149. if (empty_bucket_id == -1 &&
  1150. deferred_message_bucket[in_bucket].ap_message_ids.count() == 0) {
  1151. empty_bucket_id = in_bucket;
  1152. }
  1153. }
  1154. if (closest_bucket == -1 && empty_bucket_id == -1) {
  1155. // gah?!
  1156. #if CONFIG_HAL_BOARD == HAL_BOARD_SITL
  1157. ::fprintf(stderr, "no buckets?!\n");
  1158. abort();
  1159. #endif
  1160. return false;
  1161. }
  1162. if (closest_bucket_interval_delta != 0 &&
  1163. empty_bucket_id != -1) {
  1164. // allocate a bucket for this interval
  1165. deferred_message_bucket[empty_bucket_id].interval_ms = interval_ms;
  1166. deferred_message_bucket[empty_bucket_id].last_sent_ms = AP_HAL::millis16();
  1167. closest_bucket = empty_bucket_id;
  1168. closest_bucket_interval_delta = 0;
  1169. }
  1170. deferred_message_bucket[closest_bucket].ap_message_ids.set(id);
  1171. if (sending_bucket_id == no_bucket_to_send) {
  1172. sending_bucket_id = closest_bucket;
  1173. bucket_message_ids_to_send = deferred_message_bucket[closest_bucket].ap_message_ids;
  1174. }
  1175. return true;
  1176. }
  1177. // queue a message to be sent (try_send_message does the *actual*
  1178. // mavlink work!)
  1179. void GCS_MAVLINK::send_message(enum ap_message id)
  1180. {
  1181. if (id == MSG_HEARTBEAT) {
  1182. save_signing_timestamp(false);
  1183. // update the mask of all streaming channels
  1184. if (is_streaming()) {
  1185. GCS_MAVLINK::chan_is_streaming |= (1U<<(chan-MAVLINK_COMM_0));
  1186. } else {
  1187. GCS_MAVLINK::chan_is_streaming &= ~(1U<<(chan-MAVLINK_COMM_0));
  1188. }
  1189. }
  1190. pushed_ap_message_ids.set(id);
  1191. }
  1192. void GCS_MAVLINK::packetReceived(const mavlink_status_t &status,
  1193. const mavlink_message_t &msg)
  1194. {
  1195. // we exclude radio packets because we historically used this to
  1196. // make it possible to use the CLI over the radio
  1197. if (msg.msgid != MAVLINK_MSG_ID_RADIO && msg.msgid != MAVLINK_MSG_ID_RADIO_STATUS) {
  1198. const uint8_t mask = (1U<<(chan-MAVLINK_COMM_0));
  1199. if (!(mask & mavlink_private)) {
  1200. mavlink_active |= mask;
  1201. }
  1202. }
  1203. if (!(status.flags & MAVLINK_STATUS_FLAG_IN_MAVLINK1) &&
  1204. (status.flags & MAVLINK_STATUS_FLAG_OUT_MAVLINK1) &&
  1205. AP::serialmanager().get_mavlink_protocol(chan) == AP_SerialManager::SerialProtocol_MAVLink2) {
  1206. // if we receive any MAVLink2 packets on a connection
  1207. // currently sending MAVLink1 then switch to sending
  1208. // MAVLink2
  1209. mavlink_status_t *cstatus = mavlink_get_channel_status(chan);
  1210. if (cstatus != nullptr) {
  1211. cstatus->flags &= ~MAVLINK_STATUS_FLAG_OUT_MAVLINK1;
  1212. }
  1213. }
  1214. if (!routing.check_and_forward(chan, msg)) {
  1215. // the routing code has indicated we should not handle this packet locally
  1216. return;
  1217. }
  1218. if (!accept_packet(status, msg)) {
  1219. // e.g. enforce-sysid says we shouldn't look at this packet
  1220. return;
  1221. }
  1222. handleMessage(msg);
  1223. }
  1224. void
  1225. GCS_MAVLINK::update_receive(uint32_t max_time_us)
  1226. {
  1227. // do absolutely nothing if we are locked
  1228. if (locked()) {
  1229. return;
  1230. }
  1231. // receive new packets
  1232. mavlink_message_t msg;
  1233. mavlink_status_t status;
  1234. uint32_t tstart_us = AP_HAL::micros();
  1235. uint32_t now_ms = AP_HAL::millis();
  1236. hal.util->perf_begin(_perf_update);
  1237. status.packet_rx_drop_count = 0;
  1238. const uint16_t nbytes = _port->available();
  1239. for (uint16_t i=0; i<nbytes; i++)
  1240. {
  1241. const uint8_t c = (uint8_t)_port->read();
  1242. const uint32_t protocol_timeout = 4000;
  1243. if (alternative.handler &&
  1244. now_ms - alternative.last_mavlink_ms > protocol_timeout) {
  1245. /*
  1246. we have an alternative protocol handler installed and we
  1247. haven't parsed a MAVLink packet for 4 seconds. Try
  1248. parsing using alternative handler
  1249. */
  1250. if (alternative.handler(c, mavlink_comm_port[chan])) {
  1251. alternative.last_alternate_ms = now_ms;
  1252. gcs_alternative_active[chan] = true;
  1253. }
  1254. /*
  1255. we may also try parsing as MAVLink if we haven't had a
  1256. successful parse on the alternative protocol for 4s
  1257. */
  1258. if (now_ms - alternative.last_alternate_ms <= protocol_timeout) {
  1259. continue;
  1260. }
  1261. }
  1262. bool parsed_packet = false;
  1263. // Try to get a new message
  1264. if (mavlink_parse_char(chan, c, &msg, &status)) {
  1265. hal.util->persistent_data.last_mavlink_msgid = msg.msgid;
  1266. hal.util->perf_begin(_perf_packet);
  1267. packetReceived(status, msg);
  1268. hal.util->perf_end(_perf_packet);
  1269. parsed_packet = true;
  1270. gcs_alternative_active[chan] = false;
  1271. alternative.last_mavlink_ms = now_ms;
  1272. hal.util->persistent_data.last_mavlink_msgid = 0;
  1273. }
  1274. if (parsed_packet || i % 100 == 0) {
  1275. // make sure we don't spend too much time parsing mavlink messages
  1276. if (AP_HAL::micros() - tstart_us > max_time_us) {
  1277. break;
  1278. }
  1279. }
  1280. }
  1281. const uint32_t tnow = AP_HAL::millis();
  1282. // send a timesync message every 10 seconds; this is for data
  1283. // collection purposes
  1284. if (tnow - _timesync_request.last_sent_ms > _timesync_request.interval_ms && !is_private()) {
  1285. if (HAVE_PAYLOAD_SPACE(chan, TIMESYNC)) {
  1286. send_timesync();
  1287. _timesync_request.last_sent_ms = tnow;
  1288. }
  1289. }
  1290. // consider logging mavlink stats:
  1291. if (is_active() || is_streaming()) {
  1292. if (tnow - last_mavlink_stats_logged > 1000) {
  1293. log_mavlink_stats();
  1294. last_mavlink_stats_logged = tnow;
  1295. }
  1296. }
  1297. #if GCS_DEBUG_SEND_MESSAGE_TIMINGS
  1298. const uint16_t now16_ms{AP_HAL::millis16()};
  1299. if (uint16_t(now16_ms - try_send_message_stats.statustext_last_sent_ms) > 10000U) {
  1300. if (try_send_message_stats.longest_time_us) {
  1301. gcs().send_text(MAV_SEVERITY_INFO,
  1302. "GCS.chan(%u): ap_msg=%u took %uus to send",
  1303. chan,
  1304. try_send_message_stats.longest_id,
  1305. try_send_message_stats.longest_time_us);
  1306. try_send_message_stats.longest_time_us = 0;
  1307. }
  1308. if (try_send_message_stats.no_space_for_message &&
  1309. (is_active() || is_streaming())) {
  1310. gcs().send_text(MAV_SEVERITY_INFO,
  1311. "GCS.chan(%u): out-of-space: %u",
  1312. chan,
  1313. try_send_message_stats.no_space_for_message);
  1314. try_send_message_stats.no_space_for_message = 0;
  1315. }
  1316. if (try_send_message_stats.out_of_time) {
  1317. gcs().send_text(MAV_SEVERITY_INFO,
  1318. "GCS.chan(%u): out-of-time=%u",
  1319. chan,
  1320. try_send_message_stats.out_of_time);
  1321. try_send_message_stats.out_of_time = 0;
  1322. }
  1323. if (max_slowdown_ms) {
  1324. gcs().send_text(MAV_SEVERITY_INFO,
  1325. "GCS.chan(%u): max slowdown=%u",
  1326. chan,
  1327. max_slowdown_ms);
  1328. max_slowdown_ms = 0;
  1329. }
  1330. if (try_send_message_stats.behind) {
  1331. gcs().send_text(MAV_SEVERITY_INFO,
  1332. "GCS.chan(%u): behind=%u",
  1333. chan,
  1334. try_send_message_stats.behind);
  1335. try_send_message_stats.behind = 0;
  1336. }
  1337. if (try_send_message_stats.fnbts_maxtime) {
  1338. gcs().send_text(MAV_SEVERITY_INFO,
  1339. "GCS.chan(%u): fnbts_maxtime=%uus",
  1340. chan,
  1341. try_send_message_stats.fnbts_maxtime);
  1342. try_send_message_stats.fnbts_maxtime = 0;
  1343. }
  1344. if (try_send_message_stats.max_retry_deferred_body_us) {
  1345. gcs().send_text(MAV_SEVERITY_INFO,
  1346. "GCS.chan(%u): retry_body_maxtime=%uus (%u)",
  1347. chan,
  1348. try_send_message_stats.max_retry_deferred_body_us,
  1349. try_send_message_stats.max_retry_deferred_body_type
  1350. );
  1351. try_send_message_stats.max_retry_deferred_body_us = 0;
  1352. }
  1353. for (uint8_t i=0; i<ARRAY_SIZE(deferred_message_bucket); i++) {
  1354. gcs().send_text(MAV_SEVERITY_INFO,
  1355. "B. intvl. (%u): %u %u %u %u %u",
  1356. chan,
  1357. deferred_message_bucket[0].interval_ms,
  1358. deferred_message_bucket[1].interval_ms,
  1359. deferred_message_bucket[2].interval_ms,
  1360. deferred_message_bucket[3].interval_ms,
  1361. deferred_message_bucket[4].interval_ms);
  1362. }
  1363. try_send_message_stats.statustext_last_sent_ms = now16_ms;
  1364. }
  1365. #endif
  1366. hal.util->perf_end(_perf_update);
  1367. }
  1368. /*
  1369. record stats about this link to logger
  1370. */
  1371. void GCS_MAVLINK::log_mavlink_stats()
  1372. {
  1373. mavlink_status_t *status = mavlink_get_channel_status(chan);
  1374. if (status == nullptr) {
  1375. return;
  1376. }
  1377. const struct log_MAV pkt = {
  1378. LOG_PACKET_HEADER_INIT(LOG_MAV_MSG),
  1379. time_us : AP_HAL::micros64(),
  1380. chan : (uint8_t)chan,
  1381. packet_tx_count : send_packet_count,
  1382. packet_rx_success_count: status->packet_rx_success_count,
  1383. packet_rx_drop_count : status->packet_rx_drop_count
  1384. };
  1385. AP::logger().WriteBlock(&pkt, sizeof(pkt));
  1386. }
  1387. /*
  1388. send the SYSTEM_TIME message
  1389. */
  1390. void GCS_MAVLINK::send_system_time()
  1391. {
  1392. uint64_t time_unix = 0;
  1393. AP::rtc().get_utc_usec(time_unix); // may fail, leaving time_unix at 0
  1394. mavlink_msg_system_time_send(
  1395. chan,
  1396. time_unix,
  1397. AP_HAL::millis());
  1398. }
  1399. /*
  1400. send RC_CHANNELS messages
  1401. */
  1402. void GCS_MAVLINK::send_rc_channels() const
  1403. {
  1404. AP_RSSI *rssi = AP::rssi();
  1405. uint8_t receiver_rssi = 0;
  1406. if (rssi != nullptr) {
  1407. receiver_rssi = rssi->read_receiver_rssi_uint8();
  1408. }
  1409. uint16_t values[18] = {};
  1410. rc().get_radio_in(values, ARRAY_SIZE(values));
  1411. mavlink_msg_rc_channels_send(
  1412. chan,
  1413. AP_HAL::millis(),
  1414. RC_Channels::get_valid_channel_count(),
  1415. values[0],
  1416. values[1],
  1417. values[2],
  1418. values[3],
  1419. values[4],
  1420. values[5],
  1421. values[6],
  1422. values[7],
  1423. values[8],
  1424. values[9],
  1425. values[10],
  1426. values[11],
  1427. values[12],
  1428. values[13],
  1429. values[14],
  1430. values[15],
  1431. values[16],
  1432. values[17],
  1433. receiver_rssi);
  1434. }
  1435. bool GCS_MAVLINK::sending_mavlink1() const
  1436. {
  1437. const mavlink_status_t *status = mavlink_get_channel_status(chan);
  1438. if (status == nullptr) {
  1439. // should not happen
  1440. return true;
  1441. }
  1442. return ((status->flags & MAVLINK_STATUS_FLAG_OUT_MAVLINK1) != 0);
  1443. }
  1444. void GCS_MAVLINK::send_rc_channels_raw() const
  1445. {
  1446. // for mavlink1 send RC_CHANNELS_RAW, for compatibility with OSD
  1447. // implementations
  1448. if (!sending_mavlink1()) {
  1449. return;
  1450. }
  1451. AP_RSSI *rssi = AP::rssi();
  1452. uint8_t receiver_rssi = 0;
  1453. if (rssi != nullptr) {
  1454. receiver_rssi = rssi->read_receiver_rssi_uint8();
  1455. }
  1456. uint16_t values[8] = {};
  1457. rc().get_radio_in(values, ARRAY_SIZE(values));
  1458. mavlink_msg_rc_channels_raw_send(
  1459. chan,
  1460. AP_HAL::millis(),
  1461. 0,
  1462. values[0],
  1463. values[1],
  1464. values[2],
  1465. values[3],
  1466. values[4],
  1467. values[5],
  1468. values[6],
  1469. values[7],
  1470. receiver_rssi);
  1471. }
  1472. void GCS_MAVLINK::send_raw_imu()
  1473. {
  1474. const AP_InertialSensor &ins = AP::ins();
  1475. const Compass &compass = AP::compass();
  1476. const Vector3f &accel = ins.get_accel(0);
  1477. const Vector3f &gyro = ins.get_gyro(0);
  1478. Vector3f mag;
  1479. if (compass.get_count() >= 1) {
  1480. mag = compass.get_field(0);
  1481. } else {
  1482. mag.zero();
  1483. }
  1484. mavlink_msg_raw_imu_send(
  1485. chan,
  1486. AP_HAL::micros(),
  1487. accel.x * 1000.0f / GRAVITY_MSS,
  1488. accel.y * 1000.0f / GRAVITY_MSS,
  1489. accel.z * 1000.0f / GRAVITY_MSS,
  1490. gyro.x * 1000.0f,
  1491. gyro.y * 1000.0f,
  1492. gyro.z * 1000.0f,
  1493. mag.x,
  1494. mag.y,
  1495. mag.z);
  1496. }
  1497. 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))
  1498. {
  1499. const AP_InertialSensor &ins = AP::ins();
  1500. const Compass &compass = AP::compass();
  1501. bool have_data = false;
  1502. Vector3f accel{};
  1503. if (ins.get_accel_count() > instance) {
  1504. accel = ins.get_accel(instance);
  1505. have_data = true;
  1506. }
  1507. Vector3f gyro{};
  1508. if (ins.get_accel_count() > instance) {
  1509. gyro = ins.get_gyro(instance);
  1510. have_data = true;
  1511. }
  1512. Vector3f mag{};
  1513. if (compass.get_count() > instance) {
  1514. mag = compass.get_field(instance);
  1515. have_data = true;
  1516. }
  1517. if (!have_data) {
  1518. return;
  1519. }
  1520. send_fn(
  1521. chan,
  1522. AP_HAL::millis(),
  1523. accel.x * 1000.0f / GRAVITY_MSS,
  1524. accel.y * 1000.0f / GRAVITY_MSS,
  1525. accel.z * 1000.0f / GRAVITY_MSS,
  1526. gyro.x * 1000.0f,
  1527. gyro.y * 1000.0f,
  1528. gyro.z * 1000.0f,
  1529. mag.x,
  1530. mag.y,
  1531. mag.z);
  1532. }
  1533. // send data for barometer and airspeed sensors instances. In the
  1534. // case that we run out of instances of one before the other we send
  1535. // the relevant fields as 0.
  1536. 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))
  1537. {
  1538. const AP_Baro &barometer = AP::baro();
  1539. bool have_data = false;
  1540. float press_abs = 0.0f;
  1541. float temperature = 0.0f;
  1542. if (instance < barometer.num_instances()) {
  1543. press_abs = barometer.get_pressure(instance) * 0.01f;
  1544. temperature = barometer.get_temperature(instance)*100;
  1545. have_data = true;
  1546. }
  1547. float press_diff = 0; // pascal
  1548. AP_Airspeed *airspeed = AP_Airspeed::get_singleton();
  1549. if (airspeed != nullptr &&
  1550. airspeed->enabled(instance)) {
  1551. press_diff = airspeed->get_differential_pressure(instance) * 0.01f;
  1552. have_data = true;
  1553. }
  1554. if (!have_data) {
  1555. return;
  1556. }
  1557. send_fn(
  1558. chan,
  1559. AP_HAL::millis(),
  1560. press_abs, // hectopascal
  1561. press_diff, // hectopascal
  1562. temperature); // 0.01 degrees C
  1563. }
  1564. void GCS_MAVLINK::send_scaled_pressure()
  1565. {
  1566. send_scaled_pressure_instance(0, mavlink_msg_scaled_pressure_send);
  1567. }
  1568. void GCS_MAVLINK::send_scaled_pressure2()
  1569. {
  1570. send_scaled_pressure_instance(1, mavlink_msg_scaled_pressure2_send);
  1571. }
  1572. void GCS_MAVLINK::send_scaled_pressure3()
  1573. {
  1574. send_scaled_pressure_instance(2, mavlink_msg_scaled_pressure3_send);
  1575. }
  1576. void GCS_MAVLINK::send_sensor_offsets()
  1577. {
  1578. const AP_InertialSensor &ins = AP::ins();
  1579. const Compass &compass = AP::compass();
  1580. // run this message at a much lower rate - otherwise it
  1581. // pointlessly wastes quite a lot of bandwidth
  1582. static uint8_t counter;
  1583. if (counter++ < 10) {
  1584. return;
  1585. }
  1586. counter = 0;
  1587. const Vector3f &mag_offsets = compass.get_offsets(0);
  1588. const Vector3f &accel_offsets = ins.get_accel_offsets(0);
  1589. const Vector3f &gyro_offsets = ins.get_gyro_offsets(0);
  1590. const AP_Baro &barometer = AP::baro();
  1591. mavlink_msg_sensor_offsets_send(chan,
  1592. mag_offsets.x,
  1593. mag_offsets.y,
  1594. mag_offsets.z,
  1595. compass.get_declination(),
  1596. barometer.get_pressure(),
  1597. barometer.get_temperature()*100,
  1598. gyro_offsets.x,
  1599. gyro_offsets.y,
  1600. gyro_offsets.z,
  1601. accel_offsets.x,
  1602. accel_offsets.y,
  1603. accel_offsets.z);
  1604. }
  1605. void GCS_MAVLINK::send_ahrs()
  1606. {
  1607. const AP_AHRS &ahrs = AP::ahrs();
  1608. const Vector3f &omega_I = ahrs.get_gyro_drift();
  1609. mavlink_msg_ahrs_send(
  1610. chan,
  1611. omega_I.x,
  1612. omega_I.y,
  1613. omega_I.z,
  1614. 0,
  1615. 0,
  1616. ahrs.get_error_rp(),
  1617. ahrs.get_error_yaw());
  1618. }
  1619. /*
  1620. send a statustext text string to specific MAVLink bitmask
  1621. */
  1622. void GCS::send_statustext(MAV_SEVERITY severity, uint8_t dest_bitmask, const char *text)
  1623. {
  1624. #if CONFIG_HAL_BOARD == HAL_BOARD_SITL
  1625. if (strlen(text) > MAVLINK_MSG_STATUSTEXT_FIELD_TEXT_LEN) {
  1626. AP_HAL::panic("Statustext (%s) too long", text);
  1627. }
  1628. #endif
  1629. AP_Logger *logger = AP_Logger::get_singleton();
  1630. if (logger != nullptr) {
  1631. logger->Write_Message(text);
  1632. }
  1633. if (frsky != nullptr) {
  1634. frsky->queue_message(severity, text);
  1635. }
  1636. AP_Notify *notify = AP_Notify::get_singleton();
  1637. if (notify) {
  1638. notify->send_text(text);
  1639. }
  1640. // filter destination ports to only allow active ports.
  1641. statustext_t statustext{};
  1642. statustext.bitmask = (GCS_MAVLINK::active_channel_mask() | GCS_MAVLINK::streaming_channel_mask() ) & dest_bitmask;
  1643. if (!statustext.bitmask) {
  1644. // nowhere to send
  1645. return;
  1646. }
  1647. statustext.msg.severity = severity;
  1648. strncpy(statustext.msg.text, text, sizeof(statustext.msg.text));
  1649. WITH_SEMAPHORE(_statustext_sem);
  1650. // The force push will ensure comm links do not block other comm links forever if they fail.
  1651. // If we push to a full buffer then we overwrite the oldest entry, effectively removing the
  1652. // block but not until the buffer fills up.
  1653. _statustext_queue.push_force(statustext);
  1654. // try and send immediately if possible
  1655. service_statustext();
  1656. }
  1657. /*
  1658. send a statustext message to specific MAVLink connections in a bitmask
  1659. */
  1660. void GCS::service_statustext(void)
  1661. {
  1662. // create bitmask of what mavlink ports we should send this text to.
  1663. // note, if sending to all ports, we only need to store the bitmask for each and the string only once.
  1664. // once we send over a link, clear the port but other busy ports bit may stay allowing for faster links
  1665. // to clear the bit and send quickly but slower links to still store the string. Regardless of mixed
  1666. // bitrates of ports, a maximum of _status_capacity strings can be buffered. Downside
  1667. // is if you have a super slow link mixed with a faster port, if there are _status_capacity
  1668. // strings in the slow queue then the next item can not be queued for the faster link
  1669. if (_statustext_queue.empty()) {
  1670. // nothing to do
  1671. return;
  1672. }
  1673. for (uint8_t idx=0; idx<_status_capacity; ) {
  1674. statustext_t *statustext = _statustext_queue[idx];
  1675. if (statustext == nullptr) {
  1676. break;
  1677. }
  1678. // try and send to all active mavlink ports listed in the statustext.bitmask
  1679. for (uint8_t i=0; i<MAVLINK_COMM_NUM_BUFFERS; i++) {
  1680. uint8_t chan_bit = (1U<<i);
  1681. // logical AND (&) to mask them together
  1682. if (statustext->bitmask & chan_bit) {
  1683. // something is queued on a port and that's the port index we're looped at
  1684. mavlink_channel_t chan_index = (mavlink_channel_t)(MAVLINK_COMM_0+i);
  1685. if (HAVE_PAYLOAD_SPACE(chan_index, STATUSTEXT)) {
  1686. // we have space so send then clear that channel bit on the mask
  1687. mavlink_msg_statustext_send(chan_index, statustext->msg.severity, statustext->msg.text);
  1688. statustext->bitmask &= ~chan_bit;
  1689. }
  1690. }
  1691. }
  1692. if (statustext->bitmask == 0) {
  1693. _statustext_queue.remove(idx);
  1694. } else {
  1695. // move to next index
  1696. idx++;
  1697. }
  1698. }
  1699. }
  1700. void GCS::send_message(enum ap_message id)
  1701. {
  1702. for (uint8_t i=0; i<num_gcs(); i++) {
  1703. chan(i)->send_message(id);
  1704. }
  1705. }
  1706. void GCS::update_send()
  1707. {
  1708. if (!initialised_missionitemprotocol_objects) {
  1709. initialised_missionitemprotocol_objects = true;
  1710. // once-only initialisation of MissionItemProtocol objects:
  1711. AP_Mission *mission = AP::mission();
  1712. if (mission != nullptr) {
  1713. _missionitemprotocol_waypoints = new MissionItemProtocol_Waypoints(*mission);
  1714. }
  1715. AP_Rally *rally = AP::rally();
  1716. if (rally != nullptr) {
  1717. _missionitemprotocol_rally = new MissionItemProtocol_Rally(*rally);
  1718. }
  1719. }
  1720. if (_missionitemprotocol_waypoints != nullptr) {
  1721. _missionitemprotocol_waypoints->update();
  1722. }
  1723. if (_missionitemprotocol_rally != nullptr) {
  1724. _missionitemprotocol_rally->update();
  1725. }
  1726. for (uint8_t i=0; i<num_gcs(); i++) {
  1727. chan(i)->update_send();
  1728. }
  1729. WITH_SEMAPHORE(_statustext_sem);
  1730. service_statustext();
  1731. }
  1732. void GCS::update_receive(void)
  1733. {
  1734. for (uint8_t i=0; i<num_gcs(); i++) {
  1735. chan(i)->update_receive();
  1736. }
  1737. // also update UART pass-thru, if enabled
  1738. update_passthru();
  1739. }
  1740. void GCS::send_mission_item_reached_message(uint16_t mission_index)
  1741. {
  1742. for (uint8_t i=0; i<num_gcs(); i++) {
  1743. chan(i)->mission_item_reached_index = mission_index;
  1744. chan(i)->send_message(MSG_MISSION_ITEM_REACHED);
  1745. }
  1746. }
  1747. void GCS::setup_console()
  1748. {
  1749. AP_HAL::UARTDriver *uart = AP::serialmanager().find_serial(AP_SerialManager::SerialProtocol_MAVLink, 0);
  1750. if (uart == nullptr) {
  1751. // this is probably not going to end well.
  1752. return;
  1753. }
  1754. if (ARRAY_SIZE(chan_parameters) == 0) {
  1755. return;
  1756. }
  1757. create_gcs_mavlink_backend(chan_parameters[0], *uart);
  1758. }
  1759. GCS_MAVLINK_Parameters::GCS_MAVLINK_Parameters()
  1760. {
  1761. AP_Param::setup_object_defaults(this, var_info);
  1762. }
  1763. void GCS::create_gcs_mavlink_backend(GCS_MAVLINK_Parameters &params, AP_HAL::UARTDriver &uart)
  1764. {
  1765. if (_num_gcs >= ARRAY_SIZE(chan_parameters)) {
  1766. return;
  1767. }
  1768. _chan[_num_gcs] = new_gcs_mavlink_backend(params, uart);
  1769. if (_chan[_num_gcs] == nullptr) {
  1770. return;
  1771. }
  1772. if (!_chan[_num_gcs]->init(_num_gcs)) {
  1773. delete _chan[_num_gcs];
  1774. _chan[_num_gcs] = nullptr;
  1775. return;
  1776. }
  1777. _num_gcs++;
  1778. }
  1779. void GCS::setup_uarts()
  1780. {
  1781. for (uint8_t i = 1; i < MAVLINK_COMM_NUM_BUFFERS; i++) {
  1782. if (i >= ARRAY_SIZE(chan_parameters)) {
  1783. // should not happen
  1784. break;
  1785. }
  1786. AP_HAL::UARTDriver *uart = AP::serialmanager().find_serial(AP_SerialManager::SerialProtocol_MAVLink, i);
  1787. if (uart == nullptr) {
  1788. // no more mavlink uarts
  1789. break;
  1790. }
  1791. create_gcs_mavlink_backend(chan_parameters[i], *uart);
  1792. }
  1793. if (frsky == nullptr) {
  1794. frsky = new AP_Frsky_Telem();
  1795. if (frsky == nullptr || !frsky->init()) {
  1796. delete frsky;
  1797. frsky = nullptr;
  1798. }
  1799. }
  1800. #if !HAL_MINIMIZE_FEATURES
  1801. devo_telemetry.init();
  1802. #endif
  1803. }
  1804. // report battery2 state
  1805. void GCS_MAVLINK::send_battery2()
  1806. {
  1807. const AP_BattMonitor &battery = AP::battery();
  1808. if (battery.num_instances() > 1) {
  1809. float current;
  1810. if (battery.current_amps(current, 1)) {
  1811. current *= 100; // 10*mA
  1812. } else {
  1813. current = -1;
  1814. }
  1815. mavlink_msg_battery2_send(chan, battery.voltage(1)*1000, current);
  1816. }
  1817. }
  1818. /*
  1819. handle a SET_MODE MAVLink message
  1820. */
  1821. void GCS_MAVLINK::handle_set_mode(const mavlink_message_t &msg)
  1822. {
  1823. mavlink_set_mode_t packet;
  1824. mavlink_msg_set_mode_decode(&msg, &packet);
  1825. const MAV_MODE _base_mode = (MAV_MODE)packet.base_mode;
  1826. const uint32_t _custom_mode = packet.custom_mode;
  1827. const MAV_RESULT result = _set_mode_common(_base_mode, _custom_mode);
  1828. // send ACK or NAK. Note that this is extraodinarily improper -
  1829. // we are sending a command-ack for a message which is not a
  1830. // command. The command we are acking (ID=11) doesn't actually
  1831. // exist, but if it did we'd probably be acking something
  1832. // completely unrelated to setting modes.
  1833. if (HAVE_PAYLOAD_SPACE(chan, MAVLINK_MSG_ID_COMMAND_ACK)) {
  1834. mavlink_msg_command_ack_send(chan, MAVLINK_MSG_ID_SET_MODE, result);
  1835. }
  1836. }
  1837. /*
  1838. code common to both SET_MODE mavlink message and command long set_mode msg
  1839. */
  1840. MAV_RESULT GCS_MAVLINK::_set_mode_common(const MAV_MODE _base_mode, const uint32_t _custom_mode)
  1841. {
  1842. MAV_RESULT result = MAV_RESULT_UNSUPPORTED;
  1843. // only accept custom modes because there is no easy mapping from Mavlink flight modes to AC flight modes
  1844. if (_base_mode & MAV_MODE_FLAG_CUSTOM_MODE_ENABLED) {
  1845. if (set_mode(_custom_mode)) {
  1846. result = MAV_RESULT_ACCEPTED;
  1847. }
  1848. } else if (_base_mode == (MAV_MODE)MAV_MODE_FLAG_DECODE_POSITION_SAFETY) {
  1849. // set the safety switch position. Must be in a command by itself
  1850. if (_custom_mode == 0) {
  1851. // turn safety off (pwm outputs flow to the motors)
  1852. hal.rcout->force_safety_off();
  1853. result = MAV_RESULT_ACCEPTED;
  1854. } else if (_custom_mode == 1) {
  1855. // turn safety on (no pwm outputs to the motors)
  1856. if (hal.rcout->force_safety_on()) {
  1857. result = MAV_RESULT_ACCEPTED;
  1858. }
  1859. }
  1860. }
  1861. return result;
  1862. }
  1863. /*
  1864. send OPTICAL_FLOW message
  1865. */
  1866. void GCS_MAVLINK::send_opticalflow()
  1867. {
  1868. #if AP_AHRS_NAVEKF_AVAILABLE
  1869. const OpticalFlow *optflow = AP::opticalflow();
  1870. // exit immediately if no optical flow sensor or not healthy
  1871. if (optflow == nullptr ||
  1872. !optflow->healthy()) {
  1873. return;
  1874. }
  1875. // get rates from sensor
  1876. const Vector2f &flowRate = optflow->flowRate();
  1877. const Vector2f &bodyRate = optflow->bodyRate();
  1878. const AP_AHRS &ahrs = AP::ahrs();
  1879. float hagl = 0;
  1880. if (ahrs.have_inertial_nav()) {
  1881. if (!ahrs.get_hagl(hagl)) {
  1882. return;
  1883. }
  1884. }
  1885. // populate and send message
  1886. mavlink_msg_optical_flow_send(
  1887. chan,
  1888. AP_HAL::millis(),
  1889. 0, // sensor id is zero
  1890. flowRate.x,
  1891. flowRate.y,
  1892. flowRate.x - bodyRate.x,
  1893. flowRate.y - bodyRate.y,
  1894. optflow->quality(),
  1895. hagl, // ground distance (in meters) set to zero
  1896. flowRate.x,
  1897. flowRate.y);
  1898. #endif
  1899. }
  1900. /*
  1901. send AUTOPILOT_VERSION packet
  1902. */
  1903. void GCS_MAVLINK::send_autopilot_version() const
  1904. {
  1905. uint32_t flight_sw_version;
  1906. uint32_t middleware_sw_version = 0;
  1907. uint32_t board_version = 0;
  1908. char flight_custom_version[MAVLINK_MSG_AUTOPILOT_VERSION_FIELD_FLIGHT_CUSTOM_VERSION_LEN]{};
  1909. char middleware_custom_version[MAVLINK_MSG_AUTOPILOT_VERSION_FIELD_MIDDLEWARE_CUSTOM_VERSION_LEN]{};
  1910. char os_custom_version[MAVLINK_MSG_AUTOPILOT_VERSION_FIELD_OS_CUSTOM_VERSION_LEN]{};
  1911. uint16_t vendor_id = 0;
  1912. uint16_t product_id = 0;
  1913. uint64_t uid = 0;
  1914. uint8_t uid2[MAVLINK_MSG_AUTOPILOT_VERSION_FIELD_UID2_LEN] = {0};
  1915. const AP_FWVersion &version = AP::fwversion();
  1916. flight_sw_version = version.major << (8 * 3) | \
  1917. version.minor << (8 * 2) | \
  1918. version.patch << (8 * 1) | \
  1919. (uint32_t)(version.fw_type) << (8 * 0);
  1920. if (version.fw_hash_str) {
  1921. strncpy(flight_custom_version, version.fw_hash_str, sizeof(flight_custom_version) - 1);
  1922. flight_custom_version[sizeof(flight_custom_version) - 1] = '\0';
  1923. }
  1924. if (version.middleware_hash_str) {
  1925. strncpy(middleware_custom_version, version.middleware_hash_str, sizeof(middleware_custom_version) - 1);
  1926. middleware_custom_version[sizeof(middleware_custom_version) - 1] = '\0';
  1927. }
  1928. if (version.os_hash_str) {
  1929. strncpy(os_custom_version, version.os_hash_str, sizeof(os_custom_version) - 1);
  1930. os_custom_version[sizeof(os_custom_version) - 1] = '\0';
  1931. }
  1932. mavlink_msg_autopilot_version_send(
  1933. chan,
  1934. capabilities(),
  1935. flight_sw_version,
  1936. middleware_sw_version,
  1937. version.os_sw_version,
  1938. board_version,
  1939. (uint8_t *)flight_custom_version,
  1940. (uint8_t *)middleware_custom_version,
  1941. (uint8_t *)os_custom_version,
  1942. vendor_id,
  1943. product_id,
  1944. uid,
  1945. uid2
  1946. );
  1947. }
  1948. /*
  1949. send LOCAL_POSITION_NED message
  1950. */
  1951. void GCS_MAVLINK::send_local_position() const
  1952. {
  1953. const AP_AHRS &ahrs = AP::ahrs();
  1954. Vector3f local_position, velocity;
  1955. if (!ahrs.get_relative_position_NED_home(local_position) ||
  1956. !ahrs.get_velocity_NED(velocity)) {
  1957. // we don't know the position and velocity
  1958. return;
  1959. }
  1960. mavlink_msg_local_position_ned_send(
  1961. chan,
  1962. AP_HAL::millis(),
  1963. local_position.x,
  1964. local_position.y,
  1965. local_position.z,
  1966. velocity.x,
  1967. velocity.y,
  1968. velocity.z);
  1969. }
  1970. /*
  1971. send VIBRATION message
  1972. */
  1973. void GCS_MAVLINK::send_vibration() const
  1974. {
  1975. const AP_InertialSensor &ins = AP::ins();
  1976. Vector3f vibration = ins.get_vibration_levels();
  1977. mavlink_msg_vibration_send(
  1978. chan,
  1979. AP_HAL::micros64(),
  1980. vibration.x,
  1981. vibration.y,
  1982. vibration.z,
  1983. ins.get_accel_clip_count(0),
  1984. ins.get_accel_clip_count(1),
  1985. ins.get_accel_clip_count(2));
  1986. }
  1987. void GCS_MAVLINK::send_named_float(const char *name, float value) const
  1988. {
  1989. char float_name[MAVLINK_MSG_NAMED_VALUE_FLOAT_FIELD_NAME_LEN+1] {};
  1990. strncpy(float_name, name, MAVLINK_MSG_NAMED_VALUE_FLOAT_FIELD_NAME_LEN);
  1991. mavlink_msg_named_value_float_send(chan, AP_HAL::millis(), float_name, value);
  1992. }
  1993. void GCS_MAVLINK::send_home_position() const
  1994. {
  1995. if (!AP::ahrs().home_is_set()) {
  1996. return;
  1997. }
  1998. const Location &home = AP::ahrs().get_home();
  1999. const float q[4] = {1.0f, 0.0f, 0.0f, 0.0f};
  2000. mavlink_msg_home_position_send(
  2001. chan,
  2002. home.lat,
  2003. home.lng,
  2004. home.alt * 10,
  2005. 0.0f, 0.0f, 0.0f,
  2006. q,
  2007. 0.0f, 0.0f, 0.0f,
  2008. AP_HAL::micros64());
  2009. }
  2010. void GCS_MAVLINK::send_gps_global_origin() const
  2011. {
  2012. Location ekf_origin;
  2013. if (!AP::ahrs().get_origin(ekf_origin)) {
  2014. return;
  2015. }
  2016. mavlink_msg_gps_global_origin_send(
  2017. chan,
  2018. ekf_origin.lat,
  2019. ekf_origin.lng,
  2020. ekf_origin.alt * 10,
  2021. AP_HAL::micros64());
  2022. }
  2023. /*
  2024. Send MAVLink heartbeat
  2025. */
  2026. void GCS_MAVLINK::send_heartbeat() const
  2027. {
  2028. mavlink_msg_heartbeat_send(
  2029. chan,
  2030. gcs().frame_type(),
  2031. MAV_AUTOPILOT_ARDUPILOTMEGA,
  2032. base_mode(),
  2033. gcs().custom_mode(),
  2034. system_status());
  2035. }
  2036. MAV_RESULT GCS_MAVLINK::handle_command_set_message_interval(const mavlink_command_long_t &packet)
  2037. {
  2038. const uint32_t msg_id = (uint32_t)packet.param1;
  2039. const int32_t interval_us = (int32_t)packet.param2;
  2040. uint16_t interval_ms;
  2041. if (interval_us == 0) {
  2042. // zero is "reset to default rate"
  2043. if (!get_default_interval_for_mavlink_message_id(msg_id, interval_ms)) {
  2044. return MAV_RESULT_FAILED;
  2045. }
  2046. } else if (interval_us == -1) {
  2047. // minus-one is "stop sending"
  2048. interval_ms = 0;
  2049. } else if (interval_us < 1000) {
  2050. // don't squash sub-ms times to zero
  2051. interval_ms = 1;
  2052. } else if (interval_us > 60000000) {
  2053. interval_ms = 60000;
  2054. } else {
  2055. interval_ms = interval_us / 1000;
  2056. }
  2057. if (set_mavlink_message_id_interval(msg_id, interval_ms)) {
  2058. return MAV_RESULT_ACCEPTED;
  2059. }
  2060. return MAV_RESULT_FAILED;
  2061. }
  2062. MAV_RESULT GCS_MAVLINK::handle_command_request_message(const mavlink_command_long_t &packet)
  2063. {
  2064. const uint32_t mavlink_id = (uint32_t)packet.param1;
  2065. const ap_message id = mavlink_id_to_ap_message_id(mavlink_id);
  2066. if (id == MSG_LAST) {
  2067. return MAV_RESULT_FAILED;
  2068. }
  2069. send_message(id);
  2070. return MAV_RESULT_ACCEPTED;
  2071. }
  2072. bool GCS_MAVLINK::get_ap_message_interval(ap_message id, uint16_t &interval_ms) const
  2073. {
  2074. // check if it's a specially-handled message:
  2075. const int8_t deferred_offset = get_deferred_message_index(id);
  2076. if (deferred_offset != -1) {
  2077. interval_ms = deferred_message[deferred_offset].interval_ms;
  2078. return true;
  2079. }
  2080. // check the deferred message buckets:
  2081. for (uint8_t i=0; i<ARRAY_SIZE(deferred_message_bucket); i++) {
  2082. const deferred_message_bucket_t &bucket = deferred_message_bucket[i];
  2083. if (bucket.ap_message_ids.get(id)) {
  2084. interval_ms = bucket.interval_ms;
  2085. return true;
  2086. }
  2087. }
  2088. return false;
  2089. }
  2090. MAV_RESULT GCS_MAVLINK::handle_command_get_message_interval(const mavlink_command_long_t &packet)
  2091. {
  2092. if (comm_get_txspace(chan) < PAYLOAD_SIZE(chan, MESSAGE_INTERVAL) + PAYLOAD_SIZE(chan, COMMAND_ACK)) {
  2093. return MAV_RESULT_TEMPORARILY_REJECTED;
  2094. }
  2095. const uint32_t mavlink_id = (uint32_t)packet.param1;
  2096. if (mavlink_id >= 2 << 15) {
  2097. // response packet limits range this works against!
  2098. mavlink_msg_message_interval_send(chan, mavlink_id, 0); // not available
  2099. return MAV_RESULT_FAILED;
  2100. }
  2101. const ap_message id = mavlink_id_to_ap_message_id(mavlink_id);
  2102. if (id == MSG_LAST) {
  2103. mavlink_msg_message_interval_send(chan, mavlink_id, 0); // not available
  2104. return MAV_RESULT_FAILED;
  2105. }
  2106. uint16_t interval_ms = 0;
  2107. if (!get_ap_message_interval(id, interval_ms)) {
  2108. // not streaming this message at the moment...
  2109. mavlink_msg_message_interval_send(chan, mavlink_id, -1); // disabled
  2110. return MAV_RESULT_ACCEPTED;
  2111. }
  2112. if (interval_ms == 0) {
  2113. mavlink_msg_message_interval_send(chan, mavlink_id, -1); // disabled
  2114. return MAV_RESULT_ACCEPTED;
  2115. }
  2116. mavlink_msg_message_interval_send(chan, mavlink_id, interval_ms * 1000);
  2117. return MAV_RESULT_ACCEPTED;
  2118. }
  2119. // are we still delaying telemetry to try to avoid Xbee bricking?
  2120. bool GCS_MAVLINK::telemetry_delayed() const
  2121. {
  2122. uint32_t tnow = AP_HAL::millis() >> 10;
  2123. if (tnow > telem_delay()) {
  2124. return false;
  2125. }
  2126. if (chan == MAVLINK_COMM_0 && hal.gpio->usb_connected()) {
  2127. // this is USB telemetry, so won't be an Xbee
  2128. return false;
  2129. }
  2130. // we're either on the 2nd UART, or no USB cable is connected
  2131. // we need to delay telemetry by the TELEM_DELAY time
  2132. return true;
  2133. }
  2134. /*
  2135. send SERVO_OUTPUT_RAW
  2136. */
  2137. void GCS_MAVLINK::send_servo_output_raw()
  2138. {
  2139. uint16_t values[16] {};
  2140. if (in_hil_mode()) {
  2141. for (uint8_t i=0; i<16; i++) {
  2142. values[i] = SRV_Channels::srv_channel(i)->get_output_pwm();
  2143. }
  2144. } else {
  2145. hal.rcout->read(values, 16);
  2146. }
  2147. for (uint8_t i=0; i<16; i++) {
  2148. if (values[i] == 65535) {
  2149. values[i] = 0;
  2150. }
  2151. }
  2152. mavlink_msg_servo_output_raw_send(
  2153. chan,
  2154. AP_HAL::micros(),
  2155. 0, // port
  2156. values[0], values[1], values[2], values[3],
  2157. values[4], values[5], values[6], values[7],
  2158. values[8], values[9], values[10], values[11],
  2159. values[12], values[13], values[14], values[15]);
  2160. }
  2161. void GCS_MAVLINK::send_accelcal_vehicle_position(uint32_t position)
  2162. {
  2163. if (HAVE_PAYLOAD_SPACE(chan, COMMAND_LONG)) {
  2164. mavlink_msg_command_long_send(
  2165. chan,
  2166. 0,
  2167. 0,
  2168. MAV_CMD_ACCELCAL_VEHICLE_POS,
  2169. 0,
  2170. (float) position,
  2171. 0, 0, 0, 0, 0, 0);
  2172. }
  2173. }
  2174. float GCS_MAVLINK::vfr_hud_airspeed() const
  2175. {
  2176. AP_Airspeed *airspeed = AP_Airspeed::get_singleton();
  2177. if (airspeed != nullptr && airspeed->healthy()) {
  2178. return airspeed->get_airspeed();
  2179. }
  2180. // because most vehicles don't have airspeed sensors, we return a
  2181. // different sort of speed estimate in the relevant field for
  2182. // comparison's sake.
  2183. return AP::gps().ground_speed();
  2184. }
  2185. float GCS_MAVLINK::vfr_hud_climbrate() const
  2186. {
  2187. Vector3f velned;
  2188. if (!AP::ahrs().get_velocity_NED(velned)) {
  2189. velned.zero();
  2190. }
  2191. return -velned.z;
  2192. }
  2193. float GCS_MAVLINK::vfr_hud_alt() const
  2194. {
  2195. return global_position_current_loc.alt * 0.01f; // cm -> m
  2196. }
  2197. void GCS_MAVLINK::send_vfr_hud()
  2198. {
  2199. AP_AHRS &ahrs = AP::ahrs();
  2200. // return values ignored; we send stale data
  2201. ahrs.get_position(global_position_current_loc);
  2202. mavlink_msg_vfr_hud_send(
  2203. chan,
  2204. vfr_hud_airspeed(),
  2205. ahrs.groundspeed(),
  2206. (ahrs.yaw_sensor / 100) % 360,
  2207. vfr_hud_throttle(),
  2208. vfr_hud_alt(),
  2209. vfr_hud_climbrate());
  2210. }
  2211. void GCS_MAVLINK::zero_rc_outputs()
  2212. {
  2213. // Send an invalid signal to the motors to prevent spinning due to neutral (1500) pwm pulse being cut short
  2214. // For that matter, send an invalid signal to all channels to prevent undesired/unexpected behavior
  2215. SRV_Channels::cork();
  2216. for (int i=0; i<NUM_RC_CHANNELS; i++) {
  2217. hal.rcout->write(i, 0);
  2218. }
  2219. SRV_Channels::push();
  2220. }
  2221. /*
  2222. handle a MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN command
  2223. Optionally disable PX4IO overrides. This is done for quadplanes to
  2224. prevent the mixer running while rebooting which can start the VTOL
  2225. motors. That can be dangerous when a preflight reboot is done with
  2226. the pilot close to the aircraft and can also damage the aircraft
  2227. */
  2228. MAV_RESULT GCS_MAVLINK::handle_preflight_reboot(const mavlink_command_long_t &packet)
  2229. {
  2230. if (is_equal(packet.param1, 42.0f) &&
  2231. is_equal(packet.param2, 24.0f) &&
  2232. is_equal(packet.param3, 71.0f) &&
  2233. is_equal(packet.param4, 93.0f)) {
  2234. // this is a magic sequence to force the main loop to
  2235. // lockup. This is for testing the stm32 watchdog
  2236. // functionality
  2237. while (true) {
  2238. send_text(MAV_SEVERITY_WARNING,"entering lockup");
  2239. hal.scheduler->delay(250);
  2240. }
  2241. }
  2242. if (hal.util->get_soft_armed()) {
  2243. // refuse reboot when armed
  2244. return MAV_RESULT_FAILED;
  2245. }
  2246. if (!(is_equal(packet.param1, 1.0f) || is_equal(packet.param1, 3.0f))) {
  2247. // param1 must be 1 or 3 - 1 being reboot, 3 being reboot-to-bootloader
  2248. return MAV_RESULT_UNSUPPORTED;
  2249. }
  2250. if (should_zero_rc_outputs_on_reboot()) {
  2251. zero_rc_outputs();
  2252. }
  2253. // send ack before we reboot
  2254. mavlink_msg_command_ack_send(chan, packet.command, MAV_RESULT_ACCEPTED);
  2255. // Notify might want to blink some LEDs:
  2256. AP_Notify *notify = AP_Notify::get_singleton();
  2257. if (notify) {
  2258. AP_Notify::flags.firmware_update = 1;
  2259. notify->update();
  2260. }
  2261. // force safety on
  2262. hal.rcout->force_safety_on();
  2263. // flush pending parameter writes
  2264. AP_Param::flush();
  2265. hal.scheduler->delay(200);
  2266. // when packet.param1 == 3 we reboot to hold in bootloader
  2267. const bool hold_in_bootloader = is_equal(packet.param1, 3.0f);
  2268. hal.scheduler->reboot(hold_in_bootloader);
  2269. return MAV_RESULT_FAILED;
  2270. }
  2271. /*
  2272. handle a flight termination request
  2273. */
  2274. MAV_RESULT GCS_MAVLINK::handle_flight_termination(const mavlink_command_long_t &packet)
  2275. {
  2276. AP_AdvancedFailsafe *failsafe = get_advanced_failsafe();
  2277. if (failsafe == nullptr) {
  2278. return MAV_RESULT_UNSUPPORTED;
  2279. }
  2280. bool should_terminate = packet.param1 > 0.5f;
  2281. if (failsafe->gcs_terminate(should_terminate, "GCS request")) {
  2282. return MAV_RESULT_ACCEPTED;
  2283. }
  2284. return MAV_RESULT_FAILED;
  2285. }
  2286. /*
  2287. handle a R/C bind request (for spektrum)
  2288. */
  2289. MAV_RESULT GCS_MAVLINK::handle_rc_bind(const mavlink_command_long_t &packet)
  2290. {
  2291. // initiate bind procedure. We accept the DSM type from either
  2292. // param1 or param2 due to a past mixup with what parameter is the
  2293. // right one
  2294. if (!RC_Channels::receiver_bind(packet.param2>0?packet.param2:packet.param1)) {
  2295. return MAV_RESULT_FAILED;
  2296. }
  2297. return MAV_RESULT_ACCEPTED;
  2298. }
  2299. uint64_t GCS_MAVLINK::timesync_receive_timestamp_ns() const
  2300. {
  2301. uint64_t ret = _port->receive_time_constraint_us(PAYLOAD_SIZE(chan, TIMESYNC));
  2302. if (ret == 0) {
  2303. ret = AP_HAL::micros64();
  2304. }
  2305. return ret*1000LL;
  2306. }
  2307. uint64_t GCS_MAVLINK::timesync_timestamp_ns() const
  2308. {
  2309. // we add in our own system id try to ensure we only consider
  2310. // responses to our own timesync request messages
  2311. return AP_HAL::micros64()*1000LL + mavlink_system.sysid;
  2312. }
  2313. /*
  2314. return a timesync request
  2315. Sends back ts1 as received, and tc1 is the local timestamp in usec
  2316. */
  2317. void GCS_MAVLINK::handle_timesync(const mavlink_message_t &msg)
  2318. {
  2319. // decode incoming timesync message
  2320. mavlink_timesync_t tsync;
  2321. mavlink_msg_timesync_decode(&msg, &tsync);
  2322. if (tsync.tc1 != 0) {
  2323. // this is a response to a timesync request
  2324. if (tsync.ts1 != _timesync_request.sent_ts1) {
  2325. // we didn't actually send the request.... or it's a
  2326. // response to an ancient request...
  2327. return;
  2328. }
  2329. const uint64_t round_trip_time_us = (timesync_receive_timestamp_ns() - _timesync_request.sent_ts1)*0.001f;
  2330. #if 0
  2331. gcs().send_text(MAV_SEVERITY_INFO,
  2332. "timesync response sysid=%u (latency=%fms)",
  2333. msg.sysid,
  2334. round_trip_time_us*0.001f);
  2335. #endif
  2336. AP_Logger *logger = AP_Logger::get_singleton();
  2337. if (logger != nullptr) {
  2338. AP::logger().Write(
  2339. "TSYN",
  2340. "TimeUS,SysID,RTT",
  2341. "s-s",
  2342. "F-F",
  2343. "QBQ",
  2344. AP_HAL::micros64(),
  2345. msg.sysid,
  2346. round_trip_time_us
  2347. );
  2348. }
  2349. return;
  2350. }
  2351. if (!HAVE_PAYLOAD_SPACE(chan, TIMESYNC)) {
  2352. // drop this timesync request entirely
  2353. return;
  2354. }
  2355. // create new timesync struct with tc1 field as system time in
  2356. // nanoseconds. The client timestamp is as close as possible to
  2357. // the time we received the TIMESYNC message.
  2358. mavlink_timesync_t rsync;
  2359. rsync.tc1 = timesync_receive_timestamp_ns();
  2360. rsync.ts1 = tsync.ts1;
  2361. // respond with a timesync message
  2362. mavlink_msg_timesync_send(
  2363. chan,
  2364. rsync.tc1,
  2365. rsync.ts1
  2366. );
  2367. }
  2368. /*
  2369. * broadcast a timesync message. We may get multiple responses to this request.
  2370. */
  2371. void GCS_MAVLINK::send_timesync()
  2372. {
  2373. _timesync_request.sent_ts1 = timesync_timestamp_ns();
  2374. mavlink_msg_timesync_send(
  2375. chan,
  2376. 0,
  2377. _timesync_request.sent_ts1
  2378. );
  2379. }
  2380. void GCS_MAVLINK::handle_statustext(const mavlink_message_t &msg)
  2381. {
  2382. AP_Logger *logger = AP_Logger::get_singleton();
  2383. if (logger == nullptr) {
  2384. return;
  2385. }
  2386. mavlink_statustext_t packet;
  2387. mavlink_msg_statustext_decode(&msg, &packet);
  2388. const uint8_t max_prefix_len = 20;
  2389. const uint8_t text_len = MAVLINK_MSG_STATUSTEXT_FIELD_TEXT_LEN+1+max_prefix_len;
  2390. char text[text_len] = { 'G','C','S',':'};
  2391. uint8_t offset = strlen(text);
  2392. if (msg.sysid != sysid_my_gcs()) {
  2393. offset = hal.util->snprintf(text,
  2394. max_prefix_len,
  2395. "SRC=%u/%u:",
  2396. msg.sysid,
  2397. msg.compid);
  2398. offset = MIN(offset, max_prefix_len);
  2399. }
  2400. memcpy(&text[offset], packet.text, MAVLINK_MSG_STATUSTEXT_FIELD_TEXT_LEN);
  2401. logger->Write_Message(text);
  2402. }
  2403. void GCS_MAVLINK::handle_system_time_message(const mavlink_message_t &msg)
  2404. {
  2405. mavlink_system_time_t packet;
  2406. mavlink_msg_system_time_decode(&msg, &packet);
  2407. AP::rtc().set_utc_usec(packet.time_unix_usec, AP_RTC::SOURCE_MAVLINK_SYSTEM_TIME);
  2408. }
  2409. MAV_RESULT GCS_MAVLINK::handle_command_camera(const mavlink_command_long_t &packet)
  2410. {
  2411. AP_Camera *camera = AP::camera();
  2412. if (camera == nullptr) {
  2413. return MAV_RESULT_UNSUPPORTED;
  2414. }
  2415. MAV_RESULT result = MAV_RESULT_FAILED;
  2416. switch (packet.command) {
  2417. case MAV_CMD_DO_DIGICAM_CONFIGURE:
  2418. camera->configure(packet.param1,
  2419. packet.param2,
  2420. packet.param3,
  2421. packet.param4,
  2422. packet.param5,
  2423. packet.param6,
  2424. packet.param7);
  2425. result = MAV_RESULT_ACCEPTED;
  2426. break;
  2427. case MAV_CMD_DO_DIGICAM_CONTROL:
  2428. camera->control(packet.param1,
  2429. packet.param2,
  2430. packet.param3,
  2431. packet.param4,
  2432. packet.param5,
  2433. packet.param6);
  2434. result = MAV_RESULT_ACCEPTED;
  2435. break;
  2436. case MAV_CMD_DO_SET_CAM_TRIGG_DIST:
  2437. camera->set_trigger_distance(packet.param1);
  2438. result = MAV_RESULT_ACCEPTED;
  2439. break;
  2440. default:
  2441. result = MAV_RESULT_UNSUPPORTED;
  2442. break;
  2443. }
  2444. return result;
  2445. }
  2446. // sets ekf_origin if it has not been set.
  2447. // should only be used when there is no GPS to provide an absolute position
  2448. void GCS_MAVLINK::set_ekf_origin(const Location& loc)
  2449. {
  2450. // check location is valid
  2451. if (!loc.check_latlng()) {
  2452. return;
  2453. }
  2454. AP_AHRS &ahrs = AP::ahrs();
  2455. // check if EKF origin has already been set
  2456. Location ekf_origin;
  2457. if (ahrs.get_origin(ekf_origin)) {
  2458. return;
  2459. }
  2460. if (!ahrs.set_origin(loc)) {
  2461. return;
  2462. }
  2463. ahrs.Log_Write_Home_And_Origin();
  2464. // send ekf origin to GCS
  2465. if (!try_send_message(MSG_ORIGIN)) {
  2466. // try again later
  2467. send_message(MSG_ORIGIN);
  2468. }
  2469. }
  2470. void GCS_MAVLINK::handle_set_gps_global_origin(const mavlink_message_t &msg)
  2471. {
  2472. mavlink_set_gps_global_origin_t packet;
  2473. mavlink_msg_set_gps_global_origin_decode(&msg, &packet);
  2474. // sanity check location
  2475. if (!check_latlng(packet.latitude, packet.longitude)) {
  2476. // silently drop the request
  2477. return;
  2478. }
  2479. Location ekf_origin {};
  2480. ekf_origin.lat = packet.latitude;
  2481. ekf_origin.lng = packet.longitude;
  2482. ekf_origin.alt = packet.altitude / 10;
  2483. set_ekf_origin(ekf_origin);
  2484. }
  2485. /*
  2486. handle a DATA96 message
  2487. */
  2488. void GCS_MAVLINK::handle_data_packet(const mavlink_message_t &msg)
  2489. {
  2490. #if HAL_RCINPUT_WITH_AP_RADIO
  2491. mavlink_data96_t m;
  2492. mavlink_msg_data96_decode(&msg, &m);
  2493. switch (m.type) {
  2494. case 42:
  2495. case 43: {
  2496. // pass to AP_Radio (for firmware upload and playing test tunes)
  2497. AP_Radio *radio = AP_Radio::get_singleton();
  2498. if (radio != nullptr) {
  2499. radio->handle_data_packet(chan, m);
  2500. }
  2501. break;
  2502. }
  2503. default:
  2504. // unknown
  2505. break;
  2506. }
  2507. #endif
  2508. }
  2509. void GCS_MAVLINK::handle_vision_position_delta(const mavlink_message_t &msg)
  2510. {
  2511. AP_VisualOdom *visual_odom = AP::visualodom();
  2512. if (visual_odom == nullptr) {
  2513. return;
  2514. }
  2515. visual_odom->handle_msg(msg);
  2516. }
  2517. void GCS_MAVLINK::handle_vision_position_estimate(const mavlink_message_t &msg)
  2518. {
  2519. mavlink_vision_position_estimate_t m;
  2520. mavlink_msg_vision_position_estimate_decode(&msg, &m);
  2521. handle_common_vision_position_estimate_data(m.usec, m.x, m.y, m.z, m.roll, m.pitch, m.yaw,
  2522. PAYLOAD_SIZE(chan, VISION_POSITION_ESTIMATE));
  2523. }
  2524. void GCS_MAVLINK::handle_global_vision_position_estimate(const mavlink_message_t &msg)
  2525. {
  2526. mavlink_global_vision_position_estimate_t m;
  2527. mavlink_msg_global_vision_position_estimate_decode(&msg, &m);
  2528. handle_common_vision_position_estimate_data(m.usec, m.x, m.y, m.z, m.roll, m.pitch, m.yaw,
  2529. PAYLOAD_SIZE(chan, GLOBAL_VISION_POSITION_ESTIMATE));
  2530. }
  2531. void GCS_MAVLINK::handle_vicon_position_estimate(const mavlink_message_t &msg)
  2532. {
  2533. mavlink_vicon_position_estimate_t m;
  2534. mavlink_msg_vicon_position_estimate_decode(&msg, &m);
  2535. handle_common_vision_position_estimate_data(m.usec, m.x, m.y, m.z, m.roll, m.pitch, m.yaw,
  2536. PAYLOAD_SIZE(chan, VICON_POSITION_ESTIMATE));
  2537. }
  2538. // there are several messages which all have identical fields in them.
  2539. // This function provides common handling for the data contained in
  2540. // these packets
  2541. void GCS_MAVLINK::handle_common_vision_position_estimate_data(const uint64_t usec,
  2542. const float x,
  2543. const float y,
  2544. const float z,
  2545. const float roll,
  2546. const float pitch,
  2547. const float yaw,
  2548. const uint16_t payload_size)
  2549. {
  2550. // correct offboard timestamp to be in local ms since boot
  2551. uint32_t timestamp_ms = correct_offboard_timestamp_usec_to_ms(usec, payload_size);
  2552. // sensor assumed to be at 0,0,0 body-frame; need parameters for this?
  2553. // or a new message
  2554. const Vector3f sensor_offset = {};
  2555. const Vector3f pos = {
  2556. x,
  2557. y,
  2558. z
  2559. };
  2560. Quaternion attitude;
  2561. attitude.from_euler(roll, pitch, yaw); // from_vector312?
  2562. const float posErr = 0; // parameter required?
  2563. const float angErr = 0; // parameter required?
  2564. const uint32_t reset_timestamp_ms = 0; // no data available
  2565. AP::ahrs().writeExtNavData(sensor_offset,
  2566. pos,
  2567. attitude,
  2568. posErr,
  2569. angErr,
  2570. timestamp_ms,
  2571. reset_timestamp_ms);
  2572. log_vision_position_estimate_data(usec, timestamp_ms, x, y, z, roll, pitch, yaw);
  2573. }
  2574. void GCS_MAVLINK::log_vision_position_estimate_data(const uint64_t usec,
  2575. const uint32_t corrected_msec,
  2576. const float x,
  2577. const float y,
  2578. const float z,
  2579. const float roll,
  2580. const float pitch,
  2581. const float yaw)
  2582. {
  2583. AP::logger().Write("VISP", "TimeUS,RemTimeUS,CTimeMS,PX,PY,PZ,Roll,Pitch,Yaw",
  2584. "sssmmmddh", "FFC000000", "QQIffffff",
  2585. (uint64_t)AP_HAL::micros64(),
  2586. (uint64_t)usec,
  2587. corrected_msec,
  2588. (double)x,
  2589. (double)y,
  2590. (double)z,
  2591. (double)(roll * RAD_TO_DEG),
  2592. (double)(pitch * RAD_TO_DEG),
  2593. (double)(yaw * RAD_TO_DEG));
  2594. }
  2595. void GCS_MAVLINK::handle_att_pos_mocap(const mavlink_message_t &msg)
  2596. {
  2597. mavlink_att_pos_mocap_t m;
  2598. mavlink_msg_att_pos_mocap_decode(&msg, &m);
  2599. // sensor assumed to be at 0,0,0 body-frame; need parameters for this?
  2600. const Vector3f sensor_offset = {};
  2601. const Vector3f pos = {
  2602. m.x,
  2603. m.y,
  2604. m.z
  2605. };
  2606. Quaternion attitude = Quaternion(m.q);
  2607. const float posErr = 0; // parameter required?
  2608. const float angErr = 0; // parameter required?
  2609. // correct offboard timestamp to be in local ms since boot
  2610. uint32_t timestamp_ms = correct_offboard_timestamp_usec_to_ms(m.time_usec, PAYLOAD_SIZE(chan, ATT_POS_MOCAP));
  2611. const uint32_t reset_timestamp_ms = 0; // no data available
  2612. AP::ahrs().writeExtNavData(sensor_offset,
  2613. pos,
  2614. attitude,
  2615. posErr,
  2616. angErr,
  2617. timestamp_ms,
  2618. reset_timestamp_ms);
  2619. // calculate euler orientation for logging
  2620. float roll;
  2621. float pitch;
  2622. float yaw;
  2623. attitude.to_euler(roll, pitch, yaw);
  2624. log_vision_position_estimate_data(m.time_usec, timestamp_ms, m.x, m.y, m.z, roll, pitch, yaw);
  2625. }
  2626. void GCS_MAVLINK::handle_command_ack(const mavlink_message_t &msg)
  2627. {
  2628. AP_AccelCal *accelcal = AP::ins().get_acal();
  2629. if (accelcal != nullptr) {
  2630. accelcal->handleMessage(msg);
  2631. }
  2632. }
  2633. // allow override of RC channel values for HIL or for complete GCS
  2634. // control of switch position and RC PWM values.
  2635. void GCS_MAVLINK::handle_rc_channels_override(const mavlink_message_t &msg)
  2636. {
  2637. if(msg.sysid != sysid_my_gcs()) {
  2638. return; // Only accept control from our gcs
  2639. }
  2640. const uint32_t tnow = AP_HAL::millis();
  2641. mavlink_rc_channels_override_t packet;
  2642. mavlink_msg_rc_channels_override_decode(&msg, &packet);
  2643. const uint16_t override_data[] = {
  2644. packet.chan1_raw,
  2645. packet.chan2_raw,
  2646. packet.chan3_raw,
  2647. packet.chan4_raw,
  2648. packet.chan5_raw,
  2649. packet.chan6_raw,
  2650. packet.chan7_raw,
  2651. packet.chan8_raw,
  2652. packet.chan9_raw,
  2653. packet.chan10_raw,
  2654. packet.chan11_raw,
  2655. packet.chan12_raw,
  2656. packet.chan13_raw,
  2657. packet.chan14_raw,
  2658. packet.chan15_raw,
  2659. packet.chan16_raw
  2660. };
  2661. for (uint8_t i=0; i<ARRAY_SIZE(override_data); i++) {
  2662. // Per MAVLink spec a value of UINT16_MAX means to ignore this field.
  2663. if (override_data[i] != UINT16_MAX) {
  2664. RC_Channels::set_override(i, override_data[i], tnow);
  2665. }
  2666. }
  2667. }
  2668. // allow override of RC channel values for HIL or for complete GCS
  2669. // control of switch position and RC PWM values.
  2670. void GCS_MAVLINK::handle_optical_flow(const mavlink_message_t &msg)
  2671. {
  2672. OpticalFlow *optflow = AP::opticalflow();
  2673. if (optflow == nullptr) {
  2674. return;
  2675. }
  2676. optflow->handle_msg(msg);
  2677. }
  2678. /*
  2679. handle messages which don't require vehicle specific data
  2680. */
  2681. void GCS_MAVLINK::handle_common_message(const mavlink_message_t &msg)
  2682. {
  2683. switch (msg.msgid) {
  2684. case MAVLINK_MSG_ID_COMMAND_ACK: {
  2685. handle_command_ack(msg);
  2686. break;
  2687. }
  2688. case MAVLINK_MSG_ID_SETUP_SIGNING:
  2689. handle_setup_signing(msg);
  2690. break;
  2691. case MAVLINK_MSG_ID_PARAM_REQUEST_LIST:
  2692. case MAVLINK_MSG_ID_PARAM_SET:
  2693. case MAVLINK_MSG_ID_PARAM_REQUEST_READ:
  2694. handle_common_param_message(msg);
  2695. break;
  2696. case MAVLINK_MSG_ID_SET_GPS_GLOBAL_ORIGIN:
  2697. handle_set_gps_global_origin(msg);
  2698. break;
  2699. case MAVLINK_MSG_ID_DEVICE_OP_READ:
  2700. handle_device_op_read(msg);
  2701. break;
  2702. case MAVLINK_MSG_ID_DEVICE_OP_WRITE:
  2703. handle_device_op_write(msg);
  2704. break;
  2705. case MAVLINK_MSG_ID_TIMESYNC:
  2706. handle_timesync(msg);
  2707. break;
  2708. case MAVLINK_MSG_ID_LOG_REQUEST_LIST:
  2709. case MAVLINK_MSG_ID_LOG_REQUEST_DATA:
  2710. case MAVLINK_MSG_ID_LOG_ERASE:
  2711. case MAVLINK_MSG_ID_LOG_REQUEST_END:
  2712. case MAVLINK_MSG_ID_REMOTE_LOG_BLOCK_STATUS:
  2713. AP::logger().handle_mavlink_msg(*this, msg);
  2714. break;
  2715. case MAVLINK_MSG_ID_DIGICAM_CONTROL:
  2716. {
  2717. AP_Camera *camera = AP::camera();
  2718. if (camera == nullptr) {
  2719. return;
  2720. }
  2721. camera->control_msg(msg);
  2722. }
  2723. break;
  2724. case MAVLINK_MSG_ID_SET_MODE:
  2725. handle_set_mode(msg);
  2726. break;
  2727. case MAVLINK_MSG_ID_AUTOPILOT_VERSION_REQUEST:
  2728. handle_send_autopilot_version(msg);
  2729. break;
  2730. case MAVLINK_MSG_ID_MISSION_WRITE_PARTIAL_LIST:
  2731. case MAVLINK_MSG_ID_MISSION_REQUEST_LIST:
  2732. case MAVLINK_MSG_ID_MISSION_COUNT:
  2733. case MAVLINK_MSG_ID_MISSION_CLEAR_ALL:
  2734. case MAVLINK_MSG_ID_MISSION_ITEM:
  2735. case MAVLINK_MSG_ID_MISSION_ITEM_INT:
  2736. case MAVLINK_MSG_ID_MISSION_REQUEST_INT:
  2737. case MAVLINK_MSG_ID_MISSION_REQUEST:
  2738. case MAVLINK_MSG_ID_MISSION_ACK:
  2739. case MAVLINK_MSG_ID_MISSION_SET_CURRENT:
  2740. handle_common_mission_message(msg);
  2741. break;
  2742. case MAVLINK_MSG_ID_COMMAND_LONG:
  2743. handle_command_long(msg);
  2744. break;
  2745. case MAVLINK_MSG_ID_COMMAND_INT:
  2746. handle_command_int(msg);
  2747. break;
  2748. case MAVLINK_MSG_ID_FENCE_POINT:
  2749. case MAVLINK_MSG_ID_FENCE_FETCH_POINT:
  2750. handle_fence_message(msg);
  2751. break;
  2752. case MAVLINK_MSG_ID_GIMBAL_REPORT:
  2753. handle_mount_message(msg);
  2754. break;
  2755. case MAVLINK_MSG_ID_PARAM_VALUE:
  2756. handle_param_value(msg);
  2757. break;
  2758. case MAVLINK_MSG_ID_SERIAL_CONTROL:
  2759. handle_serial_control(msg);
  2760. break;
  2761. case MAVLINK_MSG_ID_GPS_RTCM_DATA:
  2762. case MAVLINK_MSG_ID_GPS_INPUT:
  2763. case MAVLINK_MSG_ID_HIL_GPS:
  2764. case MAVLINK_MSG_ID_GPS_INJECT_DATA:
  2765. AP::gps().handle_msg(msg);
  2766. break;
  2767. case MAVLINK_MSG_ID_STATUSTEXT:
  2768. handle_statustext(msg);
  2769. break;
  2770. case MAVLINK_MSG_ID_LED_CONTROL:
  2771. // send message to Notify
  2772. AP_Notify::handle_led_control(msg);
  2773. break;
  2774. case MAVLINK_MSG_ID_MOUNT_CONFIGURE: // deprecated. Use MAV_CMD_DO_MOUNT_CONFIGURE
  2775. case MAVLINK_MSG_ID_MOUNT_CONTROL: // deprecated. Use MAV_CMD_DO_MOUNT_CONTROL
  2776. handle_mount_message(msg);
  2777. break;
  2778. case MAVLINK_MSG_ID_PLAY_TUNE:
  2779. // send message to Notify
  2780. AP_Notify::handle_play_tune(msg);
  2781. break;
  2782. case MAVLINK_MSG_ID_RALLY_POINT:
  2783. case MAVLINK_MSG_ID_RALLY_FETCH_POINT:
  2784. handle_common_rally_message(msg);
  2785. break;
  2786. case MAVLINK_MSG_ID_REQUEST_DATA_STREAM:
  2787. handle_request_data_stream(msg);
  2788. break;
  2789. case MAVLINK_MSG_ID_DATA96:
  2790. handle_data_packet(msg);
  2791. break;
  2792. case MAVLINK_MSG_ID_VISION_POSITION_DELTA:
  2793. handle_vision_position_delta(msg);
  2794. break;
  2795. case MAVLINK_MSG_ID_VISION_POSITION_ESTIMATE:
  2796. handle_vision_position_estimate(msg);
  2797. break;
  2798. case MAVLINK_MSG_ID_GLOBAL_VISION_POSITION_ESTIMATE:
  2799. handle_global_vision_position_estimate(msg);
  2800. break;
  2801. case MAVLINK_MSG_ID_VICON_POSITION_ESTIMATE:
  2802. handle_vicon_position_estimate(msg);
  2803. break;
  2804. case MAVLINK_MSG_ID_ATT_POS_MOCAP:
  2805. handle_att_pos_mocap(msg);
  2806. break;
  2807. case MAVLINK_MSG_ID_SYSTEM_TIME:
  2808. handle_system_time_message(msg);
  2809. break;
  2810. case MAVLINK_MSG_ID_RC_CHANNELS_OVERRIDE:
  2811. handle_rc_channels_override(msg);
  2812. break;
  2813. case MAVLINK_MSG_ID_OPTICAL_FLOW:
  2814. handle_optical_flow(msg);
  2815. break;
  2816. }
  2817. }
  2818. void GCS_MAVLINK::handle_common_mission_message(const mavlink_message_t &msg)
  2819. {
  2820. AP_Mission *_mission = AP::mission();
  2821. if (_mission == nullptr) {
  2822. return;
  2823. }
  2824. switch (msg.msgid) {
  2825. case MAVLINK_MSG_ID_MISSION_WRITE_PARTIAL_LIST: // MAV ID: 38
  2826. {
  2827. handle_mission_write_partial_list(msg);
  2828. break;
  2829. }
  2830. // GCS has sent us a mission item, store to EEPROM
  2831. case MAVLINK_MSG_ID_MISSION_ITEM: // MAV ID: 39
  2832. case MAVLINK_MSG_ID_MISSION_ITEM_INT:
  2833. handle_mission_item(msg);
  2834. break;
  2835. // read an individual command from EEPROM and send it to the GCS
  2836. case MAVLINK_MSG_ID_MISSION_REQUEST_INT:
  2837. handle_mission_request_int(msg);
  2838. break;
  2839. case MAVLINK_MSG_ID_MISSION_REQUEST:
  2840. handle_mission_request(msg);
  2841. break;
  2842. case MAVLINK_MSG_ID_MISSION_SET_CURRENT: // MAV ID: 41
  2843. {
  2844. handle_mission_set_current(*_mission, msg);
  2845. break;
  2846. }
  2847. // GCS request the full list of commands, we return just the number and leave the GCS to then request each command individually
  2848. case MAVLINK_MSG_ID_MISSION_REQUEST_LIST: // MAV ID: 43
  2849. {
  2850. handle_mission_request_list(msg);
  2851. break;
  2852. }
  2853. // GCS provides the full number of commands it wishes to upload
  2854. // individual commands will then be sent from the GCS using the MAVLINK_MSG_ID_MISSION_ITEM message
  2855. case MAVLINK_MSG_ID_MISSION_COUNT: // MAV ID: 44
  2856. {
  2857. handle_mission_count(msg);
  2858. break;
  2859. }
  2860. case MAVLINK_MSG_ID_MISSION_CLEAR_ALL: // MAV ID: 45
  2861. {
  2862. handle_mission_clear_all(msg);
  2863. break;
  2864. }
  2865. case MAVLINK_MSG_ID_MISSION_ACK:
  2866. /* not used */
  2867. break;
  2868. }
  2869. }
  2870. void GCS_MAVLINK::handle_send_autopilot_version(const mavlink_message_t &msg)
  2871. {
  2872. send_message(MSG_AUTOPILOT_VERSION);
  2873. }
  2874. void GCS_MAVLINK::send_banner()
  2875. {
  2876. // mark the firmware version in the tlog
  2877. const AP_FWVersion &fwver = AP::fwversion();
  2878. send_text(MAV_SEVERITY_INFO, "%s", fwver.fw_string);
  2879. if (fwver.middleware_name && fwver.os_name) {
  2880. send_text(MAV_SEVERITY_INFO, "%s: %s %s: %s",
  2881. fwver.middleware_name, fwver.middleware_hash_str,
  2882. fwver.os_name, fwver.os_hash_str);
  2883. } else if (fwver.os_name) {
  2884. send_text(MAV_SEVERITY_INFO, "%s: %s",
  2885. fwver.os_name, fwver.os_hash_str);
  2886. }
  2887. // send system ID if we can
  2888. char sysid[40];
  2889. if (hal.util->get_system_id(sysid)) {
  2890. send_text(MAV_SEVERITY_INFO, "%s", sysid);
  2891. }
  2892. }
  2893. void GCS_MAVLINK::send_simstate() const
  2894. {
  2895. #if CONFIG_HAL_BOARD == HAL_BOARD_SITL
  2896. SITL::SITL *sitl = AP::sitl();
  2897. if (sitl == nullptr) {
  2898. return;
  2899. }
  2900. sitl->simstate_send(get_chan());
  2901. #endif
  2902. }
  2903. MAV_RESULT GCS_MAVLINK::handle_command_flash_bootloader(const mavlink_command_long_t &packet)
  2904. {
  2905. if (uint32_t(packet.param5) != 290876) {
  2906. gcs().send_text(MAV_SEVERITY_INFO, "Magic not set");
  2907. return MAV_RESULT_FAILED;
  2908. }
  2909. if (!hal.util->flash_bootloader()) {
  2910. return MAV_RESULT_FAILED;
  2911. }
  2912. return MAV_RESULT_ACCEPTED;
  2913. }
  2914. MAV_RESULT GCS_MAVLINK::handle_command_preflight_set_sensor_offsets(const mavlink_command_long_t &packet)
  2915. {
  2916. Compass &compass = AP::compass();
  2917. uint8_t compassNumber = -1;
  2918. if (is_equal(packet.param1, 2.0f)) {
  2919. compassNumber = 0;
  2920. } else if (is_equal(packet.param1, 5.0f)) {
  2921. compassNumber = 1;
  2922. } else if (is_equal(packet.param1, 6.0f)) {
  2923. compassNumber = 2;
  2924. }
  2925. if (compassNumber == (uint8_t) -1) {
  2926. return MAV_RESULT_FAILED;
  2927. }
  2928. compass.set_and_save_offsets(compassNumber, Vector3f(packet.param2, packet.param3, packet.param4));
  2929. return MAV_RESULT_ACCEPTED;
  2930. }
  2931. bool GCS_MAVLINK::calibrate_gyros()
  2932. {
  2933. AP::ins().init_gyro();
  2934. if (!AP::ins().gyro_calibrated_ok_all()) {
  2935. return false;
  2936. }
  2937. AP::ahrs().reset_gyro_drift();
  2938. return true;
  2939. }
  2940. MAV_RESULT GCS_MAVLINK::_handle_command_preflight_calibration_baro()
  2941. {
  2942. // fast barometer calibration
  2943. gcs().send_text(MAV_SEVERITY_INFO, "Updating barometer calibration");
  2944. AP::baro().update_calibration();
  2945. gcs().send_text(MAV_SEVERITY_INFO, "Barometer calibration complete");
  2946. AP_Airspeed *airspeed = AP_Airspeed::get_singleton();
  2947. if (airspeed != nullptr) {
  2948. airspeed->calibrate(false);
  2949. }
  2950. return MAV_RESULT_ACCEPTED;
  2951. }
  2952. MAV_RESULT GCS_MAVLINK::_handle_command_preflight_calibration(const mavlink_command_long_t &packet)
  2953. {
  2954. EXPECT_DELAY_MS(30000);
  2955. if (is_equal(packet.param1,1.0f)) {
  2956. if (!calibrate_gyros()) {
  2957. return MAV_RESULT_FAILED;
  2958. }
  2959. return MAV_RESULT_ACCEPTED;
  2960. }
  2961. if (is_equal(packet.param3,1.0f)) {
  2962. return _handle_command_preflight_calibration_baro();
  2963. }
  2964. if (is_equal(packet.param5,1.0f)) {
  2965. // start with gyro calibration
  2966. if (!calibrate_gyros()) {
  2967. return MAV_RESULT_FAILED;
  2968. }
  2969. // start accel cal
  2970. AP::ins().acal_init();
  2971. AP::ins().get_acal()->start(this);
  2972. return MAV_RESULT_ACCEPTED;
  2973. }
  2974. if (is_equal(packet.param5,2.0f)) {
  2975. if (!calibrate_gyros()) {
  2976. return MAV_RESULT_FAILED;
  2977. }
  2978. float trim_roll, trim_pitch;
  2979. if (!AP::ins().calibrate_trim(trim_roll, trim_pitch)) {
  2980. return MAV_RESULT_FAILED;
  2981. }
  2982. // reset ahrs's trim to suggested values from calibration routine
  2983. AP::ahrs().set_trim(Vector3f(trim_roll, trim_pitch, 0));
  2984. return MAV_RESULT_ACCEPTED;
  2985. }
  2986. if (is_equal(packet.param5,4.0f)) {
  2987. // simple accel calibration
  2988. return AP::ins().simple_accel_cal();
  2989. }
  2990. return MAV_RESULT_UNSUPPORTED;
  2991. }
  2992. MAV_RESULT GCS_MAVLINK::handle_command_preflight_calibration(const mavlink_command_long_t &packet)
  2993. {
  2994. if (hal.util->get_soft_armed()) {
  2995. // *preflight*, remember?
  2996. return MAV_RESULT_FAILED;
  2997. }
  2998. // now call subclass methods:
  2999. return _handle_command_preflight_calibration(packet);
  3000. }
  3001. MAV_RESULT GCS_MAVLINK::handle_command_preflight_can(const mavlink_command_long_t &packet)
  3002. {
  3003. #if HAL_WITH_UAVCAN
  3004. if (hal.util->get_soft_armed()) {
  3005. // *preflight*, remember?
  3006. return MAV_RESULT_TEMPORARILY_REJECTED;
  3007. }
  3008. bool start_stop = is_equal(packet.param1,1.0f) ? true : false;
  3009. bool result = true;
  3010. bool can_exists = false;
  3011. uint8_t num_drivers = AP::can().get_num_drivers();
  3012. for (uint8_t i = 0; i < num_drivers; i++) {
  3013. switch (AP::can().get_protocol_type(i)) {
  3014. case AP_BoardConfig_CAN::Protocol_Type_KDECAN: {
  3015. // To be replaced with macro saying if KDECAN library is included
  3016. #if APM_BUILD_TYPE(APM_BUILD_ArduCopter) || APM_BUILD_TYPE(APM_BUILD_ArduPlane) || APM_BUILD_TYPE(APM_BUILD_ArduSub)
  3017. AP_KDECAN *ap_kdecan = AP_KDECAN::get_kdecan(i);
  3018. if (ap_kdecan != nullptr) {
  3019. can_exists = true;
  3020. result = ap_kdecan->run_enumeration(start_stop) && result;
  3021. }
  3022. break;
  3023. #else
  3024. UNUSED_RESULT(start_stop); // prevent unused variable error
  3025. #endif
  3026. }
  3027. case AP_BoardConfig_CAN::Protocol_Type_UAVCAN:
  3028. case AP_BoardConfig_CAN::Protocol_Type_None:
  3029. default:
  3030. break;
  3031. }
  3032. }
  3033. MAV_RESULT ack = MAV_RESULT_DENIED;
  3034. if (can_exists) {
  3035. ack = result ? MAV_RESULT_ACCEPTED : MAV_RESULT_FAILED;
  3036. }
  3037. return ack;
  3038. #else
  3039. return MAV_RESULT_UNSUPPORTED;
  3040. #endif
  3041. }
  3042. MAV_RESULT GCS_MAVLINK::handle_command_battery_reset(const mavlink_command_long_t &packet)
  3043. {
  3044. const uint16_t battery_mask = packet.param1;
  3045. const float percentage = packet.param2;
  3046. if (AP::battery().reset_remaining(battery_mask, percentage)) {
  3047. return MAV_RESULT_ACCEPTED;
  3048. }
  3049. return MAV_RESULT_FAILED;
  3050. }
  3051. MAV_RESULT GCS_MAVLINK::handle_command_mag_cal(const mavlink_command_long_t &packet)
  3052. {
  3053. return AP::compass().handle_mag_cal_command(packet);
  3054. }
  3055. MAV_RESULT GCS_MAVLINK::handle_command_request_autopilot_capabilities(const mavlink_command_long_t &packet)
  3056. {
  3057. if (!is_equal(packet.param1,1.0f)) {
  3058. return MAV_RESULT_FAILED;
  3059. }
  3060. send_message(MSG_AUTOPILOT_VERSION);
  3061. return MAV_RESULT_ACCEPTED;
  3062. }
  3063. MAV_RESULT GCS_MAVLINK::handle_command_do_send_banner(const mavlink_command_long_t &packet)
  3064. {
  3065. send_banner();
  3066. return MAV_RESULT_ACCEPTED;
  3067. }
  3068. MAV_RESULT GCS_MAVLINK::handle_command_do_set_mode(const mavlink_command_long_t &packet)
  3069. {
  3070. const MAV_MODE _base_mode = (MAV_MODE)packet.param1;
  3071. const uint32_t _custom_mode = (uint32_t)packet.param2;
  3072. return _set_mode_common(_base_mode, _custom_mode);
  3073. }
  3074. MAV_RESULT GCS_MAVLINK::handle_command_get_home_position(const mavlink_command_long_t &packet)
  3075. {
  3076. if (!AP::ahrs().home_is_set()) {
  3077. return MAV_RESULT_FAILED;
  3078. }
  3079. if (!try_send_message(MSG_HOME)) {
  3080. // try again later
  3081. send_message(MSG_HOME);
  3082. }
  3083. if (!try_send_message(MSG_ORIGIN)) {
  3084. // try again later
  3085. send_message(MSG_ORIGIN);
  3086. }
  3087. return MAV_RESULT_ACCEPTED;
  3088. }
  3089. MAV_RESULT GCS_MAVLINK::handle_command_do_gripper(const mavlink_command_long_t &packet)
  3090. {
  3091. AP_Gripper *gripper = AP::gripper();
  3092. if (gripper == nullptr) {
  3093. return MAV_RESULT_FAILED;
  3094. }
  3095. // param1 : gripper number (ignored)
  3096. // param2 : action (0=release, 1=grab). See GRIPPER_ACTIONS enum.
  3097. if(!gripper->enabled()) {
  3098. return MAV_RESULT_FAILED;
  3099. }
  3100. MAV_RESULT result = MAV_RESULT_ACCEPTED;
  3101. switch ((uint8_t)packet.param2) {
  3102. case GRIPPER_ACTION_RELEASE:
  3103. gripper->release();
  3104. break;
  3105. case GRIPPER_ACTION_GRAB:
  3106. gripper->grab();
  3107. break;
  3108. default:
  3109. result = MAV_RESULT_FAILED;
  3110. break;
  3111. }
  3112. return result;
  3113. }
  3114. MAV_RESULT GCS_MAVLINK::handle_command_accelcal_vehicle_pos(const mavlink_command_long_t &packet)
  3115. {
  3116. if (!AP::ins().get_acal()->gcs_vehicle_position(packet.param1)) {
  3117. return MAV_RESULT_FAILED;
  3118. }
  3119. return MAV_RESULT_ACCEPTED;
  3120. }
  3121. MAV_RESULT GCS_MAVLINK::handle_command_mount(const mavlink_command_long_t &packet)
  3122. {
  3123. AP_Mount *mount = AP::mount();
  3124. if (mount == nullptr) {
  3125. return MAV_RESULT_UNSUPPORTED;
  3126. }
  3127. return mount->handle_command_long(packet);
  3128. }
  3129. MAV_RESULT GCS_MAVLINK::handle_command_do_set_home(const mavlink_command_long_t &packet)
  3130. {
  3131. if (is_equal(packet.param1, 1.0f) || (is_zero(packet.param5) && is_zero(packet.param6))) {
  3132. // param1 is 1 (or both lat and lon are zero); use current location
  3133. if (!set_home_to_current_location(true)) {
  3134. return MAV_RESULT_FAILED;
  3135. }
  3136. return MAV_RESULT_ACCEPTED;
  3137. }
  3138. // ensure param1 is zero
  3139. if (!is_zero(packet.param1)) {
  3140. return MAV_RESULT_FAILED;
  3141. }
  3142. Location new_home_loc;
  3143. new_home_loc.lat = (int32_t)(packet.param5 * 1.0e7f);
  3144. new_home_loc.lng = (int32_t)(packet.param6 * 1.0e7f);
  3145. new_home_loc.alt = (int32_t)(packet.param7 * 100.0f);
  3146. if (!set_home(new_home_loc, true)) {
  3147. return MAV_RESULT_FAILED;
  3148. }
  3149. return MAV_RESULT_ACCEPTED;
  3150. }
  3151. MAV_RESULT GCS_MAVLINK::handle_command_long_packet(const mavlink_command_long_t &packet)
  3152. {
  3153. MAV_RESULT result = MAV_RESULT_FAILED;
  3154. switch (packet.command) {
  3155. case MAV_CMD_ACCELCAL_VEHICLE_POS:
  3156. result = handle_command_accelcal_vehicle_pos(packet);
  3157. break;
  3158. case MAV_CMD_DO_SET_MODE:
  3159. result = handle_command_do_set_mode(packet);
  3160. break;
  3161. case MAV_CMD_DO_SEND_BANNER:
  3162. result = handle_command_do_send_banner(packet);
  3163. break;
  3164. case MAV_CMD_DO_SET_HOME:
  3165. result = handle_command_do_set_home(packet);
  3166. break;
  3167. case MAV_CMD_DO_FENCE_ENABLE:
  3168. result = handle_command_do_fence_enable(packet);
  3169. break;
  3170. case MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN:
  3171. result = handle_preflight_reboot(packet);
  3172. break;
  3173. case MAV_CMD_DO_START_MAG_CAL:
  3174. case MAV_CMD_DO_ACCEPT_MAG_CAL:
  3175. case MAV_CMD_DO_CANCEL_MAG_CAL: {
  3176. result = handle_command_mag_cal(packet);
  3177. break;
  3178. }
  3179. case MAV_CMD_START_RX_PAIR:
  3180. result = handle_rc_bind(packet);
  3181. break;
  3182. case MAV_CMD_DO_DIGICAM_CONFIGURE:
  3183. case MAV_CMD_DO_DIGICAM_CONTROL:
  3184. case MAV_CMD_DO_SET_CAM_TRIGG_DIST:
  3185. result = handle_command_camera(packet);
  3186. break;
  3187. case MAV_CMD_DO_GRIPPER:
  3188. result = handle_command_do_gripper(packet);
  3189. break;
  3190. case MAV_CMD_DO_MOUNT_CONFIGURE:
  3191. case MAV_CMD_DO_MOUNT_CONTROL:
  3192. result = handle_command_mount(packet);
  3193. break;
  3194. case MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES: {
  3195. result = handle_command_request_autopilot_capabilities(packet);
  3196. break;
  3197. }
  3198. case MAV_CMD_DO_SET_ROI_LOCATION:
  3199. case MAV_CMD_DO_SET_ROI:
  3200. result = handle_command_do_set_roi(packet);
  3201. break;
  3202. case MAV_CMD_PREFLIGHT_CALIBRATION:
  3203. result = handle_command_preflight_calibration(packet);
  3204. break;
  3205. case MAV_CMD_BATTERY_RESET:
  3206. result = handle_command_battery_reset(packet);
  3207. break;
  3208. case MAV_CMD_PREFLIGHT_UAVCAN:
  3209. result = handle_command_preflight_can(packet);
  3210. break;
  3211. case MAV_CMD_FLASH_BOOTLOADER:
  3212. result = handle_command_flash_bootloader(packet);
  3213. break;
  3214. case MAV_CMD_PREFLIGHT_SET_SENSOR_OFFSETS: {
  3215. result = handle_command_preflight_set_sensor_offsets(packet);
  3216. break;
  3217. }
  3218. case MAV_CMD_GET_HOME_POSITION:
  3219. result = handle_command_get_home_position(packet);
  3220. break;
  3221. case MAV_CMD_PREFLIGHT_STORAGE:
  3222. if (is_equal(packet.param1, 2.0f)) {
  3223. AP_Param::erase_all();
  3224. send_text(MAV_SEVERITY_WARNING, "All parameters reset, reboot board");
  3225. result= MAV_RESULT_ACCEPTED;
  3226. }
  3227. break;
  3228. case MAV_CMD_SET_MESSAGE_INTERVAL:
  3229. result = handle_command_set_message_interval(packet);
  3230. break;
  3231. case MAV_CMD_GET_MESSAGE_INTERVAL:
  3232. result = handle_command_get_message_interval(packet);
  3233. break;
  3234. case MAV_CMD_REQUEST_MESSAGE:
  3235. result = handle_command_request_message(packet);
  3236. break;
  3237. case MAV_CMD_DO_SET_SERVO:
  3238. case MAV_CMD_DO_REPEAT_SERVO:
  3239. case MAV_CMD_DO_SET_RELAY:
  3240. case MAV_CMD_DO_REPEAT_RELAY:
  3241. result = handle_servorelay_message(packet);
  3242. break;
  3243. case MAV_CMD_DO_FLIGHTTERMINATION:
  3244. result = handle_flight_termination(packet);
  3245. break;
  3246. case MAV_CMD_COMPONENT_ARM_DISARM:
  3247. if (is_equal(packet.param1,1.0f)) {
  3248. // run pre_arm_checks and arm_checks and display failures
  3249. const bool do_arming_checks = !is_equal(packet.param2,magic_force_arm_value);
  3250. if (AP::arming().is_armed() ||
  3251. AP::arming().arm(AP_Arming::Method::MAVLINK, do_arming_checks)) {
  3252. return MAV_RESULT_ACCEPTED;
  3253. }
  3254. return MAV_RESULT_FAILED;
  3255. }
  3256. if (is_zero(packet.param1)) {
  3257. if (!AP::arming().is_armed()) {
  3258. return MAV_RESULT_ACCEPTED;
  3259. }
  3260. // allow vehicle to disallow disarm. Copter does this if
  3261. // the vehicle isn't considered landed.
  3262. if (!allow_disarm() &&
  3263. !is_equal(packet.param2, magic_force_disarm_value)) {
  3264. return MAV_RESULT_FAILED;
  3265. }
  3266. if (AP::arming().disarm()) {
  3267. return MAV_RESULT_ACCEPTED;
  3268. }
  3269. return MAV_RESULT_FAILED;
  3270. }
  3271. return MAV_RESULT_UNSUPPORTED;
  3272. default:
  3273. result = MAV_RESULT_UNSUPPORTED;
  3274. break;
  3275. }
  3276. return result;
  3277. }
  3278. bool GCS_MAVLINK::command_long_stores_location(const MAV_CMD command)
  3279. {
  3280. switch(command) {
  3281. case MAV_CMD_DO_SET_HOME:
  3282. case MAV_CMD_DO_SET_ROI:
  3283. case MAV_CMD_NAV_TAKEOFF:
  3284. return true;
  3285. default:
  3286. return false;
  3287. }
  3288. return false;
  3289. }
  3290. void GCS_MAVLINK::convert_COMMAND_LONG_to_COMMAND_INT(const mavlink_command_long_t &in, mavlink_command_int_t &out)
  3291. {
  3292. out.target_system = in.target_system;
  3293. out.target_component = in.target_component;
  3294. out.frame = MAV_FRAME_GLOBAL_RELATIVE_ALT; // FIXME?
  3295. out.command = in.command;
  3296. out.current = 0;
  3297. out.autocontinue = 0;
  3298. out.param1 = in.param1;
  3299. out.param2 = in.param2;
  3300. out.param3 = in.param3;
  3301. out.param4 = in.param4;
  3302. if (command_long_stores_location((MAV_CMD)in.command)) {
  3303. out.x = in.param5 *1e7;
  3304. out.y = in.param6 *1e7;
  3305. } else {
  3306. out.x = in.param5;
  3307. out.y = in.param6;
  3308. }
  3309. out.z = in.param7;
  3310. }
  3311. void GCS_MAVLINK::handle_command_long(const mavlink_message_t &msg)
  3312. {
  3313. // decode packet
  3314. mavlink_command_long_t packet;
  3315. mavlink_msg_command_long_decode(&msg, &packet);
  3316. hal.util->persistent_data.last_mavlink_cmd = packet.command;
  3317. const MAV_RESULT result = handle_command_long_packet(packet);
  3318. // send ACK or NAK
  3319. mavlink_msg_command_ack_send(chan, packet.command, result);
  3320. // log the packet:
  3321. mavlink_command_int_t packet_int;
  3322. convert_COMMAND_LONG_to_COMMAND_INT(packet, packet_int);
  3323. AP::logger().Write_Command(packet_int, result, true);
  3324. hal.util->persistent_data.last_mavlink_cmd = 0;
  3325. }
  3326. MAV_RESULT GCS_MAVLINK::handle_command_do_set_roi(const Location &roi_loc)
  3327. {
  3328. AP_Mount *mount = AP::mount();
  3329. if (mount == nullptr) {
  3330. return MAV_RESULT_UNSUPPORTED;
  3331. }
  3332. // sanity check location
  3333. if (!roi_loc.check_latlng()) {
  3334. return MAV_RESULT_FAILED;
  3335. }
  3336. if (roi_loc.lat == 0 && roi_loc.lng == 0 && roi_loc.alt == 0) {
  3337. // switch off the camera tracking if enabled
  3338. if (mount->get_mode() == MAV_MOUNT_MODE_GPS_POINT) {
  3339. mount->set_mode_to_default();
  3340. }
  3341. } else {
  3342. // send the command to the camera mount
  3343. mount->set_roi_target(roi_loc);
  3344. }
  3345. return MAV_RESULT_ACCEPTED;
  3346. }
  3347. MAV_RESULT GCS_MAVLINK::handle_command_int_do_set_home(const mavlink_command_int_t &packet)
  3348. {
  3349. if (is_equal(packet.param1, 1.0f) || (packet.x == 0 && packet.y == 0)) {
  3350. // param1 is 1 (or both lat and lon are zero); use current location
  3351. if (!set_home_to_current_location(true)) {
  3352. return MAV_RESULT_FAILED;
  3353. }
  3354. return MAV_RESULT_ACCEPTED;
  3355. }
  3356. // ensure param1 is zero
  3357. if (!is_zero(packet.param1)) {
  3358. return MAV_RESULT_FAILED;
  3359. }
  3360. Location::AltFrame frame;
  3361. if (!mavlink_coordinate_frame_to_location_alt_frame((MAV_FRAME)packet.frame, frame)) {
  3362. // unknown coordinate frame
  3363. return MAV_RESULT_UNSUPPORTED;
  3364. }
  3365. const Location new_home_loc{
  3366. packet.x,
  3367. packet.y,
  3368. int32_t(packet.z * 100),
  3369. frame,
  3370. };
  3371. if (!set_home(new_home_loc, true)) {
  3372. return MAV_RESULT_FAILED;
  3373. }
  3374. return MAV_RESULT_ACCEPTED;
  3375. }
  3376. MAV_RESULT GCS_MAVLINK::handle_command_do_set_roi(const mavlink_command_int_t &packet)
  3377. {
  3378. // be aware that this method is called for both MAV_CMD_DO_SET_ROI
  3379. // and MAV_CMD_DO_SET_ROI_LOCATION. If you intend to support any
  3380. // of the extra fields in the former then you will need to split
  3381. // off support for MAV_CMD_DO_SET_ROI_LOCATION (which doesn't
  3382. // support the extra fields).
  3383. // param1 : /* Region of interest mode (not used)*/
  3384. // param2 : /* MISSION index/ target ID (not used)*/
  3385. // param3 : /* ROI index (not used)*/
  3386. // param4 : /* empty */
  3387. // x : lat
  3388. // y : lon
  3389. // z : alt
  3390. Location roi_loc;
  3391. roi_loc.lat = packet.x;
  3392. roi_loc.lng = packet.y;
  3393. roi_loc.alt = (int32_t)(packet.z * 100.0f);
  3394. return handle_command_do_set_roi(roi_loc);
  3395. }
  3396. MAV_RESULT GCS_MAVLINK::handle_command_do_set_roi(const mavlink_command_long_t &packet)
  3397. {
  3398. // be aware that this method is called for both MAV_CMD_DO_SET_ROI
  3399. // and MAV_CMD_DO_SET_ROI_LOCATION. If you intend to support any
  3400. // of the extra fields in the former then you will need to split
  3401. // off support for MAV_CMD_DO_SET_ROI_LOCATION (which doesn't
  3402. // support the extra fields).
  3403. Location roi_loc;
  3404. roi_loc.lat = (int32_t)(packet.param5 * 1.0e7f);
  3405. roi_loc.lng = (int32_t)(packet.param6 * 1.0e7f);
  3406. roi_loc.alt = (int32_t)(packet.param7 * 100.0f);
  3407. return handle_command_do_set_roi(roi_loc);
  3408. }
  3409. MAV_RESULT GCS_MAVLINK::handle_command_int_packet(const mavlink_command_int_t &packet)
  3410. {
  3411. switch (packet.command) {
  3412. case MAV_CMD_DO_SET_ROI:
  3413. case MAV_CMD_DO_SET_ROI_LOCATION:
  3414. return handle_command_do_set_roi(packet);
  3415. case MAV_CMD_DO_SET_HOME:
  3416. return handle_command_int_do_set_home(packet);
  3417. default:
  3418. break;
  3419. }
  3420. return MAV_RESULT_UNSUPPORTED;
  3421. }
  3422. void GCS_MAVLINK::handle_command_int(const mavlink_message_t &msg)
  3423. {
  3424. // decode packet
  3425. mavlink_command_int_t packet;
  3426. mavlink_msg_command_int_decode(&msg, &packet);
  3427. hal.util->persistent_data.last_mavlink_cmd = packet.command;
  3428. const MAV_RESULT result = handle_command_int_packet(packet);
  3429. // send ACK or NAK
  3430. mavlink_msg_command_ack_send(chan, packet.command, result);
  3431. AP::logger().Write_Command(packet, result);
  3432. hal.util->persistent_data.last_mavlink_cmd = 0;
  3433. }
  3434. void GCS::try_send_queued_message_for_type(MAV_MISSION_TYPE type) {
  3435. MissionItemProtocol *prot = get_prot_for_mission_type(type);
  3436. if (prot == nullptr) {
  3437. return;
  3438. }
  3439. prot->queued_request_send();
  3440. }
  3441. bool GCS_MAVLINK::try_send_mission_message(const enum ap_message id)
  3442. {
  3443. AP_Mission *mission = AP::mission();
  3444. if (mission == nullptr) {
  3445. return true;
  3446. }
  3447. bool ret = true;
  3448. switch (id) {
  3449. case MSG_CURRENT_WAYPOINT:
  3450. CHECK_PAYLOAD_SIZE(MISSION_CURRENT);
  3451. mavlink_msg_mission_current_send(chan, mission->get_current_nav_index());
  3452. ret = true;
  3453. break;
  3454. case MSG_MISSION_ITEM_REACHED:
  3455. CHECK_PAYLOAD_SIZE(MISSION_ITEM_REACHED);
  3456. mavlink_msg_mission_item_reached_send(chan, mission_item_reached_index);
  3457. ret = true;
  3458. break;
  3459. case MSG_NEXT_MISSION_REQUEST_WAYPOINTS:
  3460. CHECK_PAYLOAD_SIZE(MISSION_REQUEST);
  3461. gcs().try_send_queued_message_for_type(MAV_MISSION_TYPE_MISSION);
  3462. ret = true;
  3463. break;
  3464. case MSG_NEXT_MISSION_REQUEST_RALLY:
  3465. CHECK_PAYLOAD_SIZE(MISSION_REQUEST);
  3466. gcs().try_send_queued_message_for_type(MAV_MISSION_TYPE_RALLY);
  3467. ret = true;
  3468. break;
  3469. default:
  3470. ret = true;
  3471. break;
  3472. }
  3473. return ret;
  3474. }
  3475. void GCS_MAVLINK::send_hwstatus()
  3476. {
  3477. mavlink_msg_hwstatus_send(
  3478. chan,
  3479. hal.analogin->board_voltage()*1000,
  3480. 0);
  3481. }
  3482. void GCS_MAVLINK::send_rpm() const
  3483. {
  3484. AP_RPM *rpm = AP::rpm();
  3485. if (rpm == nullptr) {
  3486. return;
  3487. }
  3488. if (!rpm->enabled(0) && !rpm->enabled(1)) {
  3489. return;
  3490. }
  3491. mavlink_msg_rpm_send(
  3492. chan,
  3493. rpm->get_rpm(0),
  3494. rpm->get_rpm(1));
  3495. }
  3496. void GCS_MAVLINK::send_sys_status()
  3497. {
  3498. // send extended status only once vehicle has been initialised
  3499. // to avoid unnecessary errors being reported to user
  3500. if (!gcs().vehicle_initialised()) {
  3501. return;
  3502. }
  3503. const AP_BattMonitor &battery = AP::battery();
  3504. float battery_current;
  3505. int8_t battery_remaining;
  3506. if (battery.healthy() && battery.current_amps(battery_current)) {
  3507. battery_remaining = get_battery_remaining_percentage();
  3508. battery_current *= 100;
  3509. } else {
  3510. battery_current = -1;
  3511. battery_remaining = -1;
  3512. }
  3513. uint32_t control_sensors_present;
  3514. uint32_t control_sensors_enabled;
  3515. uint32_t control_sensors_health;
  3516. gcs().get_sensor_status_flags(control_sensors_present, control_sensors_enabled, control_sensors_health);
  3517. const uint32_t errors = AP::internalerror().errors();
  3518. const uint16_t errors1 = errors & 0xffff;
  3519. const uint16_t errors2 = (errors>>16) & 0xffff;
  3520. const uint16_t errors4 = AP::internalerror().count() & 0xffff;
  3521. mavlink_msg_sys_status_send(
  3522. chan,
  3523. control_sensors_present,
  3524. control_sensors_enabled,
  3525. control_sensors_health,
  3526. static_cast<uint16_t>(AP::scheduler().load_average() * 1000),
  3527. battery.voltage() * 1000, // mV
  3528. battery_current, // in 10mA units
  3529. battery_remaining, // in %
  3530. 0, // comm drops %,
  3531. 0, // comm drops in pkts,
  3532. errors1,
  3533. errors2,
  3534. 0, // errors3
  3535. errors4); // errors4
  3536. }
  3537. void GCS_MAVLINK::send_extended_sys_state() const
  3538. {
  3539. mavlink_msg_extended_sys_state_send(chan, vtol_state(), landed_state());
  3540. }
  3541. void GCS_MAVLINK::send_attitude() const
  3542. {
  3543. const AP_AHRS &ahrs = AP::ahrs();
  3544. const Vector3f omega = ahrs.get_gyro();
  3545. mavlink_msg_attitude_send(
  3546. chan,
  3547. AP_HAL::millis(),
  3548. ahrs.roll,
  3549. ahrs.pitch,
  3550. ahrs.yaw,
  3551. omega.x,
  3552. omega.y,
  3553. omega.z);
  3554. }
  3555. int32_t GCS_MAVLINK::global_position_int_alt() const {
  3556. return global_position_current_loc.alt * 10UL;
  3557. }
  3558. int32_t GCS_MAVLINK::global_position_int_relative_alt() const {
  3559. float posD;
  3560. AP::ahrs().get_relative_position_D_home(posD);
  3561. posD *= -1000.0f; // change from down to up and metres to millimeters
  3562. return posD;
  3563. }
  3564. void GCS_MAVLINK::send_global_position_int()
  3565. {
  3566. AP_AHRS &ahrs = AP::ahrs();
  3567. ahrs.get_position(global_position_current_loc); // return value ignored; we send stale data
  3568. Vector3f vel;
  3569. if (!ahrs.get_velocity_NED(vel)) {
  3570. vel.zero();
  3571. }
  3572. mavlink_msg_global_position_int_send(
  3573. chan,
  3574. AP_HAL::millis(),
  3575. global_position_current_loc.lat, // in 1E7 degrees
  3576. global_position_current_loc.lng, // in 1E7 degrees
  3577. global_position_int_alt(), // millimeters above ground/sea level
  3578. global_position_int_relative_alt(), // millimeters above home
  3579. vel.x * 100, // X speed cm/s (+ve North)
  3580. vel.y * 100, // Y speed cm/s (+ve East)
  3581. vel.z * 100, // Z speed cm/s (+ve Down)
  3582. ahrs.yaw_sensor); // compass heading in 1/100 degree
  3583. }
  3584. void GCS_MAVLINK::send_gimbal_report() const
  3585. {
  3586. AP_Mount *mount = AP::mount();
  3587. if (mount == nullptr) {
  3588. return;
  3589. }
  3590. mount->send_gimbal_report(chan);
  3591. }
  3592. void GCS_MAVLINK::send_mount_status() const
  3593. {
  3594. AP_Mount *mount = AP::mount();
  3595. if (mount == nullptr) {
  3596. return;
  3597. }
  3598. mount->send_mount_status(chan);
  3599. }
  3600. void GCS_MAVLINK::send_set_position_target_global_int(uint8_t target_system, uint8_t target_component, const Location& loc)
  3601. {
  3602. const uint16_t type_mask = POSITION_TARGET_TYPEMASK_VX_IGNORE | POSITION_TARGET_TYPEMASK_VY_IGNORE | POSITION_TARGET_TYPEMASK_VZ_IGNORE | \
  3603. POSITION_TARGET_TYPEMASK_AX_IGNORE | POSITION_TARGET_TYPEMASK_AY_IGNORE | POSITION_TARGET_TYPEMASK_AZ_IGNORE | \
  3604. POSITION_TARGET_TYPEMASK_YAW_IGNORE | POSITION_TARGET_TYPEMASK_YAW_RATE_IGNORE;
  3605. // convert altitude to relative to home
  3606. int32_t rel_alt;
  3607. if (!loc.get_alt_cm(Location::AltFrame::ABOVE_HOME, rel_alt)) {
  3608. return;
  3609. }
  3610. mavlink_msg_set_position_target_global_int_send(
  3611. chan,
  3612. AP_HAL::millis(),
  3613. target_system,
  3614. target_component,
  3615. MAV_FRAME_GLOBAL_RELATIVE_ALT_INT,
  3616. type_mask,
  3617. loc.lat,
  3618. loc.lng,
  3619. rel_alt,
  3620. 0,0,0, // vx, vy, vz
  3621. 0,0,0, // ax, ay, az
  3622. 0,0); // yaw, yaw_rate
  3623. }
  3624. bool GCS_MAVLINK::try_send_message(const enum ap_message id)
  3625. {
  3626. bool ret = true;
  3627. switch(id) {
  3628. case MSG_ROV_MOTOR_TEMP:
  3629. mavlink_msg_rov_motor_temp_send_struct(chan,&rov_motor_temp);
  3630. break;
  3631. case MSG_ROV_STATE_MONITORING:
  3632. mavlink_msg_rov_state_monitoring_send_struct(chan,&rov_message);
  3633. break;
  3634. case MSG_SET_SLAVE_PARAMETER:
  3635. mavlink_msg_set_slave_parameter_send_struct(chan,&get_stm32_param);
  3636. break;
  3637. case MSG_MOTOR_SPEED:
  3638. mavlink_msg_motor_speed_send_struct(chan,&mav_motor_speed_back);
  3639. break;
  3640. case MSG_HV_REG_GET:
  3641. mavlink_msg_hv_reg_get_send_struct(chan,&hv_reg_get);
  3642. break;
  3643. case MSG_ATTITUDE:
  3644. CHECK_PAYLOAD_SIZE(ATTITUDE);
  3645. send_attitude();
  3646. break;
  3647. case MSG_NEXT_PARAM:
  3648. CHECK_PAYLOAD_SIZE(PARAM_VALUE);
  3649. queued_param_send();
  3650. break;
  3651. case MSG_GIMBAL_REPORT:
  3652. CHECK_PAYLOAD_SIZE(GIMBAL_REPORT);
  3653. send_gimbal_report();
  3654. break;
  3655. case MSG_HEARTBEAT:
  3656. CHECK_PAYLOAD_SIZE(HEARTBEAT);
  3657. last_heartbeat_time = AP_HAL::millis();
  3658. send_heartbeat();
  3659. break;
  3660. case MSG_HWSTATUS:
  3661. CHECK_PAYLOAD_SIZE(HWSTATUS);
  3662. send_hwstatus();
  3663. break;
  3664. case MSG_LOCATION:
  3665. CHECK_PAYLOAD_SIZE(GLOBAL_POSITION_INT);
  3666. send_global_position_int();
  3667. break;
  3668. case MSG_HOME:
  3669. CHECK_PAYLOAD_SIZE(HOME_POSITION);
  3670. send_home_position();
  3671. break;
  3672. case MSG_ORIGIN:
  3673. CHECK_PAYLOAD_SIZE(GPS_GLOBAL_ORIGIN);
  3674. send_gps_global_origin();
  3675. break;
  3676. case MSG_RPM:
  3677. CHECK_PAYLOAD_SIZE(RPM);
  3678. send_rpm();
  3679. break;
  3680. case MSG_CURRENT_WAYPOINT:
  3681. case MSG_MISSION_ITEM_REACHED:
  3682. case MSG_NEXT_MISSION_REQUEST_WAYPOINTS:
  3683. case MSG_NEXT_MISSION_REQUEST_RALLY:
  3684. ret = try_send_mission_message(id);
  3685. break;
  3686. case MSG_MAG_CAL_PROGRESS:
  3687. ret = AP::compass().send_mag_cal_progress(*this);
  3688. break;
  3689. case MSG_MAG_CAL_REPORT:
  3690. ret = AP::compass().send_mag_cal_report(*this);
  3691. break;
  3692. case MSG_BATTERY_STATUS:
  3693. send_battery_status();
  3694. break;
  3695. case MSG_BATTERY2:
  3696. CHECK_PAYLOAD_SIZE(BATTERY2);
  3697. send_battery2();
  3698. break;
  3699. case MSG_EKF_STATUS_REPORT:
  3700. #if AP_AHRS_NAVEKF_AVAILABLE
  3701. CHECK_PAYLOAD_SIZE(EKF_STATUS_REPORT);
  3702. AP::ahrs_navekf().send_ekf_status_report(chan);
  3703. #endif
  3704. break;
  3705. case MSG_MEMINFO:
  3706. CHECK_PAYLOAD_SIZE(MEMINFO);
  3707. send_meminfo();
  3708. break;
  3709. case MSG_FENCE_STATUS:
  3710. CHECK_PAYLOAD_SIZE(FENCE_STATUS);
  3711. send_fence_status();
  3712. break;
  3713. case MSG_RANGEFINDER:
  3714. CHECK_PAYLOAD_SIZE(RANGEFINDER);
  3715. send_rangefinder();
  3716. break;
  3717. case MSG_DISTANCE_SENSOR:
  3718. send_distance_sensor();
  3719. break;
  3720. case MSG_CAMERA_FEEDBACK:
  3721. {
  3722. AP_Camera *camera = AP::camera();
  3723. if (camera == nullptr) {
  3724. break;
  3725. }
  3726. CHECK_PAYLOAD_SIZE(CAMERA_FEEDBACK);
  3727. camera->send_feedback(chan);
  3728. }
  3729. break;
  3730. case MSG_SYSTEM_TIME:
  3731. CHECK_PAYLOAD_SIZE(SYSTEM_TIME);
  3732. send_system_time();
  3733. break;
  3734. case MSG_GPS_RAW:
  3735. CHECK_PAYLOAD_SIZE(GPS_RAW_INT);
  3736. AP::gps().send_mavlink_gps_raw(chan);
  3737. break;
  3738. case MSG_GPS_RTK:
  3739. CHECK_PAYLOAD_SIZE(GPS_RTK);
  3740. AP::gps().send_mavlink_gps_rtk(chan, 0);
  3741. break;
  3742. case MSG_GPS2_RAW:
  3743. CHECK_PAYLOAD_SIZE(GPS2_RAW);
  3744. AP::gps().send_mavlink_gps2_raw(chan);
  3745. break;
  3746. case MSG_GPS2_RTK:
  3747. CHECK_PAYLOAD_SIZE(GPS2_RTK);
  3748. AP::gps().send_mavlink_gps_rtk(chan, 1);
  3749. break;
  3750. case MSG_LOCAL_POSITION:
  3751. CHECK_PAYLOAD_SIZE(LOCAL_POSITION_NED);
  3752. send_local_position();
  3753. break;
  3754. case MSG_MOUNT_STATUS:
  3755. CHECK_PAYLOAD_SIZE(MOUNT_STATUS);
  3756. send_mount_status();
  3757. break;
  3758. case MSG_OPTICAL_FLOW:
  3759. CHECK_PAYLOAD_SIZE(OPTICAL_FLOW);
  3760. send_opticalflow();
  3761. break;
  3762. case MSG_POSITION_TARGET_GLOBAL_INT:
  3763. CHECK_PAYLOAD_SIZE(POSITION_TARGET_GLOBAL_INT);
  3764. send_position_target_global_int();
  3765. break;
  3766. case MSG_POSITION_TARGET_LOCAL_NED:
  3767. CHECK_PAYLOAD_SIZE(POSITION_TARGET_LOCAL_NED);
  3768. send_position_target_local_ned();
  3769. break;
  3770. case MSG_POWER_STATUS:
  3771. CHECK_PAYLOAD_SIZE(POWER_STATUS);
  3772. send_power_status();
  3773. break;
  3774. case MSG_RC_CHANNELS:
  3775. CHECK_PAYLOAD_SIZE(RC_CHANNELS);
  3776. send_rc_channels();
  3777. break;
  3778. case MSG_RC_CHANNELS_RAW:
  3779. CHECK_PAYLOAD_SIZE(RC_CHANNELS_RAW);
  3780. send_rc_channels_raw();
  3781. break;
  3782. case MSG_RAW_IMU:
  3783. CHECK_PAYLOAD_SIZE(RAW_IMU);
  3784. send_raw_imu();
  3785. break;
  3786. case MSG_SCALED_IMU:
  3787. CHECK_PAYLOAD_SIZE(SCALED_IMU);
  3788. send_scaled_imu(0, mavlink_msg_scaled_imu_send);
  3789. break;
  3790. case MSG_SCALED_IMU2:
  3791. CHECK_PAYLOAD_SIZE(SCALED_IMU2);
  3792. send_scaled_imu(1, mavlink_msg_scaled_imu2_send);
  3793. break;
  3794. case MSG_SCALED_IMU3:
  3795. CHECK_PAYLOAD_SIZE(SCALED_IMU3);
  3796. send_scaled_imu(2, mavlink_msg_scaled_imu3_send);
  3797. break;
  3798. case MSG_SCALED_PRESSURE:
  3799. CHECK_PAYLOAD_SIZE(SCALED_PRESSURE);
  3800. send_scaled_pressure();
  3801. break;
  3802. case MSG_SCALED_PRESSURE2:
  3803. CHECK_PAYLOAD_SIZE(SCALED_PRESSURE2);
  3804. send_scaled_pressure2();
  3805. break;
  3806. case MSG_SCALED_PRESSURE3:
  3807. CHECK_PAYLOAD_SIZE(SCALED_PRESSURE3);
  3808. send_scaled_pressure3();
  3809. break;
  3810. case MSG_SENSOR_OFFSETS:
  3811. CHECK_PAYLOAD_SIZE(SENSOR_OFFSETS);
  3812. send_sensor_offsets();
  3813. break;
  3814. case MSG_SERVO_OUTPUT_RAW:
  3815. CHECK_PAYLOAD_SIZE(SERVO_OUTPUT_RAW);
  3816. send_servo_output_raw();
  3817. break;
  3818. case MSG_SIMSTATE:
  3819. CHECK_PAYLOAD_SIZE(SIMSTATE);
  3820. send_simstate();
  3821. break;
  3822. case MSG_SYS_STATUS:
  3823. CHECK_PAYLOAD_SIZE(SYS_STATUS);
  3824. send_sys_status();
  3825. break;
  3826. case MSG_AHRS2:
  3827. CHECK_PAYLOAD_SIZE(AHRS2);
  3828. send_ahrs2();
  3829. break;
  3830. case MSG_AHRS3:
  3831. CHECK_PAYLOAD_SIZE(AHRS3);
  3832. send_ahrs3();
  3833. break;
  3834. case MSG_PID_TUNING:
  3835. CHECK_PAYLOAD_SIZE(PID_TUNING);
  3836. send_pid_tuning();
  3837. break;
  3838. case MSG_NAV_CONTROLLER_OUTPUT:
  3839. CHECK_PAYLOAD_SIZE(NAV_CONTROLLER_OUTPUT);
  3840. send_nav_controller_output();
  3841. break;
  3842. case MSG_AHRS:
  3843. CHECK_PAYLOAD_SIZE(AHRS);
  3844. send_ahrs();
  3845. break;
  3846. case MSG_EXTENDED_SYS_STATE:
  3847. CHECK_PAYLOAD_SIZE(EXTENDED_SYS_STATE);
  3848. send_extended_sys_state();
  3849. break;
  3850. case MSG_VFR_HUD:
  3851. CHECK_PAYLOAD_SIZE(VFR_HUD);
  3852. send_vfr_hud();
  3853. break;
  3854. case MSG_VIBRATION:
  3855. CHECK_PAYLOAD_SIZE(VIBRATION);
  3856. send_vibration();
  3857. break;
  3858. case MSG_AUTOPILOT_VERSION:
  3859. CHECK_PAYLOAD_SIZE(AUTOPILOT_VERSION);
  3860. send_autopilot_version();
  3861. break;
  3862. case MSG_ESC_TELEMETRY: {
  3863. #ifdef HAVE_AP_BLHELI_SUPPORT
  3864. CHECK_PAYLOAD_SIZE(ESC_TELEMETRY_1_TO_4);
  3865. AP_BLHeli *blheli = AP_BLHeli::get_singleton();
  3866. if (blheli) {
  3867. blheli->send_esc_telemetry_mavlink(uint8_t(chan));
  3868. }
  3869. #endif
  3870. #if HAL_WITH_UAVCAN
  3871. uint8_t num_drivers = AP::can().get_num_drivers();
  3872. for (uint8_t i = 0; i < num_drivers; i++) {
  3873. switch (AP::can().get_protocol_type(i)) {
  3874. case AP_BoardConfig_CAN::Protocol_Type_KDECAN: {
  3875. // To be replaced with macro saying if KDECAN library is included
  3876. #if APM_BUILD_TYPE(APM_BUILD_ArduCopter) || APM_BUILD_TYPE(APM_BUILD_ArduPlane) || APM_BUILD_TYPE(APM_BUILD_ArduSub)
  3877. AP_KDECAN *ap_kdecan = AP_KDECAN::get_kdecan(i);
  3878. if (ap_kdecan != nullptr) {
  3879. ap_kdecan->send_mavlink(uint8_t(chan));
  3880. }
  3881. #endif
  3882. break;
  3883. }
  3884. case AP_BoardConfig_CAN::Protocol_Type_ToshibaCAN: {
  3885. AP_ToshibaCAN *ap_tcan = AP_ToshibaCAN::get_tcan(i);
  3886. if (ap_tcan != nullptr) {
  3887. ap_tcan->send_esc_telemetry_mavlink(uint8_t(chan));
  3888. }
  3889. break;
  3890. }
  3891. case AP_BoardConfig_CAN::Protocol_Type_UAVCAN:
  3892. case AP_BoardConfig_CAN::Protocol_Type_None:
  3893. default:
  3894. break;
  3895. }
  3896. }
  3897. #endif
  3898. break;
  3899. }
  3900. default:
  3901. // try_send_message must always at some stage return true for
  3902. // a message, or we will attempt to infinitely retry the
  3903. // message as part of send_message.
  3904. // This message will be sent out at the same rate as the
  3905. // unknown message, so should be safe.
  3906. gcs().send_text(MAV_SEVERITY_DEBUG, "Sending unknown message (%u)", id);
  3907. #if CONFIG_HAL_BOARD == HAL_BOARD_SITL
  3908. AP_HAL::panic("Sending unknown ap_message %u", id);
  3909. #endif
  3910. break;
  3911. }
  3912. return ret;
  3913. }
  3914. uint16_t GCS_MAVLINK::get_interval_for_stream(GCS_MAVLINK::streams id) const
  3915. {
  3916. const int16_t frate = streamRates[id].get();
  3917. if (frate == 0) {
  3918. return 0;
  3919. }
  3920. const uint32_t ret = 1000/frate;
  3921. if (ret > 60000) {
  3922. return 60000;
  3923. }
  3924. return ret;
  3925. }
  3926. void GCS_MAVLINK::initialise_message_intervals_for_stream(GCS_MAVLINK::streams id)
  3927. {
  3928. for (uint8_t i=0; all_stream_entries[i].ap_message_ids != nullptr; i++) {
  3929. const GCS_MAVLINK::stream_entries &entries = all_stream_entries[i];
  3930. if (entries.stream_id != id) {
  3931. continue;
  3932. }
  3933. // found it!
  3934. const uint16_t interval_ms = get_interval_for_stream(id);
  3935. for (uint8_t j=0; j<entries.num_ap_message_ids; j++) {
  3936. set_ap_message_interval(entries.ap_message_ids[j], interval_ms);
  3937. }
  3938. break;
  3939. }
  3940. }
  3941. void GCS_MAVLINK::initialise_message_intervals_from_streamrates()
  3942. {
  3943. // this is O(n^2), but it's once at boot and across a 10-entry list...
  3944. for (uint8_t i=0; all_stream_entries[i].ap_message_ids != nullptr; i++) {
  3945. initialise_message_intervals_for_stream(all_stream_entries[i].stream_id);
  3946. }
  3947. set_mavlink_message_id_interval(MAVLINK_MSG_ID_HEARTBEAT, 1000);
  3948. }
  3949. bool GCS_MAVLINK::get_default_interval_for_ap_message(const ap_message id, uint16_t &interval) const
  3950. {
  3951. if (id == MSG_HEARTBEAT) {
  3952. // handle heartbeat requests as a special case because heartbeat is not "streamed"
  3953. interval = 1000;
  3954. return true;
  3955. }
  3956. // find which stream this ap_message is in
  3957. for (uint8_t i=0; all_stream_entries[i].ap_message_ids != nullptr; i++) {
  3958. const GCS_MAVLINK::stream_entries &entries = all_stream_entries[i];
  3959. for (uint8_t j=0; j<entries.num_ap_message_ids; j++) {
  3960. if (entries.ap_message_ids[j] == id) {
  3961. interval = get_interval_for_stream(all_stream_entries[i].stream_id);
  3962. return true;
  3963. }
  3964. }
  3965. }
  3966. return false;
  3967. }
  3968. bool GCS_MAVLINK::get_default_interval_for_mavlink_message_id(const uint32_t mavlink_message_id, uint16_t &interval) const
  3969. {
  3970. const ap_message id = mavlink_id_to_ap_message_id(mavlink_message_id);
  3971. if (id == MSG_LAST) {
  3972. return false;
  3973. }
  3974. return get_default_interval_for_ap_message(id, interval);
  3975. }
  3976. /*
  3977. correct an offboard timestamp in microseconds into a local timestamp
  3978. since boot in milliseconds. See the JitterCorrection code for details
  3979. Return a value in milliseconds since boot (for use by the EKF)
  3980. */
  3981. uint32_t GCS_MAVLINK::correct_offboard_timestamp_usec_to_ms(uint64_t offboard_usec, uint16_t payload_size)
  3982. {
  3983. uint64_t local_us;
  3984. // if the HAL supports it then constrain the latest possible time
  3985. // the packet could have been sent by the uart receive time and
  3986. // the baudrate and packet size.
  3987. uint64_t uart_receive_time = _port->receive_time_constraint_us(payload_size);
  3988. if (uart_receive_time != 0) {
  3989. local_us = uart_receive_time;
  3990. } else {
  3991. local_us = AP_HAL::micros64();
  3992. }
  3993. uint64_t corrected_us = lag_correction.correct_offboard_timestamp_usec(offboard_usec, local_us);
  3994. return corrected_us / 1000U;
  3995. }
  3996. /*
  3997. return true if we will accept this packet. Used to implement SYSID_ENFORCE
  3998. */
  3999. bool GCS_MAVLINK::accept_packet(const mavlink_status_t &status,
  4000. const mavlink_message_t &msg)
  4001. {
  4002. if (msg.sysid == mavlink_system.sysid) {
  4003. // accept packets from our own components
  4004. // (e.g. mavlink-connected companion computers)
  4005. return true;
  4006. }
  4007. if (msg.sysid == sysid_my_gcs()) {
  4008. return true;
  4009. }
  4010. if (msg.msgid == MAVLINK_MSG_ID_RADIO ||
  4011. msg.msgid == MAVLINK_MSG_ID_RADIO_STATUS) {
  4012. return true;
  4013. }
  4014. if (!sysid_enforce()) {
  4015. return true;
  4016. }
  4017. return false;
  4018. }
  4019. /*
  4020. update UART pass-thru, if enabled
  4021. */
  4022. void GCS::update_passthru(void)
  4023. {
  4024. WITH_SEMAPHORE(_passthru.sem);
  4025. uint32_t now = AP_HAL::millis();
  4026. bool enabled = AP::serialmanager().get_passthru(_passthru.port1, _passthru.port2, _passthru.timeout_s);
  4027. if (enabled && !_passthru.enabled) {
  4028. _passthru.start_ms = now;
  4029. _passthru.last_ms = 0;
  4030. _passthru.enabled = true;
  4031. _passthru.last_port1_data_ms = now;
  4032. gcs().send_text(MAV_SEVERITY_INFO, "Passthru enabled");
  4033. if (!_passthru.timer_installed) {
  4034. _passthru.timer_installed = true;
  4035. hal.scheduler->register_timer_process(FUNCTOR_BIND_MEMBER(&GCS::passthru_timer, void));
  4036. }
  4037. } else if (!enabled && _passthru.enabled) {
  4038. _passthru.enabled = false;
  4039. _passthru.port1->lock_port(0, 0);
  4040. _passthru.port2->lock_port(0, 0);
  4041. gcs().send_text(MAV_SEVERITY_INFO, "Passthru disabled");
  4042. } else if (enabled &&
  4043. _passthru.timeout_s &&
  4044. now - _passthru.last_port1_data_ms > uint32_t(_passthru.timeout_s)*1000U) {
  4045. // timed out, disable
  4046. _passthru.enabled = false;
  4047. _passthru.port1->lock_port(0, 0);
  4048. _passthru.port2->lock_port(0, 0);
  4049. AP::serialmanager().disable_passthru();
  4050. gcs().send_text(MAV_SEVERITY_INFO, "Passthru timed out");
  4051. }
  4052. }
  4053. /*
  4054. called at 1kHz to handle pass-thru between SERIA0_PASSTHRU port and hal.console
  4055. */
  4056. void GCS::passthru_timer(void)
  4057. {
  4058. WITH_SEMAPHORE(_passthru.sem);
  4059. if (!_passthru.enabled) {
  4060. // it has been disabled after starting
  4061. return;
  4062. }
  4063. if (_passthru.start_ms != 0) {
  4064. uint32_t now = AP_HAL::millis();
  4065. if (now - _passthru.start_ms < 1000) {
  4066. // delay for 1s so the reply for the SERIAL0_PASSTHRU param set can be seen by GCS
  4067. return;
  4068. }
  4069. _passthru.start_ms = 0;
  4070. }
  4071. // while pass-thru is enabled lock both ports. They remain
  4072. // locked until disabled again, or reboot
  4073. const uint32_t lock_key = 0x3256AB9F;
  4074. _passthru.port1->lock_port(lock_key, lock_key);
  4075. _passthru.port2->lock_port(lock_key, lock_key);
  4076. int16_t b;
  4077. uint8_t buf[64];
  4078. uint8_t nbytes = 0;
  4079. // read from port1, and write to port2
  4080. while (nbytes < sizeof(buf) && (b = _passthru.port1->read_locked(lock_key)) >= 0) {
  4081. buf[nbytes++] = b;
  4082. }
  4083. if (nbytes > 0) {
  4084. _passthru.last_port1_data_ms = AP_HAL::millis();
  4085. _passthru.port2->write_locked(buf, nbytes, lock_key);
  4086. }
  4087. // read from port2, and write to port1
  4088. nbytes = 0;
  4089. while (nbytes < sizeof(buf) && (b = _passthru.port2->read_locked(lock_key)) >= 0) {
  4090. buf[nbytes++] = b;
  4091. }
  4092. if (nbytes > 0) {
  4093. _passthru.port1->write_locked(buf, nbytes, lock_key);
  4094. }
  4095. }
  4096. bool GCS_MAVLINK::mavlink_coordinate_frame_to_location_alt_frame(const MAV_FRAME coordinate_frame, Location::AltFrame &frame)
  4097. {
  4098. switch (coordinate_frame) {
  4099. case MAV_FRAME_GLOBAL_RELATIVE_ALT: // solo shot manager incorrectly sends RELATIVE_ALT instead of RELATIVE_ALT_INT
  4100. case MAV_FRAME_GLOBAL_RELATIVE_ALT_INT:
  4101. frame = Location::AltFrame::ABOVE_HOME;
  4102. return true;
  4103. case MAV_FRAME_GLOBAL_TERRAIN_ALT:
  4104. case MAV_FRAME_GLOBAL_TERRAIN_ALT_INT:
  4105. frame = Location::AltFrame::ABOVE_TERRAIN;
  4106. return true;
  4107. case MAV_FRAME_GLOBAL:
  4108. case MAV_FRAME_GLOBAL_INT:
  4109. frame = Location::AltFrame::ABSOLUTE;
  4110. return true;
  4111. default:
  4112. #if CONFIG_HAL_BOARD == HAL_BOARD_SITL
  4113. gcs().send_text(MAV_SEVERITY_INFO, "Unknown mavlink coordinate frame %u", coordinate_frame);
  4114. #endif
  4115. return false;
  4116. }
  4117. }
  4118. uint64_t GCS_MAVLINK::capabilities() const
  4119. {
  4120. uint64_t ret = 0;
  4121. AP_SerialManager::SerialProtocol mavlink_protocol = AP::serialmanager().get_mavlink_protocol(chan);
  4122. if (mavlink_protocol == AP_SerialManager::SerialProtocol_MAVLink2) {
  4123. ret |= MAV_PROTOCOL_CAPABILITY_MAVLINK2;
  4124. }
  4125. AP_AdvancedFailsafe *failsafe = get_advanced_failsafe();
  4126. if (failsafe != nullptr && failsafe->enabled()) {
  4127. // Copter and Sub may also set this bit as they can always terminate
  4128. ret |= MAV_PROTOCOL_CAPABILITY_FLIGHT_TERMINATION;
  4129. }
  4130. if (AP::rally()) {
  4131. ret |= MAV_PROTOCOL_CAPABILITY_MISSION_RALLY;
  4132. }
  4133. return ret;
  4134. }
  4135. 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)
  4136. {
  4137. if (c == nullptr) {
  4138. return;
  4139. }
  4140. int16_t override_value = 0;
  4141. if (value_in != INT16_MAX) {
  4142. const int16_t radio_min = c->get_radio_min();
  4143. const int16_t radio_max = c->get_radio_max();
  4144. if (reversed) {
  4145. value_in *= -1;
  4146. }
  4147. override_value = radio_min + (radio_max - radio_min) * (value_in + offset) / scaler;
  4148. }
  4149. c->set_override(override_value, tnow);
  4150. }
  4151. uint8_t GCS_MAVLINK::get_battery_remaining_percentage(uint8_t instance) const {
  4152. const AP_BattMonitor &battery = AP::battery();
  4153. return battery.capacity_remaining_pct(instance);
  4154. }
  4155. GCS &gcs()
  4156. {
  4157. return *GCS::get_singleton();
  4158. }