GnssAdapter.cpp 294 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482
  1. /* Copyright (c) 2017-2021 The Linux Foundation. All rights reserved.
  2. *
  3. * Redistribution and use in source and binary forms, with or without
  4. * modification, are permitted provided that the following conditions are
  5. * met:
  6. * * Redistributions of source code must retain the above copyright
  7. * notice, this list of conditions and the following disclaimer.
  8. * * Redistributions in binary form must reproduce the above
  9. * copyright notice, this list of conditions and the following
  10. * disclaimer in the documentation and/or other materials provided
  11. * with the distribution.
  12. * * Neither the name of The Linux Foundation, nor the names of its
  13. * contributors may be used to endorse or promote products derived
  14. * from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
  17. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  18. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
  19. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
  20. * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  21. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  22. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  23. * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  24. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  25. * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  26. * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. *
  28. */
  29. #define LOG_NDEBUG 0
  30. #define LOG_TAG "LocSvc_GnssAdapter"
  31. #include <inttypes.h>
  32. #include <sys/stat.h>
  33. #include <errno.h>
  34. #include <ctype.h>
  35. #include <cutils/properties.h>
  36. #include <math.h>
  37. #include <arpa/inet.h>
  38. #include <netinet/in.h>
  39. #include <netdb.h>
  40. #include <GnssAdapter.h>
  41. #include <string>
  42. #include <sstream>
  43. #include <loc_log.h>
  44. #include <loc_nmea.h>
  45. #include <Agps.h>
  46. #include <SystemStatus.h>
  47. #include <vector>
  48. #include <loc_misc_utils.h>
  49. #include <gps_extended_c.h>
  50. #include <sys/stat.h>
  51. #define RAD2DEG (180.0 / M_PI)
  52. #define DEG2RAD (M_PI / 180.0)
  53. #define PROCESS_NAME_ENGINE_SERVICE "engine-service"
  54. #ifdef FEATURE_AUTOMOTIVE
  55. #define MIN_TRACKING_INTERVAL (100) // 100 msec
  56. #else
  57. #define MIN_TRACKING_INTERVAL (1000) // 1 sec
  58. #endif //FEATURE_AUTOMOTIVE
  59. #define BILLION_NSEC (1000000000ULL)
  60. #define NMEA_MIN_THRESHOLD_MSEC (99)
  61. #define NMEA_MAX_THRESHOLD_MSEC (975)
  62. #define DGNSS_RANGE_UPDATE_TIME_10MIN_IN_MILLI 600000
  63. using namespace loc_core;
  64. static int loadEngHubForExternalEngine = 0;
  65. static loc_param_s_type izatConfParamTable[] = {
  66. {"LOAD_ENGHUB_FOR_EXTERNAL_ENGINE", &loadEngHubForExternalEngine, nullptr,'n'}
  67. };
  68. /* Method to fetch status cb from loc_net_iface library */
  69. typedef AgpsCbInfo& (*LocAgpsGetAgpsCbInfo)(LocAgpsOpenResultCb openResultCb,
  70. LocAgpsCloseResultCb closeResultCb, void* userDataPtr);
  71. static void agpsOpenResultCb (bool isSuccess, AGpsExtType agpsType, const char* apn,
  72. AGpsBearerType bearerType, void* userDataPtr);
  73. static void agpsCloseResultCb (bool isSuccess, AGpsExtType agpsType, void* userDataPtr);
  74. typedef const CdfwInterface* (*getCdfwInterface)();
  75. typedef void getPdnTypeFromWds(const std::string& apnName, std::function<void(int)> pdnCb);
  76. GnssReportLoggerUtil::GnssReportLoggerUtil() : mLogLatency(nullptr) {
  77. int loadDiagIfaceLib = 1;
  78. const loc_param_s_type gps_conf_params[] = {
  79. {"LOC_DIAGIFACE_ENABLED", &loadDiagIfaceLib, nullptr, 'n'}
  80. };
  81. UTIL_READ_CONF(LOC_PATH_GPS_CONF, gps_conf_params);
  82. LOC_LOGi("Loc_DiagIface_enabled: %d", loadDiagIfaceLib);
  83. if (0 != loadDiagIfaceLib) {
  84. const char* libname = "liblocdiagiface.so";
  85. void* libHandle = nullptr;
  86. mLogLatency = (LogGnssLatency)dlGetSymFromLib(libHandle, libname, "LogGnssLatency");
  87. if (nullptr == mLogLatency) {
  88. LOC_LOGw("DiagIface mLogLatency is null");
  89. }
  90. }
  91. }
  92. inline bool GnssReportLoggerUtil::isLogEnabled() {
  93. return (mLogLatency != nullptr);
  94. }
  95. inline void GnssReportLoggerUtil::log(const GnssLatencyInfo& gnssLatencyMeasInfo) {
  96. if (mLogLatency != nullptr) {
  97. mLogLatency(gnssLatencyMeasInfo);
  98. }
  99. }
  100. GnssAdapter::GnssAdapter() :
  101. LocAdapterBase(0,
  102. LocContext::getLocContext(LocContext::mLocationHalName),
  103. true, nullptr, true),
  104. mEngHubProxy(new EngineHubProxyBase()),
  105. mNHzNeeded(false),
  106. mSPEAlreadyRunningAtHighestInterval(false),
  107. mLocPositionMode(),
  108. mGnssSvIdUsedInPosition(),
  109. mGnssSvIdUsedInPosAvail(false),
  110. mGnssMbSvIdUsedInPosition{},
  111. mGnssMbSvIdUsedInPosAvail(false),
  112. mControlCallbacks(),
  113. mAfwControlId(0),
  114. mNmeaMask(0),
  115. mGnssSvIdConfig(),
  116. mGnssSeconaryBandConfig(),
  117. mGnssSvTypeConfig(),
  118. mGnssSvTypeConfigCb(nullptr),
  119. mSupportNfwControl(true),
  120. mLocConfigInfo{},
  121. mNiData(),
  122. mAgpsManager(),
  123. mNfwCb(NULL),
  124. mIsE911Session(NULL),
  125. mIsMeasCorrInterfaceOpen(false),
  126. mIsAntennaInfoInterfaceOpened(false),
  127. mQDgnssListenerHDL(nullptr),
  128. mCdfwInterface(nullptr),
  129. mDGnssNeedReport(false),
  130. mDGnssDataUsage(false),
  131. mOdcpiRequestCb(nullptr),
  132. mOdcpiStateMask(0),
  133. mCallbackPriority(OdcpiPrioritytype::ODCPI_HANDLER_PRIORITY_LOW),
  134. mOdcpiTimer(this),
  135. mOdcpiRequest(),
  136. mLastDeleteAidingDataTime(0),
  137. mSystemStatus(SystemStatus::getInstance(mMsgTask)),
  138. mServerUrl(":"),
  139. mXtraObserver(mSystemStatus->getOsObserver(), mMsgTask),
  140. mLocSystemInfo{},
  141. mSystemPowerState(POWER_STATE_UNKNOWN),
  142. mBlockCPIInfo{},
  143. mPowerOn(false),
  144. mDreIntEnabled(false),
  145. mNativeAgpsHandler(mSystemStatus->getOsObserver(), *this),
  146. mGnssEnergyConsumedCb(nullptr),
  147. mPowerStateCb(nullptr),
  148. mSendNmeaConsent(false),
  149. mDgnssState(0),
  150. mDgnssLastNmeaBootTimeMilli(0),
  151. mPowerIndicationCb(nullptr),
  152. mGnssPowerStatisticsInit(false),
  153. mBootReferenceEnergy(0),
  154. mPowerElapsedRealTimeCal(30000000),
  155. mAddressRequestCb(nullptr),
  156. mPositionElapsedRealTimeCal(30000000)
  157. {
  158. LOC_LOGD("%s]: Constructor %p", __func__, this);
  159. mLocPositionMode.mode = LOC_POSITION_MODE_INVALID;
  160. pthread_condattr_t condAttr;
  161. pthread_condattr_init(&condAttr);
  162. pthread_condattr_setclock(&condAttr, CLOCK_REALTIME);
  163. pthread_cond_init(&mNiData.session.tCond, &condAttr);
  164. pthread_cond_init(&mNiData.sessionEs.tCond, &condAttr);
  165. pthread_condattr_destroy(&condAttr);
  166. /* Set ATL open/close callbacks */
  167. AgpsAtlOpenStatusCb atlOpenStatusCb =
  168. [this](int handle, int isSuccess, char* apn, uint32_t apnLen,
  169. AGpsBearerType bearerType, AGpsExtType agpsType,
  170. LocApnTypeMask mask) {
  171. mLocApi->atlOpenStatus(
  172. handle, isSuccess, apn, apnLen, bearerType, agpsType, mask);
  173. };
  174. AgpsAtlCloseStatusCb atlCloseStatusCb =
  175. [this](int handle, int isSuccess) {
  176. mLocApi->atlCloseStatus(handle, isSuccess);
  177. };
  178. mAgpsManager.registerATLCallbacks(atlOpenStatusCb, atlCloseStatusCb);
  179. readConfigCommand();
  180. initDefaultAgpsCommand();
  181. initCDFWServiceCommand();
  182. initEngHubProxyCommand();
  183. // at last step, let us inform adapater base that we are done
  184. // with initialization, e.g.: ready to process handleEngineUpEvent
  185. doneInit();
  186. }
  187. void
  188. GnssAdapter::setControlCallbacksCommand(LocationControlCallbacks& controlCallbacks)
  189. {
  190. struct MsgSetControlCallbacks : public LocMsg {
  191. GnssAdapter& mAdapter;
  192. const LocationControlCallbacks mControlCallbacks;
  193. inline MsgSetControlCallbacks(GnssAdapter& adapter,
  194. LocationControlCallbacks& controlCallbacks) :
  195. LocMsg(),
  196. mAdapter(adapter),
  197. mControlCallbacks(controlCallbacks) {}
  198. inline virtual void proc() const {
  199. mAdapter.setControlCallbacks(mControlCallbacks);
  200. }
  201. };
  202. sendMsg(new MsgSetControlCallbacks(*this, controlCallbacks));
  203. }
  204. void
  205. GnssAdapter::convertOptions(LocPosMode& out, const TrackingOptions& trackingOptions)
  206. {
  207. switch (trackingOptions.mode) {
  208. case GNSS_SUPL_MODE_MSB:
  209. out.mode = LOC_POSITION_MODE_MS_BASED;
  210. break;
  211. case GNSS_SUPL_MODE_MSA:
  212. out.mode = LOC_POSITION_MODE_MS_ASSISTED;
  213. break;
  214. default:
  215. out.mode = LOC_POSITION_MODE_STANDALONE;
  216. break;
  217. }
  218. out.share_position = true;
  219. out.min_interval = trackingOptions.minInterval;
  220. out.powerMode = trackingOptions.powerMode;
  221. out.timeBetweenMeasurements = trackingOptions.tbm;
  222. }
  223. bool
  224. GnssAdapter::checkAndSetSPEToRunforNHz(TrackingOptions & out) {
  225. // first check if NHz meas is needed at all, if not, just return false
  226. // if a NHz capable engine is subscribed for NHz measurement or NHz positions,
  227. // always run the SPE only session at 100ms TBF.
  228. // If SPE session is already set to highest interval, no need to start it again.
  229. bool isSPERunningAtHighestInterval = false;
  230. if (!mNHzNeeded) {
  231. LOC_LOGd("No nHz session needed.");
  232. } else if (mSPEAlreadyRunningAtHighestInterval) {
  233. LOC_LOGd("SPE is already running at highest interval.");
  234. isSPERunningAtHighestInterval = true;
  235. } else if (out.minInterval > MIN_TRACKING_INTERVAL) {
  236. out.minInterval = MIN_TRACKING_INTERVAL;
  237. LOC_LOGd("nHz session is needed, starting SPE only session at 100ms TBF.");
  238. mSPEAlreadyRunningAtHighestInterval = true;
  239. }
  240. return isSPERunningAtHighestInterval;
  241. }
  242. void
  243. GnssAdapter::convertLocation(Location& out, const UlpLocation& ulpLocation,
  244. const GpsLocationExtended& locationExtended)
  245. {
  246. memset(&out, 0, sizeof(Location));
  247. out.size = sizeof(Location);
  248. if (LOC_GPS_LOCATION_HAS_LAT_LONG & ulpLocation.gpsLocation.flags) {
  249. out.flags |= LOCATION_HAS_LAT_LONG_BIT;
  250. out.latitude = ulpLocation.gpsLocation.latitude;
  251. out.longitude = ulpLocation.gpsLocation.longitude;
  252. }
  253. if (LOC_GPS_LOCATION_HAS_ALTITUDE & ulpLocation.gpsLocation.flags) {
  254. out.flags |= LOCATION_HAS_ALTITUDE_BIT;
  255. out.altitude = ulpLocation.gpsLocation.altitude;
  256. }
  257. if (LOC_GPS_LOCATION_HAS_SPEED & ulpLocation.gpsLocation.flags) {
  258. out.flags |= LOCATION_HAS_SPEED_BIT;
  259. out.speed = ulpLocation.gpsLocation.speed;
  260. }
  261. if (LOC_GPS_LOCATION_HAS_BEARING & ulpLocation.gpsLocation.flags) {
  262. out.flags |= LOCATION_HAS_BEARING_BIT;
  263. out.bearing = ulpLocation.gpsLocation.bearing;
  264. }
  265. if (LOC_GPS_LOCATION_HAS_ACCURACY & ulpLocation.gpsLocation.flags) {
  266. out.flags |= LOCATION_HAS_ACCURACY_BIT;
  267. out.accuracy = ulpLocation.gpsLocation.accuracy;
  268. }
  269. if (GPS_LOCATION_EXTENDED_HAS_VERT_UNC & locationExtended.flags) {
  270. out.flags |= LOCATION_HAS_VERTICAL_ACCURACY_BIT;
  271. out.verticalAccuracy = locationExtended.vert_unc;
  272. }
  273. if (GPS_LOCATION_EXTENDED_HAS_SPEED_UNC & locationExtended.flags) {
  274. out.flags |= LOCATION_HAS_SPEED_ACCURACY_BIT;
  275. out.speedAccuracy = locationExtended.speed_unc;
  276. }
  277. if (GPS_LOCATION_EXTENDED_HAS_BEARING_UNC & locationExtended.flags) {
  278. out.flags |= LOCATION_HAS_BEARING_ACCURACY_BIT;
  279. out.bearingAccuracy = locationExtended.bearing_unc;
  280. }
  281. if (GPS_LOCATION_EXTENDED_HAS_CONFORMITY_INDEX & locationExtended.flags) {
  282. out.flags |= LOCATION_HAS_CONFORMITY_INDEX_BIT;
  283. out.conformityIndex = locationExtended.conformityIndex;
  284. }
  285. out.timestamp = ulpLocation.gpsLocation.timestamp;
  286. if (GPS_LOCATION_EXTENDED_HAS_POS_TECH_MASK & locationExtended.flags) {
  287. out.flags |= LOCATION_HAS_TECH_MASK_BIT;
  288. }
  289. if (LOC_POS_TECH_MASK_SATELLITE & locationExtended.tech_mask) {
  290. out.techMask |= LOCATION_TECHNOLOGY_GNSS_BIT;
  291. }
  292. if (LOC_POS_TECH_MASK_CELLID & locationExtended.tech_mask) {
  293. out.techMask |= LOCATION_TECHNOLOGY_CELL_BIT;
  294. }
  295. if (LOC_POS_TECH_MASK_WIFI & locationExtended.tech_mask) {
  296. out.techMask |= LOCATION_TECHNOLOGY_WIFI_BIT;
  297. }
  298. if (LOC_POS_TECH_MASK_SENSORS & locationExtended.tech_mask) {
  299. out.techMask |= LOCATION_TECHNOLOGY_SENSORS_BIT;
  300. }
  301. if (LOC_POS_TECH_MASK_REFERENCE_LOCATION & locationExtended.tech_mask) {
  302. out.techMask |= LOCATION_TECHNOLOGY_REFERENCE_LOCATION_BIT;
  303. }
  304. if (LOC_POS_TECH_MASK_INJECTED_COARSE_POSITION & locationExtended.tech_mask) {
  305. out.techMask |= LOCATION_TECHNOLOGY_INJECTED_COARSE_POSITION_BIT;
  306. }
  307. if (LOC_POS_TECH_MASK_AFLT & locationExtended.tech_mask) {
  308. out.techMask |= LOCATION_TECHNOLOGY_AFLT_BIT;
  309. }
  310. if (LOC_POS_TECH_MASK_HYBRID & locationExtended.tech_mask) {
  311. out.techMask |= LOCATION_TECHNOLOGY_HYBRID_BIT;
  312. }
  313. if (LOC_POS_TECH_MASK_PPE & locationExtended.tech_mask) {
  314. out.techMask |= LOCATION_TECHNOLOGY_PPE_BIT;
  315. }
  316. if (LOC_POS_TECH_MASK_VEH & locationExtended.tech_mask) {
  317. out.techMask |= LOCATION_TECHNOLOGY_VEH_BIT;
  318. }
  319. if (LOC_POS_TECH_MASK_VIS & locationExtended.tech_mask) {
  320. out.techMask |= LOCATION_TECHNOLOGY_VIS_BIT;
  321. }
  322. if (LOC_NAV_MASK_DGNSS_CORRECTION & locationExtended.navSolutionMask) {
  323. out.techMask |= LOCATION_TECHNOLOGY_DGNSS_BIT;
  324. }
  325. if (LOC_GPS_LOCATION_HAS_SPOOF_MASK & ulpLocation.gpsLocation.flags) {
  326. out.flags |= LOCATION_HAS_SPOOF_MASK_BIT;
  327. out.spoofMask = ulpLocation.gpsLocation.spoof_mask;
  328. }
  329. out.qualityType = LOCATION_STANDALONE_QUALITY_TYPE;
  330. if (GPS_LOCATION_EXTENDED_HAS_NAV_SOLUTION_MASK & locationExtended.flags) {
  331. out.flags |= LOCATION_HAS_QUALITY_TYPE_BIT;
  332. if ((LOC_NAV_MASK_RTK_FIXED_CORRECTION & locationExtended.navSolutionMask) &&
  333. (LOC_NAV_MASK_RTK_CORRECTION & locationExtended.navSolutionMask)) {
  334. out.qualityType = LOCATION_FIXED_QUALITY_TYPE;
  335. } else if (LOC_NAV_MASK_RTK_CORRECTION & locationExtended.navSolutionMask) {
  336. out.qualityType = LOCATION_FLOAT_QUALITY_TYPE;
  337. } else if (LOC_NAV_MASK_PPP_CORRECTION & locationExtended.navSolutionMask) {
  338. //If HEPE<5cm, we shall claim 'FIXED'; otherwise, 'FLOAT'
  339. out.qualityType = LOCATION_FLOAT_QUALITY_TYPE;
  340. if ((LOC_GPS_LOCATION_HAS_ACCURACY & ulpLocation.gpsLocation.flags) &&
  341. (ulpLocation.gpsLocation.accuracy < 0.05)) {
  342. out.qualityType = LOCATION_FIXED_QUALITY_TYPE;
  343. }
  344. } else if (LOC_NAV_MASK_DGNSS_CORRECTION & locationExtended.navSolutionMask) {
  345. out.qualityType = LOCATION_DGNSS_QUALITY_TYPE;
  346. }
  347. }
  348. }
  349. void GnssAdapter::fillElapsedRealTime(const GpsLocationExtended& locationExtended,
  350. Location& out) {
  351. if (locationExtended.flags & GPS_LOCATION_EXTENDED_HAS_GPS_TIME) {
  352. int64_t elapsedTimeNs = 0;
  353. float elapsedTimeUncMsec = 0.0;
  354. if (mPositionElapsedRealTimeCal.getElapsedRealtimeForGpsTime(
  355. locationExtended.gpsTime, elapsedTimeNs, elapsedTimeUncMsec)) {
  356. out.flags |= LOCATION_HAS_ELAPSED_REAL_TIME_BIT;
  357. out.elapsedRealTime = elapsedTimeNs;
  358. out.elapsedRealTimeUnc = (int64_t) (elapsedTimeUncMsec * 1000000);
  359. }
  360. #ifndef FEATURE_AUTOMOTIVE
  361. else if (out.timestamp > 0) {
  362. int64_t locationTimeNanos = (int64_t)out.timestamp * 1000000;
  363. bool isCurDataTimeTrustable = (out.timestamp % mLocPositionMode.min_interval == 0);
  364. out.flags |= LOCATION_HAS_ELAPSED_REAL_TIME_BIT;
  365. out.elapsedRealTime = mPositionElapsedRealTimeCal.getElapsedRealtimeEstimateNanos(
  366. locationTimeNanos, isCurDataTimeTrustable,
  367. (int64_t)mLocPositionMode.min_interval * 1000000);
  368. out.elapsedRealTimeUnc = mPositionElapsedRealTimeCal.getElapsedRealtimeUncNanos();
  369. }
  370. #endif //FEATURE_AUTOMOTIVE
  371. }
  372. }
  373. /* This is utility routine that computes number of SV used
  374. in the fix from the svUsedIdsMask.
  375. */
  376. #define MAX_SV_CNT_SUPPORTED_IN_ONE_CONSTELLATION 64
  377. uint16_t GnssAdapter::getNumSvUsed(uint64_t svUsedIdsMask,
  378. int totalSvCntInThisConstellation)
  379. {
  380. if (totalSvCntInThisConstellation > MAX_SV_CNT_SUPPORTED_IN_ONE_CONSTELLATION) {
  381. LOC_LOGe ("error: total SV count in this constellation %d exceeded limit of %d",
  382. totalSvCntInThisConstellation, MAX_SV_CNT_SUPPORTED_IN_ONE_CONSTELLATION);
  383. return 0;
  384. }
  385. uint16_t numSvUsed = 0;
  386. uint64_t mask = 0x1;
  387. for (int i = 0; i < totalSvCntInThisConstellation; i++) {
  388. if (svUsedIdsMask & mask) {
  389. numSvUsed++;
  390. }
  391. mask <<= 1;
  392. }
  393. return numSvUsed;
  394. }
  395. void
  396. GnssAdapter::convertLocationInfo(GnssLocationInfoNotification& out,
  397. const GpsLocationExtended& locationExtended,
  398. enum loc_sess_status status)
  399. {
  400. out.size = sizeof(GnssLocationInfoNotification);
  401. if (GPS_LOCATION_EXTENDED_HAS_ALTITUDE_MEAN_SEA_LEVEL & locationExtended.flags) {
  402. out.flags |= GNSS_LOCATION_INFO_ALTITUDE_MEAN_SEA_LEVEL_BIT;
  403. out.altitudeMeanSeaLevel = locationExtended.altitudeMeanSeaLevel;
  404. }
  405. if (GPS_LOCATION_EXTENDED_HAS_EXT_DOP & locationExtended.flags) {
  406. out.flags |= (GNSS_LOCATION_INFO_DOP_BIT|GNSS_LOCATION_INFO_EXT_DOP_BIT);
  407. out.pdop = locationExtended.extDOP.PDOP;
  408. out.hdop = locationExtended.extDOP.HDOP;
  409. out.vdop = locationExtended.extDOP.VDOP;
  410. out.gdop = locationExtended.extDOP.GDOP;
  411. out.tdop = locationExtended.extDOP.TDOP;
  412. } else if (GPS_LOCATION_EXTENDED_HAS_DOP & locationExtended.flags) {
  413. out.flags |= GNSS_LOCATION_INFO_DOP_BIT;
  414. out.pdop = locationExtended.pdop;
  415. out.hdop = locationExtended.hdop;
  416. out.vdop = locationExtended.vdop;
  417. }
  418. if (GPS_LOCATION_EXTENDED_HAS_MAG_DEV & locationExtended.flags) {
  419. out.flags |= GNSS_LOCATION_INFO_MAGNETIC_DEVIATION_BIT;
  420. out.magneticDeviation = locationExtended.magneticDeviation;
  421. }
  422. if (GPS_LOCATION_EXTENDED_HAS_HOR_RELIABILITY & locationExtended.flags) {
  423. out.flags |= GNSS_LOCATION_INFO_HOR_RELIABILITY_BIT;
  424. switch (locationExtended.horizontal_reliability) {
  425. case LOC_RELIABILITY_VERY_LOW:
  426. out.horReliability = LOCATION_RELIABILITY_VERY_LOW;
  427. break;
  428. case LOC_RELIABILITY_LOW:
  429. out.horReliability = LOCATION_RELIABILITY_LOW;
  430. break;
  431. case LOC_RELIABILITY_MEDIUM:
  432. out.horReliability = LOCATION_RELIABILITY_MEDIUM;
  433. break;
  434. case LOC_RELIABILITY_HIGH:
  435. out.horReliability = LOCATION_RELIABILITY_HIGH;
  436. break;
  437. default:
  438. out.horReliability = LOCATION_RELIABILITY_NOT_SET;
  439. break;
  440. }
  441. }
  442. if (GPS_LOCATION_EXTENDED_HAS_VERT_RELIABILITY & locationExtended.flags) {
  443. out.flags |= GNSS_LOCATION_INFO_VER_RELIABILITY_BIT;
  444. switch (locationExtended.vertical_reliability) {
  445. case LOC_RELIABILITY_VERY_LOW:
  446. out.verReliability = LOCATION_RELIABILITY_VERY_LOW;
  447. break;
  448. case LOC_RELIABILITY_LOW:
  449. out.verReliability = LOCATION_RELIABILITY_LOW;
  450. break;
  451. case LOC_RELIABILITY_MEDIUM:
  452. out.verReliability = LOCATION_RELIABILITY_MEDIUM;
  453. break;
  454. case LOC_RELIABILITY_HIGH:
  455. out.verReliability = LOCATION_RELIABILITY_HIGH;
  456. break;
  457. default:
  458. out.verReliability = LOCATION_RELIABILITY_NOT_SET;
  459. break;
  460. }
  461. }
  462. if (GPS_LOCATION_EXTENDED_HAS_HOR_ELIP_UNC_MAJOR & locationExtended.flags) {
  463. out.flags |= GNSS_LOCATION_INFO_HOR_ACCURACY_ELIP_SEMI_MAJOR_BIT;
  464. out.horUncEllipseSemiMajor = locationExtended.horUncEllipseSemiMajor;
  465. }
  466. if (GPS_LOCATION_EXTENDED_HAS_HOR_ELIP_UNC_MINOR & locationExtended.flags) {
  467. out.flags |= GNSS_LOCATION_INFO_HOR_ACCURACY_ELIP_SEMI_MINOR_BIT;
  468. out.horUncEllipseSemiMinor = locationExtended.horUncEllipseSemiMinor;
  469. }
  470. if (GPS_LOCATION_EXTENDED_HAS_HOR_ELIP_UNC_AZIMUTH & locationExtended.flags) {
  471. out.flags |= GNSS_LOCATION_INFO_HOR_ACCURACY_ELIP_AZIMUTH_BIT;
  472. out.horUncEllipseOrientAzimuth = locationExtended.horUncEllipseOrientAzimuth;
  473. }
  474. if (GPS_LOCATION_EXTENDED_HAS_NORTH_STD_DEV & locationExtended.flags) {
  475. out.flags |= GNSS_LOCATION_INFO_NORTH_STD_DEV_BIT;
  476. out.northStdDeviation = locationExtended.northStdDeviation;
  477. }
  478. if (GPS_LOCATION_EXTENDED_HAS_EAST_STD_DEV & locationExtended.flags) {
  479. out.flags |= GNSS_LOCATION_INFO_EAST_STD_DEV_BIT;
  480. out.eastStdDeviation = locationExtended.eastStdDeviation;
  481. }
  482. if (GPS_LOCATION_EXTENDED_HAS_NORTH_VEL & locationExtended.flags) {
  483. out.flags |= GNSS_LOCATION_INFO_NORTH_VEL_BIT;
  484. out.northVelocity = locationExtended.northVelocity;
  485. }
  486. if (GPS_LOCATION_EXTENDED_HAS_NORTH_VEL_UNC & locationExtended.flags) {
  487. out.flags |= GNSS_LOCATION_INFO_NORTH_VEL_UNC_BIT;
  488. out.northVelocityStdDeviation = locationExtended.northVelocityStdDeviation;
  489. }
  490. if (GPS_LOCATION_EXTENDED_HAS_EAST_VEL & locationExtended.flags) {
  491. out.flags |= GNSS_LOCATION_INFO_EAST_VEL_BIT;
  492. out.eastVelocity = locationExtended.eastVelocity;
  493. }
  494. if (GPS_LOCATION_EXTENDED_HAS_EAST_VEL_UNC & locationExtended.flags) {
  495. out.flags |= GNSS_LOCATION_INFO_EAST_VEL_UNC_BIT;
  496. out.eastVelocityStdDeviation = locationExtended.eastVelocityStdDeviation;
  497. }
  498. if (GPS_LOCATION_EXTENDED_HAS_UP_VEL & locationExtended.flags) {
  499. out.flags |= GNSS_LOCATION_INFO_UP_VEL_BIT;
  500. out.upVelocity = locationExtended.upVelocity;
  501. }
  502. if (GPS_LOCATION_EXTENDED_HAS_UP_VEL_UNC & locationExtended.flags) {
  503. out.flags |= GNSS_LOCATION_INFO_UP_VEL_UNC_BIT;
  504. out.upVelocityStdDeviation = locationExtended.upVelocityStdDeviation;
  505. }
  506. if (GPS_LOCATION_EXTENDED_HAS_GNSS_SV_USED_DATA & locationExtended.flags) {
  507. out.flags |= GNSS_LOCATION_INFO_GNSS_SV_USED_DATA_BIT;
  508. out.svUsedInPosition.gpsSvUsedIdsMask =
  509. locationExtended.gnss_sv_used_ids.gps_sv_used_ids_mask;
  510. out.svUsedInPosition.gloSvUsedIdsMask =
  511. locationExtended.gnss_sv_used_ids.glo_sv_used_ids_mask;
  512. out.svUsedInPosition.galSvUsedIdsMask =
  513. locationExtended.gnss_sv_used_ids.gal_sv_used_ids_mask;
  514. out.svUsedInPosition.bdsSvUsedIdsMask =
  515. locationExtended.gnss_sv_used_ids.bds_sv_used_ids_mask;
  516. out.svUsedInPosition.qzssSvUsedIdsMask =
  517. locationExtended.gnss_sv_used_ids.qzss_sv_used_ids_mask;
  518. out.svUsedInPosition.navicSvUsedIdsMask =
  519. locationExtended.gnss_sv_used_ids.navic_sv_used_ids_mask;
  520. out.flags |= GNSS_LOCATION_INFO_NUM_SV_USED_IN_POSITION_BIT;
  521. out.numSvUsedInPosition = getNumSvUsed(out.svUsedInPosition.gpsSvUsedIdsMask,
  522. GPS_SV_PRN_MAX - GPS_SV_PRN_MIN + 1);
  523. out.numSvUsedInPosition += getNumSvUsed(out.svUsedInPosition.gloSvUsedIdsMask,
  524. GLO_SV_PRN_MAX - GLO_SV_PRN_MIN + 1);
  525. out.numSvUsedInPosition += getNumSvUsed(out.svUsedInPosition.qzssSvUsedIdsMask,
  526. QZSS_SV_PRN_MAX - QZSS_SV_PRN_MIN + 1);
  527. out.numSvUsedInPosition += getNumSvUsed(out.svUsedInPosition.bdsSvUsedIdsMask,
  528. BDS_SV_PRN_MAX - BDS_SV_PRN_MIN + 1);
  529. out.numSvUsedInPosition += getNumSvUsed(out.svUsedInPosition.galSvUsedIdsMask,
  530. GAL_SV_PRN_MAX - GAL_SV_PRN_MIN + 1);
  531. out.numSvUsedInPosition += getNumSvUsed(out.svUsedInPosition.navicSvUsedIdsMask,
  532. NAVIC_SV_PRN_MAX - NAVIC_SV_PRN_MIN + 1);
  533. out.numOfMeasReceived = locationExtended.numOfMeasReceived;
  534. for (int idx =0; idx < locationExtended.numOfMeasReceived; idx++) {
  535. out.measUsageInfo[idx].gnssSignalType =
  536. locationExtended.measUsageInfo[idx].gnssSignalType;
  537. out.measUsageInfo[idx].gnssSvId =
  538. locationExtended.measUsageInfo[idx].gnssSvId;
  539. out.measUsageInfo[idx].gnssConstellation =
  540. locationExtended.measUsageInfo[idx].gnssConstellation;
  541. }
  542. }
  543. if (GPS_LOCATION_EXTENDED_HAS_NAV_SOLUTION_MASK & locationExtended.flags) {
  544. out.flags |= GNSS_LOCATION_INFO_NAV_SOLUTION_MASK_BIT;
  545. out.navSolutionMask = locationExtended.navSolutionMask;
  546. }
  547. if (GPS_LOCATION_EXTENDED_HAS_POS_DYNAMICS_DATA & locationExtended.flags) {
  548. out.flags |= GPS_LOCATION_EXTENDED_HAS_POS_DYNAMICS_DATA;
  549. if (locationExtended.bodyFrameData.bodyFrameDataMask &
  550. LOCATION_NAV_DATA_HAS_LONG_ACCEL_BIT) {
  551. out.bodyFrameData.bodyFrameDataMask |= LOCATION_NAV_DATA_HAS_LONG_ACCEL_BIT;
  552. }
  553. if (locationExtended.bodyFrameData.bodyFrameDataMask &
  554. LOCATION_NAV_DATA_HAS_LAT_ACCEL_BIT) {
  555. out.bodyFrameData.bodyFrameDataMask |= LOCATION_NAV_DATA_HAS_LAT_ACCEL_BIT;
  556. }
  557. if (locationExtended.bodyFrameData.bodyFrameDataMask &
  558. LOCATION_NAV_DATA_HAS_VERT_ACCEL_BIT) {
  559. out.bodyFrameData.bodyFrameDataMask |= LOCATION_NAV_DATA_HAS_VERT_ACCEL_BIT;
  560. }
  561. if (locationExtended.bodyFrameData.bodyFrameDataMask &
  562. LOCATION_NAV_DATA_HAS_YAW_RATE_BIT) {
  563. out.bodyFrameData.bodyFrameDataMask |= LOCATION_NAV_DATA_HAS_YAW_RATE_BIT;
  564. }
  565. if (locationExtended.bodyFrameData.bodyFrameDataMask &
  566. LOCATION_NAV_DATA_HAS_PITCH_BIT) {
  567. out.bodyFrameData.bodyFrameDataMask |= LOCATION_NAV_DATA_HAS_PITCH_BIT;
  568. }
  569. if (locationExtended.bodyFrameData.bodyFrameDataMask &
  570. LOCATION_NAV_DATA_HAS_LONG_ACCEL_UNC_BIT) {
  571. out.bodyFrameData.bodyFrameDataMask |= LOCATION_NAV_DATA_HAS_LONG_ACCEL_UNC_BIT;
  572. }
  573. if (locationExtended.bodyFrameData.bodyFrameDataMask &
  574. LOCATION_NAV_DATA_HAS_LAT_ACCEL_UNC_BIT) {
  575. out.bodyFrameData.bodyFrameDataMask |= LOCATION_NAV_DATA_HAS_LAT_ACCEL_UNC_BIT;
  576. }
  577. if (locationExtended.bodyFrameData.bodyFrameDataMask &
  578. LOCATION_NAV_DATA_HAS_VERT_ACCEL_UNC_BIT) {
  579. out.bodyFrameData.bodyFrameDataMask |= LOCATION_NAV_DATA_HAS_VERT_ACCEL_UNC_BIT;
  580. }
  581. if (locationExtended.bodyFrameData.bodyFrameDataMask &
  582. LOCATION_NAV_DATA_HAS_YAW_RATE_UNC_BIT) {
  583. out.bodyFrameData.bodyFrameDataMask |= LOCATION_NAV_DATA_HAS_YAW_RATE_UNC_BIT;
  584. }
  585. if (locationExtended.bodyFrameData.bodyFrameDataMask &
  586. LOCATION_NAV_DATA_HAS_PITCH_UNC_BIT) {
  587. out.bodyFrameData.bodyFrameDataMask |= LOCATION_NAV_DATA_HAS_PITCH_UNC_BIT;
  588. }
  589. if (locationExtended.bodyFrameDataExt.bodyFrameDataMask &
  590. LOCATION_NAV_DATA_HAS_PITCH_RATE_BIT) {
  591. out.bodyFrameDataExt.bodyFrameDataMask |= LOCATION_NAV_DATA_HAS_PITCH_RATE_BIT;
  592. }
  593. if (locationExtended.bodyFrameDataExt.bodyFrameDataMask &
  594. LOCATION_NAV_DATA_HAS_PITCH_RATE_UNC_BIT) {
  595. out.bodyFrameDataExt.bodyFrameDataMask |= LOCATION_NAV_DATA_HAS_PITCH_RATE_UNC_BIT;
  596. }
  597. if (locationExtended.bodyFrameDataExt.bodyFrameDataMask &
  598. LOCATION_NAV_DATA_HAS_ROLL_BIT) {
  599. out.bodyFrameDataExt.bodyFrameDataMask |= LOCATION_NAV_DATA_HAS_ROLL_BIT;
  600. }
  601. if (locationExtended.bodyFrameDataExt.bodyFrameDataMask &
  602. LOCATION_NAV_DATA_HAS_ROLL_UNC_BIT) {
  603. out.bodyFrameDataExt.bodyFrameDataMask |= LOCATION_NAV_DATA_HAS_ROLL_UNC_BIT;
  604. }
  605. if (locationExtended.bodyFrameDataExt.bodyFrameDataMask &
  606. LOCATION_NAV_DATA_HAS_ROLL_RATE_BIT) {
  607. out.bodyFrameDataExt.bodyFrameDataMask |= LOCATION_NAV_DATA_HAS_ROLL_RATE_BIT;
  608. }
  609. if (locationExtended.bodyFrameDataExt.bodyFrameDataMask &
  610. LOCATION_NAV_DATA_HAS_ROLL_RATE_UNC_BIT) {
  611. out.bodyFrameDataExt.bodyFrameDataMask |= LOCATION_NAV_DATA_HAS_ROLL_RATE_UNC_BIT;
  612. }
  613. if (locationExtended.bodyFrameDataExt.bodyFrameDataMask &
  614. LOCATION_NAV_DATA_HAS_YAW_BIT) {
  615. out.bodyFrameDataExt.bodyFrameDataMask |= LOCATION_NAV_DATA_HAS_YAW_BIT;
  616. }
  617. if (locationExtended.bodyFrameDataExt.bodyFrameDataMask &
  618. LOCATION_NAV_DATA_HAS_YAW_UNC_BIT) {
  619. out.bodyFrameDataExt.bodyFrameDataMask |= LOCATION_NAV_DATA_HAS_YAW_UNC_BIT;
  620. }
  621. out.bodyFrameData.longAccel = locationExtended.bodyFrameData.longAccel;
  622. out.bodyFrameData.latAccel = locationExtended.bodyFrameData.latAccel;
  623. out.bodyFrameData.vertAccel = locationExtended.bodyFrameData.vertAccel;
  624. out.bodyFrameData.yawRate = locationExtended.bodyFrameData.yawRate;
  625. out.bodyFrameData.pitch = locationExtended.bodyFrameData.pitch;
  626. out.bodyFrameData.longAccelUnc = locationExtended.bodyFrameData.longAccelUnc;
  627. out.bodyFrameData.latAccelUnc = locationExtended.bodyFrameData.latAccelUnc;
  628. out.bodyFrameData.vertAccelUnc = locationExtended.bodyFrameData.vertAccelUnc;
  629. out.bodyFrameData.yawRateUnc = locationExtended.bodyFrameData.yawRateUnc;
  630. out.bodyFrameData.pitchUnc = locationExtended.bodyFrameData.pitchUnc;
  631. out.bodyFrameDataExt.pitchRate = locationExtended.bodyFrameDataExt.pitchRate;
  632. out.bodyFrameDataExt.pitchRateUnc = locationExtended.bodyFrameDataExt.pitchRateUnc;
  633. out.bodyFrameDataExt.roll = locationExtended.bodyFrameDataExt.roll;
  634. out.bodyFrameDataExt.rollUnc = locationExtended.bodyFrameDataExt.rollUnc;
  635. out.bodyFrameDataExt.rollRate = locationExtended.bodyFrameDataExt.rollRate;
  636. out.bodyFrameDataExt.rollRateUnc = locationExtended.bodyFrameDataExt.rollRateUnc;
  637. out.bodyFrameDataExt.yaw = locationExtended.bodyFrameDataExt.yaw;
  638. out.bodyFrameDataExt.yawUnc = locationExtended.bodyFrameDataExt.yawUnc;
  639. }
  640. // Validity of this structure is established from the timeSrc of the GnssSystemTime structure.
  641. out.gnssSystemTime = locationExtended.gnssSystemTime;
  642. if (GPS_LOCATION_EXTENDED_HAS_LEAP_SECONDS & locationExtended.flags) {
  643. out.flags |= GNSS_LOCATION_INFO_LEAP_SECONDS_BIT;
  644. out.leapSeconds = locationExtended.leapSeconds;
  645. }
  646. if (GPS_LOCATION_EXTENDED_HAS_TIME_UNC & locationExtended.flags) {
  647. out.flags |= GNSS_LOCATION_INFO_TIME_UNC_BIT;
  648. out.timeUncMs = locationExtended.timeUncMs;
  649. }
  650. if (GPS_LOCATION_EXTENDED_HAS_CALIBRATION_CONFIDENCE & locationExtended.flags) {
  651. out.flags |= GNSS_LOCATION_INFO_CALIBRATION_CONFIDENCE_BIT;
  652. out.calibrationConfidence = locationExtended.calibrationConfidence;
  653. }
  654. if (GPS_LOCATION_EXTENDED_HAS_CALIBRATION_STATUS & locationExtended.flags) {
  655. out.flags |= GNSS_LOCATION_INFO_CALIBRATION_STATUS_BIT;
  656. out.calibrationStatus = locationExtended.calibrationStatus;
  657. }
  658. if (GPS_LOCATION_EXTENDED_HAS_OUTPUT_ENG_TYPE & locationExtended.flags) {
  659. out.flags |= GNSS_LOCATION_INFO_OUTPUT_ENG_TYPE_BIT;
  660. out.locOutputEngType = locationExtended.locOutputEngType;
  661. }
  662. if (GPS_LOCATION_EXTENDED_HAS_OUTPUT_ENG_MASK & locationExtended.flags) {
  663. out.flags |= GNSS_LOCATION_INFO_OUTPUT_ENG_MASK_BIT;
  664. out.locOutputEngMask = locationExtended.locOutputEngMask;
  665. }
  666. if (GPS_LOCATION_EXTENDED_HAS_CONFORMITY_INDEX & locationExtended.flags) {
  667. out.flags |= GNSS_LOCATION_INFO_CONFORMITY_INDEX_BIT;
  668. out.conformityIndex = locationExtended.conformityIndex;
  669. }
  670. if (GPS_LOCATION_EXTENDED_HAS_LLA_VRP_BASED & locationExtended.flags) {
  671. out.flags |= GNSS_LOCATION_INFO_LLA_VRP_BASED_BIT;
  672. out.llaVRPBased = locationExtended.llaVRPBased;
  673. }
  674. if (GPS_LOCATION_EXTENDED_HAS_ENU_VELOCITY_LLA_VRP_BASED & locationExtended.flags) {
  675. out.flags |= GNSS_LOCATION_INFO_ENU_VELOCITY_VRP_BASED_BIT;
  676. // copy over east, north and up vrp based velocity
  677. out.enuVelocityVRPBased[0] = locationExtended.enuVelocityVRPBased[0];
  678. out.enuVelocityVRPBased[1] = locationExtended.enuVelocityVRPBased[1];
  679. out.enuVelocityVRPBased[2] = locationExtended.enuVelocityVRPBased[2];
  680. }
  681. if (GPS_LOCATION_EXTENDED_HAS_DR_SOLUTION_STATUS_MASK & locationExtended.flags) {
  682. out.flags |= GNSS_LOCATION_INFO_DR_SOLUTION_STATUS_MASK_BIT;
  683. out.drSolutionStatusMask = locationExtended.drSolutionStatusMask;
  684. }
  685. if (GPS_LOCATION_EXTENDED_HAS_ALTITUDE_ASSUMED & locationExtended.flags) {
  686. out.flags |= GNSS_LOCATION_INFO_ALTITUDE_ASSUMED_BIT;
  687. out.altitudeAssumed = locationExtended.altitudeAssumed;
  688. }
  689. out.flags |= GNSS_LOCATION_INFO_SESSION_STATUS_BIT;
  690. out.sessionStatus = status;
  691. }
  692. inline uint32_t
  693. GnssAdapter::convertSuplVersion(const GnssConfigSuplVersion suplVersion)
  694. {
  695. switch (suplVersion) {
  696. case GNSS_CONFIG_SUPL_VERSION_2_0_4:
  697. return 0x00020004;
  698. case GNSS_CONFIG_SUPL_VERSION_2_0_0:
  699. return 0x00020000;
  700. case GNSS_CONFIG_SUPL_VERSION_2_0_2:
  701. return 0x00020002;
  702. case GNSS_CONFIG_SUPL_VERSION_1_0_0:
  703. default:
  704. return 0x00010000;
  705. }
  706. }
  707. uint32_t
  708. GnssAdapter::convertLppeCp(const GnssConfigLppeControlPlaneMask lppeControlPlaneMask)
  709. {
  710. uint32_t mask = 0;
  711. if (GNSS_CONFIG_LPPE_CONTROL_PLANE_DBH_BIT & lppeControlPlaneMask) {
  712. mask |= (1<<0);
  713. }
  714. if (GNSS_CONFIG_LPPE_CONTROL_PLANE_WLAN_AP_MEASUREMENTS_BIT & lppeControlPlaneMask) {
  715. mask |= (1<<1);
  716. }
  717. if (GNSS_CONFIG_LPPE_CONTROL_PLANE_SRN_AP_MEASUREMENTS_BIT & lppeControlPlaneMask) {
  718. mask |= (1<<2);
  719. }
  720. if (GNSS_CONFIG_LPPE_CONTROL_PLANE_SENSOR_BARO_MEASUREMENTS_BIT & lppeControlPlaneMask) {
  721. mask |= (1<<3);
  722. }
  723. if (GNSS_CONFIG_LPPE_CONTROL_PLANE_NON_E911_BIT & lppeControlPlaneMask) {
  724. mask |= (1<<4);
  725. }
  726. if (GNSS_CONFIG_LPPE_CONTROL_PLANE_CIV_ADDRESS_BIT & lppeControlPlaneMask) {
  727. mask |= (1<<5);
  728. }
  729. return mask;
  730. }
  731. uint32_t
  732. GnssAdapter::convertLppeUp(const GnssConfigLppeUserPlaneMask lppeUserPlaneMask)
  733. {
  734. uint32_t mask = 0;
  735. if (GNSS_CONFIG_LPPE_USER_PLANE_DBH_BIT & lppeUserPlaneMask) {
  736. mask |= (1<<0);
  737. }
  738. if (GNSS_CONFIG_LPPE_USER_PLANE_WLAN_AP_MEASUREMENTS_BIT & lppeUserPlaneMask) {
  739. mask |= (1<<1);
  740. }
  741. if (GNSS_CONFIG_LPPE_USER_PLANE_SRN_AP_MEASUREMENTS_BIT & lppeUserPlaneMask) {
  742. mask |= (1<<2);
  743. }
  744. if (GNSS_CONFIG_LPPE_USER_PLANE_SENSOR_BARO_MEASUREMENTS_BIT & lppeUserPlaneMask) {
  745. mask |= (1<<3);
  746. }
  747. if (GNSS_CONFIG_LPPE_USER_PLANE_NON_E911_BIT & lppeUserPlaneMask) {
  748. mask |= (1<<4);
  749. }
  750. if (GNSS_CONFIG_LPPE_USER_PLANE_CIV_ADDRESS_BIT & lppeUserPlaneMask) {
  751. mask |= (1<<5);
  752. }
  753. return mask;
  754. }
  755. uint32_t
  756. GnssAdapter::convertAGloProt(const GnssConfigAGlonassPositionProtocolMask aGloPositionProtocolMask)
  757. {
  758. uint32_t mask = 0;
  759. if (GNSS_CONFIG_RRC_CONTROL_PLANE_BIT & aGloPositionProtocolMask) {
  760. mask |= (1<<0);
  761. }
  762. if (GNSS_CONFIG_RRLP_USER_PLANE_BIT & aGloPositionProtocolMask) {
  763. mask |= (1<<1);
  764. }
  765. if (GNSS_CONFIG_LLP_USER_PLANE_BIT & aGloPositionProtocolMask) {
  766. mask |= (1<<2);
  767. }
  768. if (GNSS_CONFIG_LLP_CONTROL_PLANE_BIT & aGloPositionProtocolMask) {
  769. mask |= (1<<3);
  770. }
  771. return mask;
  772. }
  773. uint32_t
  774. GnssAdapter::convertEP4ES(const GnssConfigEmergencyPdnForEmergencySupl emergencyPdnForEmergencySupl)
  775. {
  776. switch (emergencyPdnForEmergencySupl) {
  777. case GNSS_CONFIG_EMERGENCY_PDN_FOR_EMERGENCY_SUPL_YES:
  778. return 1;
  779. case GNSS_CONFIG_EMERGENCY_PDN_FOR_EMERGENCY_SUPL_NO:
  780. default:
  781. return 0;
  782. }
  783. }
  784. uint32_t
  785. GnssAdapter::convertSuplEs(const GnssConfigSuplEmergencyServices suplEmergencyServices)
  786. {
  787. switch (suplEmergencyServices) {
  788. case GNSS_CONFIG_SUPL_EMERGENCY_SERVICES_YES:
  789. return 1;
  790. case GNSS_CONFIG_SUPL_EMERGENCY_SERVICES_NO:
  791. default:
  792. return 0;
  793. }
  794. }
  795. uint32_t
  796. GnssAdapter::convertSuplMode(const GnssConfigSuplModeMask suplModeMask)
  797. {
  798. uint32_t mask = 0;
  799. if (GNSS_CONFIG_SUPL_MODE_MSB_BIT & suplModeMask) {
  800. mask |= (1<<0);
  801. }
  802. if (GNSS_CONFIG_SUPL_MODE_MSA_BIT & suplModeMask) {
  803. mask |= (1<<1);
  804. }
  805. return mask;
  806. }
  807. void GnssAdapter::readNfwLockConfig()
  808. {
  809. char nfwCpPackageName[LOC_MAX_PARAM_STRING];
  810. char nfwSuplPackageName[LOC_MAX_PARAM_STRING];
  811. char nfwImsPackageName[LOC_MAX_PARAM_STRING];
  812. char nfwSimPackageName[LOC_MAX_PARAM_STRING];
  813. char nfwMdtPackageName[LOC_MAX_PARAM_STRING];
  814. char nfwTlocPackageName[LOC_MAX_PARAM_STRING];
  815. char nfwRlocPackageName[LOC_MAX_PARAM_STRING];
  816. char nfwV2xPackageName[LOC_MAX_PARAM_STRING];
  817. char nfwR1PackageName[LOC_MAX_PARAM_STRING];
  818. char nfwR2PackageName[LOC_MAX_PARAM_STRING];
  819. char nfwR3PackageName[LOC_MAX_PARAM_STRING];
  820. const loc_param_s_type nfw_packages_table[] =
  821. {
  822. { "NFW_CLIENT_CP", &nfwCpPackageName, NULL, 's' },
  823. { "NFW_CLIENT_SUPL", &nfwSuplPackageName, NULL, 's' },
  824. { "NFW_CLIENT_IMS", &nfwImsPackageName, NULL, 's' },
  825. { "NFW_CLIENT_SIM", &nfwSimPackageName, NULL, 's' },
  826. { "NFW_CLIENT_MDT", &nfwMdtPackageName, NULL, 's' },
  827. { "NFW_CLIENT_TLOC", &nfwTlocPackageName, NULL, 's' },
  828. { "NFW_CLIENT_RLOC", &nfwRlocPackageName, NULL, 's' },
  829. { "NFW_CLIENT_V2X", &nfwV2xPackageName, NULL, 's' },
  830. { "NFW_CLIENT_R1", &nfwR1PackageName, NULL, 's' },
  831. { "NFW_CLIENT_R2", &nfwR2PackageName, NULL, 's' },
  832. { "NFW_CLIENT_R3", &nfwR3PackageName, NULL, 's' },
  833. };
  834. UTIL_READ_CONF(LOC_PATH_GPS_CONF_STR, nfw_packages_table);
  835. mNfws[nfwImsPackageName] |= GNSS_CONFIG_GPS_LOCK_NFW_IMS;
  836. mNfws[nfwSimPackageName] |= GNSS_CONFIG_GPS_LOCK_NFW_SIM;
  837. mNfws[nfwMdtPackageName] |= GNSS_CONFIG_GPS_LOCK_NFW_MDT;
  838. mNfws[nfwTlocPackageName] |= GNSS_CONFIG_GPS_LOCK_NFW_TLOC;
  839. mNfws[nfwRlocPackageName] |= GNSS_CONFIG_GPS_LOCK_NFW_RLOC;
  840. mNfws[nfwV2xPackageName] |= GNSS_CONFIG_GPS_LOCK_NFW_V2X;
  841. mNfws[nfwR1PackageName] |= GNSS_CONFIG_GPS_LOCK_NFW_R1;
  842. mNfws[nfwR2PackageName] |= GNSS_CONFIG_GPS_LOCK_NFW_R2;
  843. mNfws[nfwR3PackageName] |= GNSS_CONFIG_GPS_LOCK_NFW_R3;
  844. mNfws[nfwSuplPackageName] |= GNSS_CONFIG_GPS_LOCK_NFW_SUPL;
  845. mNfws[nfwCpPackageName] |= GNSS_CONFIG_GPS_LOCK_NFW_CP;
  846. }
  847. void
  848. GnssAdapter::readConfigCommand()
  849. {
  850. LOC_LOGD("%s]: ", __func__);
  851. struct MsgReadConfig : public LocMsg {
  852. GnssAdapter* mAdapter;
  853. ContextBase& mContext;
  854. inline MsgReadConfig(GnssAdapter* adapter,
  855. ContextBase& context) :
  856. LocMsg(),
  857. mAdapter(adapter),
  858. mContext(context) {}
  859. inline virtual void proc() const {
  860. static bool confReadDone = false;
  861. if (!confReadDone) {
  862. confReadDone = true;
  863. // reads config into mContext->mGps_conf
  864. mContext.readConfig();
  865. mAdapter->readNfwLockConfig();
  866. }
  867. }
  868. };
  869. if (mContext != NULL) {
  870. sendMsg(new MsgReadConfig(this, *mContext));
  871. }
  872. }
  873. void
  874. GnssAdapter::setSuplHostServer(const char* server, int port, LocServerType type)
  875. {
  876. if (ContextBase::mGps_conf.AGPS_CONFIG_INJECT) {
  877. char serverUrl[MAX_URL_LEN] = {};
  878. int32_t length = -1;
  879. const char noHost[] = "NONE";
  880. if ((NULL == server) || (server[0] == 0) ||
  881. (strncasecmp(noHost, server, sizeof(noHost)) == 0)) {
  882. serverUrl[0] = '\0';
  883. length = 0;
  884. } else if (port > 0) {
  885. length = snprintf(serverUrl, sizeof(serverUrl), "%s:%u", server, port);
  886. }
  887. if (LOC_AGPS_SUPL_SERVER != type && LOC_AGPS_MO_SUPL_SERVER != type) {
  888. LOC_LOGe("Invalid type=%d", type);
  889. } else if (length >= 0) {
  890. if (LOC_AGPS_SUPL_SERVER == type) {
  891. getServerUrl().assign(serverUrl);
  892. strlcpy(ContextBase::mGps_conf.SUPL_HOST,
  893. (nullptr == server) ? serverUrl : server,
  894. LOC_MAX_PARAM_STRING);
  895. ContextBase::mGps_conf.SUPL_PORT = port;
  896. } else {
  897. if (strncasecmp(getMoServerUrl().c_str(), serverUrl, sizeof(serverUrl)) != 0) {
  898. getMoServerUrl().assign(serverUrl);
  899. }
  900. }
  901. }
  902. }
  903. }
  904. void
  905. GnssAdapter::setConfig()
  906. {
  907. LOC_LOGD("%s]: ", __func__);
  908. // set nmea mask type
  909. uint32_t mask = 0;
  910. if (NMEA_PROVIDER_MP == ContextBase::mGps_conf.NMEA_PROVIDER) {
  911. mask |= LOC_NMEA_ALL_GENERAL_SUPPORTED_MASK;
  912. if (ContextBase::mGps_conf.NMEA_TAG_BLOCK_GROUPING_ENABLED) {
  913. mask |= LOC_NMEA_MASK_TAGBLOCK_V02;
  914. }
  915. }
  916. if (ContextBase::isFeatureSupported(LOC_SUPPORTED_FEATURE_DEBUG_NMEA_V02)) {
  917. mask |= LOC_NMEA_MASK_DEBUG_V02;
  918. }
  919. if (mNmeaMask != mask) {
  920. mNmeaMask = mask;
  921. if (mNmeaMask) {
  922. for (auto it=mClientData.begin(); it != mClientData.end(); ++it) {
  923. if ((it->second.gnssNmeaCb != nullptr)) {
  924. updateEvtMask(LOC_API_ADAPTER_BIT_NMEA_1HZ_REPORT,
  925. LOC_REGISTRATION_MASK_ENABLED);
  926. break;
  927. }
  928. }
  929. }
  930. }
  931. std::string oldMoServerUrl = getMoServerUrl();
  932. setSuplHostServer(ContextBase::mGps_conf.SUPL_HOST,
  933. ContextBase::mGps_conf.SUPL_PORT,
  934. LOC_AGPS_SUPL_SERVER);
  935. setSuplHostServer(ContextBase::mGps_conf.MO_SUPL_HOST,
  936. ContextBase::mGps_conf.MO_SUPL_PORT,
  937. LOC_AGPS_MO_SUPL_SERVER);
  938. std::string moServerUrl = getMoServerUrl();
  939. std::string serverUrl = getServerUrl();
  940. // inject the configurations into modem
  941. loc_gps_cfg_s gpsConf = ContextBase::mGps_conf;
  942. loc_sap_cfg_s_type sapConf = ContextBase::mSap_conf;
  943. //cache the injected configuration with GnssConfigRequested struct
  944. GnssConfig gnssConfigRequested = {};
  945. gnssConfigRequested.flags |= GNSS_CONFIG_FLAGS_GPS_LOCK_VALID_BIT |
  946. GNSS_CONFIG_FLAGS_BLACKLISTED_SV_IDS_BIT;
  947. /* Here we process an SSR. We need to set the GPS_LOCK to the proper values, as follows:
  948. 1. Q behavior. This is identified by mSupportNfwControl being 1. In this case
  949. ContextBase::mGps_conf.GPS_LOCK is a "state", meaning it should reflect the
  950. NV value. Therefore we will set the NV to ContextBase::mGps_conf.GPS_LOCK
  951. 2. P behavior. This is identified by mSupportNfwControl being 0. In this case
  952. ContextBase::mGps_conf.GPS_LOCK is a "configuration", meaning it should hold
  953. the "mask" for NI. There are two subcases:
  954. a. Location enabled in GUI (1 == getAfwControlId()). We need to set
  955. the NV to GNSS_CONFIG_GPS_LOCK_NONE (both MO and NI enabled)
  956. b. Location disabled in GUI (0 == getAfwControlId()). We need to set
  957. the NV to ContextBase::mGps_conf.GPS_LOCK (the "mask", which is SIM-card
  958. specific)
  959. */
  960. if (mSupportNfwControl || (0 == getAfwControlId())) {
  961. gnssConfigRequested.gpsLock = gpsConf.GPS_LOCK;
  962. } else {
  963. gnssConfigRequested.gpsLock = GNSS_CONFIG_GPS_LOCK_NONE;
  964. }
  965. gnssConfigRequested.flags |= GNSS_CONFIG_FLAGS_SET_ASSISTANCE_DATA_VALID_BIT |
  966. GNSS_CONFIG_FLAGS_SUPL_VERSION_VALID_BIT |
  967. GNSS_CONFIG_FLAGS_AGLONASS_POSITION_PROTOCOL_VALID_BIT |
  968. GNSS_CONFIG_FLAGS_LPP_PROFILE_VALID_BIT;
  969. gnssConfigRequested.suplVersion = mLocApi->convertSuplVersion(gpsConf.SUPL_VER);
  970. gnssConfigRequested.lppProfileMask = gpsConf.LPP_PROFILE;
  971. gnssConfigRequested.aGlonassPositionProtocolMask = gpsConf.A_GLONASS_POS_PROTOCOL_SELECT;
  972. if (gpsConf.LPPE_CP_TECHNOLOGY) {
  973. gnssConfigRequested.flags |= GNSS_CONFIG_FLAGS_LPPE_CONTROL_PLANE_VALID_BIT;
  974. gnssConfigRequested.lppeControlPlaneMask =
  975. mLocApi->convertLppeCp(gpsConf.LPPE_CP_TECHNOLOGY);
  976. }
  977. if (gpsConf.LPPE_UP_TECHNOLOGY) {
  978. gnssConfigRequested.flags |= GNSS_CONFIG_FLAGS_LPPE_USER_PLANE_VALID_BIT;
  979. gnssConfigRequested.lppeUserPlaneMask =
  980. mLocApi->convertLppeUp(gpsConf.LPPE_UP_TECHNOLOGY);
  981. }
  982. gnssConfigRequested.blacklistedSvIds.assign(mBlacklistedSvIds.begin(),
  983. mBlacklistedSvIds.end());
  984. mLocApi->sendMsg(new LocApiMsg(
  985. [this, gpsConf, sapConf, oldMoServerUrl, moServerUrl,
  986. serverUrl, gnssConfigRequested] () mutable {
  987. gnssUpdateConfig(oldMoServerUrl, moServerUrl, serverUrl,
  988. gnssConfigRequested, gnssConfigRequested);
  989. // set nmea mask type
  990. uint32_t mask = 0;
  991. if (NMEA_PROVIDER_MP == gpsConf.NMEA_PROVIDER) {
  992. mask |= LOC_NMEA_ALL_GENERAL_SUPPORTED_MASK;
  993. if (gpsConf.NMEA_TAG_BLOCK_GROUPING_ENABLED) {
  994. mask |= LOC_NMEA_MASK_TAGBLOCK_V02;
  995. }
  996. }
  997. if (ContextBase::isFeatureSupported(LOC_SUPPORTED_FEATURE_DEBUG_NMEA_V02)) {
  998. mask |= LOC_NMEA_MASK_DEBUG_V02;
  999. }
  1000. if (mask != 0) {
  1001. mLocApi->setNMEATypesSync(mask);
  1002. }
  1003. // load tunc configuration from config file on first boot-up,
  1004. // e.g.: adapter.mLocConfigInfo.tuncConfigInfo.isValid is false
  1005. if (mLocConfigInfo.tuncConfigInfo.isValid == false) {
  1006. mLocConfigInfo.tuncConfigInfo.isValid = true;
  1007. mLocConfigInfo.tuncConfigInfo.enable =
  1008. (gpsConf.CONSTRAINED_TIME_UNCERTAINTY_ENABLED == 1);
  1009. mLocConfigInfo.tuncConfigInfo.tuncThresholdMs =
  1010. (float)gpsConf.CONSTRAINED_TIME_UNCERTAINTY_THRESHOLD;
  1011. mLocConfigInfo.tuncConfigInfo.energyBudget =
  1012. gpsConf.CONSTRAINED_TIME_UNCERTAINTY_ENERGY_BUDGET;
  1013. }
  1014. mLocApi->setConstrainedTuncMode(
  1015. mLocConfigInfo.tuncConfigInfo.enable,
  1016. mLocConfigInfo.tuncConfigInfo.tuncThresholdMs,
  1017. mLocConfigInfo.tuncConfigInfo.energyBudget);
  1018. // load pace configuration from config file on first boot-up,
  1019. // e.g.: adapter.mLocConfigInfo.paceConfigInfo.isValid is false
  1020. if (mLocConfigInfo.paceConfigInfo.isValid == false) {
  1021. mLocConfigInfo.paceConfigInfo.isValid = true;
  1022. mLocConfigInfo.paceConfigInfo.enable =
  1023. (gpsConf.POSITION_ASSISTED_CLOCK_ESTIMATOR_ENABLED==1);
  1024. }
  1025. mLocApi->setPositionAssistedClockEstimatorMode(
  1026. mLocConfigInfo.paceConfigInfo.enable);
  1027. // load robust location configuration from config file on first boot-up,
  1028. // e.g.: adapter.mLocConfigInfo.robustLocationConfigInfo.isValid is false
  1029. if (mLocConfigInfo.robustLocationConfigInfo.isValid == false) {
  1030. mLocConfigInfo.robustLocationConfigInfo.isValid = true;
  1031. bool robustLocationEnabled = (gpsConf.ROBUST_LOCATION_ENABLED & 0x01);
  1032. bool robustLocationE911Enabled = robustLocationEnabled ?
  1033. ((gpsConf.ROBUST_LOCATION_ENABLED & 0x02) != 0) : false;
  1034. mLocConfigInfo.robustLocationConfigInfo.enable = robustLocationEnabled;
  1035. mLocConfigInfo.robustLocationConfigInfo.enableFor911 = robustLocationE911Enabled;
  1036. }
  1037. mLocApi->configRobustLocation(
  1038. mLocConfigInfo.robustLocationConfigInfo.enable,
  1039. mLocConfigInfo.robustLocationConfigInfo.enableFor911);
  1040. if (sapConf.GYRO_BIAS_RANDOM_WALK_VALID ||
  1041. sapConf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY_VALID ||
  1042. sapConf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY_VALID ||
  1043. sapConf.RATE_RANDOM_WALK_SPECTRAL_DENSITY_VALID ||
  1044. sapConf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY_VALID ) {
  1045. mLocApi->setSensorPropertiesSync(
  1046. sapConf.GYRO_BIAS_RANDOM_WALK_VALID,
  1047. sapConf.GYRO_BIAS_RANDOM_WALK,
  1048. sapConf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY_VALID,
  1049. sapConf.ACCEL_RANDOM_WALK_SPECTRAL_DENSITY,
  1050. sapConf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY_VALID,
  1051. sapConf.ANGLE_RANDOM_WALK_SPECTRAL_DENSITY,
  1052. sapConf.RATE_RANDOM_WALK_SPECTRAL_DENSITY_VALID,
  1053. sapConf.RATE_RANDOM_WALK_SPECTRAL_DENSITY,
  1054. sapConf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY_VALID,
  1055. sapConf.VELOCITY_RANDOM_WALK_SPECTRAL_DENSITY);
  1056. }
  1057. mLocApi->setSensorPerfControlConfigSync(
  1058. sapConf.SENSOR_CONTROL_MODE,
  1059. sapConf.SENSOR_ACCEL_SAMPLES_PER_BATCH,
  1060. sapConf.SENSOR_ACCEL_BATCHES_PER_SEC,
  1061. sapConf.SENSOR_GYRO_SAMPLES_PER_BATCH,
  1062. sapConf.SENSOR_GYRO_BATCHES_PER_SEC,
  1063. sapConf.SENSOR_ACCEL_SAMPLES_PER_BATCH_HIGH,
  1064. sapConf.SENSOR_ACCEL_BATCHES_PER_SEC_HIGH,
  1065. sapConf.SENSOR_GYRO_SAMPLES_PER_BATCH_HIGH,
  1066. sapConf.SENSOR_GYRO_BATCHES_PER_SEC_HIGH,
  1067. sapConf.SENSOR_ALGORITHM_CONFIG_MASK);
  1068. } ));
  1069. // deal with Measurement Corrections
  1070. if (true == mIsMeasCorrInterfaceOpen) {
  1071. initMeasCorr(true);
  1072. }
  1073. }
  1074. std::vector<LocationError> GnssAdapter::gnssUpdateConfig(const std::string& oldMoServerUrl,
  1075. const std::string& moServerUrl, const std::string& serverUrl,
  1076. GnssConfig& gnssConfigRequested, GnssConfig& gnssConfigNeedEngineUpdate, size_t count) {
  1077. size_t index = 0;
  1078. LocationError err = LOCATION_ERROR_SUCCESS;
  1079. std::vector<LocationError> errsList = {err};
  1080. if (count > 0) {
  1081. errsList.insert(errsList.begin(), count, LOCATION_ERROR_SUCCESS);
  1082. }
  1083. int serverUrlLen = serverUrl.length();
  1084. int moServerUrlLen = moServerUrl.length();
  1085. if (!ContextBase::mGps_conf.AGPS_CONFIG_INJECT) {
  1086. LOC_LOGd("AGPS_CONFIG_INJECT is 0. Not setting flags for AGPS configurations");
  1087. gnssConfigRequested.flags &= ~(GNSS_CONFIG_FLAGS_SET_ASSISTANCE_DATA_VALID_BIT |
  1088. GNSS_CONFIG_FLAGS_SUPL_VERSION_VALID_BIT |
  1089. GNSS_CONFIG_FLAGS_AGLONASS_POSITION_PROTOCOL_VALID_BIT |
  1090. GNSS_CONFIG_FLAGS_LPP_PROFILE_VALID_BIT |
  1091. GNSS_CONFIG_FLAGS_LPPE_CONTROL_PLANE_VALID_BIT |
  1092. GNSS_CONFIG_FLAGS_LPPE_CONTROL_PLANE_VALID_BIT);
  1093. }
  1094. if (gnssConfigRequested.flags & GNSS_CONFIG_FLAGS_GPS_LOCK_VALID_BIT) {
  1095. if (gnssConfigNeedEngineUpdate.flags & GNSS_CONFIG_FLAGS_GPS_LOCK_VALID_BIT) {
  1096. err = mLocApi->setGpsLockSync(gnssConfigRequested.gpsLock);
  1097. if (index < count) {
  1098. errsList[index] = err;
  1099. }
  1100. }
  1101. index++;
  1102. }
  1103. if (gnssConfigRequested.flags &
  1104. GNSS_CONFIG_FLAGS_SET_ASSISTANCE_DATA_VALID_BIT) {
  1105. if (gnssConfigNeedEngineUpdate.flags &
  1106. GNSS_CONFIG_FLAGS_SET_ASSISTANCE_DATA_VALID_BIT) {
  1107. if (gnssConfigNeedEngineUpdate.assistanceServer.type ==
  1108. GNSS_ASSISTANCE_TYPE_SUPL) {
  1109. err = mLocApi->setServerSync(
  1110. serverUrl.c_str(), serverUrlLen, LOC_AGPS_SUPL_SERVER);
  1111. if (index < count) {
  1112. errsList[index] = err;
  1113. }
  1114. if (0 != oldMoServerUrl.compare(moServerUrl)) {
  1115. LocationError locErr =
  1116. mLocApi->setServerSync(moServerUrl.c_str(),
  1117. moServerUrlLen,
  1118. LOC_AGPS_MO_SUPL_SERVER);
  1119. if (locErr != LOCATION_ERROR_SUCCESS) {
  1120. LOC_LOGe("Error while setting MO SUPL_HOST server:%s",
  1121. moServerUrl.c_str());
  1122. }
  1123. }
  1124. } else if (gnssConfigNeedEngineUpdate.assistanceServer.type ==
  1125. GNSS_ASSISTANCE_TYPE_C2K) {
  1126. struct in_addr addr;
  1127. struct hostent* hp;
  1128. bool resolveAddrSuccess = true;
  1129. hp = gethostbyname(
  1130. gnssConfigNeedEngineUpdate.assistanceServer.hostName);
  1131. if (hp != NULL) { /* DNS OK */
  1132. memcpy(&addr, hp->h_addr_list[0], hp->h_length);
  1133. } else {
  1134. /* Try IP representation */
  1135. if (inet_aton(
  1136. gnssConfigNeedEngineUpdate.assistanceServer.hostName,
  1137. &addr) == 0) {
  1138. /* IP not valid */
  1139. LOC_LOGE("%s]: hostname '%s' cannot be resolved ",
  1140. __func__,
  1141. gnssConfigNeedEngineUpdate.assistanceServer.hostName);
  1142. if (index < count) {
  1143. errsList[index] = LOCATION_ERROR_INVALID_PARAMETER;
  1144. }
  1145. } else {
  1146. resolveAddrSuccess = false;
  1147. }
  1148. }
  1149. if (resolveAddrSuccess) {
  1150. unsigned int ip = htonl(addr.s_addr);
  1151. err = mLocApi->setServerSync(ip,
  1152. gnssConfigNeedEngineUpdate.assistanceServer.port,
  1153. LOC_AGPS_CDMA_PDE_SERVER);
  1154. if (index < count) {
  1155. errsList[index] = err;
  1156. }
  1157. }
  1158. }
  1159. }
  1160. index++;
  1161. }
  1162. if (gnssConfigRequested.flags & GNSS_CONFIG_FLAGS_SUPL_VERSION_VALID_BIT) {
  1163. if (gnssConfigNeedEngineUpdate.flags &
  1164. GNSS_CONFIG_FLAGS_SUPL_VERSION_VALID_BIT) {
  1165. err = mLocApi->setSUPLVersionSync(gnssConfigRequested.suplVersion);
  1166. if (index < count) {
  1167. errsList[index] = err;
  1168. }
  1169. }
  1170. index++;
  1171. }
  1172. if (gnssConfigRequested.flags & GNSS_CONFIG_FLAGS_LPP_PROFILE_VALID_BIT) {
  1173. if (gnssConfigNeedEngineUpdate.flags &
  1174. GNSS_CONFIG_FLAGS_LPP_PROFILE_VALID_BIT) {
  1175. err = mLocApi->setLPPConfigSync(gnssConfigRequested.lppProfileMask);
  1176. if (index < count) {
  1177. errsList[index] = err;
  1178. }
  1179. }
  1180. index++;
  1181. }
  1182. if (gnssConfigRequested.flags & GNSS_CONFIG_FLAGS_LPPE_CONTROL_PLANE_VALID_BIT) {
  1183. if (gnssConfigNeedEngineUpdate.flags &
  1184. GNSS_CONFIG_FLAGS_LPPE_CONTROL_PLANE_VALID_BIT) {
  1185. err = mLocApi->setLPPeProtocolCpSync(
  1186. gnssConfigRequested.lppeControlPlaneMask);
  1187. if (index < count) {
  1188. errsList[index] = err;
  1189. }
  1190. }
  1191. index++;
  1192. }
  1193. if (gnssConfigRequested.flags & GNSS_CONFIG_FLAGS_LPPE_USER_PLANE_VALID_BIT) {
  1194. if (gnssConfigNeedEngineUpdate.flags &
  1195. GNSS_CONFIG_FLAGS_LPPE_USER_PLANE_VALID_BIT) {
  1196. err = mLocApi->setLPPeProtocolUpSync(
  1197. gnssConfigRequested.lppeUserPlaneMask);
  1198. if (index < count) {
  1199. errsList[index] = err;
  1200. }
  1201. }
  1202. index++;
  1203. }
  1204. if (gnssConfigRequested.flags &
  1205. GNSS_CONFIG_FLAGS_AGLONASS_POSITION_PROTOCOL_VALID_BIT) {
  1206. if (gnssConfigNeedEngineUpdate.flags &
  1207. GNSS_CONFIG_FLAGS_AGLONASS_POSITION_PROTOCOL_VALID_BIT) {
  1208. err = mLocApi->setAGLONASSProtocolSync(
  1209. gnssConfigRequested.aGlonassPositionProtocolMask);
  1210. if (index < count) {
  1211. errsList[index] = err;
  1212. }
  1213. }
  1214. index++;
  1215. }
  1216. if (gnssConfigRequested.flags & GNSS_CONFIG_FLAGS_BLACKLISTED_SV_IDS_BIT) {
  1217. // Check if feature is supported
  1218. if (!ContextBase::isFeatureSupported(
  1219. LOC_SUPPORTED_FEATURE_CONSTELLATION_ENABLEMENT_V02)) {
  1220. LOC_LOGe("Feature constellation enablement not supported.");
  1221. err = LOCATION_ERROR_NOT_SUPPORTED;
  1222. } else {
  1223. // Send the SV ID Config to Modem
  1224. mBlacklistedSvIds.assign(gnssConfigRequested.blacklistedSvIds.begin(),
  1225. gnssConfigRequested.blacklistedSvIds.end());
  1226. err = gnssSvIdConfigUpdateSync(gnssConfigRequested.blacklistedSvIds);
  1227. if (LOCATION_ERROR_SUCCESS != err) {
  1228. LOC_LOGe("Failed to send config to modem, err %d", err);
  1229. }
  1230. }
  1231. if (index < count) {
  1232. errsList[index] = err;
  1233. }
  1234. index++;
  1235. }
  1236. if (gnssConfigRequested.flags &
  1237. GNSS_CONFIG_FLAGS_EMERGENCY_EXTENSION_SECONDS_BIT) {
  1238. if (gnssConfigNeedEngineUpdate.flags &
  1239. GNSS_CONFIG_FLAGS_EMERGENCY_EXTENSION_SECONDS_BIT) {
  1240. err = mLocApi->setEmergencyExtensionWindowSync(
  1241. gnssConfigRequested.emergencyExtensionSeconds);
  1242. if (index < count) {
  1243. errsList[index] = err;
  1244. }
  1245. }
  1246. index++;
  1247. }
  1248. if (gnssConfigRequested.flags & GNSS_CONFIG_FLAGS_MIN_SV_ELEVATION_BIT) {
  1249. GnssConfig gnssConfig = {};
  1250. gnssConfig.flags = GNSS_CONFIG_FLAGS_MIN_SV_ELEVATION_BIT;
  1251. gnssConfig.minSvElevation = gnssConfigRequested.minSvElevation;
  1252. err = mLocApi->setParameterSync(gnssConfig);
  1253. if (index < count) {
  1254. errsList[index] = err;
  1255. }
  1256. index++;
  1257. }
  1258. return errsList;
  1259. }
  1260. uint32_t*
  1261. GnssAdapter::gnssUpdateConfigCommand(const GnssConfig& config)
  1262. {
  1263. // count the number of bits set
  1264. GnssConfigFlagsMask flagsCopy = config.flags;
  1265. size_t count = 0;
  1266. while (flagsCopy > 0) {
  1267. if (flagsCopy & 1) {
  1268. count++;
  1269. }
  1270. flagsCopy >>= 1;
  1271. }
  1272. std::string idsString = "[";
  1273. uint32_t* ids = NULL;
  1274. if (count > 0) {
  1275. ids = new uint32_t[count];
  1276. if (ids == nullptr) {
  1277. LOC_LOGE("%s] new allocation failed, fatal error.", __func__);
  1278. return nullptr;
  1279. }
  1280. for (size_t i=0; i < count; ++i) {
  1281. ids[i] = generateSessionId();
  1282. IF_LOC_LOGD {
  1283. idsString += std::to_string(ids[i]) + " ";
  1284. }
  1285. }
  1286. }
  1287. idsString += "]";
  1288. LOC_LOGD("%s]: ids %s flags 0x%X", __func__, idsString.c_str(), config.flags);
  1289. struct MsgGnssUpdateConfig : public LocMsg {
  1290. GnssAdapter& mAdapter;
  1291. LocApiBase& mApi;
  1292. GnssConfig mConfig;
  1293. size_t mCount;
  1294. uint32_t* mIds;
  1295. inline MsgGnssUpdateConfig(GnssAdapter& adapter,
  1296. LocApiBase& api,
  1297. GnssConfig config,
  1298. uint32_t* ids,
  1299. size_t count) :
  1300. LocMsg(),
  1301. mAdapter(adapter),
  1302. mApi(api),
  1303. mConfig(config),
  1304. mCount(count),
  1305. mIds(nullptr) {
  1306. if (mCount > 0) {
  1307. mIds = new uint32_t[count];
  1308. if (mIds) {
  1309. for (uint32_t index = 0; index < count; index++) {
  1310. mIds[index] = ids[index];
  1311. }
  1312. } else {
  1313. LOC_LOGe("memory allocation for mIds failed");
  1314. }
  1315. }
  1316. }
  1317. inline MsgGnssUpdateConfig(const MsgGnssUpdateConfig& obj) :
  1318. MsgGnssUpdateConfig(obj.mAdapter, obj.mApi, obj.mConfig,
  1319. obj.mIds, obj.mCount) {}
  1320. inline virtual ~MsgGnssUpdateConfig()
  1321. {
  1322. if (nullptr != mIds) delete[] mIds;
  1323. }
  1324. inline virtual void proc() const {
  1325. if (!mAdapter.isEngineCapabilitiesKnown()) {
  1326. mAdapter.mPendingMsgs.push_back(new MsgGnssUpdateConfig(*this));
  1327. return;
  1328. }
  1329. GnssAdapter& adapter = mAdapter;
  1330. size_t countOfConfigs = mCount;
  1331. GnssConfig gnssConfigRequested = mConfig;
  1332. GnssConfig gnssConfigNeedEngineUpdate = mConfig;
  1333. std::vector<uint32_t> sessionIds;
  1334. sessionIds.assign(mIds, mIds + mCount);
  1335. std::vector<LocationError> errs(mCount, LOCATION_ERROR_SUCCESS);
  1336. int index = 0;
  1337. bool needSuspendResume = false;
  1338. if (gnssConfigRequested.flags & GNSS_CONFIG_FLAGS_GPS_LOCK_VALID_BIT) {
  1339. GnssConfigGpsLock newGpsLock = gnssConfigRequested.gpsLock;
  1340. newGpsLock |= GNSS_CONFIG_GPS_LOCK_MO;
  1341. ContextBase::mGps_conf.GPS_LOCK = newGpsLock;
  1342. /* If we get here it means that the changes in the framework to request for
  1343. 'P' behavior were made, and therefore we need to "behave" as in 'P'
  1344. However, we need to determine if enableCommand function has already been
  1345. called, since it could get called before this function.*/
  1346. if (0 != mAdapter.getAfwControlId()) {
  1347. /* enableCommand function has already been called since getAfwControlId
  1348. returns non zero. Now there are two possible cases:
  1349. 1. This is the first time this function is called
  1350. (mSupportNfwControl is true). We need to behave as in 'P', but
  1351. for the first time, meaning MO was enabled, but NI was not, so
  1352. we need to unlock NI
  1353. 2. This is not the first time this function is called, meaning we
  1354. are already behaving as in 'P'. No need to update the configuration
  1355. in this case (return to 'P' code) */
  1356. if (mAdapter.mSupportNfwControl) {
  1357. // case 1 above
  1358. newGpsLock = GNSS_CONFIG_GPS_LOCK_NONE;
  1359. } else {
  1360. // case 2 above
  1361. gnssConfigNeedEngineUpdate.flags &= ~(GNSS_CONFIG_FLAGS_GPS_LOCK_VALID_BIT);
  1362. }
  1363. }
  1364. gnssConfigRequested.gpsLock = newGpsLock;
  1365. mAdapter.mSupportNfwControl = false;
  1366. index++;
  1367. }
  1368. if (gnssConfigRequested.flags & GNSS_CONFIG_FLAGS_SUPL_VERSION_VALID_BIT) {
  1369. uint32_t newSuplVersion =
  1370. mAdapter.convertSuplVersion(gnssConfigRequested.suplVersion);
  1371. ContextBase::mGps_conf.SUPL_VER = newSuplVersion;
  1372. index++;
  1373. }
  1374. if (gnssConfigRequested.flags & GNSS_CONFIG_FLAGS_SET_ASSISTANCE_DATA_VALID_BIT) {
  1375. if (GNSS_ASSISTANCE_TYPE_SUPL == mConfig.assistanceServer.type) {
  1376. mAdapter.setSuplHostServer(mConfig.assistanceServer.hostName,
  1377. mConfig.assistanceServer.port,
  1378. LOC_AGPS_SUPL_SERVER);
  1379. } else {
  1380. LOC_LOGe("Not a valid gnss assistance type %u",
  1381. mConfig.assistanceServer.type);
  1382. errs.at(index) = LOCATION_ERROR_INVALID_PARAMETER;
  1383. gnssConfigNeedEngineUpdate.flags &=
  1384. ~(GNSS_CONFIG_FLAGS_SET_ASSISTANCE_DATA_VALID_BIT);
  1385. }
  1386. index++;
  1387. }
  1388. if (gnssConfigRequested.flags & GNSS_CONFIG_FLAGS_LPP_PROFILE_VALID_BIT) {
  1389. uint32_t newLppProfileMask = gnssConfigRequested.lppProfileMask;
  1390. ContextBase::mGps_conf.LPP_PROFILE = newLppProfileMask;
  1391. index++;
  1392. }
  1393. if (gnssConfigRequested.flags & GNSS_CONFIG_FLAGS_LPPE_CONTROL_PLANE_VALID_BIT) {
  1394. uint32_t newLppeControlPlaneMask =
  1395. mAdapter.convertLppeCp(gnssConfigRequested.lppeControlPlaneMask);
  1396. ContextBase::mGps_conf.LPPE_CP_TECHNOLOGY = newLppeControlPlaneMask;
  1397. index++;
  1398. }
  1399. if (gnssConfigRequested.flags & GNSS_CONFIG_FLAGS_LPPE_USER_PLANE_VALID_BIT) {
  1400. uint32_t newLppeUserPlaneMask =
  1401. mAdapter.convertLppeUp(gnssConfigRequested.lppeUserPlaneMask);
  1402. ContextBase::mGps_conf.LPPE_UP_TECHNOLOGY = newLppeUserPlaneMask;
  1403. index++;
  1404. }
  1405. if (gnssConfigRequested.flags &
  1406. GNSS_CONFIG_FLAGS_AGLONASS_POSITION_PROTOCOL_VALID_BIT) {
  1407. uint32_t newAGloProtMask =
  1408. mAdapter.convertAGloProt(gnssConfigRequested.aGlonassPositionProtocolMask);
  1409. ContextBase::mGps_conf.A_GLONASS_POS_PROTOCOL_SELECT = newAGloProtMask;
  1410. index++;
  1411. }
  1412. if (gnssConfigRequested.flags & GNSS_CONFIG_FLAGS_EM_PDN_FOR_EM_SUPL_VALID_BIT) {
  1413. uint32_t newEP4ES = mAdapter.convertEP4ES(
  1414. gnssConfigRequested.emergencyPdnForEmergencySupl);
  1415. if (newEP4ES != ContextBase::mGps_conf.USE_EMERGENCY_PDN_FOR_EMERGENCY_SUPL) {
  1416. ContextBase::mGps_conf.USE_EMERGENCY_PDN_FOR_EMERGENCY_SUPL = newEP4ES;
  1417. }
  1418. index++;
  1419. }
  1420. if (gnssConfigRequested.flags & GNSS_CONFIG_FLAGS_SUPL_EM_SERVICES_BIT) {
  1421. uint32_t newSuplEs = mAdapter.convertSuplEs(
  1422. gnssConfigRequested.suplEmergencyServices);
  1423. if (newSuplEs != ContextBase::mGps_conf.SUPL_ES) {
  1424. ContextBase::mGps_conf.SUPL_ES = newSuplEs;
  1425. }
  1426. index++;
  1427. }
  1428. if (gnssConfigRequested.flags & GNSS_CONFIG_FLAGS_SUPL_MODE_BIT) {
  1429. uint32_t newSuplMode = mAdapter.convertSuplMode(gnssConfigRequested.suplModeMask);
  1430. ContextBase::mGps_conf.SUPL_MODE = newSuplMode;
  1431. mAdapter.broadcastCapabilities(mAdapter.getCapabilities());
  1432. index++;
  1433. }
  1434. if (gnssConfigRequested.flags & GNSS_CONFIG_FLAGS_MIN_SV_ELEVATION_BIT) {
  1435. needSuspendResume = true;
  1436. index++;
  1437. }
  1438. if (needSuspendResume == true) {
  1439. mAdapter.suspendSessions();
  1440. }
  1441. LocApiCollectiveResponse *configCollectiveResponse = new LocApiCollectiveResponse(
  1442. *adapter.getContext(),
  1443. [&adapter, sessionIds, countOfConfigs] (std::vector<LocationError> errs) {
  1444. std::vector<uint32_t> ids(sessionIds);
  1445. adapter.reportResponse(countOfConfigs, errs.data(), ids.data());
  1446. });
  1447. std::string moServerUrl = adapter.getMoServerUrl();
  1448. std::string serverUrl = adapter.getServerUrl();
  1449. mApi.sendMsg(new LocApiMsg(
  1450. [&adapter, gnssConfigRequested, gnssConfigNeedEngineUpdate,
  1451. moServerUrl, serverUrl, countOfConfigs, configCollectiveResponse,
  1452. errs] () mutable {
  1453. std::vector<LocationError> errsList = adapter.gnssUpdateConfig("",
  1454. moServerUrl, serverUrl,
  1455. gnssConfigRequested, gnssConfigNeedEngineUpdate, countOfConfigs);
  1456. configCollectiveResponse->returnToSender(errsList);
  1457. }));
  1458. if (needSuspendResume == true) {
  1459. mAdapter.restartSessions();
  1460. }
  1461. }
  1462. };
  1463. if (NULL != ids) {
  1464. sendMsg(new MsgGnssUpdateConfig(*this, *mLocApi, config, ids, count));
  1465. } else {
  1466. LOC_LOGE("%s]: No GNSS config items to update", __func__);
  1467. }
  1468. return ids;
  1469. }
  1470. void
  1471. GnssAdapter::gnssSvIdConfigUpdate(const std::vector<GnssSvIdSource>& blacklistedSvIds)
  1472. {
  1473. // Clear the existing config
  1474. memset(&mGnssSvIdConfig, 0, sizeof(GnssSvIdConfig));
  1475. // Convert the sv id lists to masks
  1476. bool convertSuccess = convertToGnssSvIdConfig(blacklistedSvIds, mGnssSvIdConfig);
  1477. // Now send to Modem if conversion successful
  1478. if (convertSuccess) {
  1479. gnssSvIdConfigUpdate();
  1480. } else {
  1481. LOC_LOGe("convertToGnssSvIdConfig failed");
  1482. }
  1483. }
  1484. void
  1485. GnssAdapter::gnssSvIdConfigUpdate()
  1486. {
  1487. LOC_LOGd("blacklist bds 0x%" PRIx64 ", glo 0x%" PRIx64
  1488. ", qzss 0x%" PRIx64 ", gal 0x%" PRIx64 ", sbas 0x%" PRIx64 ", navic 0x%" PRIx64,
  1489. mGnssSvIdConfig.bdsBlacklistSvMask, mGnssSvIdConfig.gloBlacklistSvMask,
  1490. mGnssSvIdConfig.qzssBlacklistSvMask, mGnssSvIdConfig.galBlacklistSvMask,
  1491. mGnssSvIdConfig.sbasBlacklistSvMask, mGnssSvIdConfig.navicBlacklistSvMask);
  1492. // Now set required blacklisted SVs
  1493. mLocApi->setBlacklistSv(mGnssSvIdConfig);
  1494. }
  1495. LocationError
  1496. GnssAdapter::gnssSvIdConfigUpdateSync(const std::vector<GnssSvIdSource>& blacklistedSvIds)
  1497. {
  1498. // Clear the existing config
  1499. memset(&mGnssSvIdConfig, 0, sizeof(GnssSvIdConfig));
  1500. // Convert the sv id lists to masks
  1501. convertToGnssSvIdConfig(blacklistedSvIds, mGnssSvIdConfig);
  1502. // Now send to Modem
  1503. return gnssSvIdConfigUpdateSync();
  1504. }
  1505. LocationError
  1506. GnssAdapter::gnssSvIdConfigUpdateSync()
  1507. {
  1508. LOC_LOGd("blacklist bds 0x%" PRIx64 ", glo 0x%" PRIx64
  1509. ", qzss 0x%" PRIx64 ", gal 0x%" PRIx64 ", sbas 0x%" PRIx64 ", navic 0x%" PRIx64,
  1510. mGnssSvIdConfig.bdsBlacklistSvMask, mGnssSvIdConfig.gloBlacklistSvMask,
  1511. mGnssSvIdConfig.qzssBlacklistSvMask, mGnssSvIdConfig.galBlacklistSvMask,
  1512. mGnssSvIdConfig.sbasBlacklistSvMask, mGnssSvIdConfig.navicBlacklistSvMask);
  1513. // Now set required blacklisted SVs
  1514. return mLocApi->setBlacklistSvSync(mGnssSvIdConfig);
  1515. }
  1516. void
  1517. GnssAdapter::gnssSecondaryBandConfigUpdate(LocApiResponse* locApiResponse)
  1518. {
  1519. LOC_LOGd("secondary band config, size %d, enabled constellation 0x%" PRIx64 ","
  1520. "disabled constellation 0x%" PRIx64 "", mGnssSeconaryBandConfig.size,
  1521. mGnssSeconaryBandConfig.enabledSvTypesMask,
  1522. mGnssSeconaryBandConfig.blacklistedSvTypesMask);
  1523. if (mGnssSeconaryBandConfig.size == sizeof(mGnssSeconaryBandConfig)) {
  1524. // Now set required secondary band config
  1525. mLocApi->configConstellationMultiBand(mGnssSeconaryBandConfig, locApiResponse);
  1526. }
  1527. }
  1528. uint32_t*
  1529. GnssAdapter::gnssGetConfigCommand(GnssConfigFlagsMask configMask) {
  1530. // count the number of bits set
  1531. GnssConfigFlagsMask flagsCopy = configMask;
  1532. size_t count = 0;
  1533. while (flagsCopy > 0) {
  1534. if (flagsCopy & 1) {
  1535. count++;
  1536. }
  1537. flagsCopy >>= 1;
  1538. }
  1539. std::string idsString = "[";
  1540. uint32_t* ids = NULL;
  1541. if (count > 0) {
  1542. ids = new uint32_t[count];
  1543. if (nullptr == ids) {
  1544. LOC_LOGe("new allocation failed, fatal error.");
  1545. return nullptr;
  1546. }
  1547. for (size_t i=0; i < count; ++i) {
  1548. ids[i] = generateSessionId();
  1549. IF_LOC_LOGD {
  1550. idsString += std::to_string(ids[i]) + " ";
  1551. }
  1552. }
  1553. }
  1554. idsString += "]";
  1555. LOC_LOGd("ids %s flags 0x%X", idsString.c_str(), configMask);
  1556. struct MsgGnssGetConfig : public LocMsg {
  1557. GnssAdapter& mAdapter;
  1558. LocApiBase& mApi;
  1559. GnssConfigFlagsMask mConfigMask;
  1560. uint32_t* mIds;
  1561. size_t mCount;
  1562. inline MsgGnssGetConfig(GnssAdapter& adapter,
  1563. LocApiBase& api,
  1564. GnssConfigFlagsMask configMask,
  1565. uint32_t* ids,
  1566. size_t count) :
  1567. LocMsg(),
  1568. mAdapter(adapter),
  1569. mApi(api),
  1570. mConfigMask(configMask),
  1571. mCount(count),
  1572. mIds(nullptr) {
  1573. if (mCount > 0) {
  1574. mIds = new uint32_t[count];
  1575. if (mIds) {
  1576. for (uint32_t index = 0; index < count; index++) {
  1577. mIds[index] = ids[index];
  1578. }
  1579. } else {
  1580. LOC_LOGe("memory allocation for mIds failed");
  1581. }
  1582. }
  1583. }
  1584. inline MsgGnssGetConfig(const MsgGnssGetConfig& obj) :
  1585. MsgGnssGetConfig(obj.mAdapter, obj.mApi, obj.mConfigMask,
  1586. obj.mIds, obj.mCount) {}
  1587. inline virtual ~MsgGnssGetConfig()
  1588. {
  1589. if (nullptr != mIds) delete[] mIds;
  1590. }
  1591. inline virtual void proc() const {
  1592. if (!mAdapter.isEngineCapabilitiesKnown()) {
  1593. mAdapter.mPendingMsgs.push_back(new MsgGnssGetConfig(*this));
  1594. return;
  1595. }
  1596. LocationError* errs = new LocationError[mCount];
  1597. LocationError err = LOCATION_ERROR_SUCCESS;
  1598. uint32_t index = 0;
  1599. if (nullptr == errs) {
  1600. LOC_LOGE("%s] new allocation failed, fatal error.", __func__);
  1601. return;
  1602. }
  1603. if (mConfigMask & GNSS_CONFIG_FLAGS_GPS_LOCK_VALID_BIT) {
  1604. if (index < mCount) {
  1605. errs[index++] = LOCATION_ERROR_NOT_SUPPORTED;
  1606. }
  1607. }
  1608. if (mConfigMask & GNSS_CONFIG_FLAGS_SUPL_VERSION_VALID_BIT) {
  1609. if (index < mCount) {
  1610. errs[index++] = LOCATION_ERROR_NOT_SUPPORTED;
  1611. }
  1612. }
  1613. if (mConfigMask & GNSS_CONFIG_FLAGS_SET_ASSISTANCE_DATA_VALID_BIT) {
  1614. if (index < mCount) {
  1615. errs[index++] = LOCATION_ERROR_NOT_SUPPORTED;
  1616. }
  1617. }
  1618. if (mConfigMask & GNSS_CONFIG_FLAGS_LPP_PROFILE_VALID_BIT) {
  1619. if (index < mCount) {
  1620. errs[index++] = LOCATION_ERROR_NOT_SUPPORTED;
  1621. }
  1622. }
  1623. if (mConfigMask & GNSS_CONFIG_FLAGS_LPPE_CONTROL_PLANE_VALID_BIT) {
  1624. if (index < mCount) {
  1625. errs[index++] = LOCATION_ERROR_NOT_SUPPORTED;
  1626. }
  1627. }
  1628. if (mConfigMask & GNSS_CONFIG_FLAGS_LPPE_USER_PLANE_VALID_BIT) {
  1629. if (index < mCount) {
  1630. errs[index++] = LOCATION_ERROR_NOT_SUPPORTED;
  1631. }
  1632. }
  1633. if (mConfigMask & GNSS_CONFIG_FLAGS_AGLONASS_POSITION_PROTOCOL_VALID_BIT) {
  1634. if (index < mCount) {
  1635. errs[index++] = LOCATION_ERROR_NOT_SUPPORTED;
  1636. }
  1637. }
  1638. if (mConfigMask & GNSS_CONFIG_FLAGS_EM_PDN_FOR_EM_SUPL_VALID_BIT) {
  1639. if (index < mCount) {
  1640. errs[index++] = LOCATION_ERROR_NOT_SUPPORTED;
  1641. }
  1642. }
  1643. if (mConfigMask & GNSS_CONFIG_FLAGS_SUPL_EM_SERVICES_BIT) {
  1644. if (index < mCount) {
  1645. errs[index++] = LOCATION_ERROR_NOT_SUPPORTED;
  1646. }
  1647. }
  1648. if (mConfigMask & GNSS_CONFIG_FLAGS_SUPL_MODE_BIT) {
  1649. err = LOCATION_ERROR_NOT_SUPPORTED;
  1650. if (index < mCount) {
  1651. errs[index++] = LOCATION_ERROR_NOT_SUPPORTED;
  1652. }
  1653. }
  1654. if (mConfigMask & GNSS_CONFIG_FLAGS_BLACKLISTED_SV_IDS_BIT) {
  1655. // Check if feature is supported
  1656. if (!ContextBase::isFeatureSupported(
  1657. LOC_SUPPORTED_FEATURE_CONSTELLATION_ENABLEMENT_V02)) {
  1658. LOC_LOGe("Feature not supported.");
  1659. err = LOCATION_ERROR_NOT_SUPPORTED;
  1660. } else {
  1661. // Send request to Modem to fetch the config
  1662. mApi.getBlacklistSv();
  1663. err = LOCATION_ERROR_SUCCESS;
  1664. }
  1665. if (index < mCount) {
  1666. errs[index++] = err;
  1667. }
  1668. }
  1669. if (mConfigMask & GNSS_CONFIG_FLAGS_EMERGENCY_EXTENSION_SECONDS_BIT) {
  1670. err = LOCATION_ERROR_NOT_SUPPORTED;
  1671. if (index < mCount) {
  1672. errs[index++] = LOCATION_ERROR_NOT_SUPPORTED;
  1673. }
  1674. }
  1675. if (mConfigMask & GNSS_CONFIG_FLAGS_ROBUST_LOCATION_BIT) {
  1676. uint32_t sessionId = *(mIds+index);
  1677. LocApiResponse* locApiResponse =
  1678. new LocApiResponse(*mAdapter.getContext(),
  1679. [this, sessionId] (LocationError err) {
  1680. mAdapter.reportResponse(err, sessionId);});
  1681. if (!locApiResponse) {
  1682. LOC_LOGe("memory alloc failed");
  1683. mAdapter.reportResponse(LOCATION_ERROR_GENERAL_FAILURE, sessionId);
  1684. } else {
  1685. mApi.getRobustLocationConfig(sessionId, locApiResponse);
  1686. }
  1687. }
  1688. if (mConfigMask & GNSS_CONFIG_FLAGS_MIN_GPS_WEEK_BIT) {
  1689. uint32_t sessionId = *(mIds+index);
  1690. LocApiResponse* locApiResponse =
  1691. new LocApiResponse(*mAdapter.getContext(),
  1692. [this, sessionId] (LocationError err) {
  1693. mAdapter.reportResponse(err, sessionId);});
  1694. if (!locApiResponse) {
  1695. LOC_LOGe("memory alloc failed");
  1696. mAdapter.reportResponse(LOCATION_ERROR_GENERAL_FAILURE, sessionId);
  1697. } else {
  1698. mApi.getMinGpsWeek(sessionId, locApiResponse);
  1699. }
  1700. }
  1701. if (mConfigMask & GNSS_CONFIG_FLAGS_MIN_SV_ELEVATION_BIT) {
  1702. uint32_t sessionId = *(mIds+index);
  1703. LocApiResponse* locApiResponse =
  1704. new LocApiResponse(*mAdapter.getContext(),
  1705. [this, sessionId] (LocationError err) {
  1706. mAdapter.reportResponse(err, sessionId);});
  1707. if (!locApiResponse) {
  1708. LOC_LOGe("memory alloc failed");
  1709. mAdapter.reportResponse(LOCATION_ERROR_GENERAL_FAILURE, sessionId);
  1710. } else {
  1711. mApi.getParameter(sessionId, GNSS_CONFIG_FLAGS_MIN_SV_ELEVATION_BIT,
  1712. locApiResponse);
  1713. }
  1714. }
  1715. mAdapter.reportResponse(index, errs, mIds);
  1716. delete[] errs;
  1717. }
  1718. };
  1719. if (NULL != ids) {
  1720. sendMsg(new MsgGnssGetConfig(*this, *mLocApi, configMask, ids, count));
  1721. } else {
  1722. LOC_LOGe("No GNSS config items to Get");
  1723. }
  1724. return ids;
  1725. }
  1726. bool
  1727. GnssAdapter::convertToGnssSvIdConfig(
  1728. const std::vector<GnssSvIdSource>& blacklistedSvIds, GnssSvIdConfig& config)
  1729. {
  1730. bool retVal = false;
  1731. config.size = sizeof(GnssSvIdConfig);
  1732. // Empty vector => Clear any previous blacklisted SVs
  1733. if (0 == blacklistedSvIds.size()) {
  1734. config.gloBlacklistSvMask = 0;
  1735. config.bdsBlacklistSvMask = 0;
  1736. config.qzssBlacklistSvMask = 0;
  1737. config.galBlacklistSvMask = 0;
  1738. config.sbasBlacklistSvMask = 0;
  1739. config.navicBlacklistSvMask = 0;
  1740. retVal = true;
  1741. } else {
  1742. // Parse the vector and convert SV IDs to mask values
  1743. for (GnssSvIdSource source : blacklistedSvIds) {
  1744. uint64_t* svMaskPtr = NULL;
  1745. GnssSvId initialSvId = 0;
  1746. uint16_t svIndexOffset = 0;
  1747. switch(source.constellation) {
  1748. case GNSS_SV_TYPE_GLONASS:
  1749. svMaskPtr = &config.gloBlacklistSvMask;
  1750. initialSvId = GNSS_SV_CONFIG_GLO_INITIAL_SV_ID;
  1751. break;
  1752. case GNSS_SV_TYPE_BEIDOU:
  1753. svMaskPtr = &config.bdsBlacklistSvMask;
  1754. initialSvId = GNSS_SV_CONFIG_BDS_INITIAL_SV_ID;
  1755. break;
  1756. case GNSS_SV_TYPE_QZSS:
  1757. svMaskPtr = &config.qzssBlacklistSvMask;
  1758. initialSvId = GNSS_SV_CONFIG_QZSS_INITIAL_SV_ID;
  1759. break;
  1760. case GNSS_SV_TYPE_GALILEO:
  1761. svMaskPtr = &config.galBlacklistSvMask;
  1762. initialSvId = GNSS_SV_CONFIG_GAL_INITIAL_SV_ID;
  1763. break;
  1764. case GNSS_SV_TYPE_SBAS:
  1765. // SBAS does not support enable/disable whole constellation
  1766. // so do not set up svTypeMask for SBAS
  1767. svMaskPtr = &config.sbasBlacklistSvMask;
  1768. // SBAS currently has two ranges, [120, 158] and [183, 191]
  1769. if (0 == source.svId) {
  1770. LOC_LOGd("blacklist all SBAS SV");
  1771. } else if (source.svId >= GNSS_SV_CONFIG_SBAS_INITIAL2_SV_ID) {
  1772. // handle SV id in range [183, 191]
  1773. initialSvId = GNSS_SV_CONFIG_SBAS_INITIAL2_SV_ID;
  1774. svIndexOffset = GNSS_SV_CONFIG_SBAS_INITIAL_SV_LENGTH;
  1775. } else if ((source.svId >= GNSS_SV_CONFIG_SBAS_INITIAL_SV_ID) &&
  1776. (source.svId < (GNSS_SV_CONFIG_SBAS_INITIAL_SV_ID +
  1777. GNSS_SV_CONFIG_SBAS_INITIAL_SV_LENGTH))){
  1778. // handle SV id in range of [120, 158]
  1779. initialSvId = GNSS_SV_CONFIG_SBAS_INITIAL_SV_ID;
  1780. } else {
  1781. LOC_LOGe("invalid SBAS sv id %d", source.svId);
  1782. svMaskPtr = nullptr;
  1783. }
  1784. break;
  1785. case GNSS_SV_TYPE_NAVIC:
  1786. svMaskPtr = &config.navicBlacklistSvMask;
  1787. initialSvId = GNSS_SV_CONFIG_NAVIC_INITIAL_SV_ID;
  1788. break;
  1789. default:
  1790. break;
  1791. }
  1792. if (NULL == svMaskPtr) {
  1793. LOC_LOGe("Invalid constellation %d", source.constellation);
  1794. } else {
  1795. // SV ID 0 = All SV IDs
  1796. if (0 == source.svId) {
  1797. *svMaskPtr = GNSS_SV_CONFIG_ALL_BITS_ENABLED_MASK;
  1798. } else if (source.svId < initialSvId || source.svId >= initialSvId + 64) {
  1799. LOC_LOGe("Invalid sv id %d for sv type %d",
  1800. source.svId, source.constellation);
  1801. } else {
  1802. uint32_t shiftCnt = source.svId + svIndexOffset - initialSvId;
  1803. *svMaskPtr |= (1ULL << shiftCnt);
  1804. }
  1805. }
  1806. }
  1807. // Return true if any one source is valid
  1808. if (0 != config.gloBlacklistSvMask ||
  1809. 0 != config.bdsBlacklistSvMask ||
  1810. 0 != config.galBlacklistSvMask ||
  1811. 0 != config.qzssBlacklistSvMask ||
  1812. 0 != config.sbasBlacklistSvMask ||
  1813. 0 != config.navicBlacklistSvMask) {
  1814. retVal = true;
  1815. }
  1816. }
  1817. LOC_LOGd("blacklist bds 0x%" PRIx64 ", glo 0x%" PRIx64
  1818. ", qzss 0x%" PRIx64 ", gal 0x%" PRIx64 ", sbas 0x%" PRIx64 ", navic 0x%" PRIx64,
  1819. config.bdsBlacklistSvMask, config.gloBlacklistSvMask,
  1820. config.qzssBlacklistSvMask, config.galBlacklistSvMask,
  1821. config.sbasBlacklistSvMask, config.navicBlacklistSvMask);
  1822. return retVal;
  1823. }
  1824. void GnssAdapter::convertFromGnssSvIdConfig(
  1825. const GnssSvIdConfig& svConfig, std::vector<GnssSvIdSource>& blacklistedSvIds)
  1826. {
  1827. // Convert blacklisted SV mask values to vectors
  1828. if (svConfig.bdsBlacklistSvMask) {
  1829. convertGnssSvIdMaskToList(
  1830. svConfig.bdsBlacklistSvMask, blacklistedSvIds,
  1831. GNSS_SV_CONFIG_BDS_INITIAL_SV_ID, GNSS_SV_TYPE_BEIDOU);
  1832. }
  1833. if (svConfig.galBlacklistSvMask) {
  1834. convertGnssSvIdMaskToList(
  1835. svConfig.galBlacklistSvMask, blacklistedSvIds,
  1836. GNSS_SV_CONFIG_GAL_INITIAL_SV_ID, GNSS_SV_TYPE_GALILEO);
  1837. }
  1838. if (svConfig.gloBlacklistSvMask) {
  1839. convertGnssSvIdMaskToList(
  1840. svConfig.gloBlacklistSvMask, blacklistedSvIds,
  1841. GNSS_SV_CONFIG_GLO_INITIAL_SV_ID, GNSS_SV_TYPE_GLONASS);
  1842. }
  1843. if (svConfig.qzssBlacklistSvMask) {
  1844. convertGnssSvIdMaskToList(
  1845. svConfig.qzssBlacklistSvMask, blacklistedSvIds,
  1846. GNSS_SV_CONFIG_QZSS_INITIAL_SV_ID, GNSS_SV_TYPE_QZSS);
  1847. }
  1848. if (svConfig.sbasBlacklistSvMask) {
  1849. // SBAS - SV 120 to 158, maps to 0 to 38
  1850. // SV 183 to 191, maps to 39 to 47
  1851. uint64_t sbasBlacklistSvMask = svConfig.sbasBlacklistSvMask;
  1852. // operate on 120 and 158 first
  1853. sbasBlacklistSvMask <<= (64 - GNSS_SV_CONFIG_SBAS_INITIAL_SV_LENGTH);
  1854. sbasBlacklistSvMask >>= (64 - GNSS_SV_CONFIG_SBAS_INITIAL_SV_LENGTH);
  1855. convertGnssSvIdMaskToList(
  1856. sbasBlacklistSvMask, blacklistedSvIds,
  1857. GNSS_SV_CONFIG_SBAS_INITIAL_SV_ID, GNSS_SV_TYPE_SBAS);
  1858. // operate on the second range
  1859. sbasBlacklistSvMask = svConfig.sbasBlacklistSvMask;
  1860. sbasBlacklistSvMask >>= GNSS_SV_CONFIG_SBAS_INITIAL_SV_LENGTH;
  1861. convertGnssSvIdMaskToList(
  1862. sbasBlacklistSvMask, blacklistedSvIds,
  1863. GNSS_SV_CONFIG_SBAS_INITIAL2_SV_ID, GNSS_SV_TYPE_SBAS);
  1864. }
  1865. if (svConfig.navicBlacklistSvMask) {
  1866. convertGnssSvIdMaskToList(
  1867. svConfig.navicBlacklistSvMask, blacklistedSvIds,
  1868. GNSS_SV_CONFIG_NAVIC_INITIAL_SV_ID, GNSS_SV_TYPE_NAVIC);
  1869. }
  1870. }
  1871. void GnssAdapter::convertGnssSvIdMaskToList(
  1872. uint64_t svIdMask, std::vector<GnssSvIdSource>& svIds,
  1873. GnssSvId initialSvId, GnssSvType svType)
  1874. {
  1875. GnssSvIdSource source = {};
  1876. source.size = sizeof(GnssSvIdSource);
  1877. source.constellation = svType;
  1878. // SV ID 0 => All SV IDs in mask
  1879. if (GNSS_SV_CONFIG_ALL_BITS_ENABLED_MASK == svIdMask) {
  1880. LOC_LOGd("blacklist all SVs in constellation %d", source.constellation);
  1881. source.svId = 0;
  1882. svIds.push_back(source);
  1883. return;
  1884. }
  1885. // Convert each bit in svIdMask to vector entry
  1886. uint32_t bitNumber = 0;
  1887. while (svIdMask > 0) {
  1888. if (svIdMask & 0x1) {
  1889. source.svId = bitNumber + initialSvId;
  1890. // SBAS has two ranges:
  1891. // SBAS - SV 120 to 158, maps to 0 to 38
  1892. // SV 183 to 191, maps to 39 to 47
  1893. // #define GNSS_SV_CONFIG_SBAS_INITIAL_SV_ID 120
  1894. // #define GNSS_SV_CONFIG_SBAS_INITIAL_SV_LENGTH 39
  1895. // #define GNSS_SV_CONFIG_SBAS_INITIAL2_SV_ID 183
  1896. if (svType == GNSS_SV_TYPE_SBAS) {
  1897. if (bitNumber >= GNSS_SV_CONFIG_SBAS_INITIAL_SV_LENGTH) {
  1898. source.svId = bitNumber - GNSS_SV_CONFIG_SBAS_INITIAL_SV_LENGTH +
  1899. GNSS_SV_CONFIG_SBAS_INITIAL2_SV_ID;
  1900. }
  1901. }
  1902. svIds.push_back(source);
  1903. }
  1904. bitNumber++;
  1905. svIdMask >>= 1;
  1906. }
  1907. }
  1908. void GnssAdapter::reportGnssSvIdConfigEvent(const GnssSvIdConfig& config)
  1909. {
  1910. struct MsgReportGnssSvIdConfig : public LocMsg {
  1911. GnssAdapter& mAdapter;
  1912. const GnssSvIdConfig mConfig;
  1913. inline MsgReportGnssSvIdConfig(GnssAdapter& adapter,
  1914. const GnssSvIdConfig& config) :
  1915. LocMsg(),
  1916. mAdapter(adapter),
  1917. mConfig(config) {}
  1918. inline virtual void proc() const {
  1919. mAdapter.reportGnssSvIdConfig(mConfig);
  1920. }
  1921. };
  1922. sendMsg(new MsgReportGnssSvIdConfig(*this, config));
  1923. }
  1924. void GnssAdapter::reportGnssSvIdConfig(const GnssSvIdConfig& svIdConfig)
  1925. {
  1926. GnssConfig config = {};
  1927. config.size = sizeof(GnssConfig);
  1928. // Invoke control clients config callback
  1929. if (nullptr != mControlCallbacks.gnssConfigCb &&
  1930. svIdConfig.size == sizeof(GnssSvIdConfig)) {
  1931. convertFromGnssSvIdConfig(svIdConfig, config.blacklistedSvIds);
  1932. if (config.blacklistedSvIds.size() > 0) {
  1933. config.flags |= GNSS_CONFIG_FLAGS_BLACKLISTED_SV_IDS_BIT;
  1934. }
  1935. LOC_LOGd("blacklist bds 0x%" PRIx64 ", glo 0x%" PRIx64 ", "
  1936. "qzss 0x%" PRIx64 ", gal 0x%" PRIx64 ", sbas 0x%" PRIx64 ", navic 0x%" PRIx64,
  1937. svIdConfig.bdsBlacklistSvMask, svIdConfig.gloBlacklistSvMask,
  1938. svIdConfig.qzssBlacklistSvMask, svIdConfig.galBlacklistSvMask,
  1939. svIdConfig.sbasBlacklistSvMask, svIdConfig.navicBlacklistSvMask);
  1940. // use 0 session id to indicate that receiver does not yet care about session id
  1941. mControlCallbacks.gnssConfigCb(0, config);
  1942. } else {
  1943. LOC_LOGe("Failed to report, size %d", (uint32_t)config.size);
  1944. }
  1945. }
  1946. void
  1947. GnssAdapter::gnssUpdateSvTypeConfigCommand(GnssSvTypeConfig config)
  1948. {
  1949. struct MsgGnssUpdateSvTypeConfig : public LocMsg {
  1950. GnssAdapter* mAdapter;
  1951. LocApiBase* mApi;
  1952. GnssSvTypeConfig mConfig;
  1953. inline MsgGnssUpdateSvTypeConfig(
  1954. GnssAdapter* adapter,
  1955. LocApiBase* api,
  1956. GnssSvTypeConfig& config) :
  1957. LocMsg(),
  1958. mAdapter(adapter),
  1959. mApi(api),
  1960. mConfig(config) {}
  1961. inline virtual void proc() const {
  1962. if (!mAdapter->isEngineCapabilitiesKnown()) {
  1963. mAdapter->mPendingMsgs.push_back(new MsgGnssUpdateSvTypeConfig(*this));
  1964. return;
  1965. }
  1966. // Check if feature is supported
  1967. if (!ContextBase::isFeatureSupported(
  1968. LOC_SUPPORTED_FEATURE_CONSTELLATION_ENABLEMENT_V02)) {
  1969. LOC_LOGe("Feature not supported.");
  1970. } else {
  1971. // Send update request to modem
  1972. mAdapter->gnssSvTypeConfigUpdate(mConfig);
  1973. }
  1974. }
  1975. };
  1976. sendMsg(new MsgGnssUpdateSvTypeConfig(this, mLocApi, config));
  1977. }
  1978. void
  1979. GnssAdapter::gnssSvTypeConfigUpdate(const GnssSvTypeConfig& config)
  1980. {
  1981. // Gather bits removed from enabled mask
  1982. GnssSvTypesMask enabledRemoved = mGnssSvTypeConfig.enabledSvTypesMask &
  1983. (mGnssSvTypeConfig.enabledSvTypesMask ^ config.enabledSvTypesMask);
  1984. // Send reset if any constellation is removed from the enabled list
  1985. bool sendReset = (enabledRemoved != 0);
  1986. // Save new config and update
  1987. gnssSetSvTypeConfig(config);
  1988. gnssSvTypeConfigUpdate(sendReset);
  1989. }
  1990. void
  1991. GnssAdapter::gnssSvTypeConfigUpdate(bool sendReset)
  1992. {
  1993. LOC_LOGd("size %" PRIu32" constellations blacklisted 0x%" PRIx64 ", enabled 0x%" PRIx64
  1994. ", sendReset %d",
  1995. mGnssSvTypeConfig.size, mGnssSvTypeConfig.blacklistedSvTypesMask,
  1996. mGnssSvTypeConfig.enabledSvTypesMask, sendReset);
  1997. LOC_LOGd("blacklist bds 0x%" PRIx64 ", glo 0x%" PRIx64
  1998. ", qzss 0x%" PRIx64 ", gal 0x%" PRIx64 ", sbas 0x%" PRIx64 ", Navic 0x%" PRIx64,
  1999. mGnssSvIdConfig.bdsBlacklistSvMask, mGnssSvIdConfig.gloBlacklistSvMask,
  2000. mGnssSvIdConfig.qzssBlacklistSvMask, mGnssSvIdConfig.galBlacklistSvMask,
  2001. mGnssSvIdConfig.sbasBlacklistSvMask, mGnssSvIdConfig.navicBlacklistSvMask);
  2002. LOC_LOGd("blacklist bds 0x%" PRIx64 ", glo 0x%" PRIx64
  2003. ", qzss 0x%" PRIx64 ", gal 0x%" PRIx64 ", sbas 0x%" PRIx64 ", Navic 0x%" PRIx64,
  2004. mGnssSvIdConfig.bdsBlacklistSvMask, mGnssSvIdConfig.gloBlacklistSvMask,
  2005. mGnssSvIdConfig.qzssBlacklistSvMask, mGnssSvIdConfig.galBlacklistSvMask,
  2006. mGnssSvIdConfig.sbasBlacklistSvMask, mGnssSvIdConfig.navicBlacklistSvMask);
  2007. if (mGnssSvTypeConfig.size == sizeof(mGnssSvTypeConfig)) {
  2008. if (sendReset) {
  2009. mLocApi->resetConstellationControl();
  2010. }
  2011. GnssSvIdConfig blacklistConfig = {};
  2012. // Revert to previously blacklisted SVs for each enabled constellation
  2013. blacklistConfig = mGnssSvIdConfig;
  2014. // Blacklist all SVs for each disabled constellation
  2015. if (mGnssSvTypeConfig.blacklistedSvTypesMask) {
  2016. if (mGnssSvTypeConfig.blacklistedSvTypesMask & GNSS_SV_TYPES_MASK_GLO_BIT) {
  2017. blacklistConfig.gloBlacklistSvMask = GNSS_SV_CONFIG_ALL_BITS_ENABLED_MASK;
  2018. }
  2019. if (mGnssSvTypeConfig.blacklistedSvTypesMask & GNSS_SV_TYPES_MASK_BDS_BIT) {
  2020. blacklistConfig.bdsBlacklistSvMask = GNSS_SV_CONFIG_ALL_BITS_ENABLED_MASK;
  2021. }
  2022. if (mGnssSvTypeConfig.blacklistedSvTypesMask & GNSS_SV_TYPES_MASK_QZSS_BIT) {
  2023. blacklistConfig.qzssBlacklistSvMask = GNSS_SV_CONFIG_ALL_BITS_ENABLED_MASK;
  2024. }
  2025. if (mGnssSvTypeConfig.blacklistedSvTypesMask & GNSS_SV_TYPES_MASK_GAL_BIT) {
  2026. blacklistConfig.galBlacklistSvMask = GNSS_SV_CONFIG_ALL_BITS_ENABLED_MASK;
  2027. }
  2028. if (mGnssSvTypeConfig.blacklistedSvTypesMask & GNSS_SV_TYPES_MASK_NAVIC_BIT) {
  2029. blacklistConfig.navicBlacklistSvMask = GNSS_SV_CONFIG_ALL_BITS_ENABLED_MASK;
  2030. }
  2031. }
  2032. // Send blacklist info
  2033. mLocApi->setBlacklistSv(blacklistConfig);
  2034. // Send only enabled constellation config
  2035. if (mGnssSvTypeConfig.enabledSvTypesMask) {
  2036. GnssSvTypeConfig svTypeConfig = {sizeof(GnssSvTypeConfig), 0, 0};
  2037. svTypeConfig.enabledSvTypesMask = mGnssSvTypeConfig.enabledSvTypesMask;
  2038. mLocApi->setConstellationControl(svTypeConfig);
  2039. }
  2040. }
  2041. }
  2042. void
  2043. GnssAdapter::gnssGetSvTypeConfigCommand(GnssSvTypeConfigCallback callback)
  2044. {
  2045. struct MsgGnssGetSvTypeConfig : public LocMsg {
  2046. GnssAdapter* mAdapter;
  2047. LocApiBase* mApi;
  2048. GnssSvTypeConfigCallback mCallback;
  2049. inline MsgGnssGetSvTypeConfig(
  2050. GnssAdapter* adapter,
  2051. LocApiBase* api,
  2052. GnssSvTypeConfigCallback callback) :
  2053. LocMsg(),
  2054. mAdapter(adapter),
  2055. mApi(api),
  2056. mCallback(callback) {}
  2057. inline virtual void proc() const {
  2058. if (!mAdapter->isEngineCapabilitiesKnown()) {
  2059. mAdapter->mPendingMsgs.push_back(new MsgGnssGetSvTypeConfig(*this));
  2060. return;
  2061. }
  2062. if (!ContextBase::isFeatureSupported(
  2063. LOC_SUPPORTED_FEATURE_CONSTELLATION_ENABLEMENT_V02)) {
  2064. LOC_LOGe("Feature not supported.");
  2065. } else {
  2066. // Save the callback
  2067. mAdapter->gnssSetSvTypeConfigCallback(mCallback);
  2068. // Send GET request to modem
  2069. mApi->getConstellationControl();
  2070. }
  2071. }
  2072. };
  2073. sendMsg(new MsgGnssGetSvTypeConfig(this, mLocApi, callback));
  2074. }
  2075. void
  2076. GnssAdapter::gnssResetSvTypeConfigCommand()
  2077. {
  2078. struct MsgGnssResetSvTypeConfig : public LocMsg {
  2079. GnssAdapter* mAdapter;
  2080. LocApiBase* mApi;
  2081. inline MsgGnssResetSvTypeConfig(
  2082. GnssAdapter* adapter,
  2083. LocApiBase* api) :
  2084. LocMsg(),
  2085. mAdapter(adapter),
  2086. mApi(api) {}
  2087. inline virtual void proc() const {
  2088. if (!mAdapter->isEngineCapabilitiesKnown()) {
  2089. mAdapter->mPendingMsgs.push_back(new MsgGnssResetSvTypeConfig(*this));
  2090. return;
  2091. }
  2092. if (!ContextBase::isFeatureSupported(
  2093. LOC_SUPPORTED_FEATURE_CONSTELLATION_ENABLEMENT_V02)) {
  2094. LOC_LOGe("Feature not supported.");
  2095. } else {
  2096. // Reset constellation config
  2097. mAdapter->gnssSetSvTypeConfig({sizeof(GnssSvTypeConfig), 0, 0});
  2098. // Re-enforce SV blacklist config
  2099. mAdapter->gnssSvIdConfigUpdate();
  2100. // Send reset request to modem
  2101. mApi->resetConstellationControl();
  2102. }
  2103. }
  2104. };
  2105. sendMsg(new MsgGnssResetSvTypeConfig(this, mLocApi));
  2106. }
  2107. void GnssAdapter::reportGnssSvTypeConfigEvent(const GnssSvTypeConfig& config)
  2108. {
  2109. struct MsgReportGnssSvTypeConfig : public LocMsg {
  2110. GnssAdapter& mAdapter;
  2111. const GnssSvTypeConfig mConfig;
  2112. inline MsgReportGnssSvTypeConfig(GnssAdapter& adapter,
  2113. const GnssSvTypeConfig& config) :
  2114. LocMsg(),
  2115. mAdapter(adapter),
  2116. mConfig(config) {}
  2117. inline virtual void proc() const {
  2118. mAdapter.reportGnssSvTypeConfig(mConfig);
  2119. }
  2120. };
  2121. sendMsg(new MsgReportGnssSvTypeConfig(*this, config));
  2122. }
  2123. void GnssAdapter::reportGnssSvTypeConfig(const GnssSvTypeConfig& config)
  2124. {
  2125. // Invoke Get SV Type Callback
  2126. if (NULL != mGnssSvTypeConfigCb &&
  2127. config.size == sizeof(GnssSvTypeConfig)) {
  2128. LOC_LOGd("constellations blacklisted 0x%" PRIx64 ", enabled 0x%" PRIx64,
  2129. config.blacklistedSvTypesMask, config.enabledSvTypesMask);
  2130. mGnssSvTypeConfigCb(config);
  2131. } else {
  2132. LOC_LOGe("Failed to report, size %d", (uint32_t)config.size);
  2133. }
  2134. }
  2135. void GnssAdapter::deleteAidingData(const GnssAidingData &data, uint32_t sessionId) {
  2136. struct timespec bootDeleteAidingDataTime = {};
  2137. int64_t bootDeleteTimeMs;
  2138. if (clock_gettime(CLOCK_BOOTTIME, &bootDeleteAidingDataTime) == 0) {
  2139. bootDeleteTimeMs = (int64_t)bootDeleteAidingDataTime.tv_sec * 1000;
  2140. int64_t diffTimeBFirSecDelete = bootDeleteTimeMs - mLastDeleteAidingDataTime;
  2141. if (diffTimeBFirSecDelete > DELETE_AIDING_DATA_EXPECTED_TIME_MS) {
  2142. mLocApi->deleteAidingData(data, new LocApiResponse(*getContext(),
  2143. [this, sessionId] (LocationError err) {
  2144. reportResponse(err, sessionId);
  2145. }));
  2146. mLastDeleteAidingDataTime = bootDeleteTimeMs;
  2147. }
  2148. }
  2149. }
  2150. uint32_t
  2151. GnssAdapter::gnssDeleteAidingDataCommand(GnssAidingData& data)
  2152. {
  2153. uint32_t sessionId = generateSessionId();
  2154. LOC_LOGD("%s]: id %u", __func__, sessionId);
  2155. struct MsgDeleteAidingData : public LocMsg {
  2156. GnssAdapter& mAdapter;
  2157. uint32_t mSessionId;
  2158. GnssAidingData mData;
  2159. inline MsgDeleteAidingData(GnssAdapter& adapter,
  2160. uint32_t sessionId,
  2161. GnssAidingData& data) :
  2162. LocMsg(),
  2163. mAdapter(adapter),
  2164. mSessionId(sessionId),
  2165. mData(data) {}
  2166. inline virtual void proc() const {
  2167. if ((mData.posEngineMask & STANDARD_POSITIONING_ENGINE) != 0) {
  2168. mAdapter.deleteAidingData(mData, mSessionId);
  2169. SystemStatus* s = mAdapter.getSystemStatus();
  2170. if ((nullptr != s) && (mData.deleteAll)) {
  2171. s->setDefaultGnssEngineStates();
  2172. }
  2173. }
  2174. bool retVal = mAdapter.mEngHubProxy->gnssDeleteAidingData(mData);
  2175. // When SPE engine is invoked, responseCb will be invoked
  2176. // from QMI Loc API call.
  2177. // When SPE engine is not invoked, we also need to deliver responseCb
  2178. if ((mData.posEngineMask & STANDARD_POSITIONING_ENGINE) == 0) {
  2179. LocationError err = LOCATION_ERROR_NOT_SUPPORTED;
  2180. if (retVal == true) {
  2181. err = LOCATION_ERROR_SUCCESS;
  2182. }
  2183. mAdapter.reportResponse(err, mSessionId);
  2184. }
  2185. }
  2186. };
  2187. sendMsg(new MsgDeleteAidingData(*this, sessionId, data));
  2188. return sessionId;
  2189. }
  2190. void
  2191. GnssAdapter::gnssUpdateXtraThrottleCommand(const bool enabled)
  2192. {
  2193. LOC_LOGD("%s] enabled:%d", __func__, enabled);
  2194. struct UpdateXtraThrottleMsg : public LocMsg {
  2195. GnssAdapter& mAdapter;
  2196. const bool mEnabled;
  2197. inline UpdateXtraThrottleMsg(GnssAdapter& adapter, const bool enabled) :
  2198. LocMsg(),
  2199. mAdapter(adapter),
  2200. mEnabled(enabled) {}
  2201. inline virtual void proc() const {
  2202. mAdapter.mXtraObserver.updateXtraThrottle(mEnabled);
  2203. }
  2204. };
  2205. sendMsg(new UpdateXtraThrottleMsg(*this, enabled));
  2206. }
  2207. void
  2208. GnssAdapter::injectLocationCommand(double latitude, double longitude, float accuracy)
  2209. {
  2210. LOC_LOGD("%s]: latitude %8.4f longitude %8.4f accuracy %8.4f",
  2211. __func__, latitude, longitude, accuracy);
  2212. struct MsgInjectLocation : public LocMsg {
  2213. GnssAdapter& mAdapter;
  2214. LocApiBase& mApi;
  2215. ContextBase& mContext;
  2216. BlockCPIInfo& mBlockCPI;
  2217. double mLatitude;
  2218. double mLongitude;
  2219. float mAccuracy;
  2220. bool mOnDemandCpi;
  2221. inline MsgInjectLocation(GnssAdapter& adapter,
  2222. LocApiBase& api,
  2223. ContextBase& context,
  2224. BlockCPIInfo& blockCPIInfo,
  2225. double latitude,
  2226. double longitude,
  2227. float accuracy,
  2228. bool onDemandCpi) :
  2229. LocMsg(),
  2230. mAdapter(adapter),
  2231. mApi(api),
  2232. mContext(context),
  2233. mBlockCPI(blockCPIInfo),
  2234. mLatitude(latitude),
  2235. mLongitude(longitude),
  2236. mAccuracy(accuracy),
  2237. mOnDemandCpi(onDemandCpi) {}
  2238. inline virtual void proc() const {
  2239. if ((uptimeMillis() <= mBlockCPI.blockedTillTsMs) &&
  2240. (fabs(mLatitude-mBlockCPI.latitude) <= mBlockCPI.latLonDiffThreshold) &&
  2241. (fabs(mLongitude-mBlockCPI.longitude) <= mBlockCPI.latLonDiffThreshold)) {
  2242. LOC_LOGD("%s]: positon injection blocked: lat: %f, lon: %f, accuracy: %f",
  2243. __func__, mLatitude, mLongitude, mAccuracy);
  2244. } else {
  2245. if ((mAdapter.mOdcpiStateMask & CIVIC_ADDRESS_REQ_ACTIVE) &&
  2246. mAdapter.mAddressRequestCb != nullptr) {
  2247. Location location = {};
  2248. location.flags |= LOCATION_HAS_LAT_LONG_BIT;
  2249. location.latitude = mLatitude;
  2250. location.longitude = mLongitude;
  2251. location.flags |= LOCATION_HAS_ACCURACY_BIT;
  2252. location.accuracy = mAccuracy;
  2253. mAdapter.mAddressRequestCb(location);
  2254. }
  2255. mApi.injectPosition(mLatitude, mLongitude, mAccuracy, mOnDemandCpi);
  2256. }
  2257. }
  2258. };
  2259. sendMsg(new MsgInjectLocation(*this, *mLocApi, *mContext, mBlockCPIInfo,
  2260. latitude, longitude, accuracy,
  2261. mOdcpiStateMask & ODCPI_REQ_ACTIVE));
  2262. }
  2263. void
  2264. GnssAdapter::injectLocationExtCommand(const GnssLocationInfoNotification &locationInfo)
  2265. {
  2266. LOC_LOGd("latitude %8.4f longitude %8.4f accuracy %8.4f, tech mask 0x%x",
  2267. locationInfo.location.latitude, locationInfo.location.longitude,
  2268. locationInfo.location.accuracy, locationInfo.location.techMask);
  2269. struct MsgInjectLocationExt : public LocMsg {
  2270. LocApiBase& mApi;
  2271. ContextBase& mContext;
  2272. GnssLocationInfoNotification mLocationInfo;
  2273. inline MsgInjectLocationExt(LocApiBase& api,
  2274. ContextBase& context,
  2275. GnssLocationInfoNotification locationInfo) :
  2276. LocMsg(),
  2277. mApi(api),
  2278. mContext(context),
  2279. mLocationInfo(locationInfo) {}
  2280. inline virtual void proc() const {
  2281. // false to indicate for none-ODCPI
  2282. mApi.injectPosition(mLocationInfo, false);
  2283. }
  2284. };
  2285. sendMsg(new MsgInjectLocationExt(*mLocApi, *mContext, locationInfo));
  2286. }
  2287. void
  2288. GnssAdapter::injectTimeCommand(int64_t time, int64_t timeReference, int32_t uncertainty)
  2289. {
  2290. LOC_LOGD("%s]: time %lld timeReference %lld uncertainty %d",
  2291. __func__, (long long)time, (long long)timeReference, uncertainty);
  2292. struct MsgInjectTime : public LocMsg {
  2293. LocApiBase& mApi;
  2294. ContextBase& mContext;
  2295. int64_t mTime;
  2296. int64_t mTimeReference;
  2297. int32_t mUncertainty;
  2298. inline MsgInjectTime(LocApiBase& api,
  2299. ContextBase& context,
  2300. int64_t time,
  2301. int64_t timeReference,
  2302. int32_t uncertainty) :
  2303. LocMsg(),
  2304. mApi(api),
  2305. mContext(context),
  2306. mTime(time),
  2307. mTimeReference(timeReference),
  2308. mUncertainty(uncertainty) {}
  2309. inline virtual void proc() const {
  2310. mApi.setTime(mTime, mTimeReference, mUncertainty);
  2311. }
  2312. };
  2313. sendMsg(new MsgInjectTime(*mLocApi, *mContext, time, timeReference, uncertainty));
  2314. }
  2315. // This command is to called to block the position to be injected to the modem.
  2316. // This can happen for network position that comes from modem.
  2317. void
  2318. GnssAdapter::blockCPICommand(double latitude, double longitude,
  2319. float accuracy, int blockDurationMsec,
  2320. double latLonDiffThreshold)
  2321. {
  2322. struct MsgBlockCPI : public LocMsg {
  2323. BlockCPIInfo& mDstCPIInfo;
  2324. BlockCPIInfo mSrcCPIInfo;
  2325. inline MsgBlockCPI(BlockCPIInfo& dstCPIInfo,
  2326. BlockCPIInfo& srcCPIInfo) :
  2327. mDstCPIInfo(dstCPIInfo),
  2328. mSrcCPIInfo(srcCPIInfo) {}
  2329. inline virtual void proc() const {
  2330. // in the same hal thread, save the cpi to be blocked
  2331. // the global variable
  2332. mDstCPIInfo = mSrcCPIInfo;
  2333. }
  2334. };
  2335. // construct the new block CPI info and queue on the same thread
  2336. // for processing
  2337. BlockCPIInfo blockCPIInfo;
  2338. blockCPIInfo.latitude = latitude;
  2339. blockCPIInfo.longitude = longitude;
  2340. blockCPIInfo.accuracy = accuracy;
  2341. blockCPIInfo.blockedTillTsMs = uptimeMillis() + blockDurationMsec;
  2342. blockCPIInfo.latLonDiffThreshold = latLonDiffThreshold;
  2343. LOC_LOGD("%s]: block CPI lat: %f, lon: %f ", __func__, latitude, longitude);
  2344. // send a message to record down the coarse position
  2345. // to be blocked from injection in the master copy (mBlockCPIInfo)
  2346. sendMsg(new MsgBlockCPI(mBlockCPIInfo, blockCPIInfo));
  2347. }
  2348. void
  2349. GnssAdapter::updateSystemPowerState(PowerStateType systemPowerState) {
  2350. if (POWER_STATE_UNKNOWN != systemPowerState) {
  2351. mSystemPowerState = systemPowerState;
  2352. /*Manage active GNSS sessions based on power event*/
  2353. switch (systemPowerState){
  2354. case POWER_STATE_SUSPEND:
  2355. case POWER_STATE_SHUTDOWN:
  2356. suspendSessions();
  2357. LOC_LOGd("Suspending all active sessions -- powerState: %d", systemPowerState);
  2358. break;
  2359. case POWER_STATE_RESUME:
  2360. restartSessions(false);
  2361. LOC_LOGd("Re-starting all active sessions -- powerState: %d", systemPowerState);
  2362. break;
  2363. default:
  2364. break;
  2365. } // switch
  2366. mLocApi->updateSystemPowerState(mSystemPowerState);
  2367. }
  2368. }
  2369. void
  2370. GnssAdapter::updateSystemPowerStateCommand(PowerStateType systemPowerState) {
  2371. LOC_LOGd("power event %d", systemPowerState);
  2372. struct MsgUpdatePowerState : public LocMsg {
  2373. GnssAdapter& mAdapter;
  2374. PowerStateType mSystemPowerState;
  2375. inline MsgUpdatePowerState(GnssAdapter& adapter,
  2376. PowerStateType systemPowerState) :
  2377. LocMsg(),
  2378. mAdapter(adapter),
  2379. mSystemPowerState(systemPowerState) {}
  2380. inline virtual void proc() const {
  2381. mAdapter.updateSystemPowerState(mSystemPowerState);
  2382. }
  2383. };
  2384. sendMsg(new MsgUpdatePowerState(*this, systemPowerState));
  2385. }
  2386. void
  2387. GnssAdapter::addClientCommand(LocationAPI* client, const LocationCallbacks& callbacks)
  2388. {
  2389. LOC_LOGD("%s]: client %p", __func__, client);
  2390. struct MsgAddClient : public LocMsg {
  2391. GnssAdapter& mAdapter;
  2392. LocationAPI* mClient;
  2393. const LocationCallbacks mCallbacks;
  2394. inline MsgAddClient(GnssAdapter& adapter,
  2395. LocationAPI* client,
  2396. const LocationCallbacks& callbacks) :
  2397. LocMsg(),
  2398. mAdapter(adapter),
  2399. mClient(client),
  2400. mCallbacks(callbacks) {}
  2401. inline virtual void proc() const {
  2402. // check whether we need to notify client of cached location system info
  2403. mAdapter.notifyClientOfCachedLocationSystemInfo(mClient, mCallbacks);
  2404. mAdapter.saveClient(mClient, mCallbacks);
  2405. }
  2406. };
  2407. sendMsg(new MsgAddClient(*this, client, callbacks));
  2408. }
  2409. void
  2410. GnssAdapter::stopClientSessions(LocationAPI* client, bool eraseSession)
  2411. {
  2412. LOC_LOGD("%s]: client %p", __func__, client);
  2413. /* Time-based Tracking */
  2414. std::vector<LocationSessionKey> vTimeBasedTrackingClient;
  2415. for (auto it : mTimeBasedTrackingSessions) {
  2416. if (client == it.first.client) {
  2417. vTimeBasedTrackingClient.emplace_back(it.first.client, it.first.id);
  2418. }
  2419. }
  2420. for (auto key : vTimeBasedTrackingClient) {
  2421. stopTimeBasedTrackingMultiplex(key.client, key.id);
  2422. if (eraseSession)
  2423. eraseTrackingSession(key.client, key.id);
  2424. }
  2425. /* Distance-based Tracking */
  2426. for (auto it = mDistanceBasedTrackingSessions.begin();
  2427. it != mDistanceBasedTrackingSessions.end(); /* no increment here*/) {
  2428. if (client == it->first.client) {
  2429. mLocApi->stopDistanceBasedTracking(it->first.id, new LocApiResponse(*getContext(),
  2430. [this, client, id=it->first.id, eraseSession] (LocationError err) {
  2431. if (LOCATION_ERROR_SUCCESS == err) {
  2432. if (eraseSession)
  2433. eraseTrackingSession(client, id);
  2434. }
  2435. }
  2436. ));
  2437. }
  2438. ++it; // increment only when not erasing an iterator
  2439. }
  2440. }
  2441. void
  2442. GnssAdapter::updateClientsEventMask()
  2443. {
  2444. // need to register for leap second info
  2445. // for proper nmea generation
  2446. LOC_API_ADAPTER_EVENT_MASK_T mask = LOC_API_ADAPTER_BIT_LOC_SYSTEM_INFO |
  2447. LOC_API_ADAPTER_BIT_EVENT_REPORT_INFO;
  2448. for (auto it=mClientData.begin(); it != mClientData.end(); ++it) {
  2449. if (it->second.trackingCb != nullptr ||
  2450. it->second.gnssLocationInfoCb != nullptr ||
  2451. it->second.engineLocationsInfoCb != nullptr) {
  2452. mask |= LOC_API_ADAPTER_BIT_PARSED_POSITION_REPORT;
  2453. }
  2454. if (it->second.gnssSvCb != nullptr) {
  2455. mask |= LOC_API_ADAPTER_BIT_SATELLITE_REPORT;
  2456. }
  2457. if ((it->second.gnssNmeaCb != nullptr) && (mNmeaMask)) {
  2458. mask |= LOC_API_ADAPTER_BIT_NMEA_1HZ_REPORT;
  2459. }
  2460. if (it->second.gnssMeasurementsCb != nullptr) {
  2461. mask |= LOC_API_ADAPTER_BIT_GNSS_MEASUREMENT;
  2462. if (nullptr != mPowerIndicationCb) {
  2463. /* If power reporting is requested this implies Android 'S' or higher,
  2464. meaning we need to enable poly message (necessary for satellite
  2465. PVT report). We do it this way since satellite PVT are reported
  2466. in the measurements cb, they don't have their own cb, and we want
  2467. to enable poly message only for Android 'S' or higher */
  2468. mask |= LOC_API_ADAPTER_BIT_GNSS_SV_POLYNOMIAL_REPORT;
  2469. }
  2470. }
  2471. if (it->second.gnssNHzMeasurementsCb != nullptr) {
  2472. mask |= LOC_API_ADAPTER_BIT_GNSS_NHZ_MEASUREMENT;
  2473. }
  2474. if (it->second.gnssDataCb != nullptr) {
  2475. mask |= LOC_API_ADAPTER_BIT_PARSED_POSITION_REPORT;
  2476. mask |= LOC_API_ADAPTER_BIT_NMEA_1HZ_REPORT;
  2477. updateNmeaMask(mNmeaMask | LOC_NMEA_MASK_DEBUG_V02);
  2478. }
  2479. }
  2480. /*
  2481. ** For Automotive use cases we need to enable MEASUREMENT, POLY and EPHEMERIS
  2482. ** when QDR is enabled (e.g.: either enabled via conf file or
  2483. ** engine hub is loaded successfully).
  2484. ** Note: this need to be called from msg queue thread.
  2485. */
  2486. if((1 == ContextBase::mGps_conf.EXTERNAL_DR_ENABLED) ||
  2487. (true == initEngHubProxy())) {
  2488. mask |= LOC_API_ADAPTER_BIT_GNSS_MEASUREMENT;
  2489. mask |= LOC_API_ADAPTER_BIT_GNSS_SV_POLYNOMIAL_REPORT;
  2490. mask |= LOC_API_ADAPTER_BIT_PARSED_UNPROPAGATED_POSITION_REPORT;
  2491. mask |= LOC_API_ADAPTER_BIT_GNSS_SV_EPHEMERIS_REPORT;
  2492. // Nhz measurement bit is set based on callback from loc eng hub
  2493. // for Nhz engines.
  2494. mask |= checkMask(LOC_API_ADAPTER_BIT_GNSS_NHZ_MEASUREMENT);
  2495. LOC_LOGd("Auto usecase, Enable MEAS/POLY/EPHEMERIS - mask 0x%" PRIx64 "",
  2496. mask);
  2497. }
  2498. if (mAgpsManager.isRegistered()) {
  2499. mask |= LOC_API_ADAPTER_BIT_LOCATION_SERVER_REQUEST;
  2500. }
  2501. // Add ODCPI handling
  2502. if (nullptr != mOdcpiRequestCb) {
  2503. mask |= LOC_API_ADAPTER_BIT_REQUEST_WIFI;
  2504. }
  2505. // need to register for leap second info
  2506. // for proper nmea generation
  2507. mask |= LOC_API_ADAPTER_BIT_LOC_SYSTEM_INFO;
  2508. // always register for NI NOTIFY VERIFY to handle internally in HAL
  2509. mask |= LOC_API_ADAPTER_BIT_NI_NOTIFY_VERIFY_REQUEST;
  2510. // Enable the latency report
  2511. if (mask & LOC_API_ADAPTER_BIT_GNSS_MEASUREMENT) {
  2512. if (mLogger.isLogEnabled()) {
  2513. mask |= LOC_API_ADAPTER_BIT_LATENCY_INFORMATION;
  2514. }
  2515. }
  2516. updateEvtMask(mask, LOC_REGISTRATION_MASK_SET);
  2517. }
  2518. void
  2519. GnssAdapter::handleEngineUpEvent()
  2520. {
  2521. LOC_LOGD("%s]: ", __func__);
  2522. struct MsgHandleEngineUpEvent : public LocMsg {
  2523. GnssAdapter& mAdapter;
  2524. inline MsgHandleEngineUpEvent(GnssAdapter& adapter) :
  2525. LocMsg(),
  2526. mAdapter(adapter) {}
  2527. virtual void proc() const {
  2528. mAdapter.setEngineCapabilitiesKnown(true);
  2529. mAdapter.broadcastCapabilities(mAdapter.getCapabilities());
  2530. // must be called only after capabilities are known
  2531. mAdapter.setConfig();
  2532. mAdapter.gnssSvIdConfigUpdate();
  2533. mAdapter.gnssSvTypeConfigUpdate();
  2534. mAdapter.updateSystemPowerState(mAdapter.getSystemPowerState());
  2535. mAdapter.gnssSecondaryBandConfigUpdate();
  2536. // restart sessions only in power state resume
  2537. if ((POWER_STATE_SUSPEND != mAdapter.mSystemPowerState) &&
  2538. POWER_STATE_SHUTDOWN != mAdapter.mSystemPowerState) {
  2539. mAdapter.restartSessions(true);
  2540. }
  2541. for (auto msg: mAdapter.mPendingMsgs) {
  2542. mAdapter.sendMsg(msg);
  2543. }
  2544. mAdapter.mPendingMsgs.clear();
  2545. mAdapter.initGnssPowerStatistics();
  2546. }
  2547. };
  2548. readConfigCommand();
  2549. sendMsg(new MsgHandleEngineUpEvent(*this));
  2550. }
  2551. void
  2552. GnssAdapter::restartSessions(bool modemSSR)
  2553. {
  2554. LOC_LOGi(":enter");
  2555. if (modemSSR) {
  2556. // odcpi session is no longer active after restart
  2557. mOdcpiStateMask = 0;
  2558. }
  2559. // SPE will be restarted now, so set this variable to false.
  2560. mSPEAlreadyRunningAtHighestInterval = false;
  2561. if (false == mTimeBasedTrackingSessions.empty()) {
  2562. // inform engine hub that GNSS session is about to start
  2563. mEngHubProxy->gnssSetFixMode(mLocPositionMode);
  2564. mEngHubProxy->gnssStartFix();
  2565. checkUpdateDgnssNtrip(false);
  2566. }
  2567. checkAndRestartSPESession();
  2568. }
  2569. void GnssAdapter::checkAndRestartSPESession()
  2570. {
  2571. LOC_LOGD("%s]: ", __func__);
  2572. // SPE will be restarted now, so set this variable to false.
  2573. mSPEAlreadyRunningAtHighestInterval = false;
  2574. checkAndRestartTimeBasedSession();
  2575. for (auto it = mDistanceBasedTrackingSessions.begin();
  2576. it != mDistanceBasedTrackingSessions.end(); ++it) {
  2577. mLocApi->startDistanceBasedTracking(it->first.id, it->second,
  2578. new LocApiResponse(*getContext(),
  2579. [] (LocationError /*err*/) {}));
  2580. }
  2581. }
  2582. // suspend all on-going sessions
  2583. void
  2584. GnssAdapter::suspendSessions()
  2585. {
  2586. LOC_LOGi(":enter");
  2587. if (!mTimeBasedTrackingSessions.empty()) {
  2588. // inform engine hub that GNSS session has stopped
  2589. mEngHubProxy->gnssStopFix();
  2590. mLocApi->stopFix(nullptr);
  2591. if (isDgnssNmeaRequired()) {
  2592. mDgnssState &= ~DGNSS_STATE_NO_NMEA_PENDING;
  2593. }
  2594. stopDgnssNtrip();
  2595. mPositionElapsedRealTimeCal.reset();
  2596. mSPEAlreadyRunningAtHighestInterval = false;
  2597. }
  2598. }
  2599. void GnssAdapter::checkAndRestartTimeBasedSession()
  2600. {
  2601. LOC_LOGD("%s]: ", __func__);
  2602. if (!mTimeBasedTrackingSessions.empty()) {
  2603. // get the LocationOptions that has the smallest interval, which should be the active one
  2604. TrackingOptions smallestIntervalOptions; // size is zero until set for the first time
  2605. TrackingOptions highestPowerTrackingOptions;
  2606. memset(&smallestIntervalOptions, 0, sizeof(smallestIntervalOptions));
  2607. memset(&highestPowerTrackingOptions, 0, sizeof(highestPowerTrackingOptions));
  2608. for (auto it = mTimeBasedTrackingSessions.begin();
  2609. it != mTimeBasedTrackingSessions.end(); ++it) {
  2610. // size of zero means we havent set it yet
  2611. if (0 == smallestIntervalOptions.size ||
  2612. it->second.minInterval < smallestIntervalOptions.minInterval) {
  2613. smallestIntervalOptions = it->second;
  2614. }
  2615. GnssPowerMode powerMode = it->second.powerMode;
  2616. // Size of zero means we havent set it yet
  2617. if (0 == highestPowerTrackingOptions.size ||
  2618. (GNSS_POWER_MODE_INVALID != powerMode &&
  2619. powerMode < highestPowerTrackingOptions.powerMode)) {
  2620. highestPowerTrackingOptions = it->second;
  2621. }
  2622. }
  2623. highestPowerTrackingOptions.setLocationOptions(smallestIntervalOptions);
  2624. // want to run SPE session at a fixed min interval in some automotive scenarios
  2625. if(!checkAndSetSPEToRunforNHz(highestPowerTrackingOptions)) {
  2626. mLocApi->startTimeBasedTracking(highestPowerTrackingOptions, nullptr);
  2627. }
  2628. }
  2629. }
  2630. LocationCapabilitiesMask
  2631. GnssAdapter::getCapabilities()
  2632. {
  2633. LocationCapabilitiesMask mask = 0;
  2634. uint32_t carrierCapabilities = ContextBase::getCarrierCapabilities();
  2635. // time based tracking always supported
  2636. mask |= LOCATION_CAPABILITIES_TIME_BASED_TRACKING_BIT;
  2637. // geofence always supported
  2638. mask |= LOCATION_CAPABILITIES_GEOFENCE_BIT;
  2639. if (carrierCapabilities & LOC_GPS_CAPABILITY_MSB) {
  2640. mask |= LOCATION_CAPABILITIES_GNSS_MSB_BIT;
  2641. }
  2642. if (LOC_GPS_CAPABILITY_MSA & carrierCapabilities) {
  2643. mask |= LOCATION_CAPABILITIES_GNSS_MSA_BIT;
  2644. }
  2645. if (ContextBase::isMessageSupported(LOC_API_ADAPTER_MESSAGE_DISTANCE_BASE_LOCATION_BATCHING)) {
  2646. mask |= LOCATION_CAPABILITIES_TIME_BASED_BATCHING_BIT |
  2647. LOCATION_CAPABILITIES_DISTANCE_BASED_BATCHING_BIT;
  2648. }
  2649. if (ContextBase::isMessageSupported(LOC_API_ADAPTER_MESSAGE_DISTANCE_BASE_TRACKING)) {
  2650. mask |= LOCATION_CAPABILITIES_DISTANCE_BASED_TRACKING_BIT;
  2651. }
  2652. if (ContextBase::isMessageSupported(LOC_API_ADAPTER_MESSAGE_OUTDOOR_TRIP_BATCHING)) {
  2653. mask |= LOCATION_CAPABILITIES_OUTDOOR_TRIP_BATCHING_BIT;
  2654. }
  2655. if (ContextBase::gnssConstellationConfig()) {
  2656. mask |= LOCATION_CAPABILITIES_GNSS_MEASUREMENTS_BIT;
  2657. }
  2658. if (ContextBase::isFeatureSupported(LOC_SUPPORTED_FEATURE_DEBUG_NMEA_V02)) {
  2659. mask |= LOCATION_CAPABILITIES_DEBUG_NMEA_BIT;
  2660. }
  2661. if (ContextBase::isFeatureSupported(LOC_SUPPORTED_FEATURE_CONSTELLATION_ENABLEMENT_V02)) {
  2662. mask |= LOCATION_CAPABILITIES_CONSTELLATION_ENABLEMENT_BIT;
  2663. }
  2664. if (ContextBase::isFeatureSupported(LOC_SUPPORTED_FEATURE_AGPM_V02)) {
  2665. mask |= LOCATION_CAPABILITIES_AGPM_BIT;
  2666. }
  2667. //Get QWES feature status mask
  2668. mask |= ContextBase::getQwesFeatureStatus();
  2669. return mask;
  2670. }
  2671. void
  2672. GnssAdapter::notifyClientOfCachedLocationSystemInfo(
  2673. LocationAPI* client, const LocationCallbacks& callbacks) {
  2674. if (mLocSystemInfo.systemInfoMask) {
  2675. // client need to be notified if client has not yet previously registered
  2676. // for the info but now register for it.
  2677. bool notifyClientOfSystemInfo = false;
  2678. // check whether we need to notify client of cached location system info
  2679. //
  2680. // client need to be notified if client has not yet previously registered
  2681. // for the info but now register for it.
  2682. if (callbacks.locationSystemInfoCb) {
  2683. notifyClientOfSystemInfo = true;
  2684. auto it = mClientData.find(client);
  2685. if (it != mClientData.end()) {
  2686. LocationCallbacks oldCallbacks = it->second;
  2687. if (oldCallbacks.locationSystemInfoCb) {
  2688. notifyClientOfSystemInfo = false;
  2689. }
  2690. }
  2691. }
  2692. if (notifyClientOfSystemInfo) {
  2693. callbacks.locationSystemInfoCb(mLocSystemInfo);
  2694. }
  2695. }
  2696. }
  2697. bool
  2698. GnssAdapter::isTimeBasedTrackingSession(LocationAPI* client, uint32_t sessionId)
  2699. {
  2700. LocationSessionKey key(client, sessionId);
  2701. return (mTimeBasedTrackingSessions.find(key) != mTimeBasedTrackingSessions.end());
  2702. }
  2703. bool
  2704. GnssAdapter::isDistanceBasedTrackingSession(LocationAPI* client, uint32_t sessionId)
  2705. {
  2706. LocationSessionKey key(client, sessionId);
  2707. return (mDistanceBasedTrackingSessions.find(key) != mDistanceBasedTrackingSessions.end());
  2708. }
  2709. bool
  2710. GnssAdapter::hasCallbacksToStartTracking(LocationAPI* client)
  2711. {
  2712. bool allowed = false;
  2713. auto it = mClientData.find(client);
  2714. if (it != mClientData.end()) {
  2715. if (it->second.trackingCb || it->second.gnssLocationInfoCb ||
  2716. it->second.engineLocationsInfoCb || it->second.gnssMeasurementsCb ||
  2717. it->second.gnssNHzMeasurementsCb || it->second.gnssDataCb ||
  2718. it->second.gnssSvCb || it->second.gnssNmeaCb) {
  2719. allowed = true;
  2720. } else {
  2721. LOC_LOGi("missing right callback to start tracking")
  2722. }
  2723. } else {
  2724. LOC_LOGi("client %p not found", client)
  2725. }
  2726. return allowed;
  2727. }
  2728. bool
  2729. GnssAdapter::isTrackingSession(LocationAPI* client, uint32_t sessionId)
  2730. {
  2731. LocationSessionKey key(client, sessionId);
  2732. return (mTimeBasedTrackingSessions.find(key) != mTimeBasedTrackingSessions.end());
  2733. }
  2734. void
  2735. GnssAdapter::reportPowerStateIfChanged()
  2736. {
  2737. bool newPowerOn = !mTimeBasedTrackingSessions.empty() ||
  2738. !mDistanceBasedTrackingSessions.empty();
  2739. if (newPowerOn != mPowerOn) {
  2740. mPowerOn = newPowerOn;
  2741. if (mPowerStateCb != nullptr) {
  2742. mPowerStateCb(mPowerOn);
  2743. }
  2744. }
  2745. }
  2746. void
  2747. GnssAdapter::getPowerStateChangesCommand(std::function<void(bool)> powerStateCb)
  2748. {
  2749. LOC_LOGD("%s]: ", __func__);
  2750. struct MsgReportLocation : public LocMsg {
  2751. GnssAdapter& mAdapter;
  2752. std::function<void(bool)> mPowerStateCb;
  2753. inline MsgReportLocation(GnssAdapter& adapter,
  2754. std::function<void(bool)> powerStateCb) :
  2755. LocMsg(),
  2756. mAdapter(adapter),
  2757. mPowerStateCb(powerStateCb) {}
  2758. inline virtual void proc() const {
  2759. mAdapter.savePowerStateCallback(mPowerStateCb);
  2760. mPowerStateCb(mAdapter.getPowerState());
  2761. }
  2762. };
  2763. sendMsg(new MsgReportLocation(*this, powerStateCb));
  2764. }
  2765. void
  2766. GnssAdapter::saveTrackingSession(LocationAPI* client, uint32_t sessionId,
  2767. const TrackingOptions& options)
  2768. {
  2769. LocationSessionKey key(client, sessionId);
  2770. if ((options.minDistance > 0) &&
  2771. ContextBase::isMessageSupported(LOC_API_ADAPTER_MESSAGE_DISTANCE_BASE_TRACKING)) {
  2772. mDistanceBasedTrackingSessions[key] = options;
  2773. } else {
  2774. mTimeBasedTrackingSessions[key] = options;
  2775. }
  2776. reportPowerStateIfChanged();
  2777. // notify SystemStatus the engine tracking status
  2778. getSystemStatus()->setTracking(isInSession());
  2779. }
  2780. void
  2781. GnssAdapter::eraseTrackingSession(LocationAPI* client, uint32_t sessionId)
  2782. {
  2783. LocationSessionKey key(client, sessionId);
  2784. auto it = mTimeBasedTrackingSessions.find(key);
  2785. if (it != mTimeBasedTrackingSessions.end()) {
  2786. mTimeBasedTrackingSessions.erase(it);
  2787. } else {
  2788. auto itr = mDistanceBasedTrackingSessions.find(key);
  2789. if (itr != mDistanceBasedTrackingSessions.end()) {
  2790. mDistanceBasedTrackingSessions.erase(itr);
  2791. }
  2792. }
  2793. reportPowerStateIfChanged();
  2794. getSystemStatus()->setTracking(isInSession());
  2795. }
  2796. bool GnssAdapter::setLocPositionMode(const LocPosMode& mode) {
  2797. if (!mLocPositionMode.equals(mode)) {
  2798. mLocPositionMode = mode;
  2799. return true;
  2800. } else {
  2801. return false;
  2802. }
  2803. }
  2804. void
  2805. GnssAdapter::reportResponse(LocationAPI* client, LocationError err, uint32_t sessionId)
  2806. {
  2807. LOC_LOGD("%s]: client %p id %u err %u", __func__, client, sessionId, err);
  2808. auto it = mClientData.find(client);
  2809. if (it != mClientData.end() && it->second.responseCb != nullptr) {
  2810. it->second.responseCb(err, sessionId);
  2811. } else {
  2812. LOC_LOGW("%s]: client %p id %u not found in data", __func__, client, sessionId);
  2813. }
  2814. }
  2815. void
  2816. GnssAdapter::reportResponse(LocationError err, uint32_t sessionId)
  2817. {
  2818. LOC_LOGD("%s]: id %u err %u", __func__, sessionId, err);
  2819. if (mControlCallbacks.size > 0 && mControlCallbacks.responseCb != nullptr) {
  2820. mControlCallbacks.responseCb(err, sessionId);
  2821. } else {
  2822. LOC_LOGW("%s]: control client response callback not found", __func__);
  2823. }
  2824. }
  2825. void
  2826. GnssAdapter::reportResponse(size_t count, LocationError* errs, uint32_t* ids)
  2827. {
  2828. IF_LOC_LOGD {
  2829. std::string idsString = "[";
  2830. std::string errsString = "[";
  2831. if (NULL != ids && NULL != errs) {
  2832. for (size_t i=0; i < count; ++i) {
  2833. idsString += std::to_string(ids[i]) + " ";
  2834. errsString += std::to_string(errs[i]) + " ";
  2835. }
  2836. }
  2837. idsString += "]";
  2838. errsString += "]";
  2839. LOC_LOGD("%s]: ids %s errs %s",
  2840. __func__, idsString.c_str(), errsString.c_str());
  2841. }
  2842. if (mControlCallbacks.size > 0 && mControlCallbacks.collectiveResponseCb != nullptr) {
  2843. mControlCallbacks.collectiveResponseCb(count, errs, ids);
  2844. } else {
  2845. LOC_LOGW("%s]: control client callback not found", __func__);
  2846. }
  2847. }
  2848. uint32_t
  2849. GnssAdapter::startTrackingCommand(LocationAPI* client, TrackingOptions& options)
  2850. {
  2851. uint32_t sessionId = generateSessionId();
  2852. LOC_LOGD("%s]: client %p id %u minInterval %u minDistance %u mode %u powermode %u tbm %u",
  2853. __func__, client, sessionId, options.minInterval, options.minDistance, options.mode,
  2854. options.powerMode, options.tbm);
  2855. struct MsgStartTracking : public LocMsg {
  2856. GnssAdapter& mAdapter;
  2857. LocApiBase& mApi;
  2858. LocationAPI* mClient;
  2859. uint32_t mSessionId;
  2860. mutable TrackingOptions mOptions;
  2861. inline MsgStartTracking(GnssAdapter& adapter,
  2862. LocApiBase& api,
  2863. LocationAPI* client,
  2864. uint32_t sessionId,
  2865. TrackingOptions options) :
  2866. LocMsg(),
  2867. mAdapter(adapter),
  2868. mApi(api),
  2869. mClient(client),
  2870. mSessionId(sessionId),
  2871. mOptions(options) {}
  2872. inline virtual void proc() const {
  2873. // distance based tracking will need to know engine capabilities before it can start
  2874. if (!mAdapter.isEngineCapabilitiesKnown() && mOptions.minDistance > 0) {
  2875. mAdapter.mPendingMsgs.push_back(new MsgStartTracking(*this));
  2876. return;
  2877. }
  2878. LocationError err = LOCATION_ERROR_SUCCESS;
  2879. if (!mAdapter.hasCallbacksToStartTracking(mClient)) {
  2880. err = LOCATION_ERROR_CALLBACK_MISSING;
  2881. } else if (0 == mOptions.size) {
  2882. err = LOCATION_ERROR_INVALID_PARAMETER;
  2883. } else {
  2884. if (mOptions.minInterval < MIN_TRACKING_INTERVAL) {
  2885. mOptions.minInterval = MIN_TRACKING_INTERVAL;
  2886. }
  2887. if (mOptions.minDistance > 0 &&
  2888. ContextBase::isMessageSupported(
  2889. LOC_API_ADAPTER_MESSAGE_DISTANCE_BASE_TRACKING)) {
  2890. mAdapter.saveTrackingSession(mClient, mSessionId, mOptions);
  2891. mApi.startDistanceBasedTracking(mSessionId, mOptions,
  2892. new LocApiResponse(*mAdapter.getContext(),
  2893. [&mAdapter = mAdapter, mSessionId = mSessionId, mClient = mClient]
  2894. (LocationError err) {
  2895. if (LOCATION_ERROR_SUCCESS != err) {
  2896. mAdapter.eraseTrackingSession(mClient, mSessionId);
  2897. }
  2898. mAdapter.reportResponse(mClient, err, mSessionId);
  2899. }));
  2900. } else {
  2901. if (GNSS_POWER_MODE_M4 == mOptions.powerMode &&
  2902. mOptions.tbm > TRACKING_TBM_THRESHOLD_MILLIS) {
  2903. LOC_LOGd("TBM (%d) > %d Falling back to M2 power mode",
  2904. mOptions.tbm, TRACKING_TBM_THRESHOLD_MILLIS);
  2905. mOptions.powerMode = GNSS_POWER_MODE_M2;
  2906. }
  2907. // Api doesn't support multiple clients for time based tracking, so mutiplex
  2908. bool reportToClientWithNoWait =
  2909. mAdapter.startTimeBasedTrackingMultiplex(mClient, mSessionId, mOptions);
  2910. mAdapter.saveTrackingSession(mClient, mSessionId, mOptions);
  2911. if (reportToClientWithNoWait) {
  2912. mAdapter.reportResponse(mClient, LOCATION_ERROR_SUCCESS, mSessionId);
  2913. }
  2914. }
  2915. }
  2916. }
  2917. };
  2918. sendMsg(new MsgStartTracking(*this, *mLocApi, client, sessionId, options));
  2919. return sessionId;
  2920. }
  2921. bool
  2922. GnssAdapter::startTimeBasedTrackingMultiplex(LocationAPI* client, uint32_t sessionId,
  2923. const TrackingOptions& options)
  2924. {
  2925. bool reportToClientWithNoWait = true;
  2926. if (mTimeBasedTrackingSessions.empty()) {
  2927. /*Reset previous NMEA reported time stamp */
  2928. mPrevNmeaRptTimeNsec = 0;
  2929. startTimeBasedTracking(client, sessionId, options);
  2930. // need to wait for QMI callback
  2931. reportToClientWithNoWait = false;
  2932. } else {
  2933. // find the smallest interval and powerMode
  2934. TrackingOptions multiplexedOptions = {}; // size is 0 until set for the first time
  2935. GnssPowerMode multiplexedPowerMode = GNSS_POWER_MODE_INVALID;
  2936. memset(&multiplexedOptions, 0, sizeof(multiplexedOptions));
  2937. for (auto it = mTimeBasedTrackingSessions.begin(); it != mTimeBasedTrackingSessions.end(); ++it) {
  2938. // if not set or there is a new smallest interval, then set the new interval
  2939. if (0 == multiplexedOptions.size ||
  2940. it->second.minInterval < multiplexedOptions.minInterval) {
  2941. multiplexedOptions = it->second;
  2942. }
  2943. // if session is not the one we are updating and either powerMode
  2944. // is not set or there is a new smallest powerMode, then set the new powerMode
  2945. if (GNSS_POWER_MODE_INVALID == multiplexedPowerMode ||
  2946. it->second.powerMode < multiplexedPowerMode) {
  2947. multiplexedPowerMode = it->second.powerMode;
  2948. }
  2949. }
  2950. bool updateOptions = false;
  2951. // if session we are starting has smaller interval then next smallest
  2952. if (options.minInterval < multiplexedOptions.minInterval) {
  2953. multiplexedOptions.minInterval = options.minInterval;
  2954. updateOptions = true;
  2955. }
  2956. // if session we are starting has smaller powerMode then next smallest
  2957. if (options.powerMode < multiplexedPowerMode) {
  2958. multiplexedOptions.powerMode = options.powerMode;
  2959. updateOptions = true;
  2960. }
  2961. if (updateOptions) {
  2962. // restart time based tracking with the newly updated options
  2963. startTimeBasedTracking(client, sessionId, multiplexedOptions);
  2964. // need to wait for QMI callback
  2965. reportToClientWithNoWait = false;
  2966. }
  2967. // else part: no QMI call is made, need to report back to client right away
  2968. }
  2969. return reportToClientWithNoWait;
  2970. }
  2971. void
  2972. GnssAdapter::startTimeBasedTracking(LocationAPI* client, uint32_t sessionId,
  2973. const TrackingOptions& trackingOptions)
  2974. {
  2975. LOC_LOGd("minInterval %u minDistance %u mode %u powermode %u tbm %u",
  2976. trackingOptions.minInterval, trackingOptions.minDistance,
  2977. trackingOptions.mode, trackingOptions.powerMode, trackingOptions.tbm);
  2978. LocPosMode locPosMode = {};
  2979. convertOptions(locPosMode, trackingOptions);
  2980. // save position mode parameters
  2981. setLocPositionMode(locPosMode);
  2982. // inform engine hub that GNSS session is about to start
  2983. mEngHubProxy->gnssSetFixMode(mLocPositionMode);
  2984. mEngHubProxy->gnssStartFix();
  2985. // want to run SPE session at a fixed min interval in some automotive scenarios
  2986. // use a local copy of TrackingOptions as the TBF may get modified in the
  2987. // checkAndSetSPEToRunforNHz function
  2988. TrackingOptions tempOptions(trackingOptions);
  2989. if (!checkAndSetSPEToRunforNHz(tempOptions)) {
  2990. mLocApi->startTimeBasedTracking(tempOptions, new LocApiResponse(*getContext(),
  2991. [this, client, sessionId] (LocationError err) {
  2992. if (LOCATION_ERROR_SUCCESS != err) {
  2993. eraseTrackingSession(client, sessionId);
  2994. } else {
  2995. checkUpdateDgnssNtrip(false);
  2996. }
  2997. reportResponse(client, err, sessionId);
  2998. }
  2999. ));
  3000. } else {
  3001. reportResponse(client, LOCATION_ERROR_SUCCESS, sessionId);
  3002. }
  3003. }
  3004. void
  3005. GnssAdapter::updateTracking(LocationAPI* client, uint32_t sessionId,
  3006. const TrackingOptions& updatedOptions, const TrackingOptions& oldOptions)
  3007. {
  3008. LocPosMode locPosMode = {};
  3009. convertOptions(locPosMode, updatedOptions);
  3010. // save position mode parameters
  3011. setLocPositionMode(locPosMode);
  3012. // inform engine hub that GNSS session is about to start
  3013. mEngHubProxy->gnssSetFixMode(mLocPositionMode);
  3014. mEngHubProxy->gnssStartFix();
  3015. // want to run SPE session at a fixed min interval in some automotive scenarios
  3016. // use a local copy of TrackingOptions as the TBF may get modified in the
  3017. // checkAndSetSPEToRunforNHz function
  3018. TrackingOptions tempOptions(updatedOptions);
  3019. if(!checkAndSetSPEToRunforNHz(tempOptions)) {
  3020. mLocApi->startTimeBasedTracking(tempOptions, new LocApiResponse(*getContext(),
  3021. [this, client, sessionId, oldOptions] (LocationError err) {
  3022. if (LOCATION_ERROR_SUCCESS != err) {
  3023. // restore the old LocationOptions
  3024. saveTrackingSession(client, sessionId, oldOptions);
  3025. }
  3026. reportResponse(client, err, sessionId);
  3027. }
  3028. ));
  3029. } else {
  3030. reportResponse(client, LOCATION_ERROR_SUCCESS, sessionId);
  3031. }
  3032. }
  3033. void
  3034. GnssAdapter::updateTrackingOptionsCommand(LocationAPI* client, uint32_t id,
  3035. TrackingOptions& options)
  3036. {
  3037. LOC_LOGD("%s]: client %p id %u minInterval %u mode %u",
  3038. __func__, client, id, options.minInterval, options.mode);
  3039. struct MsgUpdateTracking : public LocMsg {
  3040. GnssAdapter& mAdapter;
  3041. LocApiBase& mApi;
  3042. LocationAPI* mClient;
  3043. uint32_t mSessionId;
  3044. mutable TrackingOptions mOptions;
  3045. inline MsgUpdateTracking(GnssAdapter& adapter,
  3046. LocApiBase& api,
  3047. LocationAPI* client,
  3048. uint32_t sessionId,
  3049. TrackingOptions options) :
  3050. LocMsg(),
  3051. mAdapter(adapter),
  3052. mApi(api),
  3053. mClient(client),
  3054. mSessionId(sessionId),
  3055. mOptions(options) {}
  3056. inline virtual void proc() const {
  3057. // distance based tracking will need to know engine capabilities before it can start
  3058. if (!mAdapter.isEngineCapabilitiesKnown() && mOptions.minDistance > 0) {
  3059. mAdapter.mPendingMsgs.push_back(new MsgUpdateTracking(*this));
  3060. return;
  3061. }
  3062. LocationError err = LOCATION_ERROR_SUCCESS;
  3063. bool isTimeBased = mAdapter.isTimeBasedTrackingSession(mClient, mSessionId);
  3064. bool isDistanceBased = mAdapter.isDistanceBasedTrackingSession(mClient, mSessionId);
  3065. if (!isTimeBased && !isDistanceBased) {
  3066. err = LOCATION_ERROR_ID_UNKNOWN;
  3067. } else if (0 == mOptions.size) {
  3068. err = LOCATION_ERROR_INVALID_PARAMETER;
  3069. }
  3070. if (LOCATION_ERROR_SUCCESS != err) {
  3071. mAdapter.reportResponse(mClient, err, mSessionId);
  3072. } else {
  3073. if (GNSS_POWER_MODE_M4 == mOptions.powerMode &&
  3074. mOptions.tbm > TRACKING_TBM_THRESHOLD_MILLIS) {
  3075. LOC_LOGd("TBM (%d) > %d Falling back to M2 power mode",
  3076. mOptions.tbm, TRACKING_TBM_THRESHOLD_MILLIS);
  3077. mOptions.powerMode = GNSS_POWER_MODE_M2;
  3078. }
  3079. if (mOptions.minInterval < MIN_TRACKING_INTERVAL) {
  3080. mOptions.minInterval = MIN_TRACKING_INTERVAL;
  3081. }
  3082. // Now update session as required
  3083. if (isTimeBased && mOptions.minDistance > 0) {
  3084. // switch from time based to distance based
  3085. // Api doesn't support multiple clients for time based tracking, so mutiplex
  3086. bool reportToClientWithNoWait =
  3087. mAdapter.stopTimeBasedTrackingMultiplex(mClient, mSessionId);
  3088. // erases the time based Session
  3089. mAdapter.eraseTrackingSession(mClient, mSessionId);
  3090. if (reportToClientWithNoWait) {
  3091. mAdapter.reportResponse(mClient, LOCATION_ERROR_SUCCESS, mSessionId);
  3092. }
  3093. // saves as distance based Session
  3094. mAdapter.saveTrackingSession(mClient, mSessionId, mOptions);
  3095. mApi.startDistanceBasedTracking(mSessionId, mOptions,
  3096. new LocApiResponse(*mAdapter.getContext(),
  3097. [] (LocationError /*err*/) {}));
  3098. } else if (isDistanceBased && mOptions.minDistance == 0) {
  3099. // switch from distance based to time based
  3100. mAdapter.eraseTrackingSession(mClient, mSessionId);
  3101. mApi.stopDistanceBasedTracking(mSessionId, new LocApiResponse(
  3102. *mAdapter.getContext(),
  3103. [&mAdapter = mAdapter, mSessionId = mSessionId, mOptions = mOptions,
  3104. mClient = mClient] (LocationError /*err*/) {
  3105. // Api doesn't support multiple clients for time based tracking,
  3106. // so mutiplex
  3107. bool reportToClientWithNoWait =
  3108. mAdapter.startTimeBasedTrackingMultiplex(mClient, mSessionId,
  3109. mOptions);
  3110. mAdapter.saveTrackingSession(mClient, mSessionId, mOptions);
  3111. if (reportToClientWithNoWait) {
  3112. mAdapter.reportResponse(mClient, LOCATION_ERROR_SUCCESS, mSessionId);
  3113. }
  3114. }));
  3115. } else if (isTimeBased) {
  3116. // update time based tracking
  3117. // Api doesn't support multiple clients for time based tracking, so mutiplex
  3118. bool reportToClientWithNoWait =
  3119. mAdapter.updateTrackingMultiplex(mClient, mSessionId, mOptions);
  3120. mAdapter.saveTrackingSession(mClient, mSessionId, mOptions);
  3121. if (reportToClientWithNoWait) {
  3122. mAdapter.reportResponse(mClient, err, mSessionId);
  3123. }
  3124. } else if (isDistanceBased) {
  3125. // restart distance based tracking
  3126. mApi.stopDistanceBasedTracking(mSessionId, new LocApiResponse(
  3127. *mAdapter.getContext(),
  3128. [&mAdapter = mAdapter, mSessionId = mSessionId, mOptions = mOptions,
  3129. mClient = mClient, &mApi = mApi] (LocationError err) {
  3130. if (LOCATION_ERROR_SUCCESS == err) {
  3131. mApi.startDistanceBasedTracking(mSessionId, mOptions,
  3132. new LocApiResponse(*mAdapter.getContext(),
  3133. [&mAdapter, mClient, mSessionId, mOptions]
  3134. (LocationError err) {
  3135. if (LOCATION_ERROR_SUCCESS == err) {
  3136. mAdapter.saveTrackingSession(mClient, mSessionId, mOptions);
  3137. }
  3138. mAdapter.reportResponse(mClient, err, mSessionId);
  3139. }));
  3140. }
  3141. }));
  3142. }
  3143. }
  3144. }
  3145. };
  3146. sendMsg(new MsgUpdateTracking(*this, *mLocApi, client, id, options));
  3147. }
  3148. bool
  3149. GnssAdapter::updateTrackingMultiplex(LocationAPI* client, uint32_t id,
  3150. const TrackingOptions& trackingOptions)
  3151. {
  3152. bool reportToClientWithNoWait = true;
  3153. LocationSessionKey key(client, id);
  3154. // get the session we are updating
  3155. auto it = mTimeBasedTrackingSessions.find(key);
  3156. // cache the clients existing LocationOptions
  3157. TrackingOptions oldOptions = it->second;
  3158. // if session we are updating exists and the minInterval or powerMode has changed
  3159. if (it != mTimeBasedTrackingSessions.end() &&
  3160. (it->second.minInterval != trackingOptions.minInterval ||
  3161. it->second.powerMode != trackingOptions.powerMode)) {
  3162. // find the smallest interval and powerMode, other than the session we are updating
  3163. TrackingOptions multiplexedOptions = {}; // size is 0 until set for the first time
  3164. GnssPowerMode multiplexedPowerMode = GNSS_POWER_MODE_INVALID;
  3165. memset(&multiplexedOptions, 0, sizeof(multiplexedOptions));
  3166. for (auto it2 = mTimeBasedTrackingSessions.begin();
  3167. it2 != mTimeBasedTrackingSessions.end(); ++it2) {
  3168. // if session is not the one we are updating and either interval
  3169. // is not set or there is a new smallest interval, then set the new interval
  3170. if (it2->first != key && (0 == multiplexedOptions.size ||
  3171. it2->second.minInterval < multiplexedOptions.minInterval)) {
  3172. multiplexedOptions = it2->second;
  3173. }
  3174. // if session is not the one we are updating and either powerMode
  3175. // is not set or there is a new smallest powerMode, then set the new powerMode
  3176. if (it2->first != key && (GNSS_POWER_MODE_INVALID == multiplexedPowerMode ||
  3177. it2->second.powerMode < multiplexedPowerMode)) {
  3178. multiplexedPowerMode = it2->second.powerMode;
  3179. }
  3180. // else part: no QMI call is made, need to report back to client right away
  3181. }
  3182. bool updateOptions = false;
  3183. // if session we are updating has smaller interval then next smallest
  3184. if (trackingOptions.minInterval < multiplexedOptions.minInterval) {
  3185. multiplexedOptions.minInterval = trackingOptions.minInterval;
  3186. updateOptions = true;
  3187. }
  3188. // if session we are updating has smaller powerMode then next smallest
  3189. if (trackingOptions.powerMode < multiplexedPowerMode) {
  3190. multiplexedOptions.powerMode = trackingOptions.powerMode;
  3191. updateOptions = true;
  3192. }
  3193. // if only one session exists, then tracking should be updated with it
  3194. if (1 == mTimeBasedTrackingSessions.size()) {
  3195. multiplexedOptions = trackingOptions;
  3196. updateOptions = true;
  3197. }
  3198. if (updateOptions) {
  3199. // restart time based tracking with the newly updated options
  3200. updateTracking(client, id, multiplexedOptions, oldOptions);
  3201. // need to wait for QMI callback
  3202. reportToClientWithNoWait = false;
  3203. }
  3204. }
  3205. return reportToClientWithNoWait;
  3206. }
  3207. void
  3208. GnssAdapter::stopTrackingCommand(LocationAPI* client, uint32_t id)
  3209. {
  3210. LOC_LOGD("%s]: client %p id %u", __func__, client, id);
  3211. struct MsgStopTracking : public LocMsg {
  3212. GnssAdapter& mAdapter;
  3213. LocApiBase& mApi;
  3214. LocationAPI* mClient;
  3215. uint32_t mSessionId;
  3216. inline MsgStopTracking(GnssAdapter& adapter,
  3217. LocApiBase& api,
  3218. LocationAPI* client,
  3219. uint32_t sessionId) :
  3220. LocMsg(),
  3221. mAdapter(adapter),
  3222. mApi(api),
  3223. mClient(client),
  3224. mSessionId(sessionId) {}
  3225. inline virtual void proc() const {
  3226. bool isTimeBased = mAdapter.isTimeBasedTrackingSession(mClient, mSessionId);
  3227. bool isDistanceBased = mAdapter.isDistanceBasedTrackingSession(mClient, mSessionId);
  3228. if (isTimeBased || isDistanceBased) {
  3229. if (isTimeBased) {
  3230. // Api doesn't support multiple clients for time based tracking, so mutiplex
  3231. bool reportToClientWithNoWait =
  3232. mAdapter.stopTimeBasedTrackingMultiplex(mClient, mSessionId);
  3233. mAdapter.eraseTrackingSession(mClient, mSessionId);
  3234. if (reportToClientWithNoWait) {
  3235. mAdapter.reportResponse(mClient, LOCATION_ERROR_SUCCESS, mSessionId);
  3236. }
  3237. } else if (isDistanceBased) {
  3238. mApi.stopDistanceBasedTracking(mSessionId, new LocApiResponse(
  3239. *mAdapter.getContext(),
  3240. [&mAdapter = mAdapter, mSessionId = mSessionId, mClient = mClient]
  3241. (LocationError err) {
  3242. if (LOCATION_ERROR_SUCCESS == err) {
  3243. mAdapter.eraseTrackingSession(mClient, mSessionId);
  3244. }
  3245. mAdapter.reportResponse(mClient, err, mSessionId);
  3246. }));
  3247. }
  3248. } else {
  3249. mAdapter.reportResponse(mClient, LOCATION_ERROR_ID_UNKNOWN, mSessionId);
  3250. }
  3251. }
  3252. };
  3253. sendMsg(new MsgStopTracking(*this, *mLocApi, client, id));
  3254. }
  3255. bool
  3256. GnssAdapter::stopTimeBasedTrackingMultiplex(LocationAPI* client, uint32_t id)
  3257. {
  3258. bool reportToClientWithNoWait = true;
  3259. if (1 == mTimeBasedTrackingSessions.size()) {
  3260. stopTracking(client, id);
  3261. // need to wait for QMI callback
  3262. reportToClientWithNoWait = false;
  3263. } else {
  3264. LocationSessionKey key(client, id);
  3265. // get the session we are stopping
  3266. auto it = mTimeBasedTrackingSessions.find(key);
  3267. if (it != mTimeBasedTrackingSessions.end()) {
  3268. // find the smallest interval and powerMode, other than the session we are stopping
  3269. TrackingOptions multiplexedOptions = {}; // size is 0 until set for the first time
  3270. GnssPowerMode multiplexedPowerMode = GNSS_POWER_MODE_INVALID;
  3271. memset(&multiplexedOptions, 0, sizeof(multiplexedOptions));
  3272. for (auto it2 = mTimeBasedTrackingSessions.begin();
  3273. it2 != mTimeBasedTrackingSessions.end(); ++it2) {
  3274. // if session is not the one we are stopping and either interval
  3275. // is not set or there is a new smallest interval, then set the new interval
  3276. if (it2->first != key && (0 == multiplexedOptions.size ||
  3277. it2->second.minInterval < multiplexedOptions.minInterval)) {
  3278. multiplexedOptions = it2->second;
  3279. }
  3280. // if session is not the one we are stopping and either powerMode
  3281. // is not set or there is a new smallest powerMode, then set the new powerMode
  3282. if (it2->first != key && (GNSS_POWER_MODE_INVALID == multiplexedPowerMode ||
  3283. it2->second.powerMode < multiplexedPowerMode)) {
  3284. multiplexedPowerMode = it2->second.powerMode;
  3285. }
  3286. }
  3287. // if session we are stopping has smaller interval then next smallest or
  3288. // if session we are stopping has smaller powerMode then next smallest
  3289. if (it->second.minInterval < multiplexedOptions.minInterval ||
  3290. it->second.powerMode < multiplexedPowerMode) {
  3291. multiplexedOptions.powerMode = multiplexedPowerMode;
  3292. // restart time based tracking with the newly updated options
  3293. startTimeBasedTracking(client, id, multiplexedOptions);
  3294. // need to wait for QMI callback
  3295. reportToClientWithNoWait = false;
  3296. }
  3297. // else part: no QMI call is made, need to report back to client right away
  3298. }
  3299. }
  3300. return reportToClientWithNoWait;
  3301. }
  3302. void
  3303. GnssAdapter::stopTracking(LocationAPI* client, uint32_t id)
  3304. {
  3305. // inform engine hub that GNSS session has stopped
  3306. mEngHubProxy->gnssStopFix();
  3307. mLocApi->stopFix(new LocApiResponse(*getContext(),
  3308. [this, client, id] (LocationError err) {
  3309. reportResponse(client, err, id);
  3310. }));
  3311. if (isDgnssNmeaRequired()) {
  3312. mDgnssState &= ~DGNSS_STATE_NO_NMEA_PENDING;
  3313. }
  3314. stopDgnssNtrip();
  3315. mPositionElapsedRealTimeCal.reset();
  3316. mSPEAlreadyRunningAtHighestInterval = false;
  3317. }
  3318. bool
  3319. GnssAdapter::hasNiNotifyCallback(LocationAPI* client)
  3320. {
  3321. auto it = mClientData.find(client);
  3322. return (it != mClientData.end() && it->second.gnssNiCb);
  3323. }
  3324. void
  3325. GnssAdapter::gnssNiResponseCommand(LocationAPI* client,
  3326. uint32_t id,
  3327. GnssNiResponse response)
  3328. {
  3329. LOC_LOGD("%s]: client %p id %u response %u", __func__, client, id, response);
  3330. struct MsgGnssNiResponse : public LocMsg {
  3331. GnssAdapter& mAdapter;
  3332. LocationAPI* mClient;
  3333. uint32_t mSessionId;
  3334. GnssNiResponse mResponse;
  3335. inline MsgGnssNiResponse(GnssAdapter& adapter,
  3336. LocationAPI* client,
  3337. uint32_t sessionId,
  3338. GnssNiResponse response) :
  3339. LocMsg(),
  3340. mAdapter(adapter),
  3341. mClient(client),
  3342. mSessionId(sessionId),
  3343. mResponse(response) {}
  3344. inline virtual void proc() const {
  3345. NiData& niData = mAdapter.getNiData();
  3346. LocationError err = LOCATION_ERROR_SUCCESS;
  3347. if (!mAdapter.hasNiNotifyCallback(mClient)) {
  3348. err = LOCATION_ERROR_ID_UNKNOWN;
  3349. } else {
  3350. NiSession* pSession = NULL;
  3351. if (mSessionId == niData.sessionEs.reqID &&
  3352. NULL != niData.sessionEs.rawRequest) {
  3353. pSession = &niData.sessionEs;
  3354. // ignore any SUPL NI non-Es session if a SUPL NI ES is accepted
  3355. if (mResponse == GNSS_NI_RESPONSE_ACCEPT &&
  3356. NULL != niData.session.rawRequest) {
  3357. pthread_mutex_lock(&niData.session.tLock);
  3358. niData.session.resp = GNSS_NI_RESPONSE_IGNORE;
  3359. niData.session.respRecvd = true;
  3360. pthread_cond_signal(&niData.session.tCond);
  3361. pthread_mutex_unlock(&niData.session.tLock);
  3362. }
  3363. } else if (mSessionId == niData.session.reqID &&
  3364. NULL != niData.session.rawRequest) {
  3365. pSession = &niData.session;
  3366. }
  3367. if (pSession) {
  3368. LOC_LOGI("%s]: gnssNiResponseCommand: send user mResponse %u for id %u",
  3369. __func__, mResponse, mSessionId);
  3370. pthread_mutex_lock(&pSession->tLock);
  3371. pSession->resp = mResponse;
  3372. pSession->respRecvd = true;
  3373. pthread_cond_signal(&pSession->tCond);
  3374. pthread_mutex_unlock(&pSession->tLock);
  3375. } else {
  3376. err = LOCATION_ERROR_ID_UNKNOWN;
  3377. LOC_LOGE("%s]: gnssNiResponseCommand: id %u not an active session",
  3378. __func__, mSessionId);
  3379. }
  3380. }
  3381. mAdapter.reportResponse(mClient, err, mSessionId);
  3382. }
  3383. };
  3384. sendMsg(new MsgGnssNiResponse(*this, client, id, response));
  3385. }
  3386. void
  3387. GnssAdapter::gnssNiResponseCommand(GnssNiResponse response, void* rawRequest)
  3388. {
  3389. LOC_LOGD("%s]: response %u", __func__, response);
  3390. struct MsgGnssNiResponse : public LocMsg {
  3391. GnssAdapter& mAdapter;
  3392. LocApiBase& mApi;
  3393. const GnssNiResponse mResponse;
  3394. const void* mPayload;
  3395. inline MsgGnssNiResponse(GnssAdapter& adapter,
  3396. LocApiBase& api,
  3397. const GnssNiResponse response,
  3398. const void* rawRequest) :
  3399. LocMsg(),
  3400. mAdapter(adapter),
  3401. mApi(api),
  3402. mResponse(response),
  3403. mPayload(rawRequest) {}
  3404. inline virtual ~MsgGnssNiResponse() {
  3405. }
  3406. inline virtual void proc() const {
  3407. mApi.informNiResponse(mResponse, mPayload);
  3408. }
  3409. };
  3410. sendMsg(new MsgGnssNiResponse(*this, *mLocApi, response, rawRequest));
  3411. }
  3412. uint32_t
  3413. GnssAdapter::enableCommand(LocationTechnologyType techType)
  3414. {
  3415. uint32_t sessionId = generateSessionId();
  3416. LOC_LOGD("%s]: id %u techType %u", __func__, sessionId, techType);
  3417. struct MsgEnableGnss : public LocMsg {
  3418. GnssAdapter& mAdapter;
  3419. LocApiBase& mApi;
  3420. ContextBase& mContext;
  3421. uint32_t mSessionId;
  3422. LocationTechnologyType mTechType;
  3423. inline MsgEnableGnss(GnssAdapter& adapter,
  3424. LocApiBase& api,
  3425. ContextBase& context,
  3426. uint32_t sessionId,
  3427. LocationTechnologyType techType) :
  3428. LocMsg(),
  3429. mAdapter(adapter),
  3430. mApi(api),
  3431. mContext(context),
  3432. mSessionId(sessionId),
  3433. mTechType(techType) {}
  3434. inline virtual void proc() const {
  3435. LocationError err = LOCATION_ERROR_SUCCESS;
  3436. uint32_t afwControlId = mAdapter.getAfwControlId();
  3437. if (mTechType != LOCATION_TECHNOLOGY_TYPE_GNSS) {
  3438. err = LOCATION_ERROR_INVALID_PARAMETER;
  3439. } else if (afwControlId > 0) {
  3440. err = LOCATION_ERROR_ALREADY_STARTED;
  3441. } else {
  3442. mContext.modemPowerVote(true);
  3443. mAdapter.setAfwControlId(mSessionId);
  3444. GnssConfigGpsLock gpsLock = GNSS_CONFIG_GPS_LOCK_NONE;
  3445. if (mAdapter.mSupportNfwControl) {
  3446. ContextBase::mGps_conf.GPS_LOCK &= GNSS_CONFIG_GPS_LOCK_NFW_ALL;
  3447. gpsLock = ContextBase::mGps_conf.GPS_LOCK;
  3448. }
  3449. mApi.sendMsg(new LocApiMsg([&mApi = mApi, gpsLock]() {
  3450. mApi.setGpsLockSync(gpsLock);
  3451. }));
  3452. mAdapter.mXtraObserver.updateLockStatus(gpsLock);
  3453. }
  3454. mAdapter.reportResponse(err, mSessionId);
  3455. }
  3456. };
  3457. if (mContext != NULL) {
  3458. sendMsg(new MsgEnableGnss(*this, *mLocApi, *mContext, sessionId, techType));
  3459. } else {
  3460. LOC_LOGE("%s]: Context is NULL", __func__);
  3461. }
  3462. return sessionId;
  3463. }
  3464. void
  3465. GnssAdapter::disableCommand(uint32_t id)
  3466. {
  3467. LOC_LOGD("%s]: id %u", __func__, id);
  3468. struct MsgDisableGnss : public LocMsg {
  3469. GnssAdapter& mAdapter;
  3470. LocApiBase& mApi;
  3471. ContextBase& mContext;
  3472. uint32_t mSessionId;
  3473. inline MsgDisableGnss(GnssAdapter& adapter,
  3474. LocApiBase& api,
  3475. ContextBase& context,
  3476. uint32_t sessionId) :
  3477. LocMsg(),
  3478. mAdapter(adapter),
  3479. mApi(api),
  3480. mContext(context),
  3481. mSessionId(sessionId) {}
  3482. inline virtual void proc() const {
  3483. LocationError err = LOCATION_ERROR_SUCCESS;
  3484. uint32_t afwControlId = mAdapter.getAfwControlId();
  3485. if (afwControlId != mSessionId) {
  3486. err = LOCATION_ERROR_ID_UNKNOWN;
  3487. } else {
  3488. mContext.modemPowerVote(false);
  3489. mAdapter.setAfwControlId(0);
  3490. if (mAdapter.mSupportNfwControl) {
  3491. /* We need to disable MO (AFW) */
  3492. ContextBase::mGps_conf.GPS_LOCK |= GNSS_CONFIG_GPS_LOCK_MO;
  3493. }
  3494. GnssConfigGpsLock gpsLock = ContextBase::mGps_conf.GPS_LOCK;
  3495. mApi.sendMsg(new LocApiMsg([&mApi = mApi, gpsLock]() {
  3496. mApi.setGpsLockSync(gpsLock);
  3497. }));
  3498. mAdapter.mXtraObserver.updateLockStatus(gpsLock);
  3499. }
  3500. mAdapter.reportResponse(err, mSessionId);
  3501. }
  3502. };
  3503. if (mContext != NULL) {
  3504. sendMsg(new MsgDisableGnss(*this, *mLocApi, *mContext, id));
  3505. }
  3506. }
  3507. // This function computes the VRP based latitude, longitude and alittude, and
  3508. // north, east and up velocity and save the result into EHubTechReport.
  3509. void
  3510. GnssAdapter::computeVRPBasedLla(const UlpLocation& loc, GpsLocationExtended& locExt,
  3511. const LeverArmConfigInfo& leverArmConfigInfo) {
  3512. float leverArm[3];
  3513. float rollPitchYaw[3];
  3514. double lla[3];
  3515. uint16_t locFlags = loc.gpsLocation.flags;
  3516. uint64_t locExtFlags = locExt.flags;
  3517. // check for SPE fix
  3518. if (!((locExtFlags & GPS_LOCATION_EXTENDED_HAS_OUTPUT_ENG_TYPE) &&
  3519. (locExt.locOutputEngType == LOC_OUTPUT_ENGINE_SPE))){
  3520. LOC_LOGv("not SPE fix, return");
  3521. return;
  3522. }
  3523. // we can only do translation if we have VRP based lever ARM info
  3524. LeverArmTypeMask leverArmFlags = leverArmConfigInfo.leverArmValidMask;
  3525. if (!(leverArmFlags & LEVER_ARM_TYPE_GNSS_TO_VRP_BIT)) {
  3526. LOC_LOGd("no VRP based lever ARM info");
  3527. return;
  3528. }
  3529. leverArm[0] = leverArmConfigInfo.gnssToVRP.forwardOffsetMeters;
  3530. leverArm[1] = leverArmConfigInfo.gnssToVRP.sidewaysOffsetMeters;
  3531. leverArm[2] = leverArmConfigInfo.gnssToVRP.upOffsetMeters;
  3532. if ((locFlags & LOC_GPS_LOCATION_HAS_LAT_LONG) &&
  3533. (locFlags & LOC_GPS_LOCATION_HAS_ALTITUDE) &&
  3534. (locFlags & LOCATION_HAS_BEARING_BIT)) {
  3535. lla[0] = loc.gpsLocation.latitude * DEG2RAD;
  3536. lla[1] = loc.gpsLocation.longitude * DEG2RAD;
  3537. lla[2] = loc.gpsLocation.altitude;
  3538. rollPitchYaw[0] = 0.0f;
  3539. rollPitchYaw[1] = 0.0f;
  3540. rollPitchYaw[2] = loc.gpsLocation.bearing * DEG2RAD;
  3541. loc_convert_lla_gnss_to_vrp(lla, rollPitchYaw, leverArm);
  3542. // assign the converted value into position report and
  3543. // set up valid mask
  3544. locExt.llaVRPBased.latitude = lla[0] * RAD2DEG;
  3545. locExt.llaVRPBased.longitude = lla[1] * RAD2DEG;
  3546. locExt.llaVRPBased.altitude = lla[2];
  3547. locExt.flags |= GPS_LOCATION_EXTENDED_HAS_LLA_VRP_BASED;
  3548. } else {
  3549. LOC_LOGd("SPE fix missing latitude/longitude/alitutde");
  3550. return;
  3551. }
  3552. }
  3553. void
  3554. GnssAdapter::reportPositionEvent(const UlpLocation& ulpLocation,
  3555. const GpsLocationExtended& locationExtended,
  3556. enum loc_sess_status status,
  3557. LocPosTechMask techMask,
  3558. GnssDataNotification* pDataNotify,
  3559. int msInWeek)
  3560. {
  3561. // this position is from QMI LOC API, then send report to engine hub
  3562. // also, send out SPE fix promptly to the clients that have registered
  3563. // with SPE report
  3564. LOC_LOGd("reportPositionEvent, eng type: %d, unpro %d, sess status %d msInWeek %d",
  3565. locationExtended.locOutputEngType,
  3566. ulpLocation.unpropagatedPosition, status, msInWeek);
  3567. struct MsgReportSPEPosition : public LocMsg {
  3568. GnssAdapter& mAdapter;
  3569. mutable UlpLocation mUlpLocation;
  3570. mutable GpsLocationExtended mLocationExtended;
  3571. enum loc_sess_status mStatus;
  3572. LocPosTechMask mTechMask;
  3573. mutable GnssDataNotification mDataNotify;
  3574. int mMsInWeek;
  3575. inline MsgReportSPEPosition(GnssAdapter& adapter,
  3576. const UlpLocation& ulpLocation,
  3577. const GpsLocationExtended& locationExtended,
  3578. enum loc_sess_status status,
  3579. LocPosTechMask techMask,
  3580. GnssDataNotification dataNotify,
  3581. int msInWeek) :
  3582. LocMsg(),
  3583. mAdapter(adapter),
  3584. mUlpLocation(ulpLocation),
  3585. mLocationExtended(locationExtended),
  3586. mStatus(status),
  3587. mTechMask(techMask),
  3588. mDataNotify(dataNotify),
  3589. mMsInWeek(msInWeek) {}
  3590. inline virtual void proc() const {
  3591. if (mAdapter.mTimeBasedTrackingSessions.empty() &&
  3592. mAdapter.mDistanceBasedTrackingSessions.empty()) {
  3593. LOC_LOGd("reportPositionEvent, no session on-going, throw away the SPE reports");
  3594. return;
  3595. }
  3596. if (false == mUlpLocation.unpropagatedPosition && mDataNotify.size != 0) {
  3597. if (mMsInWeek >= 0) {
  3598. mAdapter.getDataInformation((GnssDataNotification&)mDataNotify,
  3599. mMsInWeek);
  3600. }
  3601. mAdapter.reportData(mDataNotify);
  3602. }
  3603. // save the association of GPS timestamp and qtimer tick cnt in PVT report
  3604. mAdapter.mPositionElapsedRealTimeCal
  3605. .saveGpsTimeAndQtimerPairInPvtReport(mLocationExtended);
  3606. if (true == mAdapter.initEngHubProxy()){
  3607. // send the SPE fix to engine hub
  3608. mAdapter.mEngHubProxy->gnssReportPosition(mUlpLocation, mLocationExtended, mStatus);
  3609. // report out all SPE fix if it is not propagated, even for failed fix
  3610. if (false == mUlpLocation.unpropagatedPosition) {
  3611. EngineLocationInfo engLocationInfo = {};
  3612. engLocationInfo.location = mUlpLocation;
  3613. engLocationInfo.locationExtended = mLocationExtended;
  3614. engLocationInfo.sessionStatus = mStatus;
  3615. // obtain the VRP based latitude/longitude/altitude for SPE fix
  3616. computeVRPBasedLla(engLocationInfo.location,
  3617. engLocationInfo.locationExtended,
  3618. mAdapter.mLocConfigInfo.leverArmConfigInfo);
  3619. mAdapter.reportEnginePositions(1, &engLocationInfo);
  3620. }
  3621. return;
  3622. }
  3623. // unpropagated report: is only for engine hub to consume and no need
  3624. // to send out to the clients
  3625. if (true == mUlpLocation.unpropagatedPosition) {
  3626. return;
  3627. }
  3628. // extract bug report info - this returns true if consumed by systemstatus
  3629. SystemStatus* s = mAdapter.getSystemStatus();
  3630. if ((nullptr != s) &&
  3631. ((LOC_SESS_SUCCESS == mStatus) || (LOC_SESS_INTERMEDIATE == mStatus))){
  3632. s->eventPosition(mUlpLocation, mLocationExtended);
  3633. }
  3634. mAdapter.reportPosition(mUlpLocation, mLocationExtended, mStatus, mTechMask);
  3635. }
  3636. };
  3637. if (mContext != NULL) {
  3638. GnssDataNotification dataNotifyCopy = {};
  3639. if (pDataNotify) {
  3640. dataNotifyCopy = *pDataNotify;
  3641. dataNotifyCopy.size = sizeof(dataNotifyCopy);
  3642. }
  3643. sendMsg(new MsgReportSPEPosition(*this, ulpLocation, locationExtended,
  3644. status, techMask, dataNotifyCopy, msInWeek));
  3645. }
  3646. }
  3647. void
  3648. GnssAdapter::reportEnginePositionsEvent(unsigned int count,
  3649. EngineLocationInfo* locationArr)
  3650. {
  3651. struct MsgReportEnginePositions : public LocMsg {
  3652. GnssAdapter& mAdapter;
  3653. unsigned int mCount;
  3654. EngineLocationInfo mEngLocInfo[LOC_OUTPUT_ENGINE_COUNT];
  3655. inline MsgReportEnginePositions(GnssAdapter& adapter,
  3656. unsigned int count,
  3657. EngineLocationInfo* locationArr) :
  3658. LocMsg(),
  3659. mAdapter(adapter),
  3660. mCount(count) {
  3661. if (mCount > LOC_OUTPUT_ENGINE_COUNT) {
  3662. mCount = LOC_OUTPUT_ENGINE_COUNT;
  3663. }
  3664. if (mCount > 0) {
  3665. memcpy(mEngLocInfo, locationArr, sizeof(EngineLocationInfo)*mCount);
  3666. }
  3667. }
  3668. inline virtual void proc() const {
  3669. mAdapter.reportEnginePositions(mCount, mEngLocInfo);
  3670. }
  3671. };
  3672. sendMsg(new MsgReportEnginePositions(*this, count, locationArr));
  3673. }
  3674. bool
  3675. GnssAdapter::needReportForAllClients(const UlpLocation& ulpLocation,
  3676. enum loc_sess_status status,
  3677. LocPosTechMask techMask) {
  3678. bool reported = false;
  3679. #ifdef USE_GLIB
  3680. if (true == initEngHubProxy()) {
  3681. reported = true;
  3682. }
  3683. #endif
  3684. return reported || LocApiBase::needReport(ulpLocation, status, techMask);
  3685. }
  3686. bool GnssAdapter::needReportForClient(LocationAPI* client, enum loc_sess_status status) {
  3687. if (LOC_SESS_SUCCESS == status || (client == nullptr && LOC_SESS_INTERMEDIATE == status &&
  3688. mDistanceBasedTrackingSessions.size() > 0)) {
  3689. return true;
  3690. }
  3691. if (status != LOC_SESS_FAILURE) {
  3692. for (auto it = mDistanceBasedTrackingSessions.begin();
  3693. it != mDistanceBasedTrackingSessions.end(); ++it) {
  3694. if (it->first.client == client) { // Always report intermediate fixes to dbt clients
  3695. return true;
  3696. }
  3697. }
  3698. }
  3699. for (auto it = mTimeBasedTrackingSessions.begin();
  3700. it != mTimeBasedTrackingSessions.end(); ++it) {
  3701. // report intermediate fix when TBT session allows, like flp;
  3702. // report any fix (even failed fix) when TBT session allows, like LE.
  3703. if ((it->first.client == client || client == nullptr) &&
  3704. it->second.qualityLevelAccepted >= status) {
  3705. return true;
  3706. }
  3707. }
  3708. return false;
  3709. }
  3710. bool GnssAdapter::needToGenerateNmeaReport(const uint32_t &gpsTimeOfWeekMs,
  3711. const struct timespec32_t &apTimeStamp)
  3712. {
  3713. bool retVal = false;
  3714. uint64_t currentTimeNsec = 0;
  3715. if (NMEA_PROVIDER_AP == ContextBase::mGps_conf.NMEA_PROVIDER && !mTimeBasedTrackingSessions.empty()) {
  3716. currentTimeNsec = (apTimeStamp.tv_sec * BILLION_NSEC + apTimeStamp.tv_nsec);
  3717. if ((GNSS_NMEA_REPORT_RATE_NHZ == ContextBase::sNmeaReportRate) ||
  3718. (GPS_DEFAULT_FIX_INTERVAL_MS <= mLocPositionMode.min_interval)) {
  3719. retVal = true;
  3720. } else { /*tbf is less than 1000 milli-seconds and NMEA reporting rate is set to 1Hz */
  3721. /* Always send NMEA string for first position report
  3722. * Send when gpsTimeOfWeekMs is closely aligned with integer boundary
  3723. */
  3724. if ((0 == mPrevNmeaRptTimeNsec) ||
  3725. (0 != gpsTimeOfWeekMs) && (NMEA_MIN_THRESHOLD_MSEC >= (gpsTimeOfWeekMs % 1000))) {
  3726. retVal = true;
  3727. } else {
  3728. uint64_t timeDiffMsec = ((currentTimeNsec - mPrevNmeaRptTimeNsec) / 1000000);
  3729. // Send when the delta time becomes >= 1 sec
  3730. if (NMEA_MAX_THRESHOLD_MSEC <= timeDiffMsec) {
  3731. retVal = true;
  3732. }
  3733. }
  3734. }
  3735. if (true == retVal) {
  3736. mPrevNmeaRptTimeNsec = currentTimeNsec;
  3737. }
  3738. }
  3739. return retVal;
  3740. }
  3741. void
  3742. GnssAdapter::logLatencyInfo()
  3743. {
  3744. if (0 == mGnssLatencyInfoQueue.size()) {
  3745. LOC_LOGv("mGnssLatencyInfoQueue.size is 0");
  3746. return;
  3747. }
  3748. mGnssLatencyInfoQueue.front().hlosQtimer5 = getQTimerTickCount();
  3749. if (0 == mGnssLatencyInfoQueue.front().hlosQtimer3) {
  3750. /* if SPE from engine hub is not reported then hlosQtimer3 = 0, set it
  3751. equal to hlosQtimer2 to make sense */
  3752. LOC_LOGv("hlosQtimer3 is 0, setting it to hlosQtimer2");
  3753. mGnssLatencyInfoQueue.front().hlosQtimer3 = mGnssLatencyInfoQueue.front().hlosQtimer2;
  3754. }
  3755. if (0 == mGnssLatencyInfoQueue.front().hlosQtimer4) {
  3756. /* if PPE from engine hub is not reported then hlosQtimer4 = 0, set it
  3757. equal to hlosQtimer3 to make sense */
  3758. LOC_LOGv("hlosQtimer4 is 0, setting it to hlosQtimer3");
  3759. mGnssLatencyInfoQueue.front().hlosQtimer4 = mGnssLatencyInfoQueue.front().hlosQtimer3;
  3760. }
  3761. if (mGnssLatencyInfoQueue.front().hlosQtimer4 < mGnssLatencyInfoQueue.front().hlosQtimer3) {
  3762. /* hlosQtimer3 is timestamped when SPE from engine hub is reported,
  3763. and hlosQtimer4 is timestamped when PPE from engine hub is reported.
  3764. The order is random though, hence making sure the timestamps are sorted */
  3765. LOC_LOGv("hlosQtimer4 is < hlosQtimer3, swapping them");
  3766. std::swap(mGnssLatencyInfoQueue.front().hlosQtimer3,
  3767. mGnssLatencyInfoQueue.front().hlosQtimer4);
  3768. }
  3769. LOC_LOGv("meQtimer1=%" PRIi64 " "
  3770. "meQtimer2=%" PRIi64 " "
  3771. "meQtimer3=%" PRIi64 " "
  3772. "peQtimer1=%" PRIi64 " "
  3773. "peQtimer2=%" PRIi64 " "
  3774. "peQtimer3=%" PRIi64 " "
  3775. "smQtimer1=%" PRIi64 " "
  3776. "smQtimer2=%" PRIi64 " "
  3777. "smQtimer3=%" PRIi64 " "
  3778. "locMwQtimer=%" PRIi64 " "
  3779. "hlosQtimer1=%" PRIi64 " "
  3780. "hlosQtimer2=%" PRIi64 " "
  3781. "hlosQtimer3=%" PRIi64 " "
  3782. "hlosQtimer4=%" PRIi64 " "
  3783. "hlosQtimer5=%" PRIi64 " ",
  3784. mGnssLatencyInfoQueue.front().meQtimer1, mGnssLatencyInfoQueue.front().meQtimer2,
  3785. mGnssLatencyInfoQueue.front().meQtimer3, mGnssLatencyInfoQueue.front().peQtimer1,
  3786. mGnssLatencyInfoQueue.front().peQtimer2, mGnssLatencyInfoQueue.front().peQtimer3,
  3787. mGnssLatencyInfoQueue.front().smQtimer1, mGnssLatencyInfoQueue.front().smQtimer2,
  3788. mGnssLatencyInfoQueue.front().smQtimer3, mGnssLatencyInfoQueue.front().locMwQtimer,
  3789. mGnssLatencyInfoQueue.front().hlosQtimer1, mGnssLatencyInfoQueue.front().hlosQtimer2,
  3790. mGnssLatencyInfoQueue.front().hlosQtimer3, mGnssLatencyInfoQueue.front().hlosQtimer4,
  3791. mGnssLatencyInfoQueue.front().hlosQtimer5);
  3792. mLogger.log(mGnssLatencyInfoQueue.front());
  3793. mGnssLatencyInfoQueue.pop();
  3794. LOC_LOGv("mGnssLatencyInfoQueue.size after pop=%zu", mGnssLatencyInfoQueue.size());
  3795. }
  3796. // only fused report (when engine hub is enabled) or
  3797. // SPE report (when engine hub is disabled) will reach this function
  3798. void
  3799. GnssAdapter::reportPosition(const UlpLocation& ulpLocation,
  3800. const GpsLocationExtended& locationExtended,
  3801. enum loc_sess_status status,
  3802. LocPosTechMask techMask)
  3803. {
  3804. bool reportToAllClients = needReportForAllClients(ulpLocation, status, techMask);
  3805. bool reportToAnyClient = needReportForAnyClient(status);
  3806. if (reportToAllClients || reportToAnyClient) {
  3807. GnssLocationInfoNotification locationInfo = {};
  3808. convertLocationInfo(locationInfo, locationExtended, status);
  3809. convertLocation(locationInfo.location, ulpLocation, locationExtended);
  3810. fillElapsedRealTime(locationExtended, locationInfo.location);
  3811. logLatencyInfo();
  3812. for (auto it=mClientData.begin(); it != mClientData.end(); ++it) {
  3813. if (reportToAllClients || needReportForClient(it->first, status)) {
  3814. if (nullptr != it->second.gnssLocationInfoCb) {
  3815. it->second.gnssLocationInfoCb(locationInfo);
  3816. } else if ((nullptr != it->second.engineLocationsInfoCb) &&
  3817. (false == initEngHubProxy())) {
  3818. // if engine hub is disabled, this is SPE fix from modem
  3819. // we need to mark one copy marked as fused and one copy marked as PPE
  3820. // and dispatch it to the engineLocationsInfoCb
  3821. GnssLocationInfoNotification engLocationsInfo[2];
  3822. engLocationsInfo[0] = locationInfo;
  3823. engLocationsInfo[0].locOutputEngType = LOC_OUTPUT_ENGINE_FUSED;
  3824. engLocationsInfo[0].flags |= GNSS_LOCATION_INFO_OUTPUT_ENG_TYPE_BIT;
  3825. engLocationsInfo[1] = locationInfo;
  3826. it->second.engineLocationsInfoCb(2, engLocationsInfo);
  3827. } else if (nullptr != it->second.trackingCb) {
  3828. it->second.trackingCb(locationInfo.location);
  3829. }
  3830. }
  3831. }
  3832. mGnssSvIdUsedInPosAvail = false;
  3833. mGnssMbSvIdUsedInPosAvail = false;
  3834. if (reportToAllClients) {
  3835. if (locationExtended.flags & GPS_LOCATION_EXTENDED_HAS_GNSS_SV_USED_DATA) {
  3836. mGnssSvIdUsedInPosAvail = true;
  3837. mGnssSvIdUsedInPosition = locationExtended.gnss_sv_used_ids;
  3838. if (locationExtended.flags & GPS_LOCATION_EXTENDED_HAS_MULTIBAND) {
  3839. mGnssMbSvIdUsedInPosAvail = true;
  3840. mGnssMbSvIdUsedInPosition = locationExtended.gnss_mb_sv_used_ids;
  3841. }
  3842. }
  3843. // if PACE is enabled
  3844. if ((true == mLocConfigInfo.paceConfigInfo.isValid) &&
  3845. (true == mLocConfigInfo.paceConfigInfo.enable)) {
  3846. // If fix has sensor contribution, and it is fused fix with DRE engine
  3847. // contributing to the fix, inject to modem
  3848. if ((LOC_POS_TECH_MASK_SENSORS & techMask) &&
  3849. (locationInfo.flags & GNSS_LOCATION_INFO_OUTPUT_ENG_TYPE_BIT) &&
  3850. (locationInfo.locOutputEngType == LOC_OUTPUT_ENGINE_FUSED) &&
  3851. (locationInfo.flags & GNSS_LOCATION_INFO_OUTPUT_ENG_MASK_BIT) &&
  3852. (locationInfo.locOutputEngMask & DEAD_RECKONING_ENGINE)) {
  3853. mLocApi->injectPosition(locationInfo, false);
  3854. }
  3855. }
  3856. }
  3857. }
  3858. if (needToGenerateNmeaReport(locationExtended.gpsTime.gpsTimeOfWeekMs,
  3859. locationExtended.timeStamp.apTimeStamp)) {
  3860. /*Only BlankNMEA sentence needs to be processed and sent, if both lat, long is 0 &
  3861. horReliability is not set. */
  3862. bool blank_fix = ((0 == ulpLocation.gpsLocation.latitude) &&
  3863. (0 == ulpLocation.gpsLocation.longitude) &&
  3864. (LOC_RELIABILITY_NOT_SET == locationExtended.horizontal_reliability));
  3865. uint8_t generate_nmea = (reportToAllClients && status != LOC_SESS_FAILURE && !blank_fix);
  3866. bool custom_nmea_gga = (1 == ContextBase::mGps_conf.CUSTOM_NMEA_GGA_FIX_QUALITY_ENABLED);
  3867. bool isTagBlockGroupingEnabled =
  3868. (1 == ContextBase::mGps_conf.NMEA_TAG_BLOCK_GROUPING_ENABLED);
  3869. std::vector<std::string> nmeaArraystr;
  3870. int indexOfGGA = -1;
  3871. loc_nmea_generate_pos(ulpLocation, locationExtended, mLocSystemInfo, generate_nmea,
  3872. custom_nmea_gga, nmeaArraystr, indexOfGGA, isTagBlockGroupingEnabled);
  3873. stringstream ss;
  3874. for (auto itor = nmeaArraystr.begin(); itor != nmeaArraystr.end(); ++itor) {
  3875. ss << *itor;
  3876. }
  3877. string s = ss.str();
  3878. reportNmea(s.c_str(), s.length());
  3879. /* DgnssNtrip */
  3880. if (-1 != indexOfGGA && isDgnssNmeaRequired()) {
  3881. mDgnssState |= DGNSS_STATE_NO_NMEA_PENDING;
  3882. mStartDgnssNtripParams.nmea = std::move(nmeaArraystr[indexOfGGA]);
  3883. bool isLocationValid = (0 != ulpLocation.gpsLocation.latitude) ||
  3884. (0 != ulpLocation.gpsLocation.longitude);
  3885. checkUpdateDgnssNtrip(isLocationValid);
  3886. }
  3887. }
  3888. }
  3889. void
  3890. GnssAdapter::reportLatencyInfoEvent(const GnssLatencyInfo& gnssLatencyInfo)
  3891. {
  3892. struct MsgReportLatencyInfo : public LocMsg {
  3893. GnssAdapter& mAdapter;
  3894. GnssLatencyInfo mGnssLatencyInfo;
  3895. inline MsgReportLatencyInfo(GnssAdapter& adapter,
  3896. const GnssLatencyInfo& gnssLatencyInfo) :
  3897. mGnssLatencyInfo(gnssLatencyInfo),
  3898. mAdapter(adapter) {}
  3899. inline virtual void proc() const {
  3900. mAdapter.mGnssLatencyInfoQueue.push(mGnssLatencyInfo);
  3901. LOC_LOGv("mGnssLatencyInfoQueue.size after push=%zu",
  3902. mAdapter.mGnssLatencyInfoQueue.size());
  3903. }
  3904. };
  3905. sendMsg(new MsgReportLatencyInfo(*this, gnssLatencyInfo));
  3906. }
  3907. void
  3908. GnssAdapter::reportEnginePositions(unsigned int count,
  3909. const EngineLocationInfo* locationArr)
  3910. {
  3911. bool needReportEnginePositions = false;
  3912. for (auto it=mClientData.begin(); it != mClientData.end(); ++it) {
  3913. if (nullptr != it->second.engineLocationsInfoCb) {
  3914. needReportEnginePositions = true;
  3915. break;
  3916. }
  3917. }
  3918. GnssLocationInfoNotification locationInfo[LOC_OUTPUT_ENGINE_COUNT] = {};
  3919. for (unsigned int i = 0; i < count; i++) {
  3920. const EngineLocationInfo* engLocation = (locationArr+i);
  3921. // if it is fused/default location, call reportPosition maintain legacy behavior
  3922. if ((GPS_LOCATION_EXTENDED_HAS_OUTPUT_ENG_TYPE & engLocation->locationExtended.flags) &&
  3923. (LOC_OUTPUT_ENGINE_FUSED == engLocation->locationExtended.locOutputEngType)) {
  3924. reportPosition(engLocation->location,
  3925. engLocation->locationExtended,
  3926. engLocation->sessionStatus,
  3927. engLocation->location.tech_mask);
  3928. }
  3929. if (needReportEnginePositions) {
  3930. convertLocationInfo(locationInfo[i], engLocation->locationExtended,
  3931. engLocation->sessionStatus);
  3932. convertLocation(locationInfo[i].location,
  3933. engLocation->location,
  3934. engLocation->locationExtended);
  3935. fillElapsedRealTime(engLocation->locationExtended,
  3936. locationInfo[i].location);
  3937. }
  3938. }
  3939. const EngineLocationInfo* engLocation = locationArr;
  3940. LOC_LOGv("engLocation->locationExtended.locOutputEngType=%d",
  3941. engLocation->locationExtended.locOutputEngType);
  3942. if (0 != mGnssLatencyInfoQueue.size()) {
  3943. if ((GPS_LOCATION_EXTENDED_HAS_OUTPUT_ENG_TYPE & engLocation->locationExtended.flags) &&
  3944. (LOC_OUTPUT_ENGINE_SPE == engLocation->locationExtended.locOutputEngType)) {
  3945. mGnssLatencyInfoQueue.front().hlosQtimer3 = getQTimerTickCount();
  3946. LOC_LOGv("SPE hlosQtimer3=%" PRIi64 " ", mGnssLatencyInfoQueue.front().hlosQtimer3);
  3947. }
  3948. if ((GPS_LOCATION_EXTENDED_HAS_OUTPUT_ENG_TYPE & engLocation->locationExtended.flags) &&
  3949. (LOC_OUTPUT_ENGINE_PPE == engLocation->locationExtended.locOutputEngType)) {
  3950. mGnssLatencyInfoQueue.front().hlosQtimer4 = getQTimerTickCount();
  3951. LOC_LOGv("PPE hlosQtimer4=%" PRIi64 " ", mGnssLatencyInfoQueue.front().hlosQtimer4);
  3952. }
  3953. }
  3954. if (needReportEnginePositions) {
  3955. for (auto it=mClientData.begin(); it != mClientData.end(); ++it) {
  3956. if (nullptr != it->second.engineLocationsInfoCb &&
  3957. needReportForClient(it->first, engLocation->sessionStatus)) {
  3958. it->second.engineLocationsInfoCb(count, locationInfo);
  3959. }
  3960. }
  3961. }
  3962. }
  3963. void
  3964. GnssAdapter::reportSvEvent(const GnssSvNotification& svNotify)
  3965. {
  3966. struct MsgReportSv : public LocMsg {
  3967. GnssAdapter& mAdapter;
  3968. const GnssSvNotification mSvNotify;
  3969. inline MsgReportSv(GnssAdapter& adapter,
  3970. const GnssSvNotification& svNotify) :
  3971. LocMsg(),
  3972. mAdapter(adapter),
  3973. mSvNotify(svNotify) {}
  3974. inline virtual void proc() const {
  3975. mAdapter.reportSv((GnssSvNotification&)mSvNotify);
  3976. }
  3977. };
  3978. sendMsg(new MsgReportSv(*this, svNotify));
  3979. }
  3980. void
  3981. GnssAdapter::reportSv(GnssSvNotification& svNotify)
  3982. {
  3983. int numSv = svNotify.count;
  3984. uint16_t gnssSvId = 0;
  3985. uint64_t svUsedIdMask = 0;
  3986. for (int i=0; i < numSv; i++) {
  3987. svUsedIdMask = 0;
  3988. gnssSvId = svNotify.gnssSvs[i].svId;
  3989. GnssSignalTypeMask signalTypeMask = svNotify.gnssSvs[i].gnssSignalTypeMask;
  3990. switch (svNotify.gnssSvs[i].type) {
  3991. case GNSS_SV_TYPE_GPS:
  3992. if (mGnssSvIdUsedInPosAvail) {
  3993. if (mGnssMbSvIdUsedInPosAvail) {
  3994. switch (signalTypeMask) {
  3995. case GNSS_SIGNAL_GPS_L1CA:
  3996. svUsedIdMask = mGnssMbSvIdUsedInPosition.gps_l1ca_sv_used_ids_mask;
  3997. break;
  3998. case GNSS_SIGNAL_GPS_L1C:
  3999. svUsedIdMask = mGnssMbSvIdUsedInPosition.gps_l1c_sv_used_ids_mask;
  4000. break;
  4001. case GNSS_SIGNAL_GPS_L2:
  4002. svUsedIdMask = mGnssMbSvIdUsedInPosition.gps_l2_sv_used_ids_mask;
  4003. break;
  4004. case GNSS_SIGNAL_GPS_L5:
  4005. svUsedIdMask = mGnssMbSvIdUsedInPosition.gps_l5_sv_used_ids_mask;
  4006. break;
  4007. }
  4008. } else {
  4009. svUsedIdMask = mGnssSvIdUsedInPosition.gps_sv_used_ids_mask;
  4010. }
  4011. }
  4012. break;
  4013. case GNSS_SV_TYPE_GLONASS:
  4014. if (mGnssSvIdUsedInPosAvail) {
  4015. if (mGnssMbSvIdUsedInPosAvail) {
  4016. switch (signalTypeMask) {
  4017. case GNSS_SIGNAL_GLONASS_G1:
  4018. svUsedIdMask = mGnssMbSvIdUsedInPosition.glo_g1_sv_used_ids_mask;
  4019. break;
  4020. case GNSS_SIGNAL_GLONASS_G2:
  4021. svUsedIdMask = mGnssMbSvIdUsedInPosition.glo_g2_sv_used_ids_mask;
  4022. break;
  4023. }
  4024. } else {
  4025. svUsedIdMask = mGnssSvIdUsedInPosition.glo_sv_used_ids_mask;
  4026. }
  4027. }
  4028. // map the svid to respective constellation range 1..xx
  4029. // then repective constellation svUsedIdMask map correctly to svid
  4030. gnssSvId = gnssSvId - GLO_SV_PRN_MIN + 1;
  4031. break;
  4032. case GNSS_SV_TYPE_BEIDOU:
  4033. if (mGnssSvIdUsedInPosAvail) {
  4034. if (mGnssMbSvIdUsedInPosAvail) {
  4035. switch (signalTypeMask) {
  4036. case GNSS_SIGNAL_BEIDOU_B1I:
  4037. svUsedIdMask = mGnssMbSvIdUsedInPosition.bds_b1i_sv_used_ids_mask;
  4038. break;
  4039. case GNSS_SIGNAL_BEIDOU_B1C:
  4040. svUsedIdMask = mGnssMbSvIdUsedInPosition.bds_b1c_sv_used_ids_mask;
  4041. break;
  4042. case GNSS_SIGNAL_BEIDOU_B2I:
  4043. svUsedIdMask = mGnssMbSvIdUsedInPosition.bds_b2i_sv_used_ids_mask;
  4044. break;
  4045. case GNSS_SIGNAL_BEIDOU_B2AI:
  4046. svUsedIdMask = mGnssMbSvIdUsedInPosition.bds_b2ai_sv_used_ids_mask;
  4047. break;
  4048. case GNSS_SIGNAL_BEIDOU_B2AQ:
  4049. svUsedIdMask = mGnssMbSvIdUsedInPosition.bds_b2aq_sv_used_ids_mask;
  4050. break;
  4051. }
  4052. } else {
  4053. svUsedIdMask = mGnssSvIdUsedInPosition.bds_sv_used_ids_mask;
  4054. }
  4055. }
  4056. gnssSvId = gnssSvId - BDS_SV_PRN_MIN + 1;
  4057. break;
  4058. case GNSS_SV_TYPE_GALILEO:
  4059. if (mGnssSvIdUsedInPosAvail) {
  4060. if (mGnssMbSvIdUsedInPosAvail) {
  4061. switch (signalTypeMask) {
  4062. case GNSS_SIGNAL_GALILEO_E1:
  4063. svUsedIdMask = mGnssMbSvIdUsedInPosition.gal_e1_sv_used_ids_mask;
  4064. break;
  4065. case GNSS_SIGNAL_GALILEO_E5A:
  4066. svUsedIdMask = mGnssMbSvIdUsedInPosition.gal_e5a_sv_used_ids_mask;
  4067. break;
  4068. case GNSS_SIGNAL_GALILEO_E5B:
  4069. svUsedIdMask = mGnssMbSvIdUsedInPosition.gal_e5b_sv_used_ids_mask;
  4070. break;
  4071. }
  4072. } else {
  4073. svUsedIdMask = mGnssSvIdUsedInPosition.gal_sv_used_ids_mask;
  4074. }
  4075. }
  4076. gnssSvId = gnssSvId - GAL_SV_PRN_MIN + 1;
  4077. break;
  4078. case GNSS_SV_TYPE_QZSS:
  4079. if (mGnssSvIdUsedInPosAvail) {
  4080. if (mGnssMbSvIdUsedInPosAvail) {
  4081. switch (signalTypeMask) {
  4082. case GNSS_SIGNAL_QZSS_L1CA:
  4083. svUsedIdMask = mGnssMbSvIdUsedInPosition.qzss_l1ca_sv_used_ids_mask;
  4084. break;
  4085. case GNSS_SIGNAL_QZSS_L1S:
  4086. svUsedIdMask = mGnssMbSvIdUsedInPosition.qzss_l1s_sv_used_ids_mask;
  4087. break;
  4088. case GNSS_SIGNAL_QZSS_L2:
  4089. svUsedIdMask = mGnssMbSvIdUsedInPosition.qzss_l2_sv_used_ids_mask;
  4090. break;
  4091. case GNSS_SIGNAL_QZSS_L5:
  4092. svUsedIdMask = mGnssMbSvIdUsedInPosition.qzss_l5_sv_used_ids_mask;
  4093. break;
  4094. }
  4095. } else {
  4096. svUsedIdMask = mGnssSvIdUsedInPosition.qzss_sv_used_ids_mask;
  4097. }
  4098. }
  4099. gnssSvId = gnssSvId - QZSS_SV_PRN_MIN + 1;
  4100. break;
  4101. case GNSS_SV_TYPE_NAVIC:
  4102. if (mGnssSvIdUsedInPosAvail) {
  4103. svUsedIdMask = mGnssSvIdUsedInPosition.navic_sv_used_ids_mask;
  4104. }
  4105. gnssSvId = gnssSvId - NAVIC_SV_PRN_MIN + 1;
  4106. break;
  4107. default:
  4108. svUsedIdMask = 0;
  4109. break;
  4110. }
  4111. // If SV ID was used in previous position fix, then set USED_IN_FIX
  4112. // flag, else clear the USED_IN_FIX flag.
  4113. if (svFitsMask(svUsedIdMask, gnssSvId) && (svUsedIdMask & (1ULL << (gnssSvId - 1)))) {
  4114. svNotify.gnssSvs[i].gnssSvOptionsMask |= GNSS_SV_OPTIONS_USED_IN_FIX_BIT;
  4115. }
  4116. }
  4117. for (auto it=mClientData.begin(); it != mClientData.end(); ++it) {
  4118. if (nullptr != it->second.gnssSvCb) {
  4119. it->second.gnssSvCb(svNotify);
  4120. }
  4121. }
  4122. if (NMEA_PROVIDER_AP == ContextBase::mGps_conf.NMEA_PROVIDER &&
  4123. !mTimeBasedTrackingSessions.empty()) {
  4124. std::vector<std::string> nmeaArraystr;
  4125. loc_nmea_generate_sv(svNotify, nmeaArraystr);
  4126. stringstream ss;
  4127. for (auto itor = nmeaArraystr.begin(); itor != nmeaArraystr.end(); ++itor) {
  4128. ss << *itor;
  4129. }
  4130. string s = ss.str();
  4131. reportNmea(s.c_str(), s.length());
  4132. }
  4133. mGnssSvIdUsedInPosAvail = false;
  4134. mGnssMbSvIdUsedInPosAvail = false;
  4135. // report to engine hub to deliver to registered plugin
  4136. mEngHubProxy->gnssReportSv(svNotify);
  4137. }
  4138. void
  4139. GnssAdapter::reportNmeaEvent(const char* nmea, size_t length)
  4140. {
  4141. if (NMEA_PROVIDER_AP == ContextBase::mGps_conf.NMEA_PROVIDER &&
  4142. !loc_nmea_is_debug(nmea, length)) {
  4143. return;
  4144. }
  4145. struct MsgReportNmea : public LocMsg {
  4146. GnssAdapter& mAdapter;
  4147. const char* mNmea;
  4148. size_t mLength;
  4149. inline MsgReportNmea(GnssAdapter& adapter,
  4150. const char* nmea,
  4151. size_t length) :
  4152. LocMsg(),
  4153. mAdapter(adapter),
  4154. mNmea(new char[length+1]),
  4155. mLength(length) {
  4156. if (mNmea == nullptr) {
  4157. LOC_LOGE("%s] new allocation failed, fatal error.", __func__);
  4158. return;
  4159. }
  4160. strlcpy((char*)mNmea, nmea, length+1);
  4161. }
  4162. inline virtual ~MsgReportNmea()
  4163. {
  4164. delete[] mNmea;
  4165. }
  4166. inline virtual void proc() const {
  4167. // extract bug report info - this returns true if consumed by systemstatus
  4168. bool ret = false;
  4169. SystemStatus* s = mAdapter.getSystemStatus();
  4170. if (nullptr != s) {
  4171. ret = s->setNmeaString(mNmea, mLength);
  4172. }
  4173. if (false == ret) {
  4174. // forward NMEA message to upper layer
  4175. mAdapter.reportNmea(mNmea, mLength);
  4176. // DgnssNtrip
  4177. mAdapter.reportGGAToNtrip(mNmea);
  4178. }
  4179. }
  4180. };
  4181. sendMsg(new MsgReportNmea(*this, nmea, length));
  4182. }
  4183. void
  4184. GnssAdapter::reportNmea(const char* nmea, size_t length)
  4185. {
  4186. GnssNmeaNotification nmeaNotification = {};
  4187. nmeaNotification.size = sizeof(GnssNmeaNotification);
  4188. struct timeval tv;
  4189. gettimeofday(&tv, (struct timezone *) NULL);
  4190. int64_t now = tv.tv_sec * 1000LL + tv.tv_usec / 1000;
  4191. nmeaNotification.timestamp = now;
  4192. nmeaNotification.nmea = nmea;
  4193. nmeaNotification.length = length;
  4194. for (auto it=mClientData.begin(); it != mClientData.end(); ++it) {
  4195. if (nullptr != it->second.gnssNmeaCb) {
  4196. it->second.gnssNmeaCb(nmeaNotification);
  4197. }
  4198. }
  4199. if (isNMEAPrintEnabled()) {
  4200. LOC_LOGd("[%" PRId64 ", %zu] %s", now, length, nmea);
  4201. }
  4202. }
  4203. void
  4204. GnssAdapter::reportDataEvent(const GnssDataNotification& dataNotify,
  4205. int msInWeek)
  4206. {
  4207. struct MsgReportData : public LocMsg {
  4208. GnssAdapter& mAdapter;
  4209. GnssDataNotification mDataNotify;
  4210. int mMsInWeek;
  4211. inline MsgReportData(GnssAdapter& adapter,
  4212. const GnssDataNotification& dataNotify,
  4213. int msInWeek) :
  4214. LocMsg(),
  4215. mAdapter(adapter),
  4216. mDataNotify(dataNotify),
  4217. mMsInWeek(msInWeek) {
  4218. }
  4219. inline virtual void proc() const {
  4220. if (mMsInWeek >= 0) {
  4221. mAdapter.getDataInformation((GnssDataNotification&)mDataNotify,
  4222. mMsInWeek);
  4223. }
  4224. mAdapter.reportData((GnssDataNotification&)mDataNotify);
  4225. }
  4226. };
  4227. sendMsg(new MsgReportData(*this, dataNotify, msInWeek));
  4228. }
  4229. void
  4230. GnssAdapter::reportData(GnssDataNotification& dataNotify)
  4231. {
  4232. for (int sig = 0; sig < GNSS_LOC_MAX_NUMBER_OF_SIGNAL_TYPES; sig++) {
  4233. if (GNSS_LOC_DATA_JAMMER_IND_BIT ==
  4234. (dataNotify.gnssDataMask[sig] & GNSS_LOC_DATA_JAMMER_IND_BIT)) {
  4235. LOC_LOGv("jammerInd[%d]=%f", sig, dataNotify.jammerInd[sig]);
  4236. }
  4237. if (GNSS_LOC_DATA_AGC_BIT ==
  4238. (dataNotify.gnssDataMask[sig] & GNSS_LOC_DATA_AGC_BIT)) {
  4239. LOC_LOGv("agc[%d]=%f", sig, dataNotify.agc[sig]);
  4240. }
  4241. }
  4242. for (auto it = mClientData.begin(); it != mClientData.end(); ++it) {
  4243. if (nullptr != it->second.gnssDataCb) {
  4244. it->second.gnssDataCb(dataNotify);
  4245. }
  4246. }
  4247. }
  4248. bool
  4249. GnssAdapter::requestNiNotifyEvent(const GnssNiNotification &notify, const void* data,
  4250. const LocInEmergency emergencyState)
  4251. {
  4252. LOC_LOGI("%s]: notif_type: %d, timeout: %d, default_resp: %d"
  4253. "requestor_id: %s (encoding: %d) text: %s text (encoding: %d) extras: %s "
  4254. "emergencyState = %d",
  4255. __func__, notify.type, notify.timeout, notify.timeoutResponse,
  4256. notify.requestor, notify.requestorEncoding,
  4257. notify.message, notify.messageEncoding, notify.extras,
  4258. emergencyState);
  4259. struct MsgReportNiNotify : public LocMsg {
  4260. GnssAdapter& mAdapter;
  4261. LocApiBase& mApi;
  4262. const GnssNiNotification mNotify;
  4263. const void* mData;
  4264. const LocInEmergency mEmergencyState;
  4265. inline MsgReportNiNotify(GnssAdapter& adapter,
  4266. LocApiBase& api,
  4267. const GnssNiNotification& notify,
  4268. const void* data,
  4269. const LocInEmergency emergencyState) :
  4270. LocMsg(),
  4271. mAdapter(adapter),
  4272. mApi(api),
  4273. mNotify(notify),
  4274. mData(data),
  4275. mEmergencyState(emergencyState) {}
  4276. inline virtual void proc() const {
  4277. bool bIsInEmergency = false;
  4278. bool bInformNiAccept = false;
  4279. bIsInEmergency = ((LOC_IN_EMERGENCY_UNKNOWN == mEmergencyState) && // older modems
  4280. (mAdapter.getE911State(mNotify.type))) ||
  4281. (LOC_IN_EMERGENCY_SET == mEmergencyState); // newer modems
  4282. if ((mAdapter.mSupportNfwControl || 0 == mAdapter.getAfwControlId()) &&
  4283. (GNSS_NI_TYPE_SUPL == mNotify.type || GNSS_NI_TYPE_EMERGENCY_SUPL == mNotify.type)
  4284. && !bIsInEmergency &&
  4285. !(GNSS_NI_OPTIONS_PRIVACY_OVERRIDE_BIT & mNotify.options) &&
  4286. (GNSS_CONFIG_GPS_LOCK_NFW_SUPL & ContextBase::mGps_conf.GPS_LOCK) &&
  4287. 1 == ContextBase::mGps_conf.NI_SUPL_DENY_ON_NFW_LOCKED) {
  4288. /* If all these conditions are TRUE, then deny the NI Request:
  4289. -'Q' Lock behavior OR 'P' Lock behavior and GNSS is Locked
  4290. -NI SUPL Request type or NI SUPL Emergency Request type
  4291. -NOT in an Emergency Call Session
  4292. -NOT Privacy Override option
  4293. -NFW is locked and config item NI_SUPL_DENY_ON_NFW_LOCKED = 1 */
  4294. mApi.informNiResponse(GNSS_NI_RESPONSE_DENY, mData);
  4295. } else if ((GNSS_NI_TYPE_SUPL == mNotify.type ||
  4296. GNSS_NI_TYPE_EMERGENCY_SUPL == mNotify.type)
  4297. && (GNSS_NI_OPTIONS_PRIVACY_OVERRIDE_BIT & mNotify.options)) {
  4298. mApi.informNiResponse(GNSS_NI_RESPONSE_ACCEPT, mData);
  4299. } else if (GNSS_NI_TYPE_EMERGENCY_SUPL == mNotify.type) {
  4300. bInformNiAccept = bIsInEmergency ||
  4301. (GNSS_CONFIG_SUPL_EMERGENCY_SERVICES_NO == ContextBase::mGps_conf.SUPL_ES);
  4302. if (bInformNiAccept) {
  4303. mAdapter.requestNiNotify(mNotify, mData, bInformNiAccept);
  4304. } else {
  4305. mApi.informNiResponse(GNSS_NI_RESPONSE_DENY, mData);
  4306. }
  4307. } else if (GNSS_NI_TYPE_CONTROL_PLANE == mNotify.type) {
  4308. if (bIsInEmergency && (1 == ContextBase::mGps_conf.CP_MTLR_ES)) {
  4309. mApi.informNiResponse(GNSS_NI_RESPONSE_ACCEPT, mData);
  4310. } else {
  4311. mAdapter.requestNiNotify(mNotify, mData, false);
  4312. }
  4313. } else {
  4314. mAdapter.requestNiNotify(mNotify, mData, false);
  4315. }
  4316. }
  4317. };
  4318. sendMsg(new MsgReportNiNotify(*this, *mLocApi, notify, data, emergencyState));
  4319. return true;
  4320. }
  4321. void
  4322. GnssAdapter::reportLocationSystemInfoEvent(const LocationSystemInfo & locationSystemInfo) {
  4323. // send system info to engine hub
  4324. mEngHubProxy->gnssReportSystemInfo(locationSystemInfo);
  4325. struct MsgLocationSystemInfo : public LocMsg {
  4326. GnssAdapter& mAdapter;
  4327. LocationSystemInfo mSystemInfo;
  4328. inline MsgLocationSystemInfo(GnssAdapter& adapter,
  4329. const LocationSystemInfo& systemInfo) :
  4330. LocMsg(),
  4331. mAdapter(adapter),
  4332. mSystemInfo(systemInfo) {}
  4333. inline virtual void proc() const {
  4334. mAdapter.reportLocationSystemInfo(mSystemInfo);
  4335. }
  4336. };
  4337. sendMsg(new MsgLocationSystemInfo(*this, locationSystemInfo));
  4338. }
  4339. void
  4340. GnssAdapter::reportLocationSystemInfo(const LocationSystemInfo & locationSystemInfo) {
  4341. // save the info into the master copy piece by piece, as other system info
  4342. // may come at different time
  4343. if (locationSystemInfo.systemInfoMask & LOCATION_SYS_INFO_LEAP_SECOND) {
  4344. mLocSystemInfo.systemInfoMask |= LOCATION_SYS_INFO_LEAP_SECOND;
  4345. const LeapSecondSystemInfo &srcLeapSecondSysInfo = locationSystemInfo.leapSecondSysInfo;
  4346. LeapSecondSystemInfo &dstLeapSecondSysInfo = mLocSystemInfo.leapSecondSysInfo;
  4347. if (srcLeapSecondSysInfo.leapSecondInfoMask &
  4348. LEAP_SECOND_SYS_INFO_CURRENT_LEAP_SECONDS_BIT) {
  4349. dstLeapSecondSysInfo.leapSecondInfoMask |=
  4350. LEAP_SECOND_SYS_INFO_CURRENT_LEAP_SECONDS_BIT;
  4351. dstLeapSecondSysInfo.leapSecondCurrent = srcLeapSecondSysInfo.leapSecondCurrent;
  4352. }
  4353. // once leap second change event is complete, modem may send up event invalidate the leap
  4354. // second change info while AP is still processing report during leap second transition
  4355. // so, we choose to keep this info around even though it is old
  4356. if (srcLeapSecondSysInfo.leapSecondInfoMask & LEAP_SECOND_SYS_INFO_LEAP_SECOND_CHANGE_BIT) {
  4357. dstLeapSecondSysInfo.leapSecondInfoMask |= LEAP_SECOND_SYS_INFO_LEAP_SECOND_CHANGE_BIT;
  4358. dstLeapSecondSysInfo.leapSecondChangeInfo = srcLeapSecondSysInfo.leapSecondChangeInfo;
  4359. }
  4360. }
  4361. // we received new info, inform client of the newly received info
  4362. if (locationSystemInfo.systemInfoMask) {
  4363. for (auto it=mClientData.begin(); it != mClientData.end(); ++it) {
  4364. if (it->second.locationSystemInfoCb != nullptr) {
  4365. it->second.locationSystemInfoCb(locationSystemInfo);
  4366. }
  4367. }
  4368. }
  4369. }
  4370. static void* niThreadProc(void *args)
  4371. {
  4372. NiSession* pSession = (NiSession*)args;
  4373. int rc = 0; /* return code from pthread calls */
  4374. struct timespec present_time = {};
  4375. struct timespec expire_time = {};
  4376. pthread_mutex_lock(&pSession->tLock);
  4377. /* Calculate absolute expire time */
  4378. clock_gettime(CLOCK_REALTIME, &present_time);
  4379. expire_time.tv_sec = present_time.tv_sec + pSession->respTimeLeft;
  4380. expire_time.tv_nsec = present_time.tv_nsec;
  4381. LOC_LOGD("%s]: time out set for abs time %ld with delay %d sec",
  4382. __func__, (long)expire_time.tv_sec, pSession->respTimeLeft);
  4383. while (!pSession->respRecvd) {
  4384. rc = pthread_cond_timedwait(&pSession->tCond,
  4385. &pSession->tLock,
  4386. &expire_time);
  4387. if (rc == ETIMEDOUT) {
  4388. pSession->resp = GNSS_NI_RESPONSE_NO_RESPONSE;
  4389. LOC_LOGD("%s]: time out after valting for specified time. Ret Val %d",
  4390. __func__, rc);
  4391. break;
  4392. }
  4393. }
  4394. LOC_LOGD("%s]: Java layer has sent us a user response and return value from "
  4395. "pthread_cond_timedwait = %d pSession->resp is %u", __func__, rc, pSession->resp);
  4396. pSession->respRecvd = false; /* Reset the user response flag for the next session*/
  4397. // adding this check to support modem restart, in which case, we need the thread
  4398. // to exit without calling sending data. We made sure that rawRequest is NULL in
  4399. // loc_eng_ni_reset_on_engine_restart()
  4400. GnssAdapter* adapter = pSession->adapter;
  4401. GnssNiResponse resp;
  4402. void* rawRequest = NULL;
  4403. bool sendResponse = false;
  4404. if (NULL != pSession->rawRequest) {
  4405. if (pSession->resp != GNSS_NI_RESPONSE_IGNORE) {
  4406. resp = pSession->resp;
  4407. rawRequest = pSession->rawRequest;
  4408. sendResponse = true;
  4409. } else {
  4410. free(pSession->rawRequest);
  4411. }
  4412. pSession->rawRequest = NULL;
  4413. }
  4414. pthread_mutex_unlock(&pSession->tLock);
  4415. pSession->respTimeLeft = 0;
  4416. pSession->reqID = 0;
  4417. if (sendResponse) {
  4418. adapter->gnssNiResponseCommand(resp, rawRequest);
  4419. }
  4420. return NULL;
  4421. }
  4422. bool
  4423. GnssAdapter::requestNiNotify(const GnssNiNotification& notify, const void* data,
  4424. const bool bInformNiAccept)
  4425. {
  4426. NiSession* pSession = NULL;
  4427. gnssNiCallback gnssNiCb = nullptr;
  4428. for (auto it=mClientData.begin(); it != mClientData.end(); ++it) {
  4429. if (nullptr != it->second.gnssNiCb) {
  4430. gnssNiCb = it->second.gnssNiCb;
  4431. break;
  4432. }
  4433. }
  4434. if (nullptr == gnssNiCb) {
  4435. if (GNSS_NI_TYPE_EMERGENCY_SUPL == notify.type) {
  4436. if (bInformNiAccept) {
  4437. mLocApi->informNiResponse(GNSS_NI_RESPONSE_ACCEPT, data);
  4438. NiData& niData = getNiData();
  4439. // ignore any SUPL NI non-Es session if a SUPL NI ES is accepted
  4440. if (NULL != niData.session.rawRequest) {
  4441. pthread_mutex_lock(&niData.session.tLock);
  4442. niData.session.resp = GNSS_NI_RESPONSE_IGNORE;
  4443. niData.session.respRecvd = true;
  4444. pthread_cond_signal(&niData.session.tCond);
  4445. pthread_mutex_unlock(&niData.session.tLock);
  4446. }
  4447. }
  4448. }
  4449. EXIT_LOG(%s, "no clients with gnssNiCb.");
  4450. return false;
  4451. }
  4452. if (notify.type == GNSS_NI_TYPE_EMERGENCY_SUPL) {
  4453. if (NULL != mNiData.sessionEs.rawRequest) {
  4454. LOC_LOGI("%s]: supl es NI in progress, new supl es NI ignored, type: %d",
  4455. __func__, notify.type);
  4456. if (NULL != data) {
  4457. free((void*)data);
  4458. }
  4459. } else {
  4460. pSession = &mNiData.sessionEs;
  4461. }
  4462. } else {
  4463. if (NULL != mNiData.session.rawRequest ||
  4464. NULL != mNiData.sessionEs.rawRequest) {
  4465. LOC_LOGI("%s]: supl NI in progress, new supl NI ignored, type: %d",
  4466. __func__, notify.type);
  4467. if (NULL != data) {
  4468. free((void*)data);
  4469. }
  4470. } else {
  4471. pSession = &mNiData.session;
  4472. }
  4473. }
  4474. if (pSession) {
  4475. /* Save request */
  4476. pSession->rawRequest = (void*)data;
  4477. pSession->reqID = ++mNiData.reqIDCounter;
  4478. pSession->adapter = this;
  4479. int sessionId = pSession->reqID;
  4480. /* For robustness, spawn a thread at this point to timeout to clear up the notification
  4481. * status, even though the OEM layer in java does not do so.
  4482. **/
  4483. pSession->respTimeLeft =
  4484. 5 + (notify.timeout != 0 ? notify.timeout : LOC_NI_NO_RESPONSE_TIME);
  4485. int rc = 0;
  4486. rc = pthread_create(&pSession->thread, NULL, niThreadProc, pSession);
  4487. if (rc) {
  4488. LOC_LOGE("%s]: Loc NI thread is not created.", __func__);
  4489. }
  4490. pthread_setname_np(pSession->thread, "NiThread");
  4491. rc = pthread_detach(pSession->thread);
  4492. if (rc) {
  4493. LOC_LOGE("%s]: Loc NI thread is not detached.", __func__);
  4494. }
  4495. if (nullptr != gnssNiCb) {
  4496. gnssNiCb(sessionId, notify);
  4497. }
  4498. }
  4499. return true;
  4500. }
  4501. void
  4502. GnssAdapter::reportGnssMeasurementsEvent(const GnssMeasurements& gnssMeasurements,
  4503. int msInWeek)
  4504. {
  4505. LOC_LOGD("%s]: msInWeek=%d", __func__, msInWeek);
  4506. if (0 != gnssMeasurements.gnssMeasNotification.count) {
  4507. struct MsgReportGnssMeasurementData : public LocMsg {
  4508. GnssAdapter& mAdapter;
  4509. GnssMeasurements mGnssMeasurements;
  4510. inline MsgReportGnssMeasurementData(GnssAdapter& adapter,
  4511. const GnssMeasurements& gnssMeasurements,
  4512. int msInWeek) :
  4513. LocMsg(),
  4514. mAdapter(adapter),
  4515. mGnssMeasurements(gnssMeasurements) {
  4516. if (-1 != msInWeek) {
  4517. mAdapter.getAgcInformation(mGnssMeasurements.gnssMeasNotification, msInWeek);
  4518. }
  4519. }
  4520. inline virtual void proc() const {
  4521. mAdapter.mPositionElapsedRealTimeCal.saveGpsTimeAndQtimerPairInMeasReport(
  4522. mGnssMeasurements.gnssSvMeasurementSet);
  4523. mAdapter.reportGnssMeasurementData(mGnssMeasurements.gnssMeasNotification);
  4524. }
  4525. };
  4526. sendMsg(new MsgReportGnssMeasurementData(*this, gnssMeasurements, msInWeek));
  4527. }
  4528. mEngHubProxy->gnssReportSvMeasurement(gnssMeasurements.gnssSvMeasurementSet);
  4529. if (mDGnssNeedReport) {
  4530. reportDGnssDataUsable(gnssMeasurements.gnssSvMeasurementSet);
  4531. }
  4532. }
  4533. void
  4534. GnssAdapter::reportGnssMeasurementData(const GnssMeasurementsNotification& measurements)
  4535. {
  4536. for (auto it=mClientData.begin(); it != mClientData.end(); ++it) {
  4537. if (!measurements.isNhz) {
  4538. if (nullptr != it->second.gnssMeasurementsCb) {
  4539. it->second.gnssMeasurementsCb(measurements);
  4540. }
  4541. } else { // nHz measurement
  4542. if (nullptr != it->second.gnssNHzMeasurementsCb) {
  4543. it->second.gnssNHzMeasurementsCb(measurements);
  4544. }
  4545. }
  4546. }
  4547. }
  4548. void
  4549. GnssAdapter::reportDGnssDataUsable(const GnssSvMeasurementSet &svMeasurementSet)
  4550. {
  4551. uint32_t i;
  4552. bool preDGnssDataUsage = mDGnssDataUsage;
  4553. mDGnssDataUsage = false;
  4554. for (i = 0; i < svMeasurementSet.svMeasCount; i++) {
  4555. const Gnss_SVMeasurementStructType& svMeas = svMeasurementSet.svMeas[i];
  4556. if (svMeas.dgnssSvMeas.dgnssMeasStatus) {
  4557. mDGnssDataUsage = true;
  4558. break;
  4559. }
  4560. }
  4561. if (mDGnssDataUsage != preDGnssDataUsage) {
  4562. if (mCdfwInterface) {
  4563. mCdfwInterface->reportUsable(mQDgnssListenerHDL, mDGnssDataUsage);
  4564. }
  4565. }
  4566. }
  4567. void
  4568. GnssAdapter::reportSvPolynomialEvent(GnssSvPolynomial &svPolynomial)
  4569. {
  4570. LOC_LOGD("%s]: ", __func__);
  4571. mEngHubProxy->gnssReportSvPolynomial(svPolynomial);
  4572. }
  4573. void
  4574. GnssAdapter::reportSvEphemerisEvent(GnssSvEphemerisReport & svEphemeris)
  4575. {
  4576. LOC_LOGD("%s]:", __func__);
  4577. mEngHubProxy->gnssReportSvEphemeris(svEphemeris);
  4578. }
  4579. bool
  4580. GnssAdapter::requestOdcpiEvent(OdcpiRequestInfo& request)
  4581. {
  4582. struct MsgRequestOdcpi : public LocMsg {
  4583. GnssAdapter& mAdapter;
  4584. OdcpiRequestInfo mOdcpiRequest;
  4585. inline MsgRequestOdcpi(GnssAdapter& adapter, OdcpiRequestInfo& request) :
  4586. LocMsg(),
  4587. mAdapter(adapter),
  4588. mOdcpiRequest(request) {}
  4589. inline virtual void proc() const {
  4590. mAdapter.requestOdcpi(mOdcpiRequest);
  4591. }
  4592. };
  4593. sendMsg(new MsgRequestOdcpi(*this, request));
  4594. return true;
  4595. }
  4596. void GnssAdapter::requestOdcpi(const OdcpiRequestInfo& request)
  4597. {
  4598. if (nullptr != mOdcpiRequestCb) {
  4599. bool sendEmergencyCallStatusEvent = false;
  4600. LOC_LOGd("request: type %d, tbf %d, isEmergency %d"
  4601. " requestActive: %d timerActive: %d",
  4602. request.type, request.tbfMillis, request.isEmergencyMode,
  4603. mOdcpiStateMask, mOdcpiTimer.isActive());
  4604. // ODCPI START and ODCPI STOP from modem can come in quick succession
  4605. // so the mOdcpiTimer helps avoid spamming the framework as well as
  4606. // extending the odcpi session past 30 seconds if needed
  4607. if (ODCPI_REQUEST_TYPE_START == request.type) {
  4608. if (!(mOdcpiStateMask & ODCPI_REQ_ACTIVE) && false == mOdcpiTimer.isActive()) {
  4609. mOdcpiRequestCb(request);
  4610. mOdcpiStateMask |= ODCPI_REQ_ACTIVE;
  4611. mOdcpiTimer.start();
  4612. sendEmergencyCallStatusEvent = true;
  4613. // if the current active odcpi session is non-emergency, and the new
  4614. // odcpi request is emergency, replace the odcpi request with new request
  4615. // and restart the timer
  4616. } else if (false == mOdcpiRequest.isEmergencyMode &&
  4617. true == request.isEmergencyMode) {
  4618. mOdcpiRequestCb(request);
  4619. mOdcpiStateMask |= ODCPI_REQ_ACTIVE;
  4620. if (true == mOdcpiTimer.isActive()) {
  4621. mOdcpiTimer.restart();
  4622. } else {
  4623. mOdcpiTimer.start();
  4624. }
  4625. sendEmergencyCallStatusEvent = true;
  4626. // if ODCPI request is not active but the timer is active, then
  4627. // just update the active state and wait for timer to expire
  4628. // before requesting new ODCPI to avoid spamming ODCPI requests
  4629. } else if (!(mOdcpiStateMask & ODCPI_REQ_ACTIVE) && true == mOdcpiTimer.isActive()) {
  4630. mOdcpiStateMask |= ODCPI_REQ_ACTIVE;
  4631. }
  4632. mOdcpiRequest = request;
  4633. //Check if Modem needs civic address
  4634. if (mAddressRequestCb != nullptr && request.isCivicAddressRequired) {
  4635. mOdcpiStateMask |= CIVIC_ADDRESS_REQ_ACTIVE;
  4636. }
  4637. // the request is being stopped, but allow timer to expire first
  4638. // before stopping the timer just in case more ODCPI requests come
  4639. // to avoid spamming more odcpi requests to the framework
  4640. } else if (ODCPI_REQUEST_TYPE_STOP == request.type) {
  4641. LOC_LOGd("request: type %d, isEmergency %d", request.type, request.isEmergencyMode);
  4642. mOdcpiRequestCb(request);
  4643. mOdcpiStateMask = 0;
  4644. sendEmergencyCallStatusEvent = true;
  4645. } else {
  4646. LOC_LOGE("Invalid ODCPI request type..");
  4647. }
  4648. // Raise InEmergencyCall event
  4649. if (sendEmergencyCallStatusEvent && request.isEmergencyMode) {
  4650. SystemStatus* systemstatus = getSystemStatus();
  4651. if (nullptr != systemstatus) {
  4652. systemstatus->eventInEmergencyCall(0 != mOdcpiStateMask);
  4653. } else {
  4654. LOC_LOGe("Failed to get system status instance.");
  4655. }
  4656. }
  4657. } else {
  4658. LOC_LOGw("ODCPI request not supported");
  4659. }
  4660. }
  4661. bool GnssAdapter::reportDeleteAidingDataEvent(GnssAidingData& aidingData)
  4662. {
  4663. LOC_LOGD("%s]:", __func__);
  4664. mEngHubProxy->gnssDeleteAidingData(aidingData);
  4665. return true;
  4666. }
  4667. bool GnssAdapter::reportKlobucharIonoModelEvent(GnssKlobucharIonoModel & ionoModel)
  4668. {
  4669. LOC_LOGD("%s]:", __func__);
  4670. mEngHubProxy->gnssReportKlobucharIonoModel(ionoModel);
  4671. return true;
  4672. }
  4673. bool GnssAdapter::reportGnssAdditionalSystemInfoEvent(
  4674. GnssAdditionalSystemInfo & additionalSystemInfo)
  4675. {
  4676. LOC_LOGD("%s]:", __func__);
  4677. mEngHubProxy->gnssReportAdditionalSystemInfo(additionalSystemInfo);
  4678. return true;
  4679. }
  4680. bool GnssAdapter::reportQwesCapabilities(
  4681. const std::unordered_map<LocationQwesFeatureType, bool> &featureMap)
  4682. {
  4683. struct MsgReportQwesFeatureStatus : public LocMsg {
  4684. GnssAdapter& mAdapter;
  4685. const std::unordered_map<LocationQwesFeatureType, bool> mFeatureMap;
  4686. inline MsgReportQwesFeatureStatus(GnssAdapter& adapter,
  4687. const std::unordered_map<LocationQwesFeatureType, bool> &featureMap) :
  4688. LocMsg(),
  4689. mAdapter(adapter),
  4690. mFeatureMap(std::move(featureMap)) {}
  4691. inline virtual void proc() const {
  4692. LOC_LOGi("ReportQwesFeatureStatus before caps %" PRIx64 " ",
  4693. mAdapter.getCapabilities());
  4694. ContextBase::setQwesFeatureStatus(mFeatureMap);
  4695. LOC_LOGi("ReportQwesFeatureStatus After caps %" PRIx64 " ",
  4696. mAdapter.getCapabilities());
  4697. mAdapter.broadcastCapabilities(mAdapter.getCapabilities());
  4698. }
  4699. };
  4700. sendMsg(new MsgReportQwesFeatureStatus(*this, featureMap));
  4701. return true;
  4702. }
  4703. void GnssAdapter::initOdcpiCommand(const OdcpiRequestCallback& callback,
  4704. OdcpiPrioritytype priority)
  4705. {
  4706. struct MsgInitOdcpi : public LocMsg {
  4707. GnssAdapter& mAdapter;
  4708. OdcpiRequestCallback mOdcpiCb;
  4709. OdcpiPrioritytype mPriority;
  4710. inline MsgInitOdcpi(GnssAdapter& adapter,
  4711. const OdcpiRequestCallback& callback,
  4712. OdcpiPrioritytype priority) :
  4713. LocMsg(),
  4714. mAdapter(adapter),
  4715. mOdcpiCb(callback), mPriority(priority){}
  4716. inline virtual void proc() const {
  4717. mAdapter.initOdcpi(mOdcpiCb, mPriority);
  4718. }
  4719. };
  4720. sendMsg(new MsgInitOdcpi(*this, callback, priority));
  4721. }
  4722. void GnssAdapter::initOdcpi(const OdcpiRequestCallback& callback,
  4723. OdcpiPrioritytype priority)
  4724. {
  4725. LOC_LOGd("In priority: %d, Curr priority: %d", priority, mCallbackPriority);
  4726. if (priority >= mCallbackPriority) {
  4727. mOdcpiRequestCb = callback;
  4728. mCallbackPriority = priority;
  4729. /* Register for WIFI request */
  4730. updateEvtMask(LOC_API_ADAPTER_BIT_REQUEST_WIFI,
  4731. LOC_REGISTRATION_MASK_ENABLED);
  4732. }
  4733. }
  4734. void GnssAdapter::injectOdcpiCommand(const Location& location)
  4735. {
  4736. struct MsgInjectOdcpi : public LocMsg {
  4737. GnssAdapter& mAdapter;
  4738. Location mLocation;
  4739. inline MsgInjectOdcpi(GnssAdapter& adapter, const Location& location, ContextBase& context):
  4740. LocMsg(),
  4741. mAdapter(adapter),
  4742. mLocation(location) {
  4743. // Update techMask to tell whether ALE FLP or Android FLP
  4744. if (context.getLBSProxyBase()->getIzatFusedProviderOverride()) {
  4745. mLocation.techMask |= LOCATION_TECHNOLOGY_HYBRID_ALE_BIT;
  4746. }
  4747. }
  4748. inline virtual void proc() const {
  4749. mAdapter.injectOdcpi(mLocation);
  4750. }
  4751. };
  4752. sendMsg(new MsgInjectOdcpi(*this, location, *mContext));
  4753. }
  4754. void GnssAdapter::injectOdcpi(const Location& location)
  4755. {
  4756. LOC_LOGd("ODCPI Injection: requestActive: %d timerActive: %d"
  4757. "lat %.7f long %.7f",
  4758. mOdcpiStateMask, mOdcpiTimer.isActive(),
  4759. location.latitude, location.longitude);
  4760. if ((mOdcpiStateMask & CIVIC_ADDRESS_REQ_ACTIVE) && mAddressRequestCb != nullptr) {
  4761. mAddressRequestCb(location);
  4762. }
  4763. mLocApi->injectPosition(location, true);
  4764. }
  4765. void GnssAdapter::setAddressRequestCbCommand(
  4766. const std::function<void(const Location&)>& addressRequestCb)
  4767. {
  4768. struct MsgSetAddrReqCb : public LocMsg {
  4769. GnssAdapter& mAdapter;
  4770. std::function<void(const Location&)> mAddrReqCb;
  4771. inline MsgSetAddrReqCb(GnssAdapter& adapter,
  4772. const std::function<void(const Location&)>& addressRequestCb) :
  4773. LocMsg(),
  4774. mAdapter(adapter),
  4775. mAddrReqCb(addressRequestCb){}
  4776. inline virtual void proc() const {
  4777. mAdapter.setAddressRequestCb(mAddrReqCb);
  4778. }
  4779. };
  4780. sendMsg(new MsgSetAddrReqCb(*this, addressRequestCb));
  4781. }
  4782. void GnssAdapter::injectLocationAndAddrCommand(
  4783. const Location& location, const GnssCivicAddress& addr)
  4784. {
  4785. struct MsgInjectLocAndAddr : public LocMsg {
  4786. GnssAdapter& mAdapter;
  4787. Location mLocation;
  4788. GnssCivicAddress mAddress;
  4789. inline MsgInjectLocAndAddr(GnssAdapter& adapter,
  4790. const Location& location, const GnssCivicAddress& addr) :
  4791. LocMsg(), mAdapter(adapter), mLocation(location), mAddress(addr) {}
  4792. inline virtual void proc() const {
  4793. LOC_LOGd("[%s] Location: %x, %" PRIu64 ", %f, %f, %f \n"
  4794. "Address: adminArea: %s, countryCode: %s, countryName: %s,\n"
  4795. "featureName: %s, latitude: %f, longitude: %f\n"
  4796. "locale: %s, locality: %s, phone: %s, postalCode: %s\n"
  4797. "premises: %s, subAdminArea: %s, subLocality: %s"
  4798. "thoroughfare: %s, subThoroughfare: %s, url: %s", __func__,
  4799. mLocation.flags, mLocation.timestamp,
  4800. mLocation.latitude, mLocation.longitude,
  4801. mLocation.accuracy, mAddress.adminArea.c_str(),
  4802. mAddress.countryCode.c_str(), mAddress.countryName.c_str(),
  4803. mAddress.featureName.c_str(), mAddress.latitude, mAddress.longitude,
  4804. mAddress.locale.c_str(), mAddress.locality.c_str(),
  4805. mAddress.phone.c_str(), mAddress.postalCode.c_str(),
  4806. mAddress.premises.c_str(), mAddress.subAdminArea.c_str(),
  4807. mAddress.subLocality.c_str(), mAddress.thoroughfare.c_str(),
  4808. mAddress.subThoroughfare.c_str(), mAddress.url.c_str());
  4809. mAdapter.injectLocationAndAddr(mLocation, mAddress);
  4810. }
  4811. };
  4812. sendMsg(new MsgInjectLocAndAddr(*this, location, addr));
  4813. }
  4814. // Called in the context of LocTimer thread
  4815. void OdcpiTimer::timeOutCallback()
  4816. {
  4817. if (nullptr != mAdapter) {
  4818. mAdapter->odcpiTimerExpireEvent();
  4819. }
  4820. }
  4821. // Called in the context of LocTimer thread
  4822. void GnssAdapter::odcpiTimerExpireEvent()
  4823. {
  4824. struct MsgOdcpiTimerExpire : public LocMsg {
  4825. GnssAdapter& mAdapter;
  4826. inline MsgOdcpiTimerExpire(GnssAdapter& adapter) :
  4827. LocMsg(),
  4828. mAdapter(adapter) {}
  4829. inline virtual void proc() const {
  4830. mAdapter.odcpiTimerExpire();
  4831. }
  4832. };
  4833. sendMsg(new MsgOdcpiTimerExpire(*this));
  4834. }
  4835. void GnssAdapter::odcpiTimerExpire()
  4836. {
  4837. LOC_LOGd("requestActive: %d timerActive: %d",
  4838. mOdcpiStateMask, mOdcpiTimer.isActive());
  4839. // if ODCPI request is still active after timer
  4840. // expires, request again and restart timer
  4841. if (mOdcpiStateMask & ODCPI_REQ_ACTIVE) {
  4842. mOdcpiRequestCb(mOdcpiRequest);
  4843. mOdcpiTimer.restart();
  4844. } else {
  4845. mOdcpiTimer.stop();
  4846. }
  4847. }
  4848. void
  4849. GnssAdapter::invokeGnssEnergyConsumedCallback(uint64_t energyConsumedSinceFirstBoot) {
  4850. if (mGnssEnergyConsumedCb) {
  4851. mGnssEnergyConsumedCb(energyConsumedSinceFirstBoot);
  4852. mGnssEnergyConsumedCb = nullptr;
  4853. }
  4854. if (!mGnssPowerStatisticsInit) {
  4855. /* We need to change the reference in case HAL process restarts (i.e. crashes)
  4856. We maintain mBootReferenceEnergy value in the file system
  4857. At the point mBootReferenceEnergy needs to get initialized we will use
  4858. the following logic:
  4859. if (boot time > 30 sec)
  4860. use the value in the file system for mBootReferenceEnergy
  4861. else
  4862. use the value we get here from the modem for mBootReferenceEnergy */
  4863. struct timespec currentTime = {};
  4864. int64_t sinceBootTimeNanos = 0;
  4865. FILE *fp = NULL;
  4866. mBootReferenceEnergy = energyConsumedSinceFirstBoot;
  4867. if (NULL != (fp = fopen("/data/vendor/location/energy.conf", "a+b"))) {
  4868. rewind(fp);
  4869. if (ElapsedRealtimeEstimator::getCurrentTime(currentTime, sinceBootTimeNanos)) {
  4870. LOC_LOGv("sinceBootTimeNanos: %" PRIu64 " ", sinceBootTimeNanos);
  4871. if ((uint32_t)(sinceBootTimeNanos / 1000000000) > 30) {
  4872. int fr = fread(&mBootReferenceEnergy, sizeof(mBootReferenceEnergy), 1, fp);
  4873. if (1 != fr) {
  4874. mBootReferenceEnergy = energyConsumedSinceFirstBoot;
  4875. LOC_LOGw("fread failed ferror(fp)=%d fr=%d", ferror(fp), fr);
  4876. }
  4877. } else {
  4878. fwrite(&mBootReferenceEnergy, sizeof(mBootReferenceEnergy), 1, fp);
  4879. }
  4880. } else {
  4881. LOC_LOGw("getCurrentTime failed");
  4882. fwrite(&mBootReferenceEnergy, sizeof(mBootReferenceEnergy), 1, fp);
  4883. }
  4884. fclose(fp);
  4885. } else {
  4886. LOC_LOGw("fopen failed");
  4887. }
  4888. LOC_LOGd("mBootReferenceEnergy: %" PRIu64 " energyConsumedSinceFirstBoot: %" PRIu64 " ",
  4889. mBootReferenceEnergy, energyConsumedSinceFirstBoot);
  4890. mGnssPowerStatisticsInit = true;
  4891. mPowerElapsedRealTimeCal.reset();
  4892. } else if (nullptr != mPowerIndicationCb) {
  4893. GnssPowerStatistics gnssPowerStatistics = {};
  4894. gnssPowerStatistics.size = sizeof(GnssPowerStatistics);
  4895. gnssPowerStatistics.totalEnergyMilliJoule =
  4896. (double)(energyConsumedSinceFirstBoot - mBootReferenceEnergy) / 10.0;
  4897. LOC_LOGv("energyConsumedSinceFirstBoot: %" PRId64", "
  4898. " mBootReferenceEnergy: %" PRId64", "
  4899. " gnssPowerStatistics.totalEnergyMilliJoule: %f",
  4900. energyConsumedSinceFirstBoot,
  4901. mBootReferenceEnergy,
  4902. gnssPowerStatistics.totalEnergyMilliJoule);
  4903. gnssPowerStatistics.elapsedRealTime =
  4904. mPowerElapsedRealTimeCal.getElapsedRealtimeEstimateNanos(0, 0, 0);
  4905. gnssPowerStatistics.elapsedRealTimeUnc =
  4906. mPowerElapsedRealTimeCal.getElapsedRealtimeUncNanos();
  4907. mPowerIndicationCb(gnssPowerStatistics);
  4908. }
  4909. }
  4910. bool
  4911. GnssAdapter::reportGnssEngEnergyConsumedEvent(uint64_t energyConsumedSinceFirstBoot){
  4912. LOC_LOGd("energyConsumedSinceFirstBoot: %" PRIu64 " ", energyConsumedSinceFirstBoot);
  4913. struct MsgReportGnssGnssEngEnergyConsumed : public LocMsg {
  4914. GnssAdapter& mAdapter;
  4915. uint64_t mGnssEnergyConsumedSinceFirstBoot;
  4916. inline MsgReportGnssGnssEngEnergyConsumed(GnssAdapter& adapter,
  4917. uint64_t energyConsumed) :
  4918. LocMsg(),
  4919. mAdapter(adapter),
  4920. mGnssEnergyConsumedSinceFirstBoot(energyConsumed) {}
  4921. inline virtual void proc() const {
  4922. mAdapter.invokeGnssEnergyConsumedCallback(mGnssEnergyConsumedSinceFirstBoot);
  4923. }
  4924. };
  4925. if (~0 != energyConsumedSinceFirstBoot) {
  4926. sendMsg(new MsgReportGnssGnssEngEnergyConsumed(*this, energyConsumedSinceFirstBoot));
  4927. } else {
  4928. LOC_LOGe("energyConsumedSinceFirstBoot not valid!");
  4929. }
  4930. return true;
  4931. }
  4932. void GnssAdapter::initDefaultAgps() {
  4933. LOC_LOGD("%s]: ", __func__);
  4934. void *handle = nullptr;
  4935. LocAgpsGetAgpsCbInfo getAgpsCbInfo =
  4936. (LocAgpsGetAgpsCbInfo)dlGetSymFromLib(handle, "libloc_net_iface.so",
  4937. "LocNetIfaceAgps_getAgpsCbInfo");
  4938. // Below step is to make sure we init nativeAgpsHandler
  4939. // for Android platforms only
  4940. AgpsCbInfo cbInfo = {};
  4941. if (nullptr != getAgpsCbInfo) {
  4942. cbInfo = getAgpsCbInfo(agpsOpenResultCb, agpsCloseResultCb, this);
  4943. } else {
  4944. cbInfo = mNativeAgpsHandler.getAgpsCbInfo();
  4945. }
  4946. if (cbInfo.statusV4Cb == nullptr) {
  4947. LOC_LOGE("%s]: statusV4Cb is nullptr!", __func__);
  4948. dlclose(handle);
  4949. return;
  4950. }
  4951. initAgps(cbInfo);
  4952. }
  4953. void GnssAdapter::initDefaultAgpsCommand() {
  4954. LOC_LOGD("%s]: ", __func__);
  4955. struct MsgInitDefaultAgps : public LocMsg {
  4956. GnssAdapter& mAdapter;
  4957. inline MsgInitDefaultAgps(GnssAdapter& adapter) :
  4958. LocMsg(),
  4959. mAdapter(adapter) {
  4960. }
  4961. inline virtual void proc() const {
  4962. mAdapter.initDefaultAgps();
  4963. }
  4964. };
  4965. sendMsg(new MsgInitDefaultAgps(*this));
  4966. }
  4967. /* INIT LOC AGPS MANAGER */
  4968. void GnssAdapter::initAgps(const AgpsCbInfo& cbInfo) {
  4969. LOC_LOGD("%s]:cbInfo.atlType - %d", __func__, cbInfo.atlType);
  4970. if (!((ContextBase::mGps_conf.CAPABILITIES & LOC_GPS_CAPABILITY_MSB) ||
  4971. (ContextBase::mGps_conf.CAPABILITIES & LOC_GPS_CAPABILITY_MSA))) {
  4972. return;
  4973. }
  4974. mAgpsManager.createAgpsStateMachines(cbInfo);
  4975. /* Register for AGPS event mask */
  4976. updateEvtMask(LOC_API_ADAPTER_BIT_LOCATION_SERVER_REQUEST,
  4977. LOC_REGISTRATION_MASK_ENABLED);
  4978. }
  4979. void GnssAdapter::initAgpsCommand(const AgpsCbInfo& cbInfo){
  4980. LOC_LOGI("GnssAdapter::initAgpsCommand");
  4981. /* Message to initialize AGPS module */
  4982. struct AgpsMsgInit: public LocMsg {
  4983. const AgpsCbInfo mCbInfo;
  4984. GnssAdapter& mAdapter;
  4985. inline AgpsMsgInit(const AgpsCbInfo& cbInfo,
  4986. GnssAdapter& adapter) :
  4987. LocMsg(), mCbInfo(cbInfo), mAdapter(adapter) {
  4988. LOC_LOGV("AgpsMsgInit");
  4989. }
  4990. inline virtual void proc() const {
  4991. LOC_LOGV("AgpsMsgInit::proc()");
  4992. mAdapter.initAgps(mCbInfo);
  4993. }
  4994. };
  4995. /* Send message to initialize AGPS Manager */
  4996. sendMsg(new AgpsMsgInit(cbInfo, *this));
  4997. }
  4998. void GnssAdapter::initNfwCommand(const NfwCbInfo& cbInfo) {
  4999. LOC_LOGi("GnssAdapter::initNfwCommand");
  5000. /* Message to initialize NFW */
  5001. struct MsgInitNfw : public LocMsg {
  5002. const NfwCbInfo mCbInfo;
  5003. GnssAdapter& mAdapter;
  5004. inline MsgInitNfw(const NfwCbInfo& cbInfo,
  5005. GnssAdapter& adapter) :
  5006. LocMsg(), mCbInfo(cbInfo), mAdapter(adapter) {
  5007. LOC_LOGv("MsgInitNfw");
  5008. }
  5009. inline virtual void proc() const {
  5010. LOC_LOGv("MsgInitNfw::proc()");
  5011. mAdapter.initNfw(mCbInfo);
  5012. }
  5013. };
  5014. /* Send message to initialize NFW */
  5015. sendMsg(new MsgInitNfw(cbInfo, *this));
  5016. }
  5017. void GnssAdapter::reportNfwNotificationEvent(GnssNfwNotification& notification) {
  5018. LOC_LOGi("GnssAdapter::reportNfwNotificationEvent");
  5019. struct MsgReportNfwNotification : public LocMsg {
  5020. const GnssNfwNotification mNotification;
  5021. GnssAdapter& mAdapter;
  5022. inline MsgReportNfwNotification(const GnssNfwNotification& notification,
  5023. GnssAdapter& adapter) :
  5024. LocMsg(), mNotification(notification), mAdapter(adapter) {
  5025. LOC_LOGv("MsgReportNfwNotification");
  5026. }
  5027. inline virtual void proc() const {
  5028. LOC_LOGv("MsgReportNfwNotification::proc()");
  5029. mAdapter.reportNfwNotification(mNotification);
  5030. }
  5031. };
  5032. sendMsg(new MsgReportNfwNotification(notification, *this));
  5033. }
  5034. /* GnssAdapter::requestATL
  5035. * Method triggered in QMI thread as part of handling below message:
  5036. * eQMI_LOC_SERVER_REQUEST_OPEN_V02
  5037. * Triggers the AGPS state machine to setup AGPS call for below WWAN types:
  5038. * eQMI_LOC_WWAN_TYPE_INTERNET_V02
  5039. * eQMI_LOC_WWAN_TYPE_AGNSS_V02
  5040. * eQMI_LOC_WWAN_TYPE_AGNSS_EMERGENCY_V02 */
  5041. bool GnssAdapter::requestATL(int connHandle, LocAGpsType agpsType,
  5042. LocApnTypeMask apnTypeMask, LocSubId subId){
  5043. LOC_LOGi("GnssAdapter::requestATL handle=%d agpsType=0x%X apnTypeMask=0x%X subId=%d",
  5044. connHandle, agpsType, apnTypeMask, subId);
  5045. sendMsg( new AgpsMsgRequestATL( &mAgpsManager, connHandle, (AGpsExtType)agpsType,
  5046. apnTypeMask, subId));
  5047. return true;
  5048. }
  5049. /* GnssAdapter::releaseATL
  5050. * Method triggered in QMI thread as part of handling below message:
  5051. * eQMI_LOC_SERVER_REQUEST_CLOSE_V02
  5052. * Triggers teardown of an existing AGPS call */
  5053. bool GnssAdapter::releaseATL(int connHandle){
  5054. LOC_LOGI("GnssAdapter::releaseATL");
  5055. /* Release SUPL/INTERNET/SUPL_ES ATL */
  5056. struct AgpsMsgReleaseATL: public LocMsg {
  5057. AgpsManager* mAgpsManager;
  5058. int mConnHandle;
  5059. inline AgpsMsgReleaseATL(AgpsManager* agpsManager, int connHandle) :
  5060. LocMsg(), mAgpsManager(agpsManager), mConnHandle(connHandle) {
  5061. LOC_LOGV("AgpsMsgReleaseATL");
  5062. }
  5063. inline virtual void proc() const {
  5064. LOC_LOGV("AgpsMsgReleaseATL::proc()");
  5065. mAgpsManager->releaseATL(mConnHandle);
  5066. }
  5067. };
  5068. sendMsg( new AgpsMsgReleaseATL(&mAgpsManager, connHandle));
  5069. return true;
  5070. }
  5071. void GnssAdapter::reportPdnTypeFromWds(int pdnType, AGpsExtType agpsType, std::string apnName,
  5072. AGpsBearerType bearerType) {
  5073. LOC_LOGd("pdnType from WDS QMI: %d, agpsType: %d, apnName: %s, bearerType: %d",
  5074. pdnType, agpsType, apnName.c_str(), bearerType);
  5075. struct MsgReportAtlPdn : public LocMsg {
  5076. GnssAdapter& mAdapter;
  5077. int mPdnType;
  5078. AgpsManager* mAgpsManager;
  5079. AGpsExtType mAgpsType;
  5080. string mApnName;
  5081. AGpsBearerType mBearerType;
  5082. inline MsgReportAtlPdn(GnssAdapter& adapter, int pdnType,
  5083. AgpsManager* agpsManager, AGpsExtType agpsType,
  5084. const string& apnName, AGpsBearerType bearerType) :
  5085. LocMsg(), mAgpsManager(agpsManager), mAgpsType(agpsType),
  5086. mApnName(apnName), mBearerType(bearerType),
  5087. mAdapter(adapter), mPdnType(pdnType) {}
  5088. inline virtual void proc() const {
  5089. mAgpsManager->reportAtlOpenSuccess(mAgpsType,
  5090. const_cast<char*>(mApnName.c_str()),
  5091. mApnName.length(), mPdnType<=0? mBearerType:mPdnType);
  5092. }
  5093. };
  5094. AGpsBearerType atlPdnType = (pdnType+1) & 3; // convert WDS QMI pdn type to AgpsBearerType
  5095. sendMsg(new MsgReportAtlPdn(*this, atlPdnType, &mAgpsManager,
  5096. agpsType, apnName, bearerType));
  5097. }
  5098. void GnssAdapter::dataConnOpenCommand(
  5099. AGpsExtType agpsType,
  5100. const char* apnName, int apnLen, AGpsBearerType bearerType){
  5101. LOC_LOGI("GnssAdapter::frameworkDataConnOpen");
  5102. struct AgpsMsgAtlOpenSuccess: public LocMsg {
  5103. GnssAdapter& mAdapter;
  5104. AgpsManager* mAgpsManager;
  5105. AGpsExtType mAgpsType;
  5106. char* mApnName;
  5107. AGpsBearerType mBearerType;
  5108. inline AgpsMsgAtlOpenSuccess(GnssAdapter& adapter, AgpsManager* agpsManager,
  5109. AGpsExtType agpsType, const char* apnName, int apnLen, AGpsBearerType bearerType) :
  5110. LocMsg(), mAgpsManager(agpsManager), mAgpsType(agpsType), mApnName(
  5111. new char[apnLen + 1]), mBearerType(bearerType), mAdapter(adapter) {
  5112. LOC_LOGV("AgpsMsgAtlOpenSuccess");
  5113. if (mApnName == nullptr) {
  5114. LOC_LOGE("%s] new allocation failed, fatal error.", __func__);
  5115. // Reporting the failure here
  5116. mAgpsManager->reportAtlClosed(mAgpsType);
  5117. return;
  5118. }
  5119. memcpy(mApnName, apnName, apnLen);
  5120. mApnName[apnLen] = 0;
  5121. }
  5122. inline ~AgpsMsgAtlOpenSuccess() {
  5123. delete[] mApnName;
  5124. }
  5125. inline virtual void proc() const {
  5126. LOC_LOGv("AgpsMsgAtlOpenSuccess::proc()");
  5127. string apn(mApnName);
  5128. //Use QMI WDS API to query IP Protocol from modem profile
  5129. void* libHandle = nullptr;
  5130. getPdnTypeFromWds* getPdnTypeFunc = (getPdnTypeFromWds*)dlGetSymFromLib(libHandle,
  5131. #ifdef USE_GLIB
  5132. "libloc_api_wds.so", "_Z10getPdnTypeRKNSt7__cxx1112basic_string"\
  5133. "IcSt11char_traitsIcESaIcEEESt8functionIFviEE");
  5134. #else
  5135. "libloc_api_wds.so", "_Z10getPdnTypeRKNSt3__112basic_stringIcNS_11char_traits"\
  5136. "IcEENS_9allocatorIcEEEENS_8functionIFviEEE");
  5137. #endif
  5138. std::function<void(int)> wdsPdnTypeCb = std::bind(&GnssAdapter::reportPdnTypeFromWds,
  5139. &mAdapter, std::placeholders::_1, mAgpsType, apn, mBearerType);
  5140. if (getPdnTypeFunc != nullptr && apn.length() > 0) {
  5141. LOC_LOGv("dlGetSymFromLib success");
  5142. (*getPdnTypeFunc)(apn, wdsPdnTypeCb);
  5143. } else {
  5144. mAgpsManager->reportAtlOpenSuccess(mAgpsType, mApnName, apn.length(), mBearerType);
  5145. }
  5146. }
  5147. };
  5148. // Added inital length checks for apnlen check to avoid security issues
  5149. // In case of failure reporting the same
  5150. if (NULL == apnName || apnLen > MAX_APN_LEN || (strlen(apnName) != apnLen)) {
  5151. LOC_LOGe("%s]: incorrect apnlen length or incorrect apnName", __func__);
  5152. mAgpsManager.reportAtlClosed(agpsType);
  5153. } else {
  5154. sendMsg( new AgpsMsgAtlOpenSuccess(*this,
  5155. &mAgpsManager, agpsType, apnName, apnLen, bearerType));
  5156. }
  5157. }
  5158. void GnssAdapter::dataConnClosedCommand(AGpsExtType agpsType){
  5159. LOC_LOGI("GnssAdapter::frameworkDataConnClosed");
  5160. struct AgpsMsgAtlClosed: public LocMsg {
  5161. AgpsManager* mAgpsManager;
  5162. AGpsExtType mAgpsType;
  5163. inline AgpsMsgAtlClosed(AgpsManager* agpsManager, AGpsExtType agpsType) :
  5164. LocMsg(), mAgpsManager(agpsManager), mAgpsType(agpsType) {
  5165. LOC_LOGV("AgpsMsgAtlClosed");
  5166. }
  5167. inline virtual void proc() const {
  5168. LOC_LOGV("AgpsMsgAtlClosed::proc()");
  5169. mAgpsManager->reportAtlClosed(mAgpsType);
  5170. }
  5171. };
  5172. sendMsg( new AgpsMsgAtlClosed(&mAgpsManager, (AGpsExtType)agpsType));
  5173. }
  5174. void GnssAdapter::dataConnFailedCommand(AGpsExtType agpsType){
  5175. LOC_LOGI("GnssAdapter::frameworkDataConnFailed");
  5176. struct AgpsMsgAtlOpenFailed: public LocMsg {
  5177. AgpsManager* mAgpsManager;
  5178. AGpsExtType mAgpsType;
  5179. inline AgpsMsgAtlOpenFailed(AgpsManager* agpsManager, AGpsExtType agpsType) :
  5180. LocMsg(), mAgpsManager(agpsManager), mAgpsType(agpsType) {
  5181. LOC_LOGV("AgpsMsgAtlOpenFailed");
  5182. }
  5183. inline virtual void proc() const {
  5184. LOC_LOGV("AgpsMsgAtlOpenFailed::proc()");
  5185. mAgpsManager->reportAtlOpenFailed(mAgpsType);
  5186. }
  5187. };
  5188. sendMsg( new AgpsMsgAtlOpenFailed(&mAgpsManager, (AGpsExtType)agpsType));
  5189. }
  5190. void GnssAdapter::convertSatelliteInfo(std::vector<GnssDebugSatelliteInfo>& out,
  5191. const GnssSvType& in_constellation,
  5192. const SystemStatusReports& in)
  5193. {
  5194. uint64_t sv_mask = 0ULL;
  5195. uint32_t svid_min = 0;
  5196. uint32_t svid_num = 0;
  5197. uint32_t svid_idx = 0;
  5198. uint64_t eph_health_good_mask = 0ULL;
  5199. uint64_t eph_health_bad_mask = 0ULL;
  5200. uint64_t server_perdiction_available_mask = 0ULL;
  5201. float server_perdiction_age = 0.0f;
  5202. // set constellationi based parameters
  5203. switch (in_constellation) {
  5204. case GNSS_SV_TYPE_GPS:
  5205. svid_min = GNSS_BUGREPORT_GPS_MIN;
  5206. svid_num = GPS_NUM;
  5207. svid_idx = 0;
  5208. if (!in.mSvHealth.empty()) {
  5209. eph_health_good_mask = in.mSvHealth.back().mGpsGoodMask;
  5210. eph_health_bad_mask = in.mSvHealth.back().mGpsBadMask;
  5211. }
  5212. if (!in.mXtra.empty()) {
  5213. server_perdiction_available_mask = in.mXtra.back().mGpsXtraValid;
  5214. server_perdiction_age = (float)(in.mXtra.back().mGpsXtraAge);
  5215. }
  5216. break;
  5217. case GNSS_SV_TYPE_GLONASS:
  5218. svid_min = GNSS_BUGREPORT_GLO_MIN;
  5219. svid_num = GLO_NUM;
  5220. svid_idx = GPS_NUM;
  5221. if (!in.mSvHealth.empty()) {
  5222. eph_health_good_mask = in.mSvHealth.back().mGloGoodMask;
  5223. eph_health_bad_mask = in.mSvHealth.back().mGloBadMask;
  5224. }
  5225. if (!in.mXtra.empty()) {
  5226. server_perdiction_available_mask = in.mXtra.back().mGloXtraValid;
  5227. server_perdiction_age = (float)(in.mXtra.back().mGloXtraAge);
  5228. }
  5229. break;
  5230. case GNSS_SV_TYPE_QZSS:
  5231. svid_min = GNSS_BUGREPORT_QZSS_MIN;
  5232. svid_num = QZSS_NUM;
  5233. svid_idx = GPS_NUM+GLO_NUM+BDS_NUM+GAL_NUM;
  5234. if (!in.mSvHealth.empty()) {
  5235. eph_health_good_mask = in.mSvHealth.back().mQzssGoodMask;
  5236. eph_health_bad_mask = in.mSvHealth.back().mQzssBadMask;
  5237. }
  5238. if (!in.mXtra.empty()) {
  5239. server_perdiction_available_mask = in.mXtra.back().mQzssXtraValid;
  5240. server_perdiction_age = (float)(in.mXtra.back().mQzssXtraAge);
  5241. }
  5242. break;
  5243. case GNSS_SV_TYPE_BEIDOU:
  5244. svid_min = GNSS_BUGREPORT_BDS_MIN;
  5245. svid_num = BDS_NUM;
  5246. svid_idx = GPS_NUM+GLO_NUM;
  5247. if (!in.mSvHealth.empty()) {
  5248. eph_health_good_mask = in.mSvHealth.back().mBdsGoodMask;
  5249. eph_health_bad_mask = in.mSvHealth.back().mBdsBadMask;
  5250. }
  5251. if (!in.mXtra.empty()) {
  5252. server_perdiction_available_mask = in.mXtra.back().mBdsXtraValid;
  5253. server_perdiction_age = (float)(in.mXtra.back().mBdsXtraAge);
  5254. }
  5255. break;
  5256. case GNSS_SV_TYPE_GALILEO:
  5257. svid_min = GNSS_BUGREPORT_GAL_MIN;
  5258. svid_num = GAL_NUM;
  5259. svid_idx = GPS_NUM+GLO_NUM+BDS_NUM;
  5260. if (!in.mSvHealth.empty()) {
  5261. eph_health_good_mask = in.mSvHealth.back().mGalGoodMask;
  5262. eph_health_bad_mask = in.mSvHealth.back().mGalBadMask;
  5263. }
  5264. if (!in.mXtra.empty()) {
  5265. server_perdiction_available_mask = in.mXtra.back().mGalXtraValid;
  5266. server_perdiction_age = (float)(in.mXtra.back().mGalXtraAge);
  5267. }
  5268. break;
  5269. case GNSS_SV_TYPE_NAVIC:
  5270. svid_min = GNSS_BUGREPORT_NAVIC_MIN;
  5271. svid_num = NAVIC_NUM;
  5272. svid_idx = GPS_NUM+GLO_NUM+QZSS_NUM+BDS_NUM+GAL_NUM;
  5273. if (!in.mSvHealth.empty()) {
  5274. eph_health_good_mask = in.mSvHealth.back().mNavicGoodMask;
  5275. eph_health_bad_mask = in.mSvHealth.back().mNavicBadMask;
  5276. }
  5277. if (!in.mXtra.empty()) {
  5278. server_perdiction_available_mask = in.mXtra.back().mNavicXtraValid;
  5279. server_perdiction_age = (float)(in.mXtra.back().mNavicXtraAge);
  5280. }
  5281. break;
  5282. default:
  5283. return;
  5284. }
  5285. // extract each sv info from systemstatus report
  5286. for(uint32_t i=0; i<svid_num && (svid_idx+i)<SV_ALL_NUM; i++) {
  5287. GnssDebugSatelliteInfo s = {};
  5288. s.size = sizeof(s);
  5289. s.svid = i + svid_min;
  5290. s.constellation = in_constellation;
  5291. if (!in.mNavData.empty()) {
  5292. s.mEphemerisType = in.mNavData.back().mNav[svid_idx+i].mType;
  5293. s.mEphemerisSource = in.mNavData.back().mNav[svid_idx+i].mSource;
  5294. }
  5295. else {
  5296. s.mEphemerisType = GNSS_EPH_TYPE_UNKNOWN;
  5297. s.mEphemerisSource = GNSS_EPH_SOURCE_UNKNOWN;
  5298. }
  5299. sv_mask = 0x1ULL << i;
  5300. if (eph_health_good_mask & sv_mask) {
  5301. s.mEphemerisHealth = GNSS_EPH_HEALTH_GOOD;
  5302. }
  5303. else if (eph_health_bad_mask & sv_mask) {
  5304. s.mEphemerisHealth = GNSS_EPH_HEALTH_BAD;
  5305. }
  5306. else {
  5307. s.mEphemerisHealth = GNSS_EPH_HEALTH_UNKNOWN;
  5308. }
  5309. if (!in.mNavData.empty()) {
  5310. s.ephemerisAgeSeconds =
  5311. (float)(in.mNavData.back().mNav[svid_idx+i].mAgeSec);
  5312. }
  5313. else {
  5314. s.ephemerisAgeSeconds = 0.0f;
  5315. }
  5316. if (server_perdiction_available_mask & sv_mask) {
  5317. s.serverPredictionIsAvailable = true;
  5318. }
  5319. else {
  5320. s.serverPredictionIsAvailable = false;
  5321. }
  5322. s.serverPredictionAgeSeconds = server_perdiction_age;
  5323. out.push_back(s);
  5324. }
  5325. return;
  5326. }
  5327. bool GnssAdapter::getDebugReport(GnssDebugReport& r)
  5328. {
  5329. LOC_LOGD("%s]: ", __func__);
  5330. SystemStatus* systemstatus = getSystemStatus();
  5331. if (nullptr == systemstatus) {
  5332. return false;
  5333. }
  5334. SystemStatusReports reports;
  5335. systemstatus->getReport(reports, true);
  5336. r.size = sizeof(r);
  5337. // location block
  5338. r.mLocation.size = sizeof(r.mLocation);
  5339. if(!reports.mLocation.empty() && reports.mLocation.back().mValid) {
  5340. r.mLocation.mValid = true;
  5341. r.mLocation.mLocation.latitude =
  5342. reports.mLocation.back().mLocation.gpsLocation.latitude;
  5343. r.mLocation.mLocation.longitude =
  5344. reports.mLocation.back().mLocation.gpsLocation.longitude;
  5345. r.mLocation.mLocation.altitude =
  5346. reports.mLocation.back().mLocation.gpsLocation.altitude;
  5347. r.mLocation.mLocation.speed =
  5348. (double)(reports.mLocation.back().mLocation.gpsLocation.speed);
  5349. r.mLocation.mLocation.bearing =
  5350. (double)(reports.mLocation.back().mLocation.gpsLocation.bearing);
  5351. r.mLocation.mLocation.accuracy =
  5352. (double)(reports.mLocation.back().mLocation.gpsLocation.accuracy);
  5353. r.mLocation.verticalAccuracyMeters =
  5354. reports.mLocation.back().mLocationEx.vert_unc;
  5355. r.mLocation.speedAccuracyMetersPerSecond =
  5356. reports.mLocation.back().mLocationEx.speed_unc;
  5357. r.mLocation.bearingAccuracyDegrees =
  5358. reports.mLocation.back().mLocationEx.bearing_unc;
  5359. r.mLocation.mUtcReported =
  5360. reports.mLocation.back().mUtcReported;
  5361. }
  5362. else if(!reports.mBestPosition.empty() && reports.mBestPosition.back().mValid) {
  5363. r.mLocation.mValid = true;
  5364. r.mLocation.mLocation.latitude =
  5365. (double)(reports.mBestPosition.back().mBestLat) * RAD2DEG;
  5366. r.mLocation.mLocation.longitude =
  5367. (double)(reports.mBestPosition.back().mBestLon) * RAD2DEG;
  5368. r.mLocation.mLocation.altitude = reports.mBestPosition.back().mBestAlt;
  5369. r.mLocation.mLocation.accuracy =
  5370. (double)(reports.mBestPosition.back().mBestHepe);
  5371. r.mLocation.mUtcReported = reports.mBestPosition.back().mUtcReported;
  5372. }
  5373. else {
  5374. r.mLocation.mValid = false;
  5375. }
  5376. if (r.mLocation.mValid) {
  5377. LOC_LOGV("getDebugReport - lat=%f lon=%f alt=%f speed=%f",
  5378. r.mLocation.mLocation.latitude,
  5379. r.mLocation.mLocation.longitude,
  5380. r.mLocation.mLocation.altitude,
  5381. r.mLocation.mLocation.speed);
  5382. }
  5383. // time block
  5384. r.mTime.size = sizeof(r.mTime);
  5385. if(!reports.mTimeAndClock.empty() && reports.mTimeAndClock.back().mTimeValid) {
  5386. r.mTime.mValid = true;
  5387. r.mTime.timeEstimate =
  5388. (((int64_t)(reports.mTimeAndClock.back().mGpsWeek)*7 +
  5389. GNSS_UTC_TIME_OFFSET)*24*60*60 -
  5390. (int64_t)(reports.mTimeAndClock.back().mLeapSeconds))*1000ULL +
  5391. (int64_t)(reports.mTimeAndClock.back().mGpsTowMs);
  5392. if (reports.mTimeAndClock.back().mTimeUncNs > 0) {
  5393. // TimeUncNs value is available
  5394. r.mTime.timeUncertaintyNs =
  5395. (float)(reports.mTimeAndClock.back().mLeapSecUnc)*1000.0f +
  5396. (float)(reports.mTimeAndClock.back().mTimeUncNs);
  5397. } else {
  5398. // fall back to legacy TimeUnc
  5399. r.mTime.timeUncertaintyNs =
  5400. ((float)(reports.mTimeAndClock.back().mTimeUnc) +
  5401. (float)(reports.mTimeAndClock.back().mLeapSecUnc))*1000.0f;
  5402. }
  5403. r.mTime.frequencyUncertaintyNsPerSec =
  5404. (float)(reports.mTimeAndClock.back().mClockFreqBiasUnc);
  5405. LOC_LOGV("getDebugReport - timeestimate=%" PRIu64 " unc=%f frequnc=%f",
  5406. r.mTime.timeEstimate,
  5407. r.mTime.timeUncertaintyNs, r.mTime.frequencyUncertaintyNsPerSec);
  5408. }
  5409. else {
  5410. r.mTime.mValid = false;
  5411. }
  5412. // satellite info block
  5413. convertSatelliteInfo(r.mSatelliteInfo, GNSS_SV_TYPE_GPS, reports);
  5414. convertSatelliteInfo(r.mSatelliteInfo, GNSS_SV_TYPE_GLONASS, reports);
  5415. convertSatelliteInfo(r.mSatelliteInfo, GNSS_SV_TYPE_QZSS, reports);
  5416. convertSatelliteInfo(r.mSatelliteInfo, GNSS_SV_TYPE_BEIDOU, reports);
  5417. convertSatelliteInfo(r.mSatelliteInfo, GNSS_SV_TYPE_GALILEO, reports);
  5418. convertSatelliteInfo(r.mSatelliteInfo, GNSS_SV_TYPE_NAVIC, reports);
  5419. LOC_LOGV("getDebugReport - satellite=%zu", r.mSatelliteInfo.size());
  5420. return true;
  5421. }
  5422. /* get AGC information from system status and fill it */
  5423. void
  5424. GnssAdapter::getAgcInformation(GnssMeasurementsNotification& measurements, int msInWeek)
  5425. {
  5426. SystemStatus* systemstatus = getSystemStatus();
  5427. if (nullptr != systemstatus) {
  5428. SystemStatusReports reports = {};
  5429. systemstatus->getReport(reports, true);
  5430. if ((!reports.mRfAndParams.empty()) && (!reports.mTimeAndClock.empty()) &&
  5431. (abs(msInWeek - (int)reports.mTimeAndClock.back().mGpsTowMs) < 2000)) {
  5432. for (size_t i = 0; i < measurements.count; i++) {
  5433. switch (measurements.measurements[i].svType) {
  5434. case GNSS_SV_TYPE_GPS:
  5435. case GNSS_SV_TYPE_QZSS:
  5436. measurements.measurements[i].agcLevelDb =
  5437. -(double)reports.mRfAndParams.back().mJammerGps;
  5438. measurements.measurements[i].flags |=
  5439. GNSS_MEASUREMENTS_DATA_AUTOMATIC_GAIN_CONTROL_BIT;
  5440. break;
  5441. case GNSS_SV_TYPE_GALILEO:
  5442. measurements.measurements[i].agcLevelDb =
  5443. -(double)reports.mRfAndParams.back().mJammerGal;
  5444. measurements.measurements[i].flags |=
  5445. GNSS_MEASUREMENTS_DATA_AUTOMATIC_GAIN_CONTROL_BIT;
  5446. break;
  5447. case GNSS_SV_TYPE_GLONASS:
  5448. measurements.measurements[i].agcLevelDb =
  5449. -(double)reports.mRfAndParams.back().mJammerGlo;
  5450. measurements.measurements[i].flags |=
  5451. GNSS_MEASUREMENTS_DATA_AUTOMATIC_GAIN_CONTROL_BIT;
  5452. break;
  5453. case GNSS_SV_TYPE_BEIDOU:
  5454. measurements.measurements[i].agcLevelDb =
  5455. -(double)reports.mRfAndParams.back().mJammerBds;
  5456. measurements.measurements[i].flags |=
  5457. GNSS_MEASUREMENTS_DATA_AUTOMATIC_GAIN_CONTROL_BIT;
  5458. break;
  5459. case GNSS_SV_TYPE_SBAS:
  5460. case GNSS_SV_TYPE_UNKNOWN:
  5461. default:
  5462. break;
  5463. }
  5464. }
  5465. }
  5466. }
  5467. }
  5468. /* get Data information from system status and fill it */
  5469. void
  5470. GnssAdapter::getDataInformation(GnssDataNotification& data, int msInWeek)
  5471. {
  5472. SystemStatus* systemstatus = getSystemStatus();
  5473. LOC_LOGV("%s]: msInWeek=%d", __func__, msInWeek);
  5474. if (nullptr != systemstatus) {
  5475. SystemStatusReports reports = {};
  5476. systemstatus->getReport(reports, true);
  5477. if ((!reports.mRfAndParams.empty()) && (!reports.mTimeAndClock.empty()) &&
  5478. (abs(msInWeek - (int)reports.mTimeAndClock.back().mGpsTowMs) < 2000)) {
  5479. for (int sig = GNSS_LOC_SIGNAL_TYPE_GPS_L1CA;
  5480. sig < GNSS_LOC_MAX_NUMBER_OF_SIGNAL_TYPES; sig++) {
  5481. data.gnssDataMask[sig] = 0;
  5482. data.jammerInd[sig] = 0.0;
  5483. data.agc[sig] = 0.0;
  5484. }
  5485. if (GNSS_INVALID_JAMMER_IND != reports.mRfAndParams.back().mJammerGps) {
  5486. data.gnssDataMask[GNSS_LOC_SIGNAL_TYPE_GPS_L1CA] |=
  5487. GNSS_LOC_DATA_AGC_BIT | GNSS_LOC_DATA_JAMMER_IND_BIT;
  5488. data.agc[GNSS_LOC_SIGNAL_TYPE_GPS_L1CA] =
  5489. -(double)reports.mRfAndParams.back().mJammerGps;
  5490. data.jammerInd[GNSS_LOC_SIGNAL_TYPE_GPS_L1CA] =
  5491. (double)reports.mRfAndParams.back().mJammerGps;
  5492. data.gnssDataMask[GNSS_LOC_SIGNAL_TYPE_QZSS_L1CA] |=
  5493. GNSS_LOC_DATA_AGC_BIT | GNSS_LOC_DATA_JAMMER_IND_BIT;
  5494. data.agc[GNSS_LOC_SIGNAL_TYPE_QZSS_L1CA] =
  5495. -(double)reports.mRfAndParams.back().mJammerGps;
  5496. data.jammerInd[GNSS_LOC_SIGNAL_TYPE_QZSS_L1CA] =
  5497. (double)reports.mRfAndParams.back().mJammerGps;
  5498. data.gnssDataMask[GNSS_LOC_SIGNAL_TYPE_SBAS_L1_CA] |=
  5499. GNSS_LOC_DATA_AGC_BIT | GNSS_LOC_DATA_JAMMER_IND_BIT;
  5500. data.agc[GNSS_LOC_SIGNAL_TYPE_SBAS_L1_CA] =
  5501. -(double)reports.mRfAndParams.back().mJammerGps;
  5502. data.jammerInd[GNSS_LOC_SIGNAL_TYPE_SBAS_L1_CA] =
  5503. (double)reports.mRfAndParams.back().mJammerGps;
  5504. }
  5505. if (GNSS_INVALID_JAMMER_IND != reports.mRfAndParams.back().mJammerGlo) {
  5506. data.gnssDataMask[GNSS_LOC_SIGNAL_TYPE_GLONASS_G1] |=
  5507. GNSS_LOC_DATA_AGC_BIT | GNSS_LOC_DATA_JAMMER_IND_BIT;
  5508. data.agc[GNSS_LOC_SIGNAL_TYPE_GLONASS_G1] =
  5509. -(double)reports.mRfAndParams.back().mJammerGlo;
  5510. data.jammerInd[GNSS_LOC_SIGNAL_TYPE_GLONASS_G1] =
  5511. (double)reports.mRfAndParams.back().mJammerGlo;
  5512. }
  5513. if (GNSS_INVALID_JAMMER_IND != reports.mRfAndParams.back().mJammerBds) {
  5514. data.gnssDataMask[GNSS_LOC_SIGNAL_TYPE_BEIDOU_B1_I] |=
  5515. GNSS_LOC_DATA_AGC_BIT | GNSS_LOC_DATA_JAMMER_IND_BIT;
  5516. data.agc[GNSS_LOC_SIGNAL_TYPE_BEIDOU_B1_I] =
  5517. -(double)reports.mRfAndParams.back().mJammerBds;
  5518. data.jammerInd[GNSS_LOC_SIGNAL_TYPE_BEIDOU_B1_I] =
  5519. (double)reports.mRfAndParams.back().mJammerBds;
  5520. }
  5521. if (GNSS_INVALID_JAMMER_IND != reports.mRfAndParams.back().mJammerGal) {
  5522. data.gnssDataMask[GNSS_LOC_SIGNAL_TYPE_GALILEO_E1_C] |=
  5523. GNSS_LOC_DATA_AGC_BIT | GNSS_LOC_DATA_JAMMER_IND_BIT;
  5524. data.agc[GNSS_LOC_SIGNAL_TYPE_GALILEO_E1_C] =
  5525. -(double)reports.mRfAndParams.back().mJammerGal;
  5526. data.jammerInd[GNSS_LOC_SIGNAL_TYPE_GALILEO_E1_C] =
  5527. (double)reports.mRfAndParams.back().mJammerGal;
  5528. }
  5529. }
  5530. }
  5531. }
  5532. /* Callbacks registered with loc_net_iface library */
  5533. static void agpsOpenResultCb (bool isSuccess, AGpsExtType agpsType, const char* apn,
  5534. AGpsBearerType bearerType, void* userDataPtr) {
  5535. LOC_LOGD("%s]: ", __func__);
  5536. if (userDataPtr == nullptr) {
  5537. LOC_LOGE("%s]: userDataPtr is nullptr.", __func__);
  5538. return;
  5539. }
  5540. if (apn == nullptr) {
  5541. LOC_LOGE("%s]: apn is nullptr.", __func__);
  5542. return;
  5543. }
  5544. GnssAdapter* adapter = (GnssAdapter*)userDataPtr;
  5545. if (isSuccess) {
  5546. adapter->dataConnOpenCommand(agpsType, apn, strlen(apn), bearerType);
  5547. } else {
  5548. adapter->dataConnFailedCommand(agpsType);
  5549. }
  5550. }
  5551. static void agpsCloseResultCb (bool isSuccess, AGpsExtType agpsType, void* userDataPtr) {
  5552. LOC_LOGD("%s]: ", __func__);
  5553. if (userDataPtr == nullptr) {
  5554. LOC_LOGE("%s]: userDataPtr is nullptr.", __func__);
  5555. return;
  5556. }
  5557. GnssAdapter* adapter = (GnssAdapter*)userDataPtr;
  5558. if (isSuccess) {
  5559. adapter->dataConnClosedCommand(agpsType);
  5560. } else {
  5561. adapter->dataConnFailedCommand(agpsType);
  5562. }
  5563. }
  5564. void
  5565. GnssAdapter::saveGnssEnergyConsumedCallback(GnssEnergyConsumedCallback energyConsumedCb) {
  5566. mGnssEnergyConsumedCb = energyConsumedCb;
  5567. }
  5568. void
  5569. GnssAdapter::getGnssEnergyConsumedCommand(GnssEnergyConsumedCallback energyConsumedCb) {
  5570. struct MsgGetGnssEnergyConsumed : public LocMsg {
  5571. GnssAdapter& mAdapter;
  5572. LocApiBase& mApi;
  5573. GnssEnergyConsumedCallback mEnergyConsumedCb;
  5574. inline MsgGetGnssEnergyConsumed(GnssAdapter& adapter, LocApiBase& api,
  5575. GnssEnergyConsumedCallback energyConsumedCb) :
  5576. LocMsg(),
  5577. mAdapter(adapter),
  5578. mApi(api),
  5579. mEnergyConsumedCb(energyConsumedCb){}
  5580. inline virtual void proc() const {
  5581. mAdapter.saveGnssEnergyConsumedCallback(mEnergyConsumedCb);
  5582. mApi.getGnssEnergyConsumed();
  5583. }
  5584. };
  5585. sendMsg(new MsgGetGnssEnergyConsumed(*this, *mLocApi, energyConsumedCb));
  5586. }
  5587. uint32_t GnssAdapter::getNfwControlBits(const std::vector<std::string>& enabledNfws) {
  5588. uint32_t nfwControlBits = 0;
  5589. for (auto& pkgName : enabledNfws) {
  5590. auto nfw = mNfws.find(pkgName);
  5591. if (mNfws.end() != nfw) {
  5592. nfwControlBits |= nfw->second;
  5593. }
  5594. }
  5595. nfwControlBits = ~nfwControlBits & GNSS_CONFIG_GPS_LOCK_NFW_ALL;
  5596. LOC_LOGd("nfwControlBits=0x%X", nfwControlBits);
  5597. return nfwControlBits;
  5598. }
  5599. void
  5600. GnssAdapter::nfwControlCommand(std::vector<std::string>& enabledNfws) {
  5601. struct MsgControlNfwLocationAccess : public LocMsg {
  5602. GnssAdapter& mAdapter;
  5603. LocApiBase& mApi;
  5604. const std::vector<std::string> mEnabledNfws;
  5605. inline MsgControlNfwLocationAccess(GnssAdapter& adapter, LocApiBase& api,
  5606. const std::vector<std::string>& enabledNfws) :
  5607. LocMsg(),
  5608. mAdapter(adapter),
  5609. mApi(api),
  5610. mEnabledNfws(std::move(enabledNfws)) {}
  5611. inline virtual void proc() const {
  5612. if (!mAdapter.isEngineCapabilitiesKnown()) {
  5613. mAdapter.mPendingMsgs.push_back(
  5614. new MsgControlNfwLocationAccess(mAdapter, mApi, mEnabledNfws));
  5615. return;
  5616. }
  5617. GnssConfigGpsLock gpsLock;
  5618. uint32_t nfwControlBits;
  5619. nfwControlBits = mAdapter.getNfwControlBits(mEnabledNfws);
  5620. gpsLock = ContextBase::mGps_conf.GPS_LOCK;
  5621. gpsLock &= GNSS_CONFIG_GPS_LOCK_MO;
  5622. gpsLock |= nfwControlBits;
  5623. ContextBase::mGps_conf.GPS_LOCK = gpsLock;
  5624. LOC_LOGv("gpsLock = 0x%X nfwControlBits = 0x%X", gpsLock, nfwControlBits);
  5625. mApi.sendMsg(new LocApiMsg([&mApi = mApi, gpsLock]() {
  5626. mApi.setGpsLockSync((GnssConfigGpsLock)gpsLock);
  5627. }));
  5628. }
  5629. };
  5630. if (mSupportNfwControl) {
  5631. sendMsg(new MsgControlNfwLocationAccess(*this, *mLocApi, enabledNfws));
  5632. } else {
  5633. LOC_LOGw("NFW control is not supported, do not use this for NFW");
  5634. }
  5635. }
  5636. // Set tunc constrained mode, use 0 session id to indicate
  5637. // that no callback is needed. Session id 0 is used for calls that
  5638. // are not invoked from the integration api, e.g.: initial configuration
  5639. // from the configure file
  5640. void
  5641. GnssAdapter::setConstrainedTunc(bool enable, float tuncConstraint,
  5642. uint32_t energyBudget, uint32_t sessionId) {
  5643. mLocConfigInfo.tuncConfigInfo.isValid = true;
  5644. mLocConfigInfo.tuncConfigInfo.enable = enable;
  5645. mLocConfigInfo.tuncConfigInfo.tuncThresholdMs = tuncConstraint;
  5646. mLocConfigInfo.tuncConfigInfo.energyBudget = energyBudget;
  5647. LocApiResponse* locApiResponse = nullptr;
  5648. if (sessionId != 0) {
  5649. locApiResponse =
  5650. new LocApiResponse(*getContext(),
  5651. [this, sessionId] (LocationError err) {
  5652. reportResponse(err, sessionId);});
  5653. if (!locApiResponse) {
  5654. LOC_LOGe("memory alloc failed");
  5655. }
  5656. }
  5657. mLocApi->setConstrainedTuncMode(
  5658. enable, tuncConstraint, energyBudget, locApiResponse);
  5659. }
  5660. uint32_t
  5661. GnssAdapter::setConstrainedTuncCommand (bool enable, float tuncConstraint,
  5662. uint32_t energyBudget) {
  5663. // generated session id will be none-zero
  5664. uint32_t sessionId = generateSessionId();
  5665. LOC_LOGd("session id %u", sessionId);
  5666. struct MsgEnableTUNC : public LocMsg {
  5667. GnssAdapter& mAdapter;
  5668. uint32_t mSessionId;
  5669. bool mEnable;
  5670. float mTuncConstraint;
  5671. uint32_t mEnergyBudget;
  5672. inline MsgEnableTUNC(GnssAdapter& adapter,
  5673. uint32_t sessionId,
  5674. bool enable,
  5675. float tuncConstraint,
  5676. uint32_t energyBudget) :
  5677. LocMsg(),
  5678. mAdapter(adapter),
  5679. mSessionId(sessionId),
  5680. mEnable(enable),
  5681. mTuncConstraint(tuncConstraint),
  5682. mEnergyBudget(energyBudget) {}
  5683. inline virtual void proc() const {
  5684. mAdapter.setConstrainedTunc(mEnable, mTuncConstraint,
  5685. mEnergyBudget, mSessionId);
  5686. }
  5687. };
  5688. sendMsg(new MsgEnableTUNC(*this, sessionId, enable,
  5689. tuncConstraint, energyBudget));
  5690. return sessionId;
  5691. }
  5692. // Set position assisted clock estimator, use 0 session id to indicate
  5693. // that no callback is needed. Session id 0 is used for calls that are
  5694. // not invoked from the integration api, e.g.: initial configuration
  5695. // from the configure file.
  5696. void
  5697. GnssAdapter::setPositionAssistedClockEstimator(bool enable,
  5698. uint32_t sessionId) {
  5699. mLocConfigInfo.paceConfigInfo.isValid = true;
  5700. mLocConfigInfo.paceConfigInfo.enable = enable;
  5701. LocApiResponse* locApiResponse = nullptr;
  5702. if (sessionId != 0) {
  5703. locApiResponse =
  5704. new LocApiResponse(*getContext(),
  5705. [this, sessionId] (LocationError err) {
  5706. reportResponse(err, sessionId);});
  5707. if (!locApiResponse) {
  5708. LOC_LOGe("memory alloc failed");
  5709. }
  5710. }
  5711. mLocApi->setPositionAssistedClockEstimatorMode(enable, locApiResponse);
  5712. }
  5713. uint32_t
  5714. GnssAdapter::setPositionAssistedClockEstimatorCommand(bool enable) {
  5715. // generated session id will be none-zero
  5716. uint32_t sessionId = generateSessionId();
  5717. LOC_LOGd("session id %u", sessionId);
  5718. struct MsgEnablePACE : public LocMsg {
  5719. GnssAdapter& mAdapter;
  5720. uint32_t mSessionId;
  5721. bool mEnable;
  5722. inline MsgEnablePACE(GnssAdapter& adapter,
  5723. uint32_t sessionId, bool enable) :
  5724. LocMsg(),
  5725. mAdapter(adapter),
  5726. mSessionId(sessionId),
  5727. mEnable(enable){}
  5728. inline virtual void proc() const {
  5729. mAdapter.setPositionAssistedClockEstimator(mEnable, mSessionId);
  5730. }
  5731. };
  5732. sendMsg(new MsgEnablePACE(*this, sessionId, enable));
  5733. return sessionId;
  5734. }
  5735. void GnssAdapter::gnssUpdateSvConfig(
  5736. uint32_t sessionId, const GnssSvTypeConfig& constellationEnablementConfig,
  5737. const GnssSvIdConfig& blacklistSvConfig) {
  5738. // suspend all tracking sessions to apply the constellation config
  5739. suspendSessions();
  5740. if (constellationEnablementConfig.size == sizeof(constellationEnablementConfig)) {
  5741. // check whether if any constellation is removed from the new config
  5742. GnssSvTypesMask currentEnabledMask = mGnssSvTypeConfig.enabledSvTypesMask;
  5743. GnssSvTypesMask newEnabledMask = constellationEnablementConfig.enabledSvTypesMask;
  5744. GnssSvTypesMask enabledRemoved = currentEnabledMask & (currentEnabledMask ^ newEnabledMask);
  5745. // Send reset if any constellation is removed from the enabled list
  5746. if (enabledRemoved != 0) {
  5747. mLocApi->resetConstellationControl();
  5748. }
  5749. // if the constellation config is valid, issue request to modem
  5750. // to enable/disable constellation
  5751. mLocApi->setConstellationControl(mGnssSvTypeConfig);
  5752. } else if (constellationEnablementConfig.size == 0) {
  5753. // when the size is not set, meaning reset to modem default
  5754. mLocApi->resetConstellationControl();
  5755. }
  5756. // save the constellation settings to be used for modem SSR
  5757. mGnssSvTypeConfig = constellationEnablementConfig;
  5758. // handle blacklisted SV settings
  5759. mGnssSvIdConfig = blacklistSvConfig;
  5760. // process blacklist svs info
  5761. mBlacklistedSvIds.clear();
  5762. // need to save the balcklisted sv info into mBlacklistedSvIds as well
  5763. convertFromGnssSvIdConfig(blacklistSvConfig, mBlacklistedSvIds);
  5764. LocApiResponse* locApiResponse = new LocApiResponse(*getContext(),
  5765. [this, sessionId] (LocationError err) {
  5766. reportResponse(err, sessionId);});
  5767. if (!locApiResponse) {
  5768. LOC_LOGe("memory alloc failed");
  5769. }
  5770. mLocApi->setBlacklistSv(mGnssSvIdConfig, locApiResponse);
  5771. // resume all tracking sessions after the constellation config has been applied
  5772. restartSessions(false);
  5773. }
  5774. uint32_t
  5775. GnssAdapter::gnssUpdateSvConfigCommand(
  5776. const GnssSvTypeConfig& constellationEnablementConfig,
  5777. const GnssSvIdConfig& blacklistSvConfig) {
  5778. // generated session id will be none-zero
  5779. uint32_t sessionId = generateSessionId();
  5780. LOC_LOGd("session id %u", sessionId);
  5781. struct MsgUpdateSvConfig : public LocMsg {
  5782. GnssAdapter& mAdapter;
  5783. uint32_t mSessionId;
  5784. GnssSvTypeConfig mConstellationEnablementConfig;
  5785. GnssSvIdConfig mBlacklistSvIdConfig;
  5786. inline MsgUpdateSvConfig(GnssAdapter& adapter,
  5787. uint32_t sessionId,
  5788. const GnssSvTypeConfig& constellationEnablementConfig,
  5789. const GnssSvIdConfig& blacklistSvConfig) :
  5790. LocMsg(),
  5791. mAdapter(adapter),
  5792. mSessionId(sessionId),
  5793. mConstellationEnablementConfig(constellationEnablementConfig),
  5794. mBlacklistSvIdConfig(blacklistSvConfig) {}
  5795. inline virtual void proc() const {
  5796. mAdapter.gnssUpdateSvConfig(mSessionId, mConstellationEnablementConfig,
  5797. mBlacklistSvIdConfig);
  5798. }
  5799. };
  5800. if (sessionId != 0) {
  5801. sendMsg(new MsgUpdateSvConfig(*this, sessionId, constellationEnablementConfig,
  5802. blacklistSvConfig));
  5803. }
  5804. return sessionId;
  5805. }
  5806. void GnssAdapter::gnssUpdateSecondaryBandConfig(
  5807. uint32_t sessionId, const GnssSvTypeConfig& secondaryBandConfig) {
  5808. LocApiResponse* locApiResponse = new LocApiResponse(*getContext(),
  5809. [this, sessionId] (LocationError err) {
  5810. reportResponse(err, sessionId);});
  5811. if (!locApiResponse) {
  5812. LOC_LOGe("memory alloc failed");
  5813. }
  5814. // handle secondary band info
  5815. mGnssSeconaryBandConfig = secondaryBandConfig;
  5816. gnssSecondaryBandConfigUpdate(locApiResponse);
  5817. }
  5818. uint32_t
  5819. GnssAdapter::gnssUpdateSecondaryBandConfigCommand(
  5820. const GnssSvTypeConfig& secondaryBandConfig) {
  5821. // generated session id will be none-zero
  5822. uint32_t sessionId = generateSessionId();
  5823. LOC_LOGd("session id %u", sessionId);
  5824. struct MsgUpdateSecondaryBandConfig : public LocMsg {
  5825. GnssAdapter& mAdapter;
  5826. uint32_t mSessionId;
  5827. GnssSvTypeConfig mSecondaryBandConfig;
  5828. inline MsgUpdateSecondaryBandConfig(GnssAdapter& adapter,
  5829. uint32_t sessionId,
  5830. const GnssSvTypeConfig& secondaryBandConfig) :
  5831. LocMsg(),
  5832. mAdapter(adapter),
  5833. mSessionId(sessionId),
  5834. mSecondaryBandConfig(secondaryBandConfig) {}
  5835. inline virtual void proc() const {
  5836. mAdapter.gnssUpdateSecondaryBandConfig(mSessionId, mSecondaryBandConfig);
  5837. }
  5838. };
  5839. if (sessionId != 0) {
  5840. sendMsg(new MsgUpdateSecondaryBandConfig(*this, sessionId, secondaryBandConfig));
  5841. }
  5842. return sessionId;
  5843. }
  5844. // This function currently retrieves secondary band configuration
  5845. // for constellation enablement/disablement.
  5846. void
  5847. GnssAdapter::gnssGetSecondaryBandConfig(uint32_t sessionId) {
  5848. LocApiResponse* locApiResponse = new LocApiResponse(*getContext(),
  5849. [this, sessionId] (LocationError err) {
  5850. reportResponse(err, sessionId);});
  5851. if (!locApiResponse) {
  5852. LOC_LOGe("memory alloc failed");
  5853. }
  5854. mLocApi->getConstellationMultiBandConfig(sessionId, locApiResponse);
  5855. }
  5856. uint32_t
  5857. GnssAdapter::gnssGetSecondaryBandConfigCommand() {
  5858. // generated session id will be none-zero
  5859. uint32_t sessionId = generateSessionId();
  5860. LOC_LOGd("session id %u", sessionId);
  5861. struct MsgGetSecondaryBandConfig : public LocMsg {
  5862. GnssAdapter& mAdapter;
  5863. uint32_t mSessionId;
  5864. inline MsgGetSecondaryBandConfig(GnssAdapter& adapter,
  5865. uint32_t sessionId) :
  5866. LocMsg(),
  5867. mAdapter(adapter),
  5868. mSessionId(sessionId) {}
  5869. inline virtual void proc() const {
  5870. mAdapter.gnssGetSecondaryBandConfig(mSessionId);
  5871. }
  5872. };
  5873. if (sessionId != 0) {
  5874. sendMsg(new MsgGetSecondaryBandConfig(*this, sessionId));
  5875. }
  5876. return sessionId;
  5877. }
  5878. void
  5879. GnssAdapter::configLeverArm(uint32_t sessionId,
  5880. const LeverArmConfigInfo& configInfo) {
  5881. LocationError err = LOCATION_ERROR_NOT_SUPPORTED;
  5882. // save the lever ARM config info for translating SPE positions from
  5883. // GNSS antenna based to VRP based
  5884. if (configInfo.leverArmValidMask & LEVER_ARM_TYPE_GNSS_TO_VRP_BIT) {
  5885. mLocConfigInfo.leverArmConfigInfo.leverArmValidMask |=
  5886. LEVER_ARM_TYPE_GNSS_TO_VRP_BIT;
  5887. mLocConfigInfo.leverArmConfigInfo.gnssToVRP = configInfo.gnssToVRP;
  5888. err = LOCATION_ERROR_SUCCESS;
  5889. }
  5890. if (configInfo.leverArmValidMask & LEVER_ARM_TYPE_DR_IMU_TO_GNSS_BIT) {
  5891. if (mDreIntEnabled && mEngHubProxy->configLeverArm(configInfo)) {
  5892. err = LOCATION_ERROR_SUCCESS;
  5893. }
  5894. }
  5895. reportResponse(err, sessionId);
  5896. }
  5897. uint32_t
  5898. GnssAdapter::configLeverArmCommand(const LeverArmConfigInfo& configInfo) {
  5899. // generated session id will be none-zero
  5900. uint32_t sessionId = generateSessionId();
  5901. LOC_LOGd("session id %u", sessionId);
  5902. struct MsgConfigLeverArm : public LocMsg {
  5903. GnssAdapter& mAdapter;
  5904. uint32_t mSessionId;
  5905. LeverArmConfigInfo mConfigInfo;
  5906. inline MsgConfigLeverArm(GnssAdapter& adapter,
  5907. uint32_t sessionId,
  5908. const LeverArmConfigInfo& configInfo) :
  5909. LocMsg(),
  5910. mAdapter(adapter),
  5911. mSessionId(sessionId),
  5912. mConfigInfo(configInfo) {}
  5913. inline virtual void proc() const {
  5914. mAdapter.configLeverArm(mSessionId, mConfigInfo);
  5915. }
  5916. };
  5917. sendMsg(new MsgConfigLeverArm(*this, sessionId, configInfo));
  5918. return sessionId;
  5919. }
  5920. bool GnssAdapter::initMeasCorr(bool bSendCbWhenNotSupported) {
  5921. LOC_LOGv("GnssAdapter::initMeasCorr");
  5922. /* Message to initialize Measurement Corrections */
  5923. struct MsgInitMeasCorr : public LocMsg {
  5924. GnssAdapter& mAdapter;
  5925. GnssMeasurementCorrectionsCapabilitiesMask mCapMask;
  5926. inline MsgInitMeasCorr(GnssAdapter& adapter,
  5927. GnssMeasurementCorrectionsCapabilitiesMask capMask) :
  5928. LocMsg(), mAdapter(adapter), mCapMask(capMask) {
  5929. LOC_LOGv("MsgInitMeasCorr");
  5930. }
  5931. inline virtual void proc() const {
  5932. LOC_LOGv("MsgInitMeasCorr::proc()");
  5933. mAdapter.mMeasCorrSetCapabilitiesCb(mCapMask);
  5934. }
  5935. };
  5936. if (ContextBase::isFeatureSupported(LOC_SUPPORTED_FEATURE_MEASUREMENTS_CORRECTION)) {
  5937. sendMsg(new MsgInitMeasCorr(*this, GNSS_MEAS_CORR_LOS_SATS |
  5938. GNSS_MEAS_CORR_EXCESS_PATH_LENGTH | GNSS_MEAS_CORR_REFLECTING_PLANE));
  5939. return true;
  5940. } else {
  5941. LOC_LOGv("MEASUREMENTS_CORRECTION feature is not supported in the modem");
  5942. if (bSendCbWhenNotSupported) {
  5943. sendMsg(new MsgInitMeasCorr(*this, 0));
  5944. }
  5945. return false;
  5946. }
  5947. }
  5948. bool GnssAdapter::openMeasCorrCommand(const measCorrSetCapabilitiesCb setCapabilitiesCb) {
  5949. LOC_LOGi("GnssAdapter::openMeasCorrCommand");
  5950. /* Send message to initialize Measurement Corrections */
  5951. mMeasCorrSetCapabilitiesCb = setCapabilitiesCb;
  5952. mIsMeasCorrInterfaceOpen = true;
  5953. if (isEngineCapabilitiesKnown()) {
  5954. LOC_LOGv("Capabilities are known, proceed with measurement corrections init");
  5955. return initMeasCorr(false);
  5956. } else {
  5957. LOC_LOGv("Capabilities are not known, wait for open");
  5958. return true;
  5959. }
  5960. }
  5961. bool GnssAdapter::measCorrSetCorrectionsCommand(const GnssMeasurementCorrections gnssMeasCorr) {
  5962. LOC_LOGi("GnssAdapter::measCorrSetCorrectionsCommand");
  5963. /* Message to set Measurement Corrections */
  5964. struct MsgSetCorrectionsMeasCorr : public LocMsg {
  5965. const GnssMeasurementCorrections mGnssMeasCorr;
  5966. GnssAdapter& mAdapter;
  5967. LocApiBase& mApi;
  5968. inline MsgSetCorrectionsMeasCorr(
  5969. const GnssMeasurementCorrections gnssMeasCorr,
  5970. GnssAdapter& adapter,
  5971. LocApiBase& api) :
  5972. LocMsg(),
  5973. mGnssMeasCorr(gnssMeasCorr),
  5974. mAdapter(adapter),
  5975. mApi(api) {
  5976. LOC_LOGv("MsgSetCorrectionsMeasCorr");
  5977. }
  5978. inline virtual void proc() const {
  5979. LOC_LOGv("MsgSetCorrectionsMeasCorr::proc()");
  5980. mApi.setMeasurementCorrections(mGnssMeasCorr);
  5981. }
  5982. };
  5983. if (ContextBase::isFeatureSupported(LOC_SUPPORTED_FEATURE_MEASUREMENTS_CORRECTION)) {
  5984. sendMsg(new MsgSetCorrectionsMeasCorr(gnssMeasCorr, *this, *mLocApi));
  5985. return true;
  5986. } else {
  5987. LOC_LOGw("Measurement Corrections are not supported!");
  5988. return false;
  5989. }
  5990. }
  5991. uint32_t GnssAdapter::antennaInfoInitCommand(const antennaInfoCb antennaInfoCallback) {
  5992. LOC_LOGi("GnssAdapter::antennaInfoInitCommand");
  5993. /* Message to initialize Antenna Information */
  5994. struct MsgInitAi : public LocMsg {
  5995. const antennaInfoCb mAntennaInfoCb;
  5996. GnssAdapter& mAdapter;
  5997. inline MsgInitAi(const antennaInfoCb antennaInfoCallback, GnssAdapter& adapter) :
  5998. LocMsg(), mAntennaInfoCb(antennaInfoCallback), mAdapter(adapter) {
  5999. LOC_LOGv("MsgInitAi");
  6000. }
  6001. inline virtual void proc() const {
  6002. LOC_LOGv("MsgInitAi::proc()");
  6003. mAdapter.reportGnssAntennaInformation(mAntennaInfoCb);
  6004. }
  6005. };
  6006. if (mIsAntennaInfoInterfaceOpened) {
  6007. return ANTENNA_INFO_ERROR_ALREADY_INIT;
  6008. } else {
  6009. mIsAntennaInfoInterfaceOpened = true;
  6010. sendMsg(new MsgInitAi(antennaInfoCallback, *this));
  6011. return ANTENNA_INFO_SUCCESS;
  6012. }
  6013. }
  6014. void
  6015. GnssAdapter::configRobustLocation(uint32_t sessionId,
  6016. bool enable, bool enableForE911) {
  6017. mLocConfigInfo.robustLocationConfigInfo.isValid = true;
  6018. mLocConfigInfo.robustLocationConfigInfo.enable = enable;
  6019. mLocConfigInfo.robustLocationConfigInfo.enableFor911 = enableForE911;
  6020. LocApiResponse* locApiResponse = nullptr;
  6021. if (sessionId != 0) {
  6022. locApiResponse =
  6023. new LocApiResponse(*getContext(),
  6024. [this, sessionId] (LocationError err) {
  6025. reportResponse(err, sessionId);});
  6026. if (!locApiResponse) {
  6027. LOC_LOGe("memory alloc failed");
  6028. }
  6029. }
  6030. mLocApi->configRobustLocation(enable, enableForE911, locApiResponse);
  6031. }
  6032. uint32_t GnssAdapter::configRobustLocationCommand(
  6033. bool enable, bool enableForE911) {
  6034. // generated session id will be none-zero
  6035. uint32_t sessionId = generateSessionId();
  6036. LOC_LOGd("session id %u", sessionId);
  6037. struct MsgConfigRobustLocation : public LocMsg {
  6038. GnssAdapter& mAdapter;
  6039. uint32_t mSessionId;
  6040. bool mEnable;
  6041. bool mEnableForE911;
  6042. inline MsgConfigRobustLocation(GnssAdapter& adapter,
  6043. uint32_t sessionId,
  6044. bool enable,
  6045. bool enableForE911) :
  6046. LocMsg(),
  6047. mAdapter(adapter),
  6048. mSessionId(sessionId),
  6049. mEnable(enable),
  6050. mEnableForE911(enableForE911) {}
  6051. inline virtual void proc() const {
  6052. mAdapter.configRobustLocation(mSessionId, mEnable, mEnableForE911);
  6053. }
  6054. };
  6055. sendMsg(new MsgConfigRobustLocation(*this, sessionId, enable, enableForE911));
  6056. return sessionId;
  6057. }
  6058. void
  6059. GnssAdapter::configMinGpsWeek(uint32_t sessionId, uint16_t minGpsWeek) {
  6060. // suspend all sessions for modem to take the min GPS week config
  6061. suspendSessions();
  6062. LocApiResponse* locApiResponse = nullptr;
  6063. if (sessionId != 0) {
  6064. locApiResponse =
  6065. new LocApiResponse(*getContext(),
  6066. [this, sessionId] (LocationError err) {
  6067. reportResponse(err, sessionId);});
  6068. if (!locApiResponse) {
  6069. LOC_LOGe("memory alloc failed");
  6070. }
  6071. }
  6072. mLocApi->configMinGpsWeek(minGpsWeek, locApiResponse);
  6073. // resume all tracking sessions after the min GPS week config
  6074. // has been changed
  6075. restartSessions(false);
  6076. }
  6077. uint32_t GnssAdapter::configMinGpsWeekCommand(uint16_t minGpsWeek) {
  6078. // generated session id will be none-zero
  6079. uint32_t sessionId = generateSessionId();
  6080. LOC_LOGd("session id %u", sessionId);
  6081. struct MsgConfigMinGpsWeek : public LocMsg {
  6082. GnssAdapter& mAdapter;
  6083. uint32_t mSessionId;
  6084. uint16_t mMinGpsWeek;
  6085. inline MsgConfigMinGpsWeek(GnssAdapter& adapter,
  6086. uint32_t sessionId,
  6087. uint16_t minGpsWeek) :
  6088. LocMsg(),
  6089. mAdapter(adapter),
  6090. mSessionId(sessionId),
  6091. mMinGpsWeek(minGpsWeek) {}
  6092. inline virtual void proc() const {
  6093. mAdapter.configMinGpsWeek(mSessionId, mMinGpsWeek);
  6094. }
  6095. };
  6096. sendMsg(new MsgConfigMinGpsWeek(*this, sessionId, minGpsWeek));
  6097. return sessionId;
  6098. }
  6099. uint32_t GnssAdapter::configDeadReckoningEngineParamsCommand(
  6100. const DeadReckoningEngineConfig& dreConfig) {
  6101. // generated session id will be none-zero
  6102. uint32_t sessionId = generateSessionId();
  6103. LOC_LOGd("session id %u", sessionId);
  6104. struct MsgConfigDrEngine : public LocMsg {
  6105. GnssAdapter& mAdapter;
  6106. uint32_t mSessionId;
  6107. DeadReckoningEngineConfig mDreConfig;
  6108. inline MsgConfigDrEngine(GnssAdapter& adapter,
  6109. uint32_t sessionId,
  6110. const DeadReckoningEngineConfig& dreConfig) :
  6111. LocMsg(),
  6112. mAdapter(adapter),
  6113. mSessionId(sessionId),
  6114. mDreConfig(dreConfig) {}
  6115. inline virtual void proc() const {
  6116. LocationError err = LOCATION_ERROR_NOT_SUPPORTED;
  6117. if (true == mAdapter.mEngHubProxy->configDeadReckoningEngineParams(mDreConfig)) {
  6118. err = LOCATION_ERROR_SUCCESS;
  6119. }
  6120. mAdapter.reportResponse(err, mSessionId);
  6121. }
  6122. };
  6123. sendMsg(new MsgConfigDrEngine(*this, sessionId, dreConfig));
  6124. return sessionId;
  6125. }
  6126. uint32_t GnssAdapter::configEngineRunStateCommand(
  6127. PositioningEngineMask engType, LocEngineRunState engState) {
  6128. // generated session id will be none-zero
  6129. uint32_t sessionId = generateSessionId();
  6130. LOC_LOGe("session id %u, eng type 0x%x, eng state %d, dre enabled %d",
  6131. sessionId, engType, engState, mDreIntEnabled);
  6132. struct MsgConfigEngineRunState : public LocMsg {
  6133. GnssAdapter& mAdapter;
  6134. uint32_t mSessionId;
  6135. PositioningEngineMask mEngType;
  6136. LocEngineRunState mEngState;
  6137. inline MsgConfigEngineRunState(GnssAdapter& adapter,
  6138. uint32_t sessionId,
  6139. PositioningEngineMask engType,
  6140. LocEngineRunState engState) :
  6141. LocMsg(),
  6142. mAdapter(adapter),
  6143. mSessionId(sessionId),
  6144. mEngType(engType),
  6145. mEngState(engState) {}
  6146. inline virtual void proc() const {
  6147. LocationError err = LOCATION_ERROR_NOT_SUPPORTED;
  6148. // Currently, only DR engine supports pause/resume request
  6149. if ((mEngType == DEAD_RECKONING_ENGINE) &&
  6150. (mAdapter.mDreIntEnabled == true)) {
  6151. if (true == mAdapter.mEngHubProxy->configEngineRunState(mEngType, mEngState)) {
  6152. err = LOCATION_ERROR_SUCCESS;
  6153. }
  6154. }
  6155. mAdapter.reportResponse(err, mSessionId);
  6156. }
  6157. };
  6158. sendMsg(new MsgConfigEngineRunState(*this, sessionId, engType, engState));
  6159. return sessionId;
  6160. }
  6161. uint32_t GnssAdapter::configOutputNmeaTypesCommand(GnssNmeaTypesMask enabledNmeaTypes) {
  6162. // generated session id will be none-zero
  6163. uint32_t sessionId = generateSessionId();
  6164. LOC_LOGd("session id %u, enabled nmea = 0x%x", sessionId, enabledNmeaTypes);
  6165. struct MsgConfigOutputNmeaType : public LocMsg {
  6166. GnssAdapter& mAdapter;
  6167. uint32_t mSessionId;
  6168. GnssNmeaTypesMask mEnabledNmeaTypes;
  6169. inline MsgConfigOutputNmeaType(GnssAdapter& adapter,
  6170. uint32_t sessionId,
  6171. GnssNmeaTypesMask enabledNmeaTypes) :
  6172. LocMsg(),
  6173. mAdapter(adapter),
  6174. mSessionId(sessionId),
  6175. mEnabledNmeaTypes(enabledNmeaTypes) {}
  6176. inline virtual void proc() const {
  6177. loc_nmea_config_output_types(mEnabledNmeaTypes);
  6178. mAdapter.reportResponse(LOCATION_ERROR_SUCCESS, mSessionId);
  6179. }
  6180. };
  6181. sendMsg(new MsgConfigOutputNmeaType(*this, sessionId, enabledNmeaTypes));
  6182. return sessionId;
  6183. }
  6184. void GnssAdapter::powerIndicationInitCommand(const powerIndicationCb powerIndicationCallback) {
  6185. LOC_LOGi("GnssAdapter::powerIndicationInitCommand");
  6186. struct MsgPowerIndicationInit : public LocMsg {
  6187. const powerIndicationCb mPowerIndicationCb;
  6188. GnssAdapter& mAdapter;
  6189. inline MsgPowerIndicationInit(const powerIndicationCb powerIndicationCallback,
  6190. GnssAdapter& adapter) :
  6191. LocMsg(), mPowerIndicationCb(powerIndicationCallback), mAdapter(adapter) {
  6192. LOC_LOGv("MsgPowerIndicationInit");
  6193. }
  6194. inline virtual void proc() const {
  6195. LOC_LOGv("MsgPowerIndicationInit::proc()");
  6196. mAdapter.setPowerIndicationCb(mPowerIndicationCb);
  6197. }
  6198. };
  6199. sendMsg(new MsgPowerIndicationInit(powerIndicationCallback, *this));
  6200. }
  6201. void GnssAdapter::powerIndicationRequestCommand() {
  6202. LOC_LOGi("GnssAdapter::powerIndicationRequestCommand");
  6203. struct MsgPowerIndicationRequest : public LocMsg {
  6204. LocApiBase& mApi;
  6205. inline MsgPowerIndicationRequest(LocApiBase& api) :
  6206. LocMsg(), mApi(api) {
  6207. LOC_LOGv("MsgPowerIndicationRequest");
  6208. }
  6209. inline virtual void proc() const {
  6210. LOC_LOGv("MsgPowerIndicationRequest::proc()");
  6211. mApi.getGnssEnergyConsumed();
  6212. }
  6213. };
  6214. sendMsg(new MsgPowerIndicationRequest(*mLocApi));
  6215. }
  6216. void GnssAdapter::reportGnssConfigEvent(uint32_t sessionId, const GnssConfig& gnssConfig)
  6217. {
  6218. struct MsgReportGnssConfig : public LocMsg {
  6219. GnssAdapter& mAdapter;
  6220. uint32_t mSessionId;
  6221. mutable GnssConfig mGnssConfig;
  6222. inline MsgReportGnssConfig(GnssAdapter& adapter,
  6223. uint32_t sessionId,
  6224. const GnssConfig& gnssConfig) :
  6225. LocMsg(),
  6226. mAdapter(adapter),
  6227. mSessionId(sessionId),
  6228. mGnssConfig(gnssConfig) {}
  6229. inline virtual void proc() const {
  6230. // Invoke control clients config callback
  6231. if (nullptr != mAdapter.mControlCallbacks.gnssConfigCb) {
  6232. mAdapter.mControlCallbacks.gnssConfigCb(mSessionId, mGnssConfig);
  6233. } else {
  6234. LOC_LOGe("Failed to report, callback not registered");
  6235. }
  6236. }
  6237. };
  6238. sendMsg(new MsgReportGnssConfig(*this, sessionId, gnssConfig));
  6239. }
  6240. /* ==== Eng Hub Proxy ================================================================= */
  6241. /* ======== UTILITIES ================================================================= */
  6242. void
  6243. GnssAdapter::initEngHubProxyCommand() {
  6244. LOC_LOGd();
  6245. struct MsgInitEngHubProxy : public LocMsg {
  6246. GnssAdapter* mAdapter;
  6247. inline MsgInitEngHubProxy(GnssAdapter* adapter) :
  6248. LocMsg(),
  6249. mAdapter(adapter) {}
  6250. inline virtual void proc() const {
  6251. mAdapter->initEngHubProxy();
  6252. }
  6253. };
  6254. sendMsg(new MsgInitEngHubProxy(this));
  6255. }
  6256. bool
  6257. GnssAdapter::initEngHubProxy() {
  6258. static bool firstTime = true;
  6259. static bool engHubLoadSuccessful = false;
  6260. const char *error = nullptr;
  6261. unsigned int processListLength = 0;
  6262. loc_process_info_s_type* processInfoList = nullptr;
  6263. do {
  6264. // load eng hub only once
  6265. if (firstTime == false) {
  6266. break;
  6267. }
  6268. int rc = loc_read_process_conf(LOC_PATH_IZAT_CONF, &processListLength,
  6269. &processInfoList);
  6270. if (rc != 0) {
  6271. LOC_LOGE("%s]: failed to parse conf file", __func__);
  6272. break;
  6273. }
  6274. EngineServiceInfo engServiceInfo = {};
  6275. bool pluginDaemonEnabled = false;
  6276. // go over the conf table to see whether any plugin daemon is enabled
  6277. for (unsigned int i = 0; i < processListLength; i++) {
  6278. if ((strncmp(processInfoList[i].name[0], PROCESS_NAME_ENGINE_SERVICE,
  6279. strlen(PROCESS_NAME_ENGINE_SERVICE)) == 0) &&
  6280. (processInfoList[i].proc_status == ENABLED)) {
  6281. pluginDaemonEnabled = true;
  6282. if (processInfoList[i].args[1]!= nullptr) {
  6283. // check if this is DRE-INT engine
  6284. if (strncmp(processInfoList[i].args[1], "DRE-INT", sizeof("DRE-INT")) == 0) {
  6285. mDreIntEnabled = true;
  6286. } else if (strncmp(processInfoList[i].args[1], "PPE-INT",
  6287. sizeof("PPE-INT")) == 0) {
  6288. // check if this is PPE-INT engine
  6289. engServiceInfo.ppeIntEnabled = true;
  6290. }
  6291. }
  6292. }
  6293. }
  6294. // no plugin daemon is enabled for this platform,
  6295. // check if external engine is present for which we need
  6296. // libloc_eng_hub.so to be loaded
  6297. if (pluginDaemonEnabled == false) {
  6298. UTIL_READ_CONF(LOC_PATH_IZAT_CONF, izatConfParamTable);
  6299. if (!loadEngHubForExternalEngine) {
  6300. break;
  6301. }
  6302. }
  6303. // load the engine hub .so, if the .so is not present
  6304. // all EngHubProxyBase calls will turn into no-op.
  6305. void *handle = nullptr;
  6306. if ((handle = dlopen("libloc_eng_hub.so", RTLD_NOW)) == nullptr) {
  6307. if ((error = dlerror()) != nullptr) {
  6308. LOC_LOGE("%s]: libloc_eng_hub.so not found %s !", __func__, error);
  6309. }
  6310. break;
  6311. }
  6312. // prepare the callback functions
  6313. // callback function for engine hub to report back position event
  6314. GnssAdapterReportEnginePositionsEventCb reportPositionEventCb =
  6315. [this](int count, EngineLocationInfo* locationArr) {
  6316. // report from engine hub on behalf of PPE will be treated as fromUlp
  6317. reportEnginePositionsEvent(count, locationArr);
  6318. };
  6319. // callback function for engine hub to request for complete aiding data
  6320. GnssAdapterReqAidingDataCb reqAidingDataCb =
  6321. [this] (const GnssAidingDataSvMask& svDataMask) {
  6322. mLocApi->requestForAidingData(svDataMask);
  6323. };
  6324. GnssAdapterUpdateNHzRequirementCb updateNHzRequirementCb =
  6325. [this] (bool nHzNeeded, bool nHzMeasNeeded) {
  6326. if (nHzMeasNeeded &&
  6327. (!checkMask(LOC_API_ADAPTER_BIT_GNSS_NHZ_MEASUREMENT))) {
  6328. updateEvtMask(LOC_API_ADAPTER_BIT_GNSS_NHZ_MEASUREMENT,
  6329. LOC_REGISTRATION_MASK_ENABLED);
  6330. } else if (checkMask(LOC_API_ADAPTER_BIT_GNSS_NHZ_MEASUREMENT)) {
  6331. updateEvtMask(LOC_API_ADAPTER_BIT_GNSS_NHZ_MEASUREMENT,
  6332. LOC_REGISTRATION_MASK_DISABLED);
  6333. }
  6334. if (mNHzNeeded != nHzNeeded) {
  6335. mNHzNeeded = nHzNeeded;
  6336. checkAndRestartSPESession();
  6337. }
  6338. };
  6339. GnssAdapterUpdateQwesFeatureStatusCb updateQwesFeatureStatusCb =
  6340. [this] (const std::unordered_map<LocationQwesFeatureType, bool> &featureMap) {
  6341. reportQwesCapabilities(featureMap);
  6342. };
  6343. getEngHubProxyFn* getter = (getEngHubProxyFn*) dlsym(handle, "getEngHubProxy");
  6344. if(getter != nullptr) {
  6345. // Wait for the script(rootdir/etc/init.qcom.rc) to create socket folder
  6346. locUtilWaitForDir(SOCKET_DIR_EHUB);
  6347. EngineHubProxyBase* hubProxy = (*getter) (mMsgTask, mSystemStatus->getOsObserver(),
  6348. engServiceInfo, reportPositionEventCb, reqAidingDataCb,
  6349. updateNHzRequirementCb, updateQwesFeatureStatusCb);
  6350. if (hubProxy != nullptr) {
  6351. mEngHubProxy = hubProxy;
  6352. engHubLoadSuccessful = true;
  6353. }
  6354. }
  6355. else {
  6356. LOC_LOGD("%s]: entered, did not find function", __func__);
  6357. }
  6358. LOC_LOGD("%s]: first time initialization %d, returned %d",
  6359. __func__, firstTime, engHubLoadSuccessful);
  6360. } while (0);
  6361. if (processInfoList != nullptr) {
  6362. free (processInfoList);
  6363. processInfoList = nullptr;
  6364. }
  6365. firstTime = false;
  6366. return engHubLoadSuccessful;
  6367. }
  6368. std::vector<double>
  6369. GnssAdapter::parseDoublesString(char* dString) {
  6370. std::vector<double> dVector;
  6371. char* tmp = NULL;
  6372. char* substr;
  6373. dVector.clear();
  6374. for (substr = strtok_r(dString, " ", &tmp);
  6375. substr != NULL;
  6376. substr = strtok_r(NULL, " ", &tmp)) {
  6377. dVector.push_back(std::stod(substr));
  6378. }
  6379. return dVector;
  6380. }
  6381. void GnssAdapter::initGnssPowerStatistics() {
  6382. if (!mGnssPowerStatisticsInit) {
  6383. mLocApi->getGnssEnergyConsumed();
  6384. }
  6385. }
  6386. void
  6387. GnssAdapter::reportGnssAntennaInformation(const antennaInfoCb antennaInfoCallback)
  6388. {
  6389. #define MAX_TEXT_WIDTH 50
  6390. #define MAX_COLUMN_WIDTH 20
  6391. /* parse antenna_corrections file and fill in
  6392. a vector of GnssAntennaInformation data structure */
  6393. std::vector<GnssAntennaInformation> gnssAntennaInformations;
  6394. GnssAntennaInformation gnssAntennaInfo;
  6395. uint32_t antennaInfoVectorSize;
  6396. loc_param_s_type ant_info_vector_table[] =
  6397. {
  6398. { "ANTENNA_INFO_VECTOR_SIZE", &antennaInfoVectorSize, NULL, 'n' }
  6399. };
  6400. UTIL_READ_CONF(LOC_PATH_ANT_CORR, ant_info_vector_table);
  6401. for (uint32_t i = 0; i < antennaInfoVectorSize; i++) {
  6402. double carrierFrequencyMHz;
  6403. char pcOffsetStr[LOC_MAX_PARAM_STRING];
  6404. uint32_t numberOfRows = 0;
  6405. uint32_t numberOfColumns = 0;
  6406. uint32_t numberOfRowsSGC = 0;
  6407. uint32_t numberOfColumnsSGC = 0;
  6408. gnssAntennaInfo.phaseCenterVariationCorrectionMillimeters.clear();
  6409. gnssAntennaInfo.phaseCenterVariationCorrectionUncertaintyMillimeters.clear();
  6410. gnssAntennaInfo.signalGainCorrectionDbi.clear();
  6411. gnssAntennaInfo.signalGainCorrectionUncertaintyDbi.clear();
  6412. string s1 = "CARRIER_FREQUENCY_";
  6413. s1 += to_string(i);
  6414. string s2 = "PC_OFFSET_";
  6415. s2 += to_string(i);
  6416. string s3 = "NUMBER_OF_ROWS_";
  6417. s3 += to_string(i);
  6418. string s4 = "NUMBER_OF_COLUMNS_";
  6419. s4 += to_string(i);
  6420. string s5 = "NUMBER_OF_ROWS_SGC_";
  6421. s5 += to_string(i);
  6422. string s6 = "NUMBER_OF_COLUMNS_SGC_";
  6423. s6 += to_string(i);
  6424. gnssAntennaInfo.size = sizeof(gnssAntennaInfo);
  6425. loc_param_s_type ant_cf_table[] =
  6426. {
  6427. { s1.c_str(), &carrierFrequencyMHz, NULL, 'f' },
  6428. { s2.c_str(), &pcOffsetStr, NULL, 's' },
  6429. { s3.c_str(), &numberOfRows, NULL, 'n' },
  6430. { s4.c_str(), &numberOfColumns, NULL, 'n' },
  6431. { s5.c_str(), &numberOfRowsSGC, NULL, 'n' },
  6432. { s6.c_str(), &numberOfColumnsSGC, NULL, 'n' },
  6433. };
  6434. UTIL_READ_CONF(LOC_PATH_ANT_CORR, ant_cf_table);
  6435. if (0 == numberOfRowsSGC) {
  6436. numberOfRowsSGC = numberOfRows;
  6437. }
  6438. if (0 == numberOfColumnsSGC) {
  6439. numberOfColumnsSGC = numberOfColumns;
  6440. }
  6441. gnssAntennaInfo.carrierFrequencyMHz = carrierFrequencyMHz;
  6442. // now parse pcOffsetStr to get each entry
  6443. std::vector<double> pcOffset;
  6444. pcOffset = parseDoublesString(pcOffsetStr);
  6445. gnssAntennaInfo.phaseCenterOffsetCoordinateMillimeters.size =
  6446. sizeof(gnssAntennaInfo.phaseCenterOffsetCoordinateMillimeters);
  6447. gnssAntennaInfo.phaseCenterOffsetCoordinateMillimeters.x = pcOffset[0];
  6448. gnssAntennaInfo.phaseCenterOffsetCoordinateMillimeters.xUncertainty = pcOffset[1];
  6449. gnssAntennaInfo.phaseCenterOffsetCoordinateMillimeters.y = pcOffset[2];
  6450. gnssAntennaInfo.phaseCenterOffsetCoordinateMillimeters.yUncertainty = pcOffset[3];
  6451. gnssAntennaInfo.phaseCenterOffsetCoordinateMillimeters.z = pcOffset[4];
  6452. gnssAntennaInfo.phaseCenterOffsetCoordinateMillimeters.zUncertainty = pcOffset[5];
  6453. uint16_t array_size = MAX_TEXT_WIDTH + MAX_COLUMN_WIDTH*numberOfColumns;
  6454. uint16_t array_size_SGC = MAX_TEXT_WIDTH + MAX_COLUMN_WIDTH*numberOfColumnsSGC;
  6455. for (uint32_t j = 0; j < numberOfRows; j++) {
  6456. char pcVarCorrStr[array_size];
  6457. char pcVarCorrUncStr[array_size];
  6458. string s1 = "PC_VARIATION_CORRECTION_" + to_string(i) + "_ROW_";
  6459. s1 += to_string(j);
  6460. string s2 = "PC_VARIATION_CORRECTION_UNC_" + to_string(i) + "_ROW_";
  6461. s2 += to_string(j);
  6462. loc_param_s_type ant_row_table[] =
  6463. {
  6464. { s1.c_str(), &pcVarCorrStr, NULL, 's' },
  6465. { s2.c_str(), &pcVarCorrUncStr, NULL, 's' },
  6466. };
  6467. UTIL_READ_CONF_LONG(LOC_PATH_ANT_CORR, ant_row_table, array_size);
  6468. gnssAntennaInfo.phaseCenterVariationCorrectionMillimeters.push_back(
  6469. parseDoublesString(pcVarCorrStr));
  6470. gnssAntennaInfo.phaseCenterVariationCorrectionUncertaintyMillimeters.push_back(
  6471. parseDoublesString(pcVarCorrUncStr));
  6472. }
  6473. for (uint32_t j = 0; j < numberOfRowsSGC; j++) {
  6474. char sigGainCorrStr[array_size_SGC];
  6475. char sigGainCorrUncStr[array_size_SGC];
  6476. string s3 = "SIGNAL_GAIN_CORRECTION_" + to_string(i) + "_ROW_";
  6477. s3 += to_string(j);
  6478. string s4 = "SIGNAL_GAIN_CORRECTION_UNC_" + to_string(i) + "_ROW_";
  6479. s4 += to_string(j);
  6480. loc_param_s_type ant_row_table[] =
  6481. {
  6482. { s3.c_str(), &sigGainCorrStr, NULL, 's' },
  6483. { s4.c_str(), &sigGainCorrUncStr, NULL, 's' },
  6484. };
  6485. UTIL_READ_CONF_LONG(LOC_PATH_ANT_CORR, ant_row_table, array_size_SGC);
  6486. gnssAntennaInfo.signalGainCorrectionDbi.push_back(
  6487. parseDoublesString(sigGainCorrStr));
  6488. gnssAntennaInfo.signalGainCorrectionUncertaintyDbi.push_back(
  6489. parseDoublesString(sigGainCorrUncStr));
  6490. }
  6491. gnssAntennaInformations.push_back(std::move(gnssAntennaInfo));
  6492. }
  6493. if (antennaInfoVectorSize > 0) {
  6494. antennaInfoCallback(gnssAntennaInformations);
  6495. }
  6496. }
  6497. /* ==== DGnss Usable Reporter ========================================================= */
  6498. void GnssAdapter::initCDFWServiceCommand() {
  6499. struct MsgInitCDFWService : public LocMsg {
  6500. GnssAdapter* mAdapter;
  6501. inline MsgInitCDFWService(GnssAdapter* adapter) :
  6502. LocMsg(),
  6503. mAdapter(adapter) {}
  6504. inline virtual void proc() const {
  6505. mAdapter->initCDFWService();
  6506. }
  6507. };
  6508. sendMsg(new MsgInitCDFWService(this));
  6509. }
  6510. /* ======== UTILITIES ================================================================= */
  6511. void GnssAdapter::initCDFWService()
  6512. {
  6513. LOC_LOGd("mCdfwInterface %p", mCdfwInterface);
  6514. if (nullptr == mCdfwInterface) {
  6515. void* libHandle = nullptr;
  6516. const char* libName = "libcdfw.so";
  6517. libHandle = nullptr;
  6518. getCdfwInterface getter = (getCdfwInterface)dlGetSymFromLib(libHandle,
  6519. libName, "getQCdfwInterface");
  6520. if (nullptr == getter) {
  6521. LOC_LOGe("dlGetSymFromLib getQCdfwInterface failed");
  6522. } else {
  6523. mCdfwInterface = getter();
  6524. }
  6525. if (nullptr != mCdfwInterface) {
  6526. QDgnssSessionActiveCb qDgnssSessionActiveCb = [this] (bool sessionActive) {
  6527. mDGnssNeedReport = sessionActive;
  6528. };
  6529. mCdfwInterface->startDgnssApiService(*mMsgTask);
  6530. mQDgnssListenerHDL = mCdfwInterface->createUsableReporter(qDgnssSessionActiveCb);
  6531. }
  6532. }
  6533. //Read Ntrip params form gps.conf on automobile PLs
  6534. #ifdef USE_GLIB
  6535. readPPENtripConfig();
  6536. #endif
  6537. }
  6538. /*==== DGnss Ntrip Source ==========================================================*/
  6539. void GnssAdapter::enablePPENtripStreamCommand(const GnssNtripConnectionParams& params,
  6540. bool enableRTKEngine) {
  6541. (void)enableRTKEngine; //future parameter, not used
  6542. if (0 == params.size || params.hostNameOrIp.empty() || params.mountPoint.empty() ||
  6543. params.username.empty() || params.password.empty()) {
  6544. LOC_LOGe("Ntrip parameters are invalid!");
  6545. return;
  6546. }
  6547. struct enableNtripMsg : public LocMsg {
  6548. GnssAdapter& mAdapter;
  6549. const GnssNtripConnectionParams mParams;
  6550. inline enableNtripMsg(GnssAdapter& adapter,
  6551. const GnssNtripConnectionParams& params) :
  6552. LocMsg(),
  6553. mAdapter(adapter),
  6554. mParams(std::move(params)) {}
  6555. inline virtual void proc() const {
  6556. mAdapter.handleEnablePPENtrip(mParams);
  6557. }
  6558. };
  6559. sendMsg(new enableNtripMsg(*this, params));
  6560. }
  6561. void GnssAdapter::handleEnablePPENtrip(const GnssNtripConnectionParams& params) {
  6562. LOC_LOGd("%d %s %d %s %s %s %d mSendNmeaConsent %d",
  6563. params.useSSL, params.hostNameOrIp.data(), params.port,
  6564. params.mountPoint.data(), params.username.data(), params.password.data(),
  6565. params.requiresNmeaLocation, mSendNmeaConsent);
  6566. GnssNtripConnectionParams* pNtripParams = &(mStartDgnssNtripParams.ntripParams);
  6567. if (pNtripParams->useSSL == params.useSSL &&
  6568. 0 == pNtripParams->hostNameOrIp.compare(params.hostNameOrIp) &&
  6569. pNtripParams->port == params.port &&
  6570. 0 == pNtripParams->mountPoint.compare(params.mountPoint) &&
  6571. 0 == pNtripParams->username.compare(params.username) &&
  6572. 0 == pNtripParams->password.compare(params.password) &&
  6573. pNtripParams->requiresNmeaLocation == params.requiresNmeaLocation &&
  6574. mDgnssState & DGNSS_STATE_ENABLE_NTRIP_COMMAND) {
  6575. LOC_LOGd("received same Ntrip param");
  6576. return;
  6577. }
  6578. mDgnssState |= DGNSS_STATE_ENABLE_NTRIP_COMMAND;
  6579. mDgnssState |= DGNSS_STATE_NO_NMEA_PENDING;
  6580. mDgnssState &= ~DGNSS_STATE_NTRIP_SESSION_STARTED;
  6581. mStartDgnssNtripParams.ntripParams = std::move(params);
  6582. mStartDgnssNtripParams.nmea.clear();
  6583. if (mSendNmeaConsent && pNtripParams->requiresNmeaLocation) {
  6584. mDgnssState &= ~DGNSS_STATE_NO_NMEA_PENDING;
  6585. mDgnssLastNmeaBootTimeMilli = 0;
  6586. return;
  6587. }
  6588. checkUpdateDgnssNtrip(false);
  6589. }
  6590. void GnssAdapter::disablePPENtripStreamCommand() {
  6591. struct disableNtripMsg : public LocMsg {
  6592. GnssAdapter& mAdapter;
  6593. inline disableNtripMsg(GnssAdapter& adapter) :
  6594. LocMsg(),
  6595. mAdapter(adapter) {}
  6596. inline virtual void proc() const {
  6597. mAdapter.handleDisablePPENtrip();
  6598. }
  6599. };
  6600. sendMsg(new disableNtripMsg(*this));
  6601. }
  6602. void GnssAdapter::handleDisablePPENtrip() {
  6603. mDgnssState &= ~DGNSS_STATE_ENABLE_NTRIP_COMMAND;
  6604. mDgnssState |= DGNSS_STATE_NO_NMEA_PENDING;
  6605. stopDgnssNtrip();
  6606. }
  6607. void GnssAdapter::checkUpdateDgnssNtrip(bool isLocationValid) {
  6608. LOC_LOGd("isInSession %d mDgnssState 0x%x isLocationValid %d",
  6609. isInSession(), mDgnssState, isLocationValid);
  6610. if (isInSession()) {
  6611. uint64_t curBootTime = getBootTimeMilliSec();
  6612. if (mDgnssState == (DGNSS_STATE_ENABLE_NTRIP_COMMAND | DGNSS_STATE_NO_NMEA_PENDING)) {
  6613. mDgnssState |= DGNSS_STATE_NTRIP_SESSION_STARTED;
  6614. mXtraObserver.startDgnssSource(mStartDgnssNtripParams);
  6615. if (isDgnssNmeaRequired()) {
  6616. mDgnssLastNmeaBootTimeMilli = curBootTime;
  6617. }
  6618. } else if ((mDgnssState & DGNSS_STATE_NTRIP_SESSION_STARTED) && isLocationValid &&
  6619. isDgnssNmeaRequired() &&
  6620. curBootTime - mDgnssLastNmeaBootTimeMilli > DGNSS_RANGE_UPDATE_TIME_10MIN_IN_MILLI ) {
  6621. mXtraObserver.updateNmeaToDgnssServer(mStartDgnssNtripParams.nmea);
  6622. mDgnssLastNmeaBootTimeMilli = curBootTime;
  6623. }
  6624. }
  6625. }
  6626. void GnssAdapter::stopDgnssNtrip() {
  6627. LOC_LOGd("isInSession %d mDgnssState 0x%x", isInSession(), mDgnssState);
  6628. mStartDgnssNtripParams.nmea.clear();
  6629. if (mDgnssState & DGNSS_STATE_NTRIP_SESSION_STARTED) {
  6630. mDgnssState &= ~DGNSS_STATE_NTRIP_SESSION_STARTED;
  6631. mXtraObserver.stopDgnssSource();
  6632. }
  6633. }
  6634. void GnssAdapter::reportGGAToNtrip(const char* nmea) {
  6635. #define POS_OF_GGA (3) //start position of "GGA"
  6636. #define COMMAS_BEFORE_VALID (6) //"$GPGGA,,,,,,0,,,,,,,,*hh"
  6637. if (!isDgnssNmeaRequired()) {
  6638. return;
  6639. }
  6640. if (nullptr == nmea || 0 == strlen(nmea)) {
  6641. return;
  6642. }
  6643. string nmeaString(nmea);
  6644. size_t foundPos = nmeaString.find("GGA");
  6645. size_t foundNth = 0;
  6646. string GGAString;
  6647. if (foundPos != string::npos && foundPos >= POS_OF_GGA) {
  6648. size_t foundNextSentence = nmeaString.find("$", foundPos);
  6649. if (foundNextSentence != string::npos) {
  6650. /* remove other sentences after GGA */
  6651. GGAString = nmeaString.substr(foundPos - POS_OF_GGA, foundNextSentence);
  6652. } else {
  6653. /* GGA is the last sentence */
  6654. GGAString = nmeaString.substr(foundPos - POS_OF_GGA);
  6655. }
  6656. LOC_LOGd("GGAString %s", GGAString.c_str());
  6657. foundPos = GGAString.find(",");
  6658. while (foundPos != string::npos && foundNth < COMMAS_BEFORE_VALID) {
  6659. foundPos++;
  6660. foundNth++;
  6661. foundPos = GGAString.find(",", foundPos);
  6662. }
  6663. if (COMMAS_BEFORE_VALID == foundNth && GGAString.at(foundPos-1) != '0') {
  6664. mDgnssState |= DGNSS_STATE_NO_NMEA_PENDING;
  6665. mStartDgnssNtripParams.nmea = std::move(GGAString);
  6666. checkUpdateDgnssNtrip(true);
  6667. }
  6668. }
  6669. return;
  6670. }
  6671. void GnssAdapter::readPPENtripConfig() {
  6672. static char NtripParamsString[LOC_MAX_PARAM_STRING];
  6673. if (mDgnssState & DGNSS_STATE_ENABLE_NTRIP_COMMAND) {
  6674. return;
  6675. }
  6676. // A sample Ntrip_Params -> 199.106.116.10 5000 Avante_Ref CV2X 1234 0 0
  6677. static loc_param_s_type gpsConfParamTable[] = {
  6678. {"Ntrip_Params", &NtripParamsString, nullptr, 's'}
  6679. };
  6680. UTIL_READ_CONF(LOC_PATH_GPS_CONF, gpsConfParamTable);
  6681. LOC_LOGd("Ntrip_Params=%s", NtripParamsString);
  6682. if (0 == strlen(NtripParamsString)) {
  6683. return;
  6684. }
  6685. // assign params to mStartDgnssNtripParams
  6686. GnssNtripConnectionParams* pNtripParams = &(mStartDgnssNtripParams.ntripParams);
  6687. string next(NtripParamsString);
  6688. stringstream ss(next);
  6689. #define GET_NEXT() getline(ss, next, ' '); \
  6690. LOC_LOGd("%s", next.c_str());
  6691. GET_NEXT();
  6692. pNtripParams->hostNameOrIp = std::move(next);
  6693. GET_NEXT();
  6694. pNtripParams->port = std::stoi(next);
  6695. GET_NEXT();
  6696. pNtripParams->mountPoint = std::move(next);
  6697. GET_NEXT();
  6698. pNtripParams->username = std::move(next);
  6699. GET_NEXT();
  6700. pNtripParams->password = std::move(next);
  6701. GET_NEXT();
  6702. mSendNmeaConsent = true;
  6703. GET_NEXT();
  6704. pNtripParams->requiresNmeaLocation = next.compare("0") ? true : false;
  6705. GET_NEXT();
  6706. pNtripParams->useSSL = next.compare("0") ? true : false;
  6707. LOC_LOGd("%d %s %d %s %s %s %d",
  6708. pNtripParams->useSSL, pNtripParams->hostNameOrIp.data(), pNtripParams->port,
  6709. pNtripParams->mountPoint.data(), pNtripParams->username.data(),
  6710. pNtripParams->password.data(), pNtripParams->requiresNmeaLocation);
  6711. /* set up state*/
  6712. mDgnssState |= DGNSS_STATE_ENABLE_NTRIP_COMMAND;
  6713. mDgnssState |= DGNSS_STATE_NO_NMEA_PENDING;
  6714. mDgnssState &= ~DGNSS_STATE_NTRIP_SESSION_STARTED;
  6715. mStartDgnssNtripParams.nmea.clear();
  6716. if (pNtripParams->requiresNmeaLocation) {
  6717. mDgnssState &= ~DGNSS_STATE_NO_NMEA_PENDING;
  6718. }
  6719. }