GnssAdapter.cpp 299 KB

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