GCS_Common.cpp 150 KB

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