| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275 |
- #include "stdafx2.h"
- #include "MobileDialFSM.h"
- #include "MbnEventImpl.h"
- #include "WirelessAgentSafeClient.h"
- #define WIN32_LEAN_AND_MEAN
- #include <windows.h>
- #include <winsock2.h>
- #include <iphlpapi.h>
- #include <ws2tcpip.h>
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <vector>
- using namespace std;
- using namespace MobileDial;
- #include "EventCode.h"
- #include "GetDevInfoHelper.h"
- #include "string_util.h"
- #include "MobileDlg.h"
- #define SUPPORT_DIAL_FROM_WEB 1
- #pragma comment (lib, "Ws2_32.lib")
- const int DATA_BUFSIZE = 8192;
- const DWORD MOBILEDIAL_TIMER_ID = 1;
- const int CHECK_CONNECT_TIMER_ID = 2;
- const int CHECK_CONNECT_BACKUP_TIMER_ID = 5;
- const int CHECK_CONNECT_DIAL_TIMER_ID = 6;
- const int RAS_CONNECTION_NOTIFICATION_TIMER_ID = 7;
- const int CHECK_RASDEVICE_CHANGED_TIMER_ID = 8;
- const int CHECK_PRE_RASDEVICE_CHANGED_TIMER_ID = 9;
- const int CHECK_CONNECT_MBN_TIMER_ID = 10;
- const int FAILURE_WAIT_TIMER_ID = 3;
- const int CHECK_NETCARD_TIMER_ID = 4;
- const int TIMER_TRY_LINK_ID = 11;
- const int TIMER_CHECK_DEVICE_ID = 12;
- const int TIMER_CHECK_DEVICE_NOCHANGED_ID = 13;
- const int MAX_TRY_CONNECT_TIMES = 3;
- const int MAX_TRY_WLAN_CONNETC_TIMES = 6;
- const DWORD BATTERY_TIMER_INTERVAL = 3000;
- const DWORD DEV_CHANGED_TIMER_INTERVAL = 3500;
- const DWORD RASCONNECTION_TIMER_INTERVAL = 500;
- const int DEFAULT_FAIL_CONNECT_MAX = 3;
- const int DEFAULT_FAIL_CONNECT_LESS = 1;
- const DWORD MOBILEDIAL_HBEAT_INTERVAL = 10000;
- const DWORD MOBILEDIAL_LIB_INTERVAL = 9000;
- const DWORD MOBILEDIAL_FLB_INTERVAL = 5000;
- const DWORD MOBILEDIAL_QUICK_TIMER_INTERVAL = 800;
- const DWORD MOBILEDIAL_FASTER_INTERVAL = 1000;
- const DWORD MOBILEDIAL_QUICK_TIMER_PLUS_INTERVAL = 3000;
- const DWORD MOBILEDIAL_FASTER_PLUS_INTERVAL = 5000;
- const DWORD MOBILEDIAL_CHECKDONGLE_INTERVAL = 5000;
- const DWORD MOBILEDIAL_WAITDIALRT_INTERVAL = 10000;
- const DWORD MOBILEDIAL_FASTERDIALRT_INTERVAL = 6000;
- const DWORD MOBILEDIAL_WLAN_CONNECT_INTERVAL = 10000;
- const int PING_INTERVAL = (60 * 1000 / MOBILEDIAL_FASTER_INTERVAL) - 1;//1 min
- const int ATTEMPT_INTERVAL = (1 * 60 * 1000 / MOBILEDIAL_CHECKDONGLE_INTERVAL) - 1;//1 min
- HRASCONN g_hrasconn = NULL;
- DWORD g_dwRasError;
- BOOL g_bFirstConnect = TRUE;
- const int DEFAULT_TIMEOUT_SEC = 3;
- const char* interfaceList[] = {
- "PC UI Interface",
- "ZTE NMEA Device",
- "ZTE Modem Device",
- "Vodafone Mobile Broadband Secondary Port Modem (Huawei)"
- };
- const int sizeInterfaceList = 4; // [Josephus in 14:50:28 2016/9/3]
- const char* modelList[] = {
- RASDT_Modem
- };
- const int sizeModelList = 1;
- //0: Connected
- //1: Disconnected
- //2: Error
- //3: Connect event
- //4: Cancel event.
- const int RasEventCount = 5;
- HANDLE g_RasEvents[RasEventCount] = { NULL };
- const int PROFILE_MAX_COUNT = 10;
- #define SYSVAR_NET_STATUS "NetState" //系统变量名称
- const char* sysVarNetStatusEnum[] = {"N", "O", "D", "I", "C", "E"};
- #define NET_STATUS_UNINIT 0 //初始状态
- #define NET_STATUS_NO_DEVICE 1 //没有设备
- #define NET_STATUS_DIAL_OFF 2 //设备没有拨号
- #define NET_STATUS_DISCONNECT 3 //上网卡已经连接但是网络不通
- #define NET_STATUS_CONNECTED 4 //网络已连接
- #define NET_STATUS_ERROR 5 //异常
- void WINAPI CustomRasDialFunc(UINT unMsg, RASCONNSTATE rasconnstate, DWORD dwError)
- {
- static DWORD dwWatiTime = 1500;
- if (dwError){
- Sleep(dwWatiTime);
- g_dwRasError = dwError;
- Dbg ("RasDial -- Error receive...");
- if(g_RasEvents[2] != NULL)
- SetEvent(g_RasEvents[2]);
- return;
- }
- bool fDoneState = !!(rasconnstate & RASCS_DONE);
- bool fPausedState = !!(rasconnstate & RASCS_PAUSED);
- bool fRunState = !(fDoneState || fPausedState);
- // Map each of the states of RasDial() and display on the screen
- // the next state that RasDial() is entering
- switch (rasconnstate)
- {
- // Running States
- case RASCS_OpenPort:
- Dbg ("RasDial -- Opening port...");
- break;
- case RASCS_PortOpened:
- Dbg ("RasDial -- Port opened.");
- break;
- case RASCS_ConnectDevice:
- Dbg ("RasDial -- Connecting device...");
- break;
- case RASCS_DeviceConnected:
- Dbg ("RasDial -- Device connected.");
- break;
- case RASCS_AllDevicesConnected:
- Dbg ("RasDial -- All devices connected.");
- break;
- case RASCS_Authenticate:
- Dbg ("RasDial -- Authenticating...");
- break;
- case RASCS_AuthNotify:
- Dbg ("RasDial -- Authentication notify.");
- break;
- case RASCS_AuthRetry:
- Dbg ("RasDial -- Retrying authentication...");
- break;
- case RASCS_AuthCallback:
- Dbg ("RasDial -- Authentication callback...");
- break;
- case RASCS_AuthChangePassword:
- Dbg ("RasDial -- Change password...");
- break;
- case RASCS_AuthProject:
- Dbg ("RasDial -- Projection phase started...");
- break;
- case RASCS_AuthLinkSpeed:
- Dbg ("RasDial -- Negotiating speed...");
- break;
- case RASCS_AuthAck:
- Dbg ("RasDial -- Authentication acknowledge...");
- break;
- case RASCS_ReAuthenticate:
- Dbg ("RasDial -- Retrying Authentication...");
- break;
- case RASCS_Authenticated:
- Dbg ("RasDial -- Authentication complete.");
- break;
- case RASCS_PrepareForCallback:
- Dbg ("RasDial -- Preparing for callback...");
- break;
- case RASCS_WaitForModemReset:
- Dbg ("RasDial -- Waiting for modem reset...");
- break;
- case RASCS_WaitForCallback:
- Dbg ("RasDial -- Waiting for callback...");
- break;
- case RASCS_Projected:
- Dbg ("RasDial -- Projection completed.");
- break;
- #if (WINVER >= 0x400)
- case RASCS_StartAuthentication:
- Dbg ("RasDial -- Starting authentication...");
- break;
- case RASCS_CallbackComplete:
- Dbg ("RasDial -- Callback complete.");
- break;
- case RASCS_LogonNetwork:
- Dbg ("RasDial -- Logon to the network.");
- break;
- #endif
- case RASCS_SubEntryConnected:
- Dbg ("RasDial -- Subentry connected.");
- break;
- case RASCS_SubEntryDisconnected:
- Dbg ("RasDial -- Subentry disconnected.");
- #if (WINVER >= 0x601)
- case RASCS_ApplySettings:
- Dbg ("RasDial -- Apply settings.");
- break;
- #endif
- // The RAS Paused States will not occur because
- // we did not use the RASDIALEXTENSIONS structure
- // to set the RDEOPT_PausedState option flag.
- // RASCS_RetryAuthentication: RasDial正在等待新的用户凭据
- // RASCS_CallbackSetByCaller: RasDial正在等待客户机的回拨号码
- // RASCS_PasswordExpired: RasDial希望用户提供一个新密码
- // Terminal States
- case RASCS_Connected:
- Sleep(dwWatiTime);
- Dbg ("RasDial -- Connection completed.");
- if(g_RasEvents[0] != NULL)
- SetEvent(g_RasEvents[0]);
- break;
- case RASCS_Disconnected:
- Sleep(dwWatiTime);
- Dbg ("RasDial -- Disconnecting...");
- if(g_RasEvents[1] != NULL)
- SetEvent(g_RasEvents[1]);
- break;
- default:
- Dbg ("RasDial -- Unknown Status = %d", rasconnstate);
- break;
- }
- }
- UINT WINAPI RasEventThreadFunc(PVOID param)
- {
- CMobileDialFSM* pFsm = (CMobileDialFSM*)param;
- if(pFsm == NULL)
- return -1;
- char szRasString[256];
- BOOL fError = FALSE;
- do
- {
- DWORD dwRes = WaitForMultipleObjects(5, g_RasEvents, FALSE, INFINITE);
- switch(dwRes)
- {
- case WAIT_OBJECT_0 + 2:
- {
- memset((void*)szRasString, 0, sizeof(char)*256);
- RasGetErrorString((UINT)g_dwRasError, szRasString, 256);
- Dbg ("RasDial -- Error: %d - %s.", g_dwRasError, szRasString);
- pFsm->m_csErrMsg = CSimpleStringA::Format("%s : %d", szRasString, g_dwRasError);
- pFsm->TellDlgTheResult(Error_Unexpect, WM_DIAL_RESULT, ADVANCE_RAS);
- //pFsm->SetRasStatus(MBD_RASDIAL_FAILED);
- // bug which makes recent dial info cannot be cleared. [1/24/2019 17:33 @Gifur]
- //pFsm->RasHangUpSuffix();
- FSMEvent* fsmEvent = new FSMEvent(USER_EVT_CONNECT_COMPLETE);
- fsmEvent->param1 = -1;
- fsmEvent->param2 = ADVANCE_RAS;
- pFsm->PostEventLIFO(fsmEvent);
- }
- break;
- case WAIT_OBJECT_0:
- {
- Dbg ("RasDial Connected Event.");
- pFsm->TellDlgTheResult(Error_Succeed, WM_DIAL_RESULT, ADVANCE_RAS);
- //pFsm->SetRasStatus(MBD_ACTIVATION_CONNECTED);
- FSMEvent* fsmEvent = new FSMEvent(USER_EVT_CONNECT_COMPLETE);
- fsmEvent->param1 = 1;
- fsmEvent->param2 = ADVANCE_RAS;
- pFsm->PostEventLIFO(fsmEvent);
- }
- break;
- case WAIT_OBJECT_0 + 1:
- {
- Dbg ("RasDial DisConnected Event.");
- pFsm->TellDlgTheResult(Error_Succeed, WM_DIAL_DISCONNECT, 1);
- pFsm->SetRasStatus(MBD_ACTIVATION_DISCONNECTED);
- FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DISCONNECT_COMPLETE);
- fsmEvent->param1 = 1;
- fsmEvent->param2 = ADVANCE_RAS;
- pFsm->PostEventLIFO(fsmEvent);
- }
- break;
- case WAIT_OBJECT_0 + 3:
- {
- //FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DEVICE_ARRIVAL);
- //fsmEvent->param1 = 1;
- //fsmEvent->param2 = 3;
- //pFsm->PostEventLIFO(fsmEvent);
- }
- break;
- case WAIT_OBJECT_0 + 4:
- {
- //FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DEVICE_LEAVE);
- //fsmEvent->param1 = 1;
- //fsmEvent->param2 = 3;
- //pFsm->PostEventLIFO(fsmEvent);
- }
- break;
- default:
- fError = TRUE;
- break;
- }
- } while (!fError);
- Dbg("Exit the RasEventThreadFunc thread");
- return 0;
- }
- CSimpleStringA GuidToString(GUID guid, bool bCover)
- {
- char c[GUID_LEN] = {0};
- if(bCover) {
- sprintf_s(c, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
- guid.Data1, guid.Data2, guid.Data3,
- guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
- guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
- } else {
- sprintf_s(c, "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
- guid.Data1, guid.Data2, guid.Data3,
- guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
- guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
- }
- CSimpleStringA s(c);
- return s;
- }
- CSimpleStringA CreateGuidString(bool bCover)
- {
- GUID guid;
- CoCreateGuid(&guid);
- return GuidToString(guid, bCover);
- }
- template<class T>
- class TimerOutHelper : public ITimerListener
- {
- public:
- typedef void (T::*FuncTimer)();
- TimerOutHelper(T *p, FuncTimer pTimerFunc, bool bDeleteSelf = false)
- : m_pObject(p), m_pTimer(pTimerFunc), m_bDeleteSelf(bDeleteSelf) {}
- virtual void OnTimeout(DWORD dwTimerID)
- {
- (m_pObject->*m_pTimer)();
- if (m_bDeleteSelf)
- delete this;
- }
- private:
- T *m_pObject;
- FuncTimer m_pTimer;
- bool m_bDeleteSelf;
- };
- CMobileDialFSM::CMobileDialFSM()
- :m_testResult(Error_Succeed),m_csMachineType(true),m_csSite(true),m_csPhoneNum(true),m_csEntryName(true)
- ,m_csUserName(true),m_csPassword(true),m_csVpnName(true)
- ,m_sock(INVALID_SOCKET),m_bConnected(false),m_dwCkFailCount(0)
- ,m_dwFailMax(DEFAULT_FAIL_CONNECT_MAX),m_batteryRemains(100),m_batteryRemainsF(100),m_bACPower(0), m_bACPowerF(0)
- ,m_n1G(0),m_n3G(0),m_n4G(0),m_bRCfgHaveDial(false), m_bPadAndFLB(false), m_bPadAndLIB(false)
- ,m_TimerInterval(MOBILEDIAL_FLB_INTERVAL),m_nRecoverMax(0)
- ,m_signalVal(0), m_dwLsErrCode(0), m_curState(MBD_NOT_INITIALIZED),m_3gState(MBD_NOT_INITIALIZED),m_HwState(MBD_NOT_INITIALIZED)
- ,m_34GReserved(0),m_34GDialSuc(0),m_bNotify(true),m_bBackupAvail(false)
- ,ping1(NULL), ping2(NULL),m_hMainWnd(NULL),m_bManageByUser(false),m_nAdvancedGen(0)
- ,m_hRasListenThread(NULL),m_csCurEntryGUID(true),m_SafeWirelessClient(NULL),m_WifiChangedEvt(NULL)
- ,m_strReservedPasword(true),m_HwDeviceMnt(NULL),m_strTerminalNo(true),m_ecSelfTest(Error_Succeed)
- ,m_fMBBDeviceMonitoring(FALSE),m_fMBBDeviceMonitorStop(FALSE),m_dwEntityID(0x212),m_mifiBattery(0)
- ,m_bManufactureSignal(FALSE),m_curMIFIDevName(true)
- {
-
- m_pMbn = new CMbnImplHelper(this);
- m_rasEntries.Clear();
- memset(&m_recentInfo, 0, sizeof(RecentDialInfo));
- InitializeCriticalSection(&m_cs4WirlessClient);
- m_HwDeviceMnt = new hw::hw_device_mnt();
- mMBBParam.connectType = 0;
- };
- CMobileDialFSM::~CMobileDialFSM()
- {
- LOG_FUNCTION();
- if(m_pMbn) {
- if(m_bPadAndFLB && !isUsingNewVerAllInOne() ) {
- m_pMbn->UnAdviseCustomEvents();
- }
- delete m_pMbn;
- m_pMbn = NULL;
- }
- if(m_bPadAndFLB && !isUsingNewVerAllInOne() ) {
- if(m_hRasListenThread != NULL) {
- TerminateThread(m_hRasListenThread, -1);
- CloseHandle(m_hRasListenThread);
- m_hRasListenThread = NULL;
- }
- for(int i=0; i<RasEventCount; ++i) {
- if(g_RasEvents[i] != NULL) {
- CloseHandle(g_RasEvents[i]);
- g_RasEvents[i] = NULL;
- }
- }
- mBlackSheepCount = 0;
- m_blackSheep.Clear();
- }
- if(ping1) {
- delete ping1;
- ping1 = NULL;
- }
- if(ping2) {
- delete ping2;
- ping2 = NULL;
- }
- m_fMBBDeviceMonitorStop = TRUE;
- // Dangerous ??
- // https://msdn.microsoft.com/en-us/library/windows/desktop/aa377567(v=vs.85).aspx
- // 不做清理了
- //if(g_hrasconn != NULL) {
- // RasHangUp(g_hrasconn);
- // g_hrasconn = NULL;
- // Sleep(3000);
- //}
- if(m_SafeWirelessClient != NULL) {
- delete m_SafeWirelessClient;
- m_SafeWirelessClient = NULL;
- }
- //DeleteCriticalSection(&m_cs4WirlessClient);
- if(m_WifiChangedEvt) {
- Dbg("destroy wifi change event listerner...");
- if(m_WifiChangedEvt->m_bRegistered) {
- spagent::spagent_assistor::unregister_notification_events(conn_tool_wifi, m_WifiChangedEvt);
- }
- delete m_WifiChangedEvt;
- m_WifiChangedEvt = NULL;
- }
- //if(m_fMBBDeviceMonitoring) {
- // do {
- // Dbg("wait monitor circle break!");
- // Sleep(300);
- // } while (m_fMBBDeviceMonitoring);
- //}
- if(m_HwDeviceMnt) {
- auto temp = m_HwDeviceMnt;
- m_HwDeviceMnt = NULL;
- Dbg("destroy hw instance...");
- delete temp;
- }
- }
- ErrorCodeEnum CMobileDialFSM::OnInit()
- {
- LOG_FUNCTION();
- Dbg("Mod version: %s, Complied at: %s %s", MOD_VERSION, __DATE__, __TIME__);
- #ifdef TWINKLE_LOCAL_DEBUG
- if (AllocConsole())
- {
- FILE* here = NULL;
- freopen_s(&here, "CONOUT$", "w", stdout);
- freopen_s(&here, "CONOUT$", "w", stderr);
- Dbg("Debug console created.");
- }
- #endif
- ErrorCodeEnum eErr;
- int netAccessFlag=99, iFailMax = 99;
- int value = 0;
- CSimpleStringA csValue;
- CSimpleStringA csEntityName = GetEntityBase()->GetEntityName();
- CSmartPointer<IConfigInfo> spConfig, spConfigCen, spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Software, spConfig);
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- m_dwFailMax = DEFAULT_FAIL_CONNECT_MAX;
- m_TimeoutSec = DEFAULT_TIMEOUT_SEC;
- m_csVpnName = "";
- spConfigRun->ReadConfigValue("init", "param1", m_csPhoneNum);
- if (m_csPhoneNum.GetLength() < 1) {
- Dbg("There are no config at runtime, config it's the new terminal device.");
- m_bRCfgHaveDial = false;
- } else {
- Dbg("For param, to read run cfg.");
- m_bRCfgHaveDial = true;
- spConfigRun->ReadConfigValue("init", "param2", m_csEntryName);
- spConfigRun->ReadConfigValue("init", "param3", m_csUserName);
- spConfigRun->ReadConfigValue("init", "param4", m_csPassword);
- spConfigRun->ReadConfigValue("init", "param5", m_csVpnName);
- }
- if(!m_csVpnName.IsNullOrEmpty()) {
- Dbg("Vpn Name: %s", (LPCTSTR)m_csVpnName);
- }
- int nValue = 0;
- if(spConfigRun->ReadConfigValueInt("init", "ManualManage", nValue) == 0 && nValue > 0) {
- Dbg("Require manage by user!!");
- m_bManageByUser = true;
- }
- if(spConfigRun->ReadConfigValueInt("init", "GenAdvanced", nValue) == 0 && nValue > 0) {
- Dbg("Advanced Gen choose: %d", nValue);
- if(nValue == ADVANCE_RAS || nValue == ADVANCE_MBN || nValue == ADVANCE_MBB) {
- CSimpleStringA csTip;
- if(nValue == ADVANCE_RAS) {
- csTip = "当前终端选择的上网类型: 3G-RAS";
- } else if(nValue == ADVANCE_MBN) {
- csTip = "当前终端选择的上网类型: 4G-MBN";
- } else {
- csTip = "当前终端选择的上网类型: HuaWei-MBB";
- }
- LogEvent(Severity_High, 0, (LPCTSTR)csTip);
- m_nAdvancedGen = nValue;
- }
- }
- m_recentInfo.usDialType = CNT_INVALID;
- m_recentInfo.ulRequestID = 0;
- if(spConfigRun->ReadConfigValue("Recent", "Type", csValue) == Error_Succeed
- && csValue.GetLength() > 0) {
- if(!csValue.Compare("MBN") && m_nAdvancedGen != ADVANCE_RAS && m_nAdvancedGen != ADVANCE_MBB) {
- m_recentInfo.usDialType = CNT_MBN;
- } else if(!csValue.Compare("RAS") && m_nAdvancedGen != ADVANCE_MBN && m_nAdvancedGen != ADVANCE_MBB) {
- m_recentInfo.usDialType = CNT_RAS;
- }
- }
- if(m_recentInfo.usDialType != CNT_INVALID) {
- spConfigRun->ReadConfigValue("Recent", "Dongle", m_recentInfo.strDongle);
- spConfigRun->ReadConfigValue("Recent", "Profile", m_recentInfo.strProfile);
- spConfigRun->ReadConfigValueInt("Recent", "Manual", m_recentInfo.fByManual);
- Dbg("Advanced connect device: %s", (LPCTSTR)m_recentInfo.strDongle);
- }
- GetCurWindowsVersion();
- GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spConfigCen);
- // Read from CenterSetting in correct format [Josephus in 12:15:21 2016/4/18]
- CSimpleStringA csServer(""), csServerBackup("");
- bool bLoadInCentSet = false;
- spConfigCen->ReadConfigValue(csEntityName, "Server", csServer);
- spConfigCen->ReadConfigValue(csEntityName, "Server_Backup", csServerBackup);
- if(csServer.GetLength() >= 7){
- CAutoArray<CSimpleStringA> servSplits = csServer.Split(' ');
- if(servSplits.GetCount() >= 2){
- m_csIp = servSplits[0];
- m_csPort = servSplits[1];
- bLoadInCentSet = true;
- }else{
- Dbg("The serverString loaded in CenterSetting has illegal format %s", (LPCTSTR)csServer);
- }
- }
- if(!bLoadInCentSet && csServerBackup.GetLength() >= 7)
- {
- Dbg("To use the ServerBackup string(%s)", (LPCTSTR)csServerBackup);
- CAutoArray<CSimpleStringA> servSplits = csServerBackup.Split(' ');
- if(servSplits.GetCount() >= 2){
- m_csIp = servSplits[0];
- m_csPort = servSplits[1];
- bLoadInCentSet = true;
- }else{
- Dbg("The serverBackupString loaded in CenterSetting has illegal format");
- }
- }
- Dbg("DualActive mark.");
- m_csIpBackup = "";
- m_csPortBackup = "";
- if(!bLoadInCentSet) {
- Dbg("For IP and port, no center setting, use local cfg.");
- spConfig->ReadConfigValue("init", "ip", m_csIp);
- spConfig->ReadConfigValue("init", "port", m_csPort);
- }
- else {
- if(csServerBackup.GetLength() >= 7) {
- Dbg("Store ServerBackup string(%s) after DualActive", (LPCTSTR)csServerBackup);
- CAutoArray<CSimpleStringA> servSplits = csServerBackup.Split(' ');
- if(servSplits.GetCount() >= 2) {
- if(!!servSplits[0].Compare("99.1.100.215")) {
- m_csIpBackup = servSplits[0];
- m_csPortBackup = servSplits[1];
- }
- }else{
- Dbg("The serverBackupString loaded in CenterSetting has illegal format after DualActive");
- }
- }
- }
- if((m_csIp.GetLength() < 7 || m_csPort.GetLength() <= 0)
- && (m_csIpBackup.GetLength() < 7 || m_csPortBackup.GetLength() <= 0)
- )
- {
- Dbg("Get ip and port failed [IP#%s][Port#%s].", (LPCTSTR)m_csIp, (LPCTSTR)m_csPort);
- Dbg("Get backup ip and port failed [IP#%s][Port#%s].", (LPCTSTR)m_csIpBackup, (LPCTSTR)m_csPortBackup);
- LogError(Severity_High, Error_Param, CombineErrorCode(MBD_CENTERSETTING_LACK),
- "未能从配置中读取用于检测网络连接的服务其地址或端口,请检查!");
- ShowFatalError("请配置用于MobileDial模块检测网络的服务器IP和端口");
- return Error_Param;
- }
-
- CSystemStaticInfo sysInfo;
- eErr = GetEntityBase()->GetFunction()->GetSystemStaticInfo(sysInfo);
- if (eErr != Error_Succeed) {
- Dbg("Get System Static info failed(%d).",eErr);
- return Error_Unexpect;
- }
- m_csMachineType = sysInfo.strMachineType;
- m_csSite = sysInfo.strSite;
- m_strTerminalNo = sysInfo.strTerminalID;
- //m_strTerminalNo = "12345";
- if(m_strTerminalNo.GetLength() < 10) {
- const int suffixLen = 10 - m_strTerminalNo.GetLength();
- CSimpleStringA strTempTerminal(true);
- strTempTerminal.Append("0000000000", suffixLen);
- strTempTerminal += m_strTerminalNo;
- m_strTerminalNo = strTempTerminal;
- } else if(m_strTerminalNo.GetLength() > 10) {
- m_strTerminalNo = m_strTerminalNo.SubString(0, 10);
- }
- //Dbg("new terminal no: %s", m_strTerminalNo.GetData());
- //return Error_Bug;
- //m_bPadAndFLB = false;
- //for(int i=MBD_NOT_INITIALIZED; i<=MBD_INTERNAL_ERROR; ++i) {
- // DWORD dwUserCode = (DWORD)((m_dwEntityID << 16) + (DWORD)(i));
- // CSimpleStringA str = ConvertStatusToString((MOBILEDIAL_CONNECTION_STATE)i);
- // if(str.IndexOf("MOBILEDIAL_UNEXPECT_STATE(") == -1) {
- // SetCurState((MOBILEDIAL_CONNECTION_STATE)i);
- // CSimpleStringA csData = GetFurtherDetail();
- // Dbg("0x%X - %s", dwUserCode, str.GetData());
- // Dbg("%s", csData.GetData());
- // }
- //}
- //return Error_Cancel;
- Dbg("%s:%s,%s,%s", (LPCTSTR)m_csPhoneNum, (LPCTSTR)m_csEntryName,(LPCTSTR)m_csMachineType, (LPCTSTR)m_csSite);
- Dbg("%s::%s, %s::%s", (LPCTSTR)m_csIp, (LPCTSTR)m_csPort, (LPCTSTR)m_csIpBackup, (LPCTSTR)m_csPortBackup);
- m_bBackupAvail = (m_csIpBackup.GetLength() >= 7 && m_csPortBackup.GetLength() > 0);
- if(m_bBackupAvail) {
- if(m_csIpBackup.Compare((LPCTSTR)m_csIp) == 0 && m_csPortBackup.Compare((LPCTSTR)m_csPortBackup) == 0) {
- m_bBackupAvail = false;
- }
- }
- WSADATA wsaData;
- int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
- if (iResult != 0) {
- Dbg("WSAStartup failed with error %d", iResult);
- RecordLastErrorMsg(iResult);
- return Error_IO;
- }
- if (CreateCheckSocket() != 0) {
- Dbg("failed to create socket for connecting test at the begin");
- WSACleanup();
- return Error_IO;
- }
- closesocket(m_sock);
- m_sock = INVALID_SOCKET;
- //m_csSite = "cmb.yzx";
- //int bPingDisable = 0;
- //spConfigCen->ReadConfigValueInt(csEntityName, "PingDisable", bPingDisable);
- //if(!bPingDisable) {
- // ping1 = new CTWPing();
- // ping1->Initial(m_csIp);
- // if(m_bBackupAvail && m_csIp.Compare(m_csIpBackup)) {
- // ping2 = new CTWPing();
- // ping2->Initial(m_csIpBackup);
- // }
- //}
- if(!m_csMachineType.Compare("RVC.Pad", true) && !m_csSite.Compare("cmb.FLB", true)) {
- Dbg("Detect MachineType: %s & SiteType: %s", (LPCTSTR)m_csMachineType, (LPCTSTR)m_csSite);
- // 行内PAD,删除旧的配置文件
- if(m_bRCfgHaveDial && !m_csPhoneNum.Compare("#777") && !m_csEntryName.Compare("szbranch")
- && !m_csUserName.Compare("123@szchinacmb.vpdn.gd") && !m_csPassword.Compare("123")) {
- Dbg("delete the old test dial param: %d", RasDeleteEntryA(NULL, m_csEntryName));
- spConfigRun->WriteConfigValue("init", "param1", "");
- spConfigRun->WriteConfigValue("init", "param2", "");
- spConfigRun->WriteConfigValue("init", "param3", "");
- spConfigRun->WriteConfigValue("init", "param4", "");
- spConfigRun->WriteConfigValue("init", "param5", "");
- m_csEntryName = m_csPhoneNum = m_csUserName = m_csPassword = "";
- }
- m_bPadAndFLB = true;
- if(isUsingNewVerAllInOne()) {
- Dbg("Detect new version all_in_one condition.");
- m_nAdvancedGen = 0;
- } else {
- if(m_nAdvancedGen != ADVANCE_MBB) {
- m_blackSheep.Init(MAX_BLACK_SHEEP_NUM);
- mBlackSheepCount = 0;
- if(m_nAdvancedGen != ADVANCE_RAS) {
- Init4GComponent();
- }
- if(m_nAdvancedGen != ADVANCE_MBN) {
- Init3GComponent();
- }
- } else {
- InitHuaweiComponent();
- }
- Recognized3GOr4G();
- this->GetEntityBase()->GetFunction()->PostThreadPoolTask(new MBBDevicMonitorTask(this));
- }
-
- } else {
- if(!m_csMachineType.Compare("RVC.Pad", true) && !m_csSite.Compare("cmb.LIB", true)) {
- Dbg("Detect MachineType: %s & SiteType: %s", (LPCTSTR)m_csMachineType, (LPCTSTR)m_csSite);
- m_bPadAndLIB = true;
- }
- m_TimerInterval = MOBILEDIAL_LIB_INTERVAL;
- }
- //电池电源监听线程
- ITimerListener *pListener = new TimerOutHelper<CMobileDialFSM>(this,
- &CMobileDialFSM::BatteryNotifierTimeOut);
- GetEntityBase()->GetFunction()->SetTimer(MOBILEDIAL_TIMER_ID, pListener, BATTERY_TIMER_INTERVAL);
- return Error_Succeed;
- }
- int CMobileDialFSM::ReadRecentValiDongle()
- {
- CSimpleStringA csInterfaceID;
- CSmartPointer<IConfigInfo> spConfigRun;
- int nType = 0;
- if(!m_pMbn->GetInterfaceID(csInterfaceID)) {
- Dbg("GetInterfaceID failed in ReadRecentValiDongle.");
- } else {
- Dbg("GetInterfaceID(%s) suc.", (LPCTSTR)csInterfaceID);
- if(GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun) == Error_Succeed) {
- spConfigRun->ReadConfigValueInt("Interfaces", (LPCTSTR)csInterfaceID, nType);
- }
- Dbg("Interface:%s: nType:%d.", (LPCTSTR)csInterfaceID, nType);
- }
- return nType;
- }
- void CMobileDialFSM::WriteCurValiDongle(const CSimpleStringA& csInterfaceID, const int nType)
- {
- CSmartPointer<IConfigInfo> spConfigRun;
- if(GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun) == Error_Succeed) {
- spConfigRun->WriteConfigValueInt("Interfaces", (LPCTSTR)csInterfaceID, nType);
- }
- return;
- }
- void CMobileDialFSM::Recognized3GOr4G()
- {
- LOG_FUNCTION();
- static bool s_old3G = false;
- static bool s_old4G = false;
- SetCurState(MBD_NOT_INITIALIZED);
- s_old4G = m_n4G > 0;
- s_old3G = m_n3G > 0;
- ResetDongleInfos();
- m_n3G = m_n4G = 0;
- m_34GReserved = 0;
- m_34GDialSuc = 0;
- if(isUsingNewVerAllInOne()) {
- LogEvent(Severity_Middle,CombineErrorCode(MBD_HOLD_MOBILEDONGLE), "当前使用新版分体式多合一设备");
- BOOL bActive = FALSE, bConnected = FALSE;
- ErrorCodeEnum ec = m_SafeWirelessClient->IsActive(bActive, bConnected);
- if(ec == Error_Succeed) {
- if(bConnected) {
- int nNum = 0;
- ec = m_SafeWirelessClient->GetAPNConfigs(-1, nNum);
- }
- }
- return;
- }
- if(m_nAdvancedGen != ADVANCE_MBB) {
- int nMBN = m_nAdvancedGen != ADVANCE_RAS ? m_pMbn->EnumerateInterfaces(TRUE) : 0;
- int nRAS = m_nAdvancedGen != ADVANCE_MBN ? EnumCurRasDevices(TRUE) : 0;
- if(nMBN == 0 && nRAS == 0) {
- SetCurState(MBD_NO_MOBILEDONGLE);
- } else {
- if(nRAS > 0) {
- m_n3G = nRAS;
- if(!s_old3G) LogEvent(Severity_Middle,CombineErrorCode(MBD_HOLD_MOBILEDONGLE),"检测到3G无线宽带上网卡");
- }
- if(nMBN > 0) {
- m_n4G = nMBN;
- if(!s_old4G) LogEvent(Severity_Middle,CombineErrorCode(MBD_HOLD_MOBILEDONGLE),"检测到4G无线宽带上网卡");
- }
- if((nMBN < 0 && nRAS < 0)
- || (m_nAdvancedGen == ADVANCE_RAS && nRAS < 0)
- || (m_nAdvancedGen == ADVANCE_MBN && nMBN < 0)) {
- SetCurState(MBD_INTERNAL_ERROR);
- }
- }
- } else {
- CheckHWDeviceStatus();
- }
- return;
- }
- ErrorCodeEnum CMobileDialFSM::OnExit()
- {
- GetEntityBase()->GetFunction()->ResetTimer(0, 0);
- if(m_bPadAndFLB && !isUsingNewVerAllInOne() )
- {
- DisConnect();
- m_pMbn->UnAdviseCustomEvents();
- for(int i=0; i<RasEventCount; ++i) {
- if(g_RasEvents[i] != NULL)
- {
- CloseHandle(g_RasEvents[i]);
- g_RasEvents[i] = NULL;
- }
- }
- }
- WSACleanup();
- return Error_Succeed;
- }
- //不做更新网卡状态的操作,所以从其他状态跳转过来时要先刷新
- void CMobileDialFSM::s0_on_entry()
- {
- LOG_FUNCTION();
- if (m_bPadAndFLB && !isUsingNewVerAllInOne()) {
- const MOBILEDIAL_CONNECTION_STATE status = GetCurState();
- #if SUPPORT_DIAL_FROM_WEB
- if(status == MBD_ACTIVATION_DISCONNECTED || status == MBD_WLAN_DISCONNECTED) {
- #else
- if(status == MBD_NO_MOBILEDONGLE || status == MBD_ACTIVATION_DISCONNECTED || status == MBD_WLAN_DISCONNECTED) {
- #endif
- Dbg("Walk convenient way in connect style: %d", status);
- FSMEvent* fsmEvent = new FSMEvent(USER_EVT_CKECK_CONNECTION_FINISHED);
- fsmEvent->param1 = 3;
- fsmEvent->param2 = 1;
- PostEventFIFO(fsmEvent);
- return;
- } else if(status == MBD_ACTIVATION_CONNECTED) {
- LogEvent(Severity_Middle, CombineErrorCode(status), "无线宽带上网卡已连接");
- if(g_bFirstConnect) {
- g_bFirstConnect = FALSE;
- }
- }
- }
- Dbg("Walk normal way in connect style.");
- m_TimeoutSec = DEFAULT_TIMEOUT_SEC;
- CheckConnectionTask* task = new CheckConnectionTask(this);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- SetSysVal(NET_STATUS_UNINIT);
- }
- void CMobileDialFSM::s0_on_exit()
- {
- }
- unsigned int CMobileDialFSM::s0_on_event(FSMEvent* pEvt)
- {
- int nRes = pEvt->param1;
- Dbg("s0_on_event %d, %d %d.", pEvt->iEvt, nRes, pEvt->param2);
- switch(pEvt->iEvt)
- {
- case USER_EVT_CKECK_CONNECTION_FINISHED:
- pEvt->SetHandled();
- {
- if(nRes != 3) {
- bool bShouldBackup = !!(pEvt->param2 & 0x4);
- bool bRealBackup = !!(pEvt->param2 & 0x2);
- CSimpleStringA csIpPrint = bRealBackup ? m_csIpBackup : m_csIp;
- CSimpleStringA csPortPrint = bRealBackup ? m_csPortBackup : m_csPort;
- if(nRes == 0) {
- CSimpleStringA csMsg;
- csMsg = CSimpleStringA::Format("s0(idle): Connect to server(%s:%s) failed(%d) FailCount(%d) FailMax(%d).",
- (LPCTSTR)csIpPrint, (LPCTSTR)csPortPrint, m_dwLsErrCode, ++m_dwCkFailCount, m_dwFailMax);
- LogEvent(Severity_Middle, CombineErrorCode(MBD_CHECK_NETWORK_CONNETCTED), (LPCTSTR)csMsg);
- const MOBILEDIAL_CONNECTION_STATE state = GetCurState();
- Dbg("s0(idle): %s.", ConvertStatusToString(state));
- // fix bug which lead netbroken show more easy and earlier --Josephus at 8:59:47 20161211
- if(m_dwCkFailCount < m_dwFailMax) {
- m_TimeoutSec = DEFAULT_TIMEOUT_SEC + 2 * m_dwCkFailCount;
- if(bShouldBackup && !bRealBackup) {
- Dbg("backup ip and port maybe no exist.");
- break;
- }
- //未达到连续次数的网络断开情况,防止状态跳转
- nRes = 4;
- if(state == MBD_NETWORK_TIMEOUT) {
- Sleep(MOBILEDIAL_QUICK_TIMER_INTERVAL);
- }
- else {
- Sleep( MOBILEDIAL_FASTER_INTERVAL);
- }
- CheckConnectionTask* task = new CheckConnectionTask(this);
- if(bRealBackup) {
- task->m_bUseBackup = true;
- }
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- }
- else if(!bShouldBackup && m_bBackupAvail) {
- m_dwCkFailCount = 0;
- m_TimeoutSec = DEFAULT_TIMEOUT_SEC;
- //未达到连续次数的网络断开情况,防止状态跳转
- nRes = 4;
- if(state == MBD_NETWORK_TIMEOUT){
- Sleep(MOBILEDIAL_QUICK_TIMER_INTERVAL);
- }
- else{
- Sleep(MOBILEDIAL_FASTER_INTERVAL);
- }
- CheckConnectionTask* task = new CheckConnectionTask(this);
- task->m_bUseBackup = true;
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- }
- }
- else {
- Dbg("s0(idle): Connect to server(%s:%s) result(%d)(%d), pad&FLB(%d) %s",
- (LPCTSTR)csIpPrint, (LPCTSTR)csPortPrint, nRes,
- m_dwLsErrCode, m_bPadAndFLB,
- ConvertStatusToString(GetCurState()));
- }
- m_dwOldErrCode = m_dwLsErrCode;
- }
- else if(pEvt->param2 == 1) {
- Dbg("Received convenient way.");
- nRes = 0;
- }
- }
- break;
- default:
- break;
- }
- return nRes;
- }
- //Connected
- void CMobileDialFSM::s1_on_entry()
- {
- LOG_FUNCTION();
- LogEvent(Severity_Middle, CombineErrorCode(MBD_VALID_CONNECTED), "网络已连接");
- ShowFatalError("网络已连接", TRUE);
- m_bConnected = true;
- SetCurState(MBD_VALID_CONNECTED);
- SendNetStatusMsg();
- SetSysVal(NET_STATUS_CONNECTED);
- ReportConnectType();
- m_dwCkFailCount = 0;
- m_TimeoutSec = DEFAULT_TIMEOUT_SEC;
- ScheduleTimer(CHECK_CONNECT_TIMER_ID, m_TimerInterval);
- }
- void CMobileDialFSM::s1_on_exit()
- {
- CancelTimer(CHECK_CONNECT_TIMER_ID);
- CancelTimer(CHECK_CONNECT_BACKUP_TIMER_ID);
- if(m_nAdvancedGen == 2) {
- if(mMBBParam.connectType == MBB_CONNECT_WIRE) {
- if(CheckLANConnectStatus() == 0) {
- SetHWStatus(MBD_NO_MOBILEDONGLE);
- } else {
- SetHWStatus(MBD_ACTIVATION_CONNECTED);
- }
- }
- }
- }
- unsigned int CMobileDialFSM::s1_on_event(FSMEvent* pEvt)
- {
- int nRes = 0;
- Dbg("s1_on_event %d, %d, %d", pEvt->iEvt, pEvt->param1, pEvt->param2);
- switch(pEvt->iEvt)
- {
- case EVT_TIMER:
- {
- if(pEvt->param1 == CHECK_CONNECT_TIMER_ID || pEvt->param1 == CHECK_CONNECT_BACKUP_TIMER_ID)
- {
- pEvt->SetHandled();
- if(IsConnectedFromHB()) {
- m_dwCkFailCount = 0;
- ScheduleTimer(CHECK_CONNECT_TIMER_ID, MOBILEDIAL_HBEAT_INTERVAL);
- } else {
- CheckConnectionTask* task = new CheckConnectionTask(this);
- if(pEvt->param1 == CHECK_CONNECT_BACKUP_TIMER_ID)
- task->m_bUseBackup = true;
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- }
- }
- }
- break;
- case USER_EVT_CKECK_CONNECTION_FINISHED:
- pEvt->SetHandled();
- {
- nRes = pEvt->param1;
- bool bShouldBackup = !!(pEvt->param2 & 0x4);
- bool bRealBackup = !!(pEvt->param2 & 0x2);
- UINT uTimerID = bRealBackup ? CHECK_CONNECT_BACKUP_TIMER_ID : CHECK_CONNECT_TIMER_ID;
- if(nRes == 1)
- {
- m_dwCkFailCount = 0;
- ScheduleTimer(uTimerID, m_TimerInterval);
- }
- else if(nRes == 0)
- {
- CSimpleStringA csIpPrint = bRealBackup ? m_csIpBackup : m_csIp;
- CSimpleStringA csPortPrint = bRealBackup ? m_csPortBackup : m_csPort;
- CSimpleStringA csMsg;
- csMsg = CSimpleStringA::Format("s1(connected): Connect to server(%s:%s) failed(%d) FailCount(%d) FailMax(%d).",
- (LPCTSTR)csIpPrint, (LPCTSTR)csPortPrint, m_dwLsErrCode, ++m_dwCkFailCount, m_dwFailMax);
- LogEvent(Severity_Middle, CombineErrorCode(MBD_CHECK_NETWORK_CONNETCTED), (LPCTSTR)csMsg);
- const MOBILEDIAL_CONNECTION_STATE state = GetCurState();
- Dbg("s1(connected): %s.", ConvertStatusToString(state));
- if(m_dwCkFailCount < m_dwFailMax) {
- if(bShouldBackup && !bRealBackup) {
- break;
- }
- m_TimeoutSec = DEFAULT_TIMEOUT_SEC + 2 * m_dwCkFailCount;
- //未达到连续次数的网络断开情况,防止状态跳转,并将时间间隔改成1s聆询
- nRes = 3;
- if(state == MBD_NETWORK_TIMEOUT)
- {
- ScheduleTimer(uTimerID, MOBILEDIAL_QUICK_TIMER_INTERVAL);
- }
- else
- {
- ScheduleTimer(uTimerID, MOBILEDIAL_FASTER_INTERVAL);
- }
- }
- else if(!bShouldBackup && m_bBackupAvail)
- {
- m_dwCkFailCount = 0;
- m_TimeoutSec = DEFAULT_TIMEOUT_SEC;
- //未达到连续次数的网络断开情况,防止状态跳转,并将时间间隔改成1s聆询
- nRes = 3;
- if(state == MBD_NETWORK_TIMEOUT) {
- ScheduleTimer(CHECK_CONNECT_BACKUP_TIMER_ID, MOBILEDIAL_QUICK_TIMER_INTERVAL);
- } else {
- ScheduleTimer(CHECK_CONNECT_BACKUP_TIMER_ID, MOBILEDIAL_FASTER_INTERVAL);
- }
- }
- m_dwOldErrCode = m_dwLsErrCode;
- }
- }
- break;
- case USER_EVT_SIGNAL:
- pEvt->SetHandled();
- {
- NetStatusVar evt;
- m_signalVal = pEvt->param1;
- Dbg("s1(connected): Send Signal %d !!", m_signalVal);
- evt.netstatus = m_signalVal;
- SpSendBroadcast(m_pEntity->GetFunction(),SP_MSG_OF(NetStatusVar),SP_MSG_SIG_OF(NetStatusVar),evt);
- }
- break;
- case USER_EVT_DEVICE_LEAVE:
- pEvt->SetHandled();
- BroadcastCableChangedFSMEvent(pEvt);
- if(pEvt->param2 == 0) {
- nRes = 1;
- } else {
- nRes = 0;
- Recognized3GOr4G();
- auto state = GetCurState();
- if(state == MBD_NO_MOBILEDONGLE) {
- nRes = 1;
- } else if(state == MBD_INTERNAL_ERROR) {
- PostEventFIFO(new FSMEvent(USER_EVT_FAILURE));
- } else if(state == MBD_ACTIVATION_DISCONNECTED) {
- FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DISCONNECT_COMPLETE);
- fsmEvent->param1 = 0;
- fsmEvent->param2 = 0;
- PostEventFIFO(fsmEvent);
- } else {
- nRes = 2;
- }
- }
- break;
- default:
- break;
- }
- return nRes;
- }
- //Disconnected
- void CMobileDialFSM::s2_on_entry()
- {
- LOG_FUNCTION();
- m_bConnected = false;
- m_dwCkFailCount = 0;
- m_TimeoutSec = DEFAULT_TIMEOUT_SEC + 2 * m_dwFailMax;
- SendNetStatusMsg();
- SetSysVal(NET_STATUS_DISCONNECT);
- MOBILEDIAL_CONNECTION_STATE status = GetCurState();
- if(m_bPadAndFLB && !isUsingNewVerAllInOne() && status > MBD_NETWORK_SEPERATE)
- {
- LogEvent(Severity_Middle,CombineErrorCode(MBD_INVALID_CONNECTED), "网络已断开");
- if(status == MBD_NO_MOBILEDONGLE){
- FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DEVICE_LEAVE);
- fsmEvent->param1 = 0;
- fsmEvent->param2 = 0;
- PostEventFIFO(fsmEvent);
- }
- else if(status == MBD_ACTIVATION_DISCONNECTED){
- FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DISCONNECT_COMPLETE);
- fsmEvent->param1 = 0;
- fsmEvent->param2 = 0;
- PostEventFIFO(fsmEvent);
- } else if(status == MBD_WLAN_DISCONNECTED) {
- FSMEvent* fsmEvent = new FSMEvent(EVT_USER_WLAN_CONNECT);
- fsmEvent->param1 = 0;
- fsmEvent->param2 = 0;
- PostEventFIFO(fsmEvent);
- }
- else {
- PostEventFIFO(new FSMEvent(USER_EVT_FAILURE));
- }
- }
- else
- {
- CSimpleStringA csTemp;
- if(m_bPadAndLIB && CheckLANConnectStatus() == 0) {
- SetCurState(MBD_NO_FOUND_CABLE);
- ShowFatalError(GetFurtherDetail());
- if(status == MBD_NETWORK_TIMEOUT){
- ScheduleTimer(CHECK_CONNECT_TIMER_ID, MOBILEDIAL_QUICK_TIMER_INTERVAL);
- }else{
- ScheduleTimer(CHECK_CONNECT_TIMER_ID, MOBILEDIAL_FASTER_INTERVAL);
- }
- } else{
- ShowFatalError(GetFurtherDetail());
- if(status == MBD_NETWORK_TIMEOUT) {
- ScheduleTimer(CHECK_CONNECT_TIMER_ID, MOBILEDIAL_QUICK_TIMER_PLUS_INTERVAL);
- }else{
- ScheduleTimer(CHECK_CONNECT_TIMER_ID, MOBILEDIAL_FASTER_PLUS_INTERVAL);
- }
- }
- }
- }
- void CMobileDialFSM::s2_on_exit()
- {
- CancelTimer(CHECK_CONNECT_TIMER_ID);
- //SetSysVal(NET_STATUS_UNINIT);
- }
- unsigned int CMobileDialFSM::s2_on_event(FSMEvent* pEvt)
- {
- int nRes = 0;
- static int s_nTimes = -1;
- static bool bCheckSwitch = false;
- switch(pEvt->iEvt)
- {
- case EVT_TIMER:
- {
- if(pEvt->param1 != CHECK_CONNECT_TIMER_ID)
- break;
- pEvt->SetHandled();
- if(IsConnectedFromHB()) {
- Dbg("(s2_event)Connected status from HB, change status.");
- LogEvent(Severity_High, CombineErrorCode(MBD_VALID_CONNECTED), "心跳正常,执行跳转");
- // s_nTimes = 0;
- nRes = 1;
- }
- else {
- if(s_nTimes == 0) {
- PingTask* pingTask = new PingTask(this);
- GetEntityBase()->GetFunction()->PostEntityTaskFIFO(pingTask);
- s_nTimes++;
- } else if(s_nTimes != -1) {
- if(++s_nTimes > PING_INTERVAL) {
- s_nTimes = 0;
- }
- }
- if(m_bPadAndFLB && !isUsingNewVerAllInOne() && m_n3G > 0) {
- if(!bCheckSwitch) {
- if(EnumCurRasDevices() == 0) {
- FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DEVICE_LEAVE);
- fsmEvent->param1 = 0;
- fsmEvent->param2 = 3;
- PostEventFIFO(fsmEvent);
- }
- bCheckSwitch = true;
- } else {
- bCheckSwitch = false;
- }
- }
- ScheduleTimer(CHECK_CONNECT_TIMER_ID, MOBILEDIAL_FASTER_PLUS_INTERVAL);
- }
- }
- break;
- case USER_EVT_PING_RESULT:
- {
- pEvt->SetHandled();
- const int nPingResult = pEvt->param1;
- if(nPingResult == 0) {
- LogWarn(Severity_Middle, Error_NetBroken, 0, "尝试Ping连接至分行服务失败!");
- } else if(nPingResult > 0) {
- if(nPingResult == 3) {
- LogEvent(Severity_None, 0,
- "Attempt to ping to branch server both succ.");
- }else if(nPingResult == 2) {
- LogEvent(Severity_None, 0,
- CSimpleStringA::Format("Attempt to ping to branch server[%s] succ.",
- (LPCTSTR)m_csIpBackup));
- }else if(nPingResult == 1) {
- LogEvent(Severity_None, 0,
- CSimpleStringA::Format(
- "Attempt to ping to branch server[%s] succ.", (LPCTSTR)m_csIp));
- }
- }
- else
- {
- s_nTimes = -1;
- Dbg("CheckNetSituationWithPing returned %d, Set flag !", nPingResult);
- }
- }
- break;
- case USER_EVT_DEVICE_LEAVE:
- pEvt->SetHandled();
- BroadcastCableChangedFSMEvent(pEvt);
- if(pEvt->param2 == 0) {
- nRes = 1;
- } else {
- nRes = 0;
- Recognized3GOr4G();
- auto state = GetCurState();
- if(state == MBD_NO_MOBILEDONGLE) {
- nRes = 1;
- } else if(state == MBD_INTERNAL_ERROR) {
- PostEventFIFO(new FSMEvent(USER_EVT_FAILURE));
- } else if(state == MBD_ACTIVATION_DISCONNECTED)
- {
- FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DISCONNECT_COMPLETE);
- fsmEvent->param1 = 0;
- fsmEvent->param2 = 0;
- PostEventFIFO(fsmEvent);
- } else {
- nRes = 2;
- }
- }
- break;
- case USER_EVT_FAILURE:
- Dbg("s2(disconnected): goto failed status %s", ConvertStatusToString(GetCurState()));
- pEvt->SetHandled();
- break;
- case EVT_USER_WLAN_CONNECT:
- pEvt->SetHandled();
- break;
- case EVT_USER_WIRELESS_STATE:
- BroadcastCableChangedFSMEvent(pEvt);
- pEvt->SetHandled();
- nRes = pEvt->param1;
- break;
- default:
- break;
- }
- return nRes;
- }
- //Failed
- void CMobileDialFSM::s3_on_entry()
- {
- LOG_FUNCTION();
- const MOBILEDIAL_CONNECTION_STATE state = GetCurState();
- CSimpleStringA csErrorString = GetFurtherDetail();
- ShowFatalError(csErrorString);
- SetSysVal(NET_STATUS_ERROR);
- if(state == MBD_NETWORK_INVALID_SOCKET) {//hardly happen.
- if(WSACleanup() == SOCKET_ERROR) {
- Dbg("s3(failed): WSACleanup() failed");
- RecordLastErrorMsg(WSAGetLastError());
- return;
- }
- Sleep(300);
- WSADATA wsaData;
- int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
- if (iResult != 0) {
- Dbg("s3(failed): WSAStartup() failed");
- RecordLastErrorMsg(iResult);
- return;
- }
- FSMEvent* fsmEvent = new FSMEvent(USER_EVT_RECOVER);
- PostEventLIFO(fsmEvent);
- }
- else {
- m_bConnected = false;
- m_dwCkFailCount = 0;
- SendNetStatusMsg();
- int mustFlag = 0;
- if(state == MBD_NO_PROFILE) {
- mustFlag = 4;
- } else if(state == MBD_ACTIVATION_CONNECTING) {
- ScheduleTimer(FAILURE_WAIT_TIMER_ID, MOBILEDIAL_FASTER_INTERVAL);
- return;
- }
- m_nRecoverMax = 0;
- ScheduleTimer(FAILURE_WAIT_TIMER_ID, MOBILEDIAL_CHECKDONGLE_INTERVAL);
- }
- }
- void CMobileDialFSM::s3_on_exit()
- {
- CancelTimer(FAILURE_WAIT_TIMER_ID);
- //SetSysVal(NET_STATUS_UNINIT);
- }
- unsigned int CMobileDialFSM::s3_on_event(FSMEvent* pEvt)
- {
- int nRes = pEvt->param1;
- Dbg("s3_on_event(failed) %d, %d, %d", pEvt->iEvt, pEvt->param1, pEvt->param2);
- switch(pEvt->iEvt)
- {
- case USER_EVT_ATTEMPT:
- pEvt->SetHandled();
- break;
- case USER_EVT_RECOVER:
- pEvt->SetHandled();
- if(GetCurState() == MBD_ACTIVATION_DISCONNECTED) {
- //
- // 因没有处理 OnConnectionComplete: newInterface: requestID: 0 status 0} 事件
- // 导致当前处于没连接状态,但是网络好的情况 [6/16/2020 17:47 @Gifur]
- //
- Recognized3GOr4G();
- }
- break;
- //case USER_EVT_STATUSCHANGE:
- // pEvt->SetHandled();
- // {
- // Dbg("s3(failed): StatusChanged[%s]", ConvertStatusToString((MOBILEDIAL_CONNECTION_STATE)nRes));
- // Recognized3GOr4G();
- // }
- // break;
- case EVT_TIMER:
- pEvt->SetHandled();
- if(pEvt->param1 == FAILURE_WAIT_TIMER_ID)
- {
- if(IsConnectedFromHB()) {
- Dbg("s3(failed): EVT_TIMER Creates USER_EVT_RECOVER triggered by heartbeat !!");
- PostEventLIFO(new FSMEvent(USER_EVT_RECOVER));
- } else {
- if(m_bPadAndFLB && !isUsingNewVerAllInOne() ) {
- if(m_nAdvancedGen != 4 && m_nAdvancedGen != 2) {
- int nRAS = EnumCurRasDevices();
- if(nRAS >= 0 && nRAS != m_n3G) {
- FSMEvent* fsmEvent = new FSMEvent(m_n3G > nRAS ? USER_EVT_DEVICE_LEAVE : USER_EVT_DEVICE_ARRIVAL);
- fsmEvent->param1 = 0;
- fsmEvent->param2 = 3;
- PostEventLIFO(fsmEvent);
- }
- }
- }
- if(!m_bManageByUser && ++m_nRecoverMax > ATTEMPT_INTERVAL) {
- Recognized3GOr4G();
- PostEventLIFO(new FSMEvent(USER_EVT_ATTEMPT));
- }
- else {
- ScheduleTimer(FAILURE_WAIT_TIMER_ID, MOBILEDIAL_CHECKDONGLE_INTERVAL);
- }
- }
- }
- break;
- case USER_EVT_DEVICE_LEAVE:
- pEvt->SetHandled();
- BroadcastCableChangedFSMEvent(pEvt);
- if(pEvt->param2 == 0) {
- nRes = 1;
- } else {
- nRes = 0;
- Recognized3GOr4G();
- auto state = GetCurState();
- if(state == MBD_NO_MOBILEDONGLE) {
- nRes = 1;
- } else if(state == MBD_ACTIVATION_DISCONNECTED) {
- FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DISCONNECT_COMPLETE);
- fsmEvent->param1 = 0;
- fsmEvent->param2 = 0;
- PostEventFIFO(fsmEvent);
- } else {
- nRes = 2;
- }
- }
- break;
-
- case USER_EVT_DEVICE_ARRIVAL:
- pEvt->SetHandled();
- {
- BroadcastCableChangedFSMEvent(pEvt);
- Recognized3GOr4G();
- if(GetCurState() == MBD_ACTIVATION_DISCONNECTED){
- PostEventFIFO(new FSMEvent(USER_EVT_DISCONNECT_COMPLETE));
- nRes = 1;
- } else {
- PostEventFIFO(new FSMEvent(USER_EVT_RECOVER));
- nRes = 0;
- }
- }
- break;
- case USER_EVT_CONNECT_COMPLETE:
- BroadcastCableChangedFSMEvent(pEvt);
- case USER_EVT_DISCONNECT_COMPLETE:
- {
- pEvt->SetHandled();
- //如果窗口是打开的那就让拨号窗口去更新状态
- if(!m_hMainWnd) {
- Recognized3GOr4G();
- }
- //PostEventLIFO(new FSMEvent(USER_EVT_RECOVER));
- }
- break;
- default:
- break;
- }
- return nRes;
- }
- //OffLine
- void CMobileDialFSM::s4_on_entry()
- {
- LOG_FUNCTION();
- #if !SUPPORT_DIAL_FROM_WEB
- m_34GDialSuc = 0;
- ShowFatalError("未检测到无线宽带上网卡,请重连设备");
- m_bConnected = false;
- m_dwCkFailCount = 0;
- SendNetStatusMsg();
- SetSysVal(NET_STATUS_NO_DEVICE);
- ScheduleTimer(CHECK_NETCARD_TIMER_ID, MOBILEDIAL_CHECKDONGLE_INTERVAL);
- #else
- Dbg("Walk normal way in connect style.");
- m_TimeoutSec = DEFAULT_TIMEOUT_SEC;
- CheckConnectionTask* task = new CheckConnectionTask(this);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- m_offDeviceFlag = 0;
- #endif
- }
- void CMobileDialFSM::s4_on_exit()
- {
- m_offDeviceFlag = 0;
- CancelTimer(CHECK_NETCARD_TIMER_ID);
- //SetSysVal(NET_STATUS_UNINIT);
- }
- unsigned int CMobileDialFSM::s4_on_event(FSMEvent* pEvt)
- {
- int nRes = pEvt->param1;
- Dbg("s4_on_event %d, %d, %d", pEvt->iEvt, pEvt->param1, pEvt->param2);
- switch(pEvt->iEvt)
- {
- #if SUPPORT_DIAL_FROM_WEB
- case USER_EVT_CKECK_CONNECTION_FINISHED:
- pEvt->SetHandled();
- {
- bool bShouldBackup = !!(pEvt->param2 & 0x4);
- bool bRealBackup = !!(pEvt->param2 & 0x2);
- CSimpleStringA csIpPrint = bRealBackup ? m_csIpBackup : m_csIp;
- CSimpleStringA csPortPrint = bRealBackup ? m_csPortBackup : m_csPort;
- if(nRes == 0) {
- CSimpleStringA csMsg;
- csMsg = CSimpleStringA::Format("s4(no device): Connect to server(%s:%s) failed(%d) FailCount(%d) FailMax(%d).",
- (LPCTSTR)csIpPrint, (LPCTSTR)csPortPrint, m_dwLsErrCode, ++m_dwCkFailCount, m_dwFailMax);
- LogEvent(Severity_Middle, CombineErrorCode(MBD_CHECK_NETWORK_CONNETCTED), (LPCTSTR)csMsg);
- const MOBILEDIAL_CONNECTION_STATE state = GetCurState();
- Dbg("s4(no device): %s.", ConvertStatusToString(state));
- // fix bug which lead netbroken show more easy and earlier --Josephus at 8:59:47 20161211
- if(m_dwCkFailCount < DEFAULT_FAIL_CONNECT_LESS) {
- m_TimeoutSec = DEFAULT_TIMEOUT_SEC + 2 * m_dwCkFailCount;
- if(bShouldBackup && !bRealBackup) {
- Dbg("backup ip and port maybe no exist.");
- break;
- }
- //未达到连续次数的网络断开情况,防止状态跳转
- nRes = 4;
- if(state == MBD_NETWORK_TIMEOUT) {
- Sleep(MOBILEDIAL_QUICK_TIMER_INTERVAL);
- }
- else {
- Sleep( MOBILEDIAL_FASTER_INTERVAL);
- }
- CheckConnectionTask* task = new CheckConnectionTask(this);
- if(bRealBackup) {
- task->m_bUseBackup = true;
- }
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- }
- else if(!bShouldBackup && m_bBackupAvail) {
- m_dwCkFailCount = 0;
- m_TimeoutSec = DEFAULT_TIMEOUT_SEC;
- //未达到连续次数的网络断开情况,防止状态跳转
- nRes = 4;
- if(state == MBD_NETWORK_TIMEOUT){
- Sleep(MOBILEDIAL_QUICK_TIMER_INTERVAL);
- }
- else{
- Sleep(MOBILEDIAL_FASTER_INTERVAL);
- }
- CheckConnectionTask* task = new CheckConnectionTask(this);
- task->m_bUseBackup = true;
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- } else {
- if(m_offDeviceFlag == 0) {
- m_34GDialSuc = 0;
- ShowFatalError("未检测到无线宽带上网卡,请重连设备");
- m_bConnected = false;
- m_dwCkFailCount = 0;
- SendNetStatusMsg();
- SetSysVal(NET_STATUS_NO_DEVICE);
- m_offDeviceFlag = 1;
- }
- ScheduleTimer(CHECK_NETCARD_TIMER_ID, MOBILEDIAL_CHECKDONGLE_INTERVAL);
- }
- }
- else { //没网卡也能连接上网,适用于分行使用网页拨号上网的情况
- Dbg("s4(no device): Connect to server(%s:%s) result(%d)(%d), pad&FLB(%d) %s",
- (LPCTSTR)csIpPrint, (LPCTSTR)csPortPrint, nRes,
- m_dwLsErrCode, m_bPadAndFLB,
- ConvertStatusToString(GetCurState()));
- }
- m_dwOldErrCode = m_dwLsErrCode;
- }
- break;
- #endif
- case USER_EVT_DEVICE_ARRIVAL:
- pEvt->SetHandled();
- {
- BroadcastCableChangedFSMEvent(pEvt);
- Recognized3GOr4G();
- if(GetCurState() == MBD_ACTIVATION_DISCONNECTED){
- nRes = 1;
- } else {
- nRes = 0;
- }
- }
- break;
- case EVT_TIMER:
- if(pEvt->param1 == CHECK_NETCARD_TIMER_ID)
- {
- pEvt->SetHandled();
- if(m_nAdvancedGen != 4 && m_nAdvancedGen != 2) {
- if(EnumCurRasDevices() > 0) {
- FSMEvent* pEvt = new FSMEvent(USER_EVT_DEVICE_ARRIVAL);
- pEvt->param1 = 0;
- pEvt->param2 = 3;
- PostEventLIFO(pEvt);
- break;
- } else {
- #if !SUPPORT_DIAL_FROM_WEB
- ScheduleTimer(CHECK_NETCARD_TIMER_ID, MOBILEDIAL_CHECKDONGLE_INTERVAL);
- #endif
- }
- } else if(m_nAdvancedGen == 2) {
- LOG_ASSERT(mMBBParam.connectType == MBB_CONNECT_WIRE);
- if(CheckLANConnectStatus() == 0) {
- //SetHWStatus(MBD_NO_MOBILEDONGLE);
- } else {
- //SetHWStatus(MBD_ACTIVATION_CONNECTED);
- FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DEVICE_ARRIVAL);
- fsmEvent->param1 = 0;
- fsmEvent->param2 = 2;
- PostEventFIFO(fsmEvent);
- break;
- }
- }
- #if SUPPORT_DIAL_FROM_WEB
- m_TimeoutSec = DEFAULT_TIMEOUT_SEC;
- CheckConnectionTask* task = new CheckConnectionTask(this);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- #endif
- }
- break;
- default:
- break;
- }
- return nRes;
- }
- //Deactivated
- void CMobileDialFSM::s5_on_entry()
- {
- LOG_FUNCTION();
- LogEvent(Severity_High, CombineErrorCode(MBD_CABLE_DIALUP_DISCONNETED), "无线宽带上网卡未连接");
- //BroadcastCableChangedEvent(MBD_CABLE_DIALUP_DISCONNETED);
- SendMsgToDialog("无线宽带上网卡未连接");
- m_bConnected = false;
- m_34GDialSuc = 0;
- m_dwCkFailCount = 0;
- SendNetStatusMsg();
- SetSysVal(NET_STATUS_DIAL_OFF);
- if(!m_bManageByUser || g_bFirstConnect) {
- if(g_bFirstConnect) {
- g_bFirstConnect = FALSE;
- Dbg("Execute First ConnectTask");
- }
- // 处理3G网卡在连接的状态下直接拔掉的情形:
- // 先接收到断开连接的事件,后续才发现到设备拔离的事件,所以要做延迟拨号处理,但测试发现尽管延迟了3秒都没有起到真正的作用
- if(m_n3G > 0) {
- ScheduleTimer(CHECK_PRE_RASDEVICE_CHANGED_TIMER_ID, MOBILEDIAL_FASTERDIALRT_INTERVAL);
- } else {
- ConnectTask* task = new ConnectTask(this);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- }
- } else {
- Dbg("Detect ManageByUser mode !!!");
- if(m_n3G > 0) {
- ScheduleTimer(CHECK_RASDEVICE_CHANGED_TIMER_ID, MOBILEDIAL_FASTERDIALRT_INTERVAL);
- }
- }
- }
- void CMobileDialFSM::s5_on_exit()
- {
- CancelTimer(CHECK_CONNECT_DIAL_TIMER_ID);
- CancelTimer(CHECK_CONNECT_TIMER_ID);
- CancelTimer(CHECK_RASDEVICE_CHANGED_TIMER_ID);
- //SetSysVal(NET_STATUS_UNINIT);
- }
- unsigned int CMobileDialFSM::s5_on_event(FSMEvent* pEvt)
- {
- int nRes = pEvt->param1;
- Dbg("s5_on_event %d, %d, %d", pEvt->iEvt, pEvt->param1, pEvt->param2);
- switch(pEvt->iEvt)
- {
- case USER_EVT_CONNECT_COMPLETE:
- pEvt->SetHandled();
- {
- BroadcastCableChangedFSMEvent(pEvt);
- if(pEvt->param2 == ADVANCE_RAS) {
- if(pEvt->param1 == 1) {
- UpdateRasConnectState(true);
- nRes = 0;
- } else if(pEvt->param1 == -1) {
- _FormatRasError(g_dwRasError);
- if(m_34GReserved != ADVANCE_RAS) {
- Dbg("Manual dial from outside(%d) ?", m_34GReserved);
- m_34GReserved = ADVANCE_RAS;
- } else {
- EraseTheRecentInfo((ULONG)g_hrasconn);
- }
- // Move here [1/24/2019 17:34 @Gifur]
- RasHangUpSuffix();
- SetRasStatus(MBD_RASDIAL_FAILED);
- m_34GDialSuc = 0;
- nRes = 1;
- }
- } else if(pEvt->param2 == ADVANCE_MBB) {
- LOG_ASSERT(g_DongleInfos.GetCount() > 0);
- _GetMBBDeviceInfo(g_DongleInfos[0]);
- }
- }
- break;
- case USER_EVT_CONNECT_FINISHED:
- pEvt->SetHandled();
- {
- if(pEvt->param1 < 0) {
- nRes = 0;
- } else {
- SendNetStatusMsg();
- if(pEvt->param1 == ADVANCE_RAS)
- {
- LogEvent(Severity_Middle,CombineErrorCode(MBD_RAS_DIALUP_CONNETED),"3G拨号成功,等待响应");
- m_34GDialSuc = ADVANCE_RAS;
- ScheduleTimer(CHECK_CONNECT_DIAL_TIMER_ID, MOBILEDIAL_FASTERDIALRT_INTERVAL);
- }
- else if(pEvt->param1 == ADVANCE_MBN)
- {
- LogEvent(Severity_Middle,CombineErrorCode(MBD_MBN_DIALUP_CONNETED),"4G拨号成功,等待响应");
- m_34GDialSuc = ADVANCE_MBN;
- ScheduleTimer(CHECK_CONNECT_MBN_TIMER_ID, MOBILEDIAL_WAITDIALRT_INTERVAL);
- }
- else if(pEvt->param1 == ADVANCE_MBB) {
- LogEvent(Severity_Middle,CombineErrorCode(MBD_MBB_DIALUP_CONNECTED),"MBB 拨号成功");
- m_34GDialSuc = ADVANCE_MBB;
- FSMEvent* fsmEvent = new FSMEvent(USER_EVT_CONNECT_COMPLETE);
- fsmEvent->param1 = 0;
- fsmEvent->param2 = ADVANCE_MBB;
- PostEventFIFO(fsmEvent);
- }
- }
- }
- break;
- case EVT_TIMER:
- {
- if(pEvt->param1 == CHECK_CONNECT_MBN_TIMER_ID) {
- pEvt->SetHandled();
- Dbg("timeout after 4g dial suc, change status auto.");
- nRes = 0;
- if(m_pMbn->CheckAndRefleshCurInterface()) {
- const MOBILEDIAL_CONNECTION_STATE state = GetCurState();
- if(state < MBD_NETWORK_SEPERATE)
- {//find connected.
- FSMEvent* pEvent = new FSMEvent(USER_EVT_CONNECT_COMPLETE);
- pEvent->param1 = 0;
- pEvent->param2 = 0;
- PostEventFIFO(pEvent);
- nRes = 1; //cancel event.
- LogEvent(Severity_Middle,CombineErrorCode(MBD_UNKNOWN),"响应超时,自动跳转");
- }
- else if(state == MBD_ACTIVATION_CONNECTING)
- {//still connecting
- nRes = 1; //cancel event.
- ScheduleTimer(CHECK_CONNECT_MBN_TIMER_ID, MOBILEDIAL_FASTERDIALRT_INTERVAL);
- }
- else if(state == MBD_ACTIVATION_DISCONNECTED)
- {//hardly happen but still has chance.
- nRes = 1; //cancel event.
- if(!m_bManageByUser) {
- ConnectTask* task = new ConnectTask(this);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- } else {
- Dbg("Detect ManageByUser mode !!!");
- }
- }
- }
- }
- else if(pEvt->param1 == CHECK_CONNECT_DIAL_TIMER_ID)
- {
- pEvt->SetHandled();
- Dbg("timeout after 3g dial suc, change status auto.");
- nRes = 0;
- MOBILEDIAL_CONNECTION_STATE state = GetRasStatus();
- if(state == MBD_ACTIVATION_CONNECTED) {
- nRes = 1; //cancel event.
- FSMEvent* pEvent = new FSMEvent(USER_EVT_CONNECT_COMPLETE);
- pEvent->param1 = 0;
- pEvent->param2 = ADVANCE_RAS;
- PostEventFIFO(pEvent);
- LogEvent(Severity_Middle,CombineErrorCode(MBD_RAS_DIALUP_CONNETED),"3G拨号成功,超时跳转");
- }
- else if(state == MBD_ACTIVATION_CONNECTING) {
- nRes = 1; //cancel event.
- if(MOBILEDIAL_WAITDIALRT_INTERVAL > MOBILEDIAL_FASTERDIALRT_INTERVAL) {
- ScheduleTimer(CHECK_CONNECT_DIAL_TIMER_ID,
- MOBILEDIAL_WAITDIALRT_INTERVAL - MOBILEDIAL_FASTERDIALRT_INTERVAL);
- } else {
- ScheduleTimer(CHECK_CONNECT_DIAL_TIMER_ID, MOBILEDIAL_WAITDIALRT_INTERVAL);
- }
- }
- }
- else if(pEvt->param1 == CHECK_RASDEVICE_CHANGED_TIMER_ID
- || pEvt->param1 == CHECK_PRE_RASDEVICE_CHANGED_TIMER_ID) {
- if(m_nAdvancedGen != 4 && m_nAdvancedGen != 2 && EnumCurRasDevices() == 0) {
- FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DEVICE_LEAVE);
- fsmEvent->param1 = 0;
- fsmEvent->param2 = 3;
- PostEventFIFO(fsmEvent);
- break;
- } else if(pEvt->param1 == CHECK_PRE_RASDEVICE_CHANGED_TIMER_ID) {
- ConnectTask* task = new ConnectTask(this);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- }
- ScheduleTimer(CHECK_RASDEVICE_CHANGED_TIMER_ID, MOBILEDIAL_FASTERDIALRT_INTERVAL);
- }
- }
- break;
- case USER_EVT_DEVICE_LEAVE:
- pEvt->SetHandled();
- BroadcastCableChangedFSMEvent(pEvt);
- if(pEvt->param2 == 0) {
- nRes = 1;
- } else {
- nRes = 0;
- Recognized3GOr4G();
- auto state = GetCurState();
- if(state == MBD_NO_MOBILEDONGLE) {
- nRes = 1;
- } else if(state == MBD_ACTIVATION_DISCONNECTED) {
- if(!m_bManageByUser) {
- ConnectTask* task = new ConnectTask(this);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- } else {
- Dbg("Detect ManageByUser mode !!!");
- }
- } else {
- nRes = 2;
- }
- }
- break;
- default:
- break;
- }
- return nRes;
- }
- void CMobileDialFSM::s6_on_entry()
- {
- LOG_FUNCTION();
- if(m_nAdvancedGen != 4 && m_nAdvancedGen != 2 && !isUsingNewVerAllInOne()) {
- ScheduleTimer(CHECK_RASDEVICE_CHANGED_TIMER_ID, DEV_CHANGED_TIMER_INTERVAL);
- }
- return;
- }
- void CMobileDialFSM::s6_on_exit()
- {
- LOG_FUNCTION();
- CancelTimer(CHECK_RASDEVICE_CHANGED_TIMER_ID);
- Recognized3GOr4G();
- return;
- }
- unsigned int CMobileDialFSM::s6_on_event(FSMEvent* pEvt)
- {
- int nRes = pEvt->param1;
- Dbg("s6_on_event %d, %d, %d", pEvt->iEvt, pEvt->param1, pEvt->param2);
- switch(pEvt->iEvt) {
- case EVT_TIMER:
- if(pEvt->param1 == CHECK_RASDEVICE_CHANGED_TIMER_ID) {
- pEvt->SetHandled();
- int nTimerInterval = DEV_CHANGED_TIMER_INTERVAL;
- int nRAS = EnumCurRasDevices();
- if(nRAS != m_n3G) {
- TellDlgTheResult(Error_Succeed, WM_DONGLE_CHANGE, 0);
- } else {
- nTimerInterval = DEV_CHANGED_TIMER_INTERVAL * 3;
- }
- ScheduleTimer(CHECK_RASDEVICE_CHANGED_TIMER_ID, nTimerInterval);
- }
- break;
- default:
- break;
- }
- return 0;
- }
- /*Linking*/
- void CMobileDialFSM::s7_on_entry()
- {
- LOG_FUNCTION();
- if(mMBBParam.wlanConnectParam.strPassword.IsNullOrEmpty()
- || mMBBParam.wlanConnectParam.strUsername.IsNullOrEmpty()) {
- SetHWStatus(MBD_RUN_CONFIG_INCOMPLEMENT);
- PostEventFIFO(new FSMEvent(USER_EVT_FAILURE));
- } else {
- m_dwWlanConnectTimes = 0;
- ScheduleTimer(TIMER_TRY_LINK_ID, MOBILEDIAL_QUICK_TIMER_INTERVAL);
- SetHWStatus(MBD_WLAN_DISCONNECTED);
- }
- m_bConnected = false;
- ShowFatalError(GetFurtherDetail());
- SendNetStatusMsg();
- }
- void CMobileDialFSM::s7_on_exit()
- {
- if(GetHWStatus() == MBD_WLAN_CONNECTED) {
- m_dwWlanConnectTimes = 0;
- ShowFatalError("WLAN 已连接", TRUE);
- Recognized3GOr4G();
- }
- CancelTimer(TIMER_TRY_LINK_ID);
- }
- unsigned int CMobileDialFSM::s7_on_event(FSMEvent* evt)
- {
- unsigned int uRet = 0;
- Dbg("s7_on_event %d, %d, %d", evt->iEvt, evt->param1, evt->param2);
- switch(evt->iEvt) {
- case EVT_TIMER:
- {
- if(evt->param1 == TIMER_TRY_LINK_ID) {
- evt->SetHandled();
- if(NeedToConnectWifi()) {
- SetHWStatus(MBD_WLAN_CONNECTING);
- WlanConnectTask* task = new WlanConnectTask(this);
- this->GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- } else {
- PostEventFIFO(new FSMEvent(USER_EVT_ATTEMPT));
- }
- ShowFatalError(GetFurtherDetail());
- SendNetStatusMsg();
- }
- }
- break;
- case EVT_USER_WLAN_CONNECT_FINISHED:
- {
- evt->SetHandled();
- uRet = evt->param1;
- m_dwWlanConnectTimes++;
- if(evt->param1 == 0) {
- const ErrorCodeEnum ec = (ErrorCodeEnum)evt->param2;
- if(ec == Error_NotExist) {
- SetHWStatus(MBD_WLAN_ENTRY_NO_FOUND);
- } else {
- SetHWStatus(MBD_WLAN_CONNECT_FAILED);
- }
- ShowFatalError(GetFurtherDetail());
- SendNetStatusMsg();
- if(m_dwWlanConnectTimes >= MAX_TRY_WLAN_CONNETC_TIMES) {
- LogError(Severity_High, Error_TimeOut, CombineErrorCode(MBD_WLAN_CONNECT_FAILED),
- CSimpleStringA::Format("连续%d次连接WLAN失败,请检查MIFI设备是否正常运行!", m_dwWlanConnectTimes)
- );
- ScheduleTimer(TIMER_TRY_LINK_ID, MOBILEDIAL_WLAN_CONNECT_INTERVAL * 2);
- } else {
- ScheduleTimer(TIMER_TRY_LINK_ID, MOBILEDIAL_WLAN_CONNECT_INTERVAL);
- }
- } else {
- SetHWStatus(MBD_WLAN_CONNECTED);
- }
- }
- break;
- case EVT_USER_WIRELESS_STATE:
- //BroadcastCableChangedFSMEvent(evt);
- evt->SetHandled();
- uRet = evt->param1;
- if(evt->param1 == 1) {
- SetHWStatus(MBD_WLAN_CONNECTED);
- } else {
- SetHWStatus(MBD_WLAN_CONNECT_FAILED);
- ScheduleTimer(TIMER_TRY_LINK_ID, MOBILEDIAL_WLAN_CONNECT_INTERVAL);
- }
- break;
- case USER_EVT_FAILURE:
- evt->SetHandled();
- break;
- default:
- break;
- }
- return uRet;
- }
- void CMobileDialFSM::s8_on_entry()
- {
- LOG_FUNCTION();
- MBBConfigUpdateTask* task = new MBBConfigUpdateTask(this);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- }
- void CMobileDialFSM::s8_on_exit()
- {
- Recognized3GOr4G();
- }
- unsigned int CMobileDialFSM::s8_on_event(FSMEvent* evt)
- {
- unsigned int uRet = 0;
- Dbg("s8_on_event %d, %d, %d", evt->iEvt, evt->param1, evt->param2);
- if(evt->iEvt == USER_EVT_CONFIG_DETECT_FINISHED) {
- evt->SetHandled();
- if(evt->param1 == 1) {
- if(m_nAdvancedGen != ADVANCE_MBB) {
- InitHuaweiComponent();
- m_nAdvancedGen = ADVANCE_MBB;
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- spConfigRun->WriteConfigValueInt("init", "GenAdvanced", m_nAdvancedGen);
- SetHWStatus(MBD_WLAN_CONFIG_REBOOT);
- ShowFatalError(GetFurtherDetail());
- SendNetStatusMsg();
- ScheduleTimer(TIMER_CHECK_DEVICE_ID, DEV_CHANGED_TIMER_INTERVAL);
- } else {
- SetHWStatus(MBD_WLAN_DEVICE_PLUG_OFF);
- ShowFatalError(GetFurtherDetail());
- SendNetStatusMsg();
- ScheduleTimer(TIMER_CHECK_DEVICE_NOCHANGED_ID, DEV_CHANGED_TIMER_INTERVAL);
- }
- uRet = 1; //stop from backing to s0.
- }
- }
- else if(evt->iEvt == EVT_TIMER) {
- if(evt->param1 == TIMER_CHECK_DEVICE_ID || evt->param1 == TIMER_CHECK_DEVICE_NOCHANGED_ID) {
- evt->SetHandled();
- if(!m_HwDeviceMnt->detect_devices()) {
- if(evt->param1 == TIMER_CHECK_DEVICE_ID) {
- Dbg("wait the selfchecker entity to kill it or manully.");
- m_ecSelfTest = Error_InvalidState;
- SetHWStatus(MBD_WLAN_CONFIG_WAIT_REBOOT);
- ShowFatalError(GetFurtherDetail());
- SendNetStatusMsg();
- } else {
- uRet = 1;
- }
- } else {
- if(evt->param1 == TIMER_CHECK_DEVICE_ID) {
- SetHWStatus(MBD_WLAN_CONFIG_REBOOT);
- ShowFatalError(GetFurtherDetail());
- SendNetStatusMsg();
- ScheduleTimer(TIMER_CHECK_DEVICE_ID, DEV_CHANGED_TIMER_INTERVAL);
- } else {
- SetHWStatus(MBD_WLAN_DEVICE_PLUG_OFF);
- ShowFatalError(GetFurtherDetail());
- SendNetStatusMsg();
- ScheduleTimer(TIMER_CHECK_DEVICE_NOCHANGED_ID, DEV_CHANGED_TIMER_INTERVAL);
- }
- }
- }
- }
- return uRet;
- }
- int CMobileDialFSM::EnumPhoneEntry()
- {
- DWORD dwCb = 0;
- DWORD dwRet = ERROR_SUCCESS;
- DWORD dwEntries = 0;
- LPRASENTRYNAME lpRasEntryName = NULL;
- // Call RasEnumEntries with lpRasEntryName = NULL. dwCb is returned with the required buffer size and
- // a return code of ERROR_BUFFER_TOO_SMALL
- dwRet = RasEnumEntries(NULL, NULL, lpRasEntryName, &dwCb, &dwEntries);
- if (dwRet == ERROR_BUFFER_TOO_SMALL)
- {
- // Allocate the memory needed for the array of RAS entry names.
- lpRasEntryName = (LPRASENTRYNAME) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwCb);
- if (lpRasEntryName == NULL){
- Dbg("HeapAlloc failed when RasEnumEntries");
- return -1;
- }
- // The first RASENTRYNAME structure in the array must contain the structure size
- lpRasEntryName[0].dwSize = sizeof(RASENTRYNAME);
- // Call RasEnumEntries to enumerate all RAS entry names
- dwRet = RasEnumEntries(NULL, NULL, lpRasEntryName, &dwCb, &dwEntries);
- // If successful, print the RAS entry names
- if (ERROR_SUCCESS == dwRet)
- {
- Dbg("The following RAS entry names were found:");
- for (DWORD i = 0; i < dwEntries; i++) {
- if (m_csEntryName.GetLength() != 0 &&
- _strnicmp(lpRasEntryName[i].szEntryName,m_csEntryName,m_csEntryName.GetLength()) == 0) {
- Dbg("Find specified entry: %s",(LPCTSTR)m_csEntryName);
- LPRASENTRY lpRasentry = NULL;
- LPBYTE lpDevInfo = NULL;
- DWORD dwEntrySz = 0, dwDevInfoSz = 0;
- dwRet = RasGetEntryProperties(NULL, lpRasEntryName[i].szEntryName, NULL, &dwEntrySz, NULL, &dwDevInfoSz);
- if(dwRet == ERROR_BUFFER_TOO_SMALL) {
- if(dwEntrySz != 0)
- lpRasentry = (LPRASENTRY)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwEntrySz);
- if(dwDevInfoSz != 0)
- lpDevInfo = (LPBYTE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwDevInfoSz);
- }
- if(lpRasentry != NULL) {
- lpRasentry->dwSize = sizeof(RASENTRY);
- dwRet = RasGetEntryProperties(NULL, lpRasEntryName[i].szEntryName, lpRasentry, &dwEntrySz, lpDevInfo, &dwDevInfoSz);
- if(dwRet != 0) {
- Dbg("RasGetEntryProperties twice failed: %d", dwRet);
- } else {
- Dbg("DeviceName: %s, DeviceType: %s", lpRasentry->szDeviceName, lpRasentry->szDeviceType);
- CSimpleStringA csEntryGUID = GuidToString(lpRasentry->guidId);
- if(!csEntryGUID.IsNullOrEmpty())
- {
- CSmartPointer<IConfigInfo> spConfigRun;
- CSimpleStringA csValue;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- if(Error_Succeed != spConfigRun->ReadConfigValue(csEntryGUID, "Status", csValue)
- || csValue.GetLength() <= 0) {
- Dbg("Cannot found entry(%s) info from runtime file: (%s), set temporary",
- (LPCTSTR)csEntryGUID, (LPCTSTR)csValue);
- spConfigRun->WriteConfigValue(csEntryGUID, "Type", "RAS");
- spConfigRun->WriteConfigValue(csEntryGUID, "Status", "Invalid-Temporary");
- spConfigRun->WriteConfigValue(csEntryGUID, "EntryName", m_csEntryName);
- spConfigRun->WriteConfigValue("RAS", "EntryGUID", csEntryGUID);
- }
- }
- }
- }
- if(lpRasentry) {
- HeapFree(GetProcessHeap(), 0, lpRasentry);
- lpRasentry = NULL;
- }
- if(lpDevInfo) {
- HeapFree(GetProcessHeap(), 0, lpDevInfo);
- lpDevInfo = NULL;
- }
- //Deallocate memory for the connection buffer
- HeapFree(GetProcessHeap(), 0, lpRasEntryName);
- lpRasEntryName = NULL;
- return 0;
- } else {
- Dbg("EntryName[%d]: %s", i, lpRasEntryName[i].szEntryName);
- }
- }
- }
- //Deallocate memory for the connection buffer
- HeapFree(GetProcessHeap(), 0, lpRasEntryName);
- lpRasEntryName = NULL;
- return -2;
- }
- // There was either a problem with RAS or there are RAS entry names to enumerate
- if(dwEntries >= 1) {
- Dbg("The operation failed to acquire the buffer size.");
- } else {
- Dbg("There were no RAS entry names found.");
- return -2;
- }
- return -3;
- }
- int CMobileDialFSM::UpdateRasConnectState(bool bUpdateCmd)
- {
- LOG_FUNCTION();
- DWORD dwCb = 0;
- DWORD dwRet = ERROR_SUCCESS;
- DWORD dwConnections = 0;
- LPRASCONN lpRasConn = NULL;
- if(bUpdateCmd) {
- int cnt = g_DongleInfos.GetCount();
- for(int i=0; i<cnt; ++i) {
- CSimpleStringA strBackup(true);
- if(g_DongleInfos[i].usDeviceType == DEVTYPE_MODEM) {
- if(g_DongleInfos[i].state == MBD_ACTIVATION_CONNECTED) {
- //if(g_DongleInfos[i].subInfo.mbnCntState == MBN_ACTIVATION_STATE_ACTIVATED) {
- Dbg("old connected entry: %s", (LPCTSTR)g_DongleInfos[i].subInfo.strProfileName);
- strBackup = (LPCTSTR)g_DongleInfos[i].subInfo.strProfileName;
- g_DongleInfos[i].state = MBD_ACTIVATION_DISCONNECTED;
- SetRasStatus(MBD_ACTIVATION_DISCONNECTED);
- }
- g_DongleInfos[i].subInfo.mbnCntState = MBN_ACTIVATION_STATE_DEACTIVATED;
- g_DongleInfos[i].subInfo.strProfileName = "";
- int cnt2 = g_DongleInfos[i].profileList.GetCount();
- if(cnt2 > 0 && !strBackup.IsNullOrEmpty()) {
- MBNProfileList& profiles = g_DongleInfos[i].profileList;
- for(int j=0; j<cnt2; ++j) {
- if(!profiles[j].strProfileName.Compare(strBackup)) {
- Dbg("Comfire: found the old connected ras entry: %s",
- (LPCTSTR)profiles[j].AccessInfo.strProfileDesc);
- break;
- }
- }
- } else if(cnt2 == 0) {
- g_DongleInfos[i].state = MBD_NO_ENTRY;
- }
- }
- }
- }
- dwRet = RasEnumConnections(lpRasConn, &dwCb, &dwConnections);
- if (dwRet == ERROR_BUFFER_TOO_SMALL && dwConnections > 0) {
- lpRasConn = (LPRASCONN) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwCb);
- if (lpRasConn == NULL) {
- SetRasStatus(MBD_INTERNAL_ERROR);
- Dbg("HeapAlloc failed when RasEnumConnections");
- return -1;
- }
- lpRasConn[0].dwSize = sizeof(RASCONN);
- int nRes = dwConnections;
- dwRet = RasEnumConnections(lpRasConn, &dwCb, &dwConnections);
- if (ERROR_SUCCESS == dwRet) {
- Dbg("The following RAS connections are currently active:");
- for (DWORD i = 0; i < dwConnections; i++) {
- RASCONNSTATUS rasStatus;
- rasStatus.dwSize = sizeof(RASCONNSTATUS);
- dwRet = RasGetConnectStatus(lpRasConn[i].hrasconn, &rasStatus);
- const RASCONNSTATE& cntState = rasStatus.rasconnstate;
- if(dwRet == ERROR_SUCCESS){
- Dbg("%s - rasconnstate: %d", lpRasConn[i].szEntryName, rasStatus.rasconnstate);
- CSimpleStringA csEntryGUID = GuidToString(lpRasConn[i].guidEntry);
- SetGlobalConnectState(csEntryGUID, cntState);
- if(cntState == RASCS_Connected) {
- Dbg("Reset the ras handle to bcz it has connected");
- g_hrasconn = lpRasConn[i].hrasconn;
- SetRasStatusWithConnStatus(cntState);
- //if(g_hrasconn != lpRasConn[i].hrasconn)
- if(m_csCurEntryGUID.Compare(csEntryGUID))
- {
- m_csCurEntryGUID = CSimpleStringA((LPCTSTR)csEntryGUID);
- CSmartPointer<IConfigInfo> spConfigRun;
- CSimpleStringA csValue;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- if(Error_Succeed != spConfigRun->ReadConfigValue(csEntryGUID, "Status", csValue)
- || csValue.GetLength() <= 0 || csValue.IsStartWith("Invalid")) {
- Dbg("Cannot found entry info from runtime file or invalid: %s", (LPCTSTR)csValue);
- } else {
- Dbg("Read %s from run-config", (LPCTSTR)csEntryGUID);
- CSimpleStringA csTest;
- spConfigRun->ReadConfigValue("RAS", "EntryGUID", csTest);
- Dbg("test: %s", (LPCTSTR)csTest);
- spConfigRun->ReadConfigValue(csEntryGUID, "PhoneNum", m_csPhoneNum);
- spConfigRun->ReadConfigValue(csEntryGUID, "EntryName", m_csEntryName);
- spConfigRun->ReadConfigValue(csEntryGUID, "UserName", m_csUserName);
- #ifdef USING_ENCRYPT
- spConfigRun->ReadConfigValue(csEntryGUID, "Password", csValue);
- m_csPassword = DecryptString(csValue);
- #else
- spConfigRun->ReadConfigValue(csEntryGUID, "Password", m_csPassword);
- #endif
- spConfigRun->ReadConfigValue(csEntryGUID, "APN", m_csVpnName);
-
- }
- }
- } else if(g_hrasconn == lpRasConn[i].hrasconn) {
- SetRasStatusWithConnStatus(cntState);
- }
- }else{
- Dbg("%s - RasGetConnectStatus failed: %u", lpRasConn[i].szEntryName, dwRet);
- }
- }
- } else {
- Dbg("RasEnumConnections twice failed %u", dwRet);
- SetRasStatus(MBD_INTERNAL_ERROR);
- nRes = -1;
- }
- //Deallocate memory for the connection buffer
- HeapFree(GetProcessHeap(), 0, lpRasConn);
- lpRasConn = NULL;
- return nRes;
- }
- // There was either a problem with RAS or there are no connections to enumerate
- if(dwConnections >= 1) {
- Dbg("The operation failed to acquire the buffer size.");
- SetRasStatus(MBD_INTERNAL_ERROR);
- return -1;
- }
- Dbg("There are no active RAS connections.");
- SetRasStatus(MBD_ACTIVATION_DISCONNECTED);
- return 0;
- }
- int CMobileDialFSM::DealConnctionActivity(LPCTSTR lpcszEntryName)
- {
- LOG_FUNCTION();
- DWORD dwCb = 0;
- DWORD dwRet = ERROR_SUCCESS;
- DWORD dwConnections = 0;
- LPRASCONN lpRasConn = NULL;
- dwRet = RasEnumConnections(lpRasConn, &dwCb, &dwConnections);
- if (dwRet == ERROR_BUFFER_TOO_SMALL && dwConnections > 0) {
- lpRasConn = (LPRASCONN) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwCb);
- if (lpRasConn == NULL) {
- Dbg("HeapAlloc failed when RasEnumConnections");
- return -1;
- }
- lpRasConn[0].dwSize = sizeof(RASCONN);
- int nRes = 0;
- dwRet = RasEnumConnections(lpRasConn, &dwCb, &dwConnections);
- if (ERROR_SUCCESS == dwRet) {
- Dbg("The following RAS connections are currently active: %d", dwConnections);
- for (DWORD i = 0; i < dwConnections; i++) {
- RASCONNSTATUS rasStatus;
- rasStatus.dwSize = sizeof(RASCONNSTATUS);
- dwRet = RasGetConnectStatus(lpRasConn[i].hrasconn, &rasStatus);
- const RASCONNSTATE& cntState = rasStatus.rasconnstate;
- if(dwRet == ERROR_SUCCESS){
- Dbg("%s - rasconnstate: %d", lpRasConn[i].szEntryName, rasStatus.rasconnstate);
- if(lpcszEntryName != NULL && strlen(lpcszEntryName) > 0
- && !strcmp(lpRasConn[i].szEntryName, lpcszEntryName)) {
- CSimpleStringA csEntryGUID = GuidToString(lpRasConn[i].guidEntry);
- /*if(cntState != RASCS_Connected)*/ {
- Dbg("Close the ras handle");
- DWORD dwRet = 0;
- dwRet = RasHangUp(lpRasConn[i].hrasconn);
- Dbg("RasHangUp returned %d", dwRet);
- if(dwRet == ERROR_SUCCESS) {
- RASCONNSTATUS connStatus;
- connStatus.dwSize = sizeof(RASCONNSTATUS);
- Dbg("TickCount allocated 3 seconds after RasHangUp...");
- //Reduce timeout tick in case occuring
- //UnLoading-Entity -Josephus@2017627 16:54:10
- DWORD tcLast = GetTickCount() + 3 * 1100;
- while((( dwRet = RasGetConnectStatus(lpRasConn[i].hrasconn, &connStatus))
- != ERROR_INVALID_HANDLE) && (tcLast > GetTickCount())) {
- Sleep(0);
- }
- bool fResult = (dwRet == ERROR_INVALID_HANDLE);
- Dbg("Cycle is done %snormally", fResult ? "" : "ab");
- }
- }
- nRes = 1;
- break;
- }
- }else{
- Dbg("%s - RasGetConnectStatus failed: %u", lpRasConn[i].szEntryName, dwRet);
- }
- }
- } else {
- Dbg("RasEnumConnections twice failed %u", dwRet);
- nRes = -1;
- }
- //Deallocate memory for the connection buffer
- HeapFree(GetProcessHeap(), 0, lpRasConn);
- lpRasConn = NULL;
- return nRes;
- }
- // There was either a problem with RAS or there are no connections to enumerate
- if(dwConnections >= 1) {
- Dbg("The operation failed to acquire the buffer size.");
- return -1;
- }
- Dbg("There are no active RAS connections.");
- return 0;
- }
- int CMobileDialFSM::CreatePhoneEntry()
- {
- return CreatePhoneEntryEx("", NULL, FALSE);
- }
- int CMobileDialFSM::CreatePhoneEntryEx(LPCTSTR lpcszDevName, const AccessKeyInfo * pNewInfo, bool fApplyNow)
- {
- DWORD dwCb = 0;
- DWORD dwRet = ERROR_SUCCESS;
- DWORD dwDevices = 0;
- BOOL bOrigin = FALSE;
- LPRASDEVINFO lpRasDevInfo = NULL;
- RASDEVINFO specialRasDevInfo = {0};
- if(strlen(lpcszDevName) == 0 && pNewInfo == NULL) {
- bOrigin = TRUE;
- }
- specialRasDevInfo.dwSize = 0;
- strcpy_s(specialRasDevInfo.szDeviceName, lpcszDevName);
- strcpy_s(specialRasDevInfo.szDeviceType, RASDT_Modem);
- LPRASENTRY lpRasExistedEntry = NULL;
- LPBYTE lpRasExistedDevInfo = NULL;
- // Call RasEnumDevices with lpRasDevInfo = NULL. dwCb is returned with the required buffer size and
- // a return code of ERROR_BUFFER_TOO_SMALL
- dwRet = RasEnumDevices(lpRasDevInfo, &dwCb, &dwDevices);
- if (dwRet == ERROR_BUFFER_TOO_SMALL)
- {
- // Allocate the memory needed for the array of RAS structure(s).
- lpRasDevInfo = (LPRASDEVINFO) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwCb);
- if (lpRasDevInfo == NULL)
- {
- Dbg("HeapAlloc for RasEnumDevices failed");
- if(!bOrigin) m_csErrMsg = "程序异常-申请内存失败!";
- return -1;
- }
- else
- {
- // The first RASDEVINFO structure in the array must contain the structure size
- lpRasDevInfo[0].dwSize = sizeof(RASDEVINFO);
- // Call RasEnumDevices to enumerate RAS devices
- dwRet = RasEnumDevices(lpRasDevInfo, &dwCb, &dwDevices);
- int bFound = FALSE;
- // If successful, print the names of the RAS devices
- if (ERROR_SUCCESS == dwRet)
- {
- Dbg("The following RAS devices were found:");
- for (DWORD i = 0; i < dwDevices; i++)
- {
- Dbg("%s <%s>",lpRasDevInfo[i].szDeviceName,lpRasDevInfo[i].szDeviceType);
- if(specialRasDevInfo.dwSize == 0) {
- if(!bOrigin) {
- if(!_strnicmp(lpRasDevInfo[i].szDeviceName, lpcszDevName, strlen(lpcszDevName))) {
- specialRasDevInfo.dwSize = strlen(lpcszDevName) + strlen(lpRasDevInfo[i].szDeviceType);
- strcpy_s(specialRasDevInfo.szDeviceName, lpRasDevInfo[i].szDeviceName);
- strcpy_s(specialRasDevInfo.szDeviceType, lpRasDevInfo[i].szDeviceType);
- Dbg("found it 1: %s::%s", specialRasDevInfo.szDeviceName,
- specialRasDevInfo.szDeviceType);
- bFound = TRUE;
- break;
- }
- } else {
- for(int j=0; j<sizeModelList; ++j)
- {
- if(!_strnicmp(lpRasDevInfo[i].szDeviceType, modelList[j], strlen(modelList[j])))
- {
- specialRasDevInfo.dwSize = strlen(modelList[j]);
- strcpy_s(specialRasDevInfo.szDeviceName, lpRasDevInfo[i].szDeviceName);
- strcpy_s(specialRasDevInfo.szDeviceType, lpRasDevInfo[i].szDeviceType);
- Dbg("found it 2: %s::%s", specialRasDevInfo.szDeviceName,
- specialRasDevInfo.szDeviceType);
- bFound = TRUE;
- break;
- }
- }
- }
- }
- }
- }
- //Deallocate memory for the connection buffer
- HeapFree(GetProcessHeap(), 0, lpRasDevInfo);
- lpRasDevInfo = NULL;
- if(!bFound) {
- Dbg("Cannot found the modem :%s", lpcszDevName);
- if(!bOrigin) m_csErrMsg = "所对应的调制解调器不存在!";
- return -1;
- }
- }
- }
- LPRASENTRY lpDefaultRasEntry = NULL;
- LPBYTE lpDefaultDeviceInfo = NULL;
- DWORD dwDefaultEntrySize = 0;
- DWORD dwDefaultInforSize = 0;
- {
- if((dwRet = RasGetEntryProperties(NULL, "", NULL,
- &dwDefaultEntrySize, NULL, &dwDefaultInforSize)) != 0)
- {
- if(dwRet == ERROR_BUFFER_TOO_SMALL)
- {
- lpDefaultRasEntry = (LPRASENTRY) HeapAlloc(
- GetProcessHeap(), HEAP_ZERO_MEMORY, dwDefaultEntrySize);
- if(dwDefaultInforSize != 0) {
- lpDefaultDeviceInfo = (LPBYTE) HeapAlloc(
- GetProcessHeap(), HEAP_ZERO_MEMORY, dwDefaultInforSize);
- Dbg("dwDefaultInforSize: %u", dwDefaultInforSize);
- }
- lpDefaultRasEntry->dwSize = sizeof(RASENTRY);
- if((dwRet = RasGetEntryProperties(NULL, "", lpDefaultRasEntry, &dwDefaultEntrySize,
- lpDefaultDeviceInfo, &dwDefaultInforSize)) != 0) {
- Dbg("RasGetEntryProperties twice failed");
- if(lpDefaultRasEntry) {
- HeapFree(GetProcessHeap(), 0, lpDefaultRasEntry);
- lpDefaultRasEntry = NULL;
- }
- if(lpDefaultDeviceInfo) {
- HeapFree(GetProcessHeap(), 0, lpDefaultDeviceInfo);
- lpDefaultDeviceInfo = NULL;
- }
- if(!bOrigin) m_csErrMsg = "RasGetEntryProperties error";
- return -1;
- }
- }
- else {
- Dbg("RasGetEntryProperties failed : %d", dwRet);
- if(!bOrigin) m_csErrMsg = "RasGetEntryProperties error";
- return -1;
- }
- } else {
- Dbg("RasGetEntryProperties improper : %d", dwRet);
- if(!bOrigin) m_csErrMsg = "RasGetEntryProperties improper";
- return -1;
- }
- }
- RASENTRY rasEntry;
- ZeroMemory(&rasEntry, sizeof(RASENTRY));
- /*
- rasEntry.dwSize = sizeof(RASENTRY);
- rasEntry.dwCountryCode = 86;
- rasEntry.dwCountryID = 86;
- rasEntry.dwDialExtraPercent = 75;
- rasEntry.dwDialExtraSampleSeconds = 120;
- rasEntry.dwDialMode = RASEDM_DialAll;
- rasEntry.dwEncryptionType = 3;
- rasEntry.dwfNetProtocols = RASNP_Ip;
- rasEntry.dwfOptions = RASEO_RequirePAP | RASEO_RequireMsCHAP2;
- if((RASEO_RequireMsCHAP2 | RASEO_RequireMsCHAP | RASEO_RequireCHAP
- | RASEO_PreviewDomain | RASEO_PreviewUserPw
- | RASEO2_DisableClassBasedStaticRoute | RASEO2_IPv6ExplicitMetric | RASEO2_IPv4ExplicitMetric
- | RASEO2_SharePhoneNumbers | RASEO2_ReconnectIfDropped
- | RASEO2_UsePreSharedKey) == 1024262928)
- {
- Dbg("the same options mask.");
- }
- rasEntry.dwfOptions2 = 367;
- rasEntry.dwFramingProtocol = RASFP_Ppp;
- rasEntry.dwHangUpExtraPercent = 10;
- rasEntry.dwHangUpExtraSampleSeconds = 120;
- rasEntry.dwRedialCount = 3;
- rasEntry.dwRedialPause = 60;
- rasEntry.dwType = RASET_Phone; //指定电话薄条目类型,这里指明是电话线
- rasEntry.dwVpnStrategy = VS_Default;
- */
- assert(lpDefaultRasEntry != NULL);
- memcpy_s(&rasEntry, sizeof(RASENTRY), lpDefaultRasEntry, sizeof(RASENTRY));
- rasEntry.dwSize = sizeof(RASENTRY);
- DWORD dwTempMask = ~(RASEO_RequireCHAP | RASEO_RequireMsCHAP2 | RASEO_RequirePAP);
- Dbg("test: 0x%08X, 0x%08X", rasEntry.dwfOptions, dwTempMask);
- if(bOrigin) {
- rasEntry.dwfOptions &= (~RASEO_RequireCHAP);
- } else {
- rasEntry.dwfOptions &= dwTempMask;
- if((pNewInfo->usAPType & AUPR_PAP) == AUPR_PAP) {
- rasEntry.dwfOptions |= RASEO_RequirePAP;
- }
- if((pNewInfo->usAPType & AUPR_CHAP) == AUPR_CHAP) {
- rasEntry.dwfOptions |= RASEO_RequireCHAP;
- }
- if((pNewInfo->usAPType & AUPR_MSV2) == AUPR_MSV2) {
- rasEntry.dwfOptions |= RASEO_RequireMsCHAP2;
- }
- }
- Dbg("Use default entry !!! 0X%08X", rasEntry.dwfOptions);
- strcpy_s(rasEntry.szDeviceName, specialRasDevInfo.szDeviceName);
- strcpy_s(rasEntry.szDeviceType, specialRasDevInfo.szDeviceType);
- if(bOrigin) {
- strcpy_s(rasEntry.szLocalPhoneNumber, (LPCTSTR)m_csPhoneNum);
- } else {
- strcpy_s(rasEntry.szLocalPhoneNumber, (LPCTSTR)pNewInfo->strPhoneNum);
- }
- if(lpDefaultRasEntry) {
- HeapFree(GetProcessHeap(), 0, lpDefaultRasEntry);
- lpDefaultRasEntry = NULL;
- }
- if(lpDefaultDeviceInfo) {
- HeapFree(GetProcessHeap(), 0, lpDefaultDeviceInfo);
- lpDefaultDeviceInfo = NULL;
- }
- DWORD dwValid = 0;
- if(bOrigin) {
- dwValid = RasValidateEntryName(NULL, m_csEntryName);
- if(dwValid != ERROR_SUCCESS && dwValid != ERROR_ALREADY_EXISTS){
- if(dwValid == ERROR_INVALID_NAME){
- Dbg("EntryName(%s) is invalid format", (LPCTSTR)m_csEntryName);
- }else{
- Dbg("validate entry name (%s) failed: %d", (LPCTSTR)m_csEntryName, dwValid);
- }
- return -1;
- }
- } else {
- dwValid = RasValidateEntryName(NULL, pNewInfo->strProfileDesc);
- if(dwValid != ERROR_SUCCESS && dwValid != ERROR_ALREADY_EXISTS){
- if(dwValid == ERROR_INVALID_NAME){
- Dbg("EntryName(%s) is invalid format", (LPCTSTR)pNewInfo->strProfileDesc);
- }else{
- Dbg("validate entry name (%s) failed: %d", (LPCTSTR)pNewInfo->strProfileDesc, dwValid);
- }
- m_csErrMsg = CSimpleStringA::Format("连接名称[%s]校验无效:0x%X", (LPCTSTR)pNewInfo->strProfileDesc, dwValid);
- return -1;
- }
- }
- if(dwValid == ERROR_ALREADY_EXISTS)
- {
- if(!bOrigin) {
- m_csErrMsg = CSimpleStringA::Format("该连接名称[%s]已存在!", (LPCTSTR)pNewInfo->strProfileDesc);
- return -1;
- }
- Dbg("EntryName(%s) is already existed", (LPCTSTR)m_csEntryName);
- }
- DWORD dwSetEntry = ERROR_SUCCESS;
- LPCTSTR lpcszTmpVpn = NULL;
- if(bOrigin) {
- lpcszTmpVpn = (LPCTSTR)m_csVpnName;
- } else {
- lpcszTmpVpn = (LPCTSTR)pNewInfo->strAccessString;
- }
- //TODO APN
- if(lpcszTmpVpn != NULL && strlen(lpcszTmpVpn) > 0)
- {
- BYTE lpb[436];
- size_t szLen = strlen(lpcszTmpVpn);
- CSimpleStringW lpwczTmpVpn = CSimpleStringA2W(CSimpleStringA(lpcszTmpVpn));
- int szWlen = wcslen((LPCWSTR)lpwczTmpVpn);
- DWORD dwSizeOflpb = sizeof(lpb);
- memset(lpb, 0, dwSizeOflpb);
- lpb[0]=180, lpb[1]=1, lpb[4]=180,lpb[5]=1;
- lpb[8]=180, lpb[9]=1, lpb[12]=1, lpb[16]=15;
- lpb[20]=1, lpb[24]=2, lpb[76]=1, lpb[80]=2, lpb[84]=2;
- for(int i=0,stip=0; i<szWlen; ++i, stip+=2) {
- *(lpb + 88 + stip) = (BYTE)(lpwczTmpVpn[i]);
- }
- lpb[344] = 1;
- lpb[248] = 1;
- dwSetEntry = RasSetEntryProperties(NULL, bOrigin ? m_csEntryName : pNewInfo->strProfileDesc, &rasEntry, sizeof(rasEntry)
- , lpb, dwSizeOflpb);
- if (dwSetEntry == ERROR_SUCCESS){
- Dbg("set entry(%s) with lpb successfully.", (LPCTSTR)(bOrigin ? m_csEntryName : pNewInfo->strProfileDesc));
- } else {
- Dbg("set entry(%s) with lpb(%s) failed: %d", (LPCTSTR)(bOrigin ? m_csEntryName : pNewInfo->strProfileDesc), lpcszTmpVpn, dwSetEntry);
- }
- }
- else
- {
- //lpbDeviceInfo 参数是一个指向缓冲区的指针,该缓冲区中包含TAPI设备的配置信息。
- //在Windows 2000和Windows NT平台上,没有使用这个参数,因此,应该设为NULL。
- dwSetEntry = RasSetEntryProperties(NULL, bOrigin ? m_csEntryName : pNewInfo->strProfileDesc, &rasEntry, sizeof(rasEntry), NULL, 0);
- if(dwSetEntry == ERROR_SUCCESS) {
- Dbg("set entry(%s) successfully.", (LPCTSTR)(bOrigin ? m_csEntryName : pNewInfo->strProfileDesc));
- } else {
- Dbg("set entry(%s) failed: %d", (LPCTSTR)(bOrigin ? m_csEntryName : pNewInfo->strProfileDesc), dwSetEntry);
- }
- }
- if (dwSetEntry == ERROR_SUCCESS){
- do {
- if((dwRet = RasGetEntryProperties(NULL, bOrigin ? m_csEntryName : pNewInfo->strProfileDesc, NULL,
- &dwDefaultEntrySize, NULL, &dwDefaultInforSize)) != 0) {
- if(dwRet == ERROR_BUFFER_TOO_SMALL) {
- lpDefaultRasEntry = (LPRASENTRY) HeapAlloc(
- GetProcessHeap(), HEAP_ZERO_MEMORY, dwDefaultEntrySize);
- if(dwDefaultInforSize != 0) {
- lpDefaultDeviceInfo = (LPBYTE) HeapAlloc(
- GetProcessHeap(), HEAP_ZERO_MEMORY, dwDefaultInforSize);
- Dbg("dwDefaultInforSize2: %u", dwDefaultInforSize);
- }
- lpDefaultRasEntry->dwSize = sizeof(RASENTRY);
- if((dwRet = RasGetEntryProperties(NULL, bOrigin ? m_csEntryName : pNewInfo->strProfileDesc,
- lpDefaultRasEntry, &dwDefaultEntrySize,
- lpDefaultDeviceInfo, &dwDefaultInforSize)) != 0) {
- Dbg("RasGetEntryProperties2 twice failed");
- break;
- }
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- CSimpleStringA csEntryGUID = GuidToString(lpDefaultRasEntry->guidId);
- spConfigRun->WriteConfigValue(csEntryGUID, "Type", "RAS");
- spConfigRun->WriteConfigValue(csEntryGUID, "Status", "Create");
- if(!bOrigin) {
- spConfigRun->WriteConfigValue(csEntryGUID, "EntryName", pNewInfo->strProfileDesc);
- spConfigRun->WriteConfigValue(csEntryGUID, "PhoneNum", pNewInfo->strPhoneNum);
- spConfigRun->WriteConfigValue(csEntryGUID, "UserName", pNewInfo->strUserName);
- #ifdef USING_ENCRYPT
- CSimpleStringA csEValue = EncryptString(pNewInfo->strPassword);
- spConfigRun->WriteConfigValue(csEntryGUID, "Password", csEValue);
- #else
- spConfigRun->WriteConfigValue(csEntryGUID, "Password", pNewInfo->strPassword);
- #endif
- spConfigRun->WriteConfigValue(csEntryGUID, "APN", pNewInfo->strAccessString);
-
- } else {
- spConfigRun->WriteConfigValue(csEntryGUID, "EntryName", m_csEntryName);
- spConfigRun->WriteConfigValue(csEntryGUID, "PhoneNum", m_csPhoneNum);
- spConfigRun->WriteConfigValue(csEntryGUID, "UserName", m_csUserName);
- #ifdef USING_ENCRYPT
- CSimpleStringA csEValue = EncryptString(m_csPassword);
- spConfigRun->WriteConfigValue(csEntryGUID, "Password", csEValue);
- #else
- spConfigRun->WriteConfigValue(csEntryGUID, "Password", m_csPassword);
- #endif
- spConfigRun->WriteConfigValue(csEntryGUID, "APN", m_csVpnName);
- }
- }
- else {
- Dbg("RasGetEntryProperties2 failed : %d", dwRet);
- break;
- }
- } else {
- Dbg("RasGetEntryProperties2 improper : %d", dwRet);
- break;
- }
- } while (FALSE);
- if(lpDefaultRasEntry) {
- HeapFree(GetProcessHeap(), 0, lpDefaultRasEntry);
- lpDefaultRasEntry = NULL;
- }
- if(lpDefaultDeviceInfo) {
- HeapFree(GetProcessHeap(), 0, lpDefaultDeviceInfo);
- lpDefaultDeviceInfo = NULL;
- }
- return 0;
- }
- return -1;
- }
- ErrorCodeEnum CMobileDialFSM::UpdateEntryInfo(LPCTSTR lpcszEntryGUID, const AccessKeyInfo& newInfo, bool fApplyNow)
- {
- ErrorCodeEnum rc = Error_Unexpect;
- CSmartPointer<IConfigInfo> spConfigRun;
- rc = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- CSimpleStringA csValue;
- CSimpleStringA csEntryName(true);
- bool fRuncfgMark = true;
- bool fReCreate = false;
- if(Error_Succeed != spConfigRun->ReadConfigValue(lpcszEntryGUID, "Status", csValue)
- || csValue.GetLength() <= 0 || csValue.IsStartWith("Invalid")) {
- int cnt = m_rasEntries.GetCount();
- for(int i=0; i<cnt; ++i) {
- if(!strcmp(m_rasEntries[i].szGUID, lpcszEntryGUID)) {
- csEntryName = m_rasEntries[i].szEntryName;
- fRuncfgMark = false;
- break;
- }
- }
- } else {
- spConfigRun->ReadConfigValue(lpcszEntryGUID, "EntryName", csEntryName);
- }
- Dbg("UpdateEntryInfo(%s),mark(%d)", lpcszEntryGUID, fRuncfgMark);
- if(csEntryName.GetLength() <= 0) {
- m_csErrMsg = "获取电话簿名称失败";
- return Error_NotExist;
- }
- DWORD dwValide = RasValidateEntryName(NULL, csEntryName);
- if(dwValide == ERROR_ALREADY_EXISTS) {
- Dbg("The entry is comfirmed exist, so it seems normal ??");
- Dbg("DealConnctionActivity returned: %d", DealConnctionActivity(csEntryName));
- dwValide = RasDeleteEntry(NULL, csEntryName);
- if(dwValide == ERROR_SUCCESS) {
- Dbg("Delete the previous one succ.");
- fReCreate = true;
- } else {
- Dbg("Delete entry(%s) failed: %d", (LPCTSTR)csEntryName, dwValide);
- m_csErrMsg = CSimpleStringA::Format("更新前清理电话簿失败 : %d", dwValide);
- return Error_Unexpect;
- ERROR_INVALID_NAME;
- }
- } else {
- Dbg("Valid entry name return: %d", dwValide);
- m_csErrMsg = "校验电话簿名称失败";
- return Error_Unexpect;
- }
- Dbg("Update EntryName: %s", (LPCTSTR)csEntryName);
- LPRASENTRY lpRasentry = NULL;
- LPBYTE lpDevInfo = NULL;
- DWORD dwEntrySz = 0, dwDevInfoSz = 0;
- DWORD dwRet = RasGetEntryProperties(NULL, /*(LPCTSTR)csEntryName*/"", NULL, &dwEntrySz, NULL, &dwDevInfoSz);
- if(dwRet == ERROR_BUFFER_TOO_SMALL) {
- if(dwEntrySz != 0) {
- lpRasentry = (LPRASENTRY)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwEntrySz);
- if(dwDevInfoSz != 0)
- lpDevInfo = (LPBYTE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwDevInfoSz);
- }
- if(lpRasentry == NULL) {
- m_csErrMsg = "分配内存失败";
- return Error_Resource;
- }
- lpRasentry->dwSize = sizeof(RASENTRY);
- dwRet = RasGetEntryProperties(NULL, /*(LPCTSTR)csEntryName*/"", lpRasentry, &dwEntrySz, lpDevInfo, &dwDevInfoSz);
- if(dwRet != ERROR_SUCCESS) {
- if(lpRasentry) {
- HeapFree(GetProcessHeap(), 0, lpRasentry);
- lpRasentry = NULL;
- }
- if(lpDevInfo) {
- HeapFree(GetProcessHeap(), 0, lpDevInfo);
- lpDevInfo = NULL;
- }
- m_csErrMsg = CSimpleStringA::Format("RasGetEntryProperties failed: %d", dwRet);
- return Error_Unexpect;
- }
- RASENTRY rasEntry;
- ZeroMemory(&rasEntry, sizeof(RASENTRY));
- memcpy_s(&rasEntry, sizeof(RASENTRY), lpRasentry, sizeof(RASENTRY));
- rasEntry.dwSize = sizeof(RASENTRY);
- DWORD dwTempMask = ~(RASEO_RequireCHAP | RASEO_RequireMsCHAP2 | RASEO_RequirePAP);
- rasEntry.dwfOptions &= dwTempMask;
- if((newInfo.usAPType & AUPR_PAP) == AUPR_PAP) {
- rasEntry.dwfOptions |= RASEO_RequirePAP;
- Dbg("Add: AUPR_PAP");
- }
- if((newInfo.usAPType & AUPR_CHAP) == AUPR_CHAP) {
- rasEntry.dwfOptions |= RASEO_RequireCHAP;
- Dbg("Add: AUPR_CHAP");
- }
- if((newInfo.usAPType & AUPR_MSV2) == AUPR_MSV2) {
- rasEntry.dwfOptions |= RASEO_RequireMsCHAP2;
- Dbg("Add: AUPR_MSV2");
- }
- strcpy_s(rasEntry.szLocalPhoneNumber, (LPCTSTR)newInfo.strPhoneNum);
- if(lpRasentry) {
- HeapFree(GetProcessHeap(), 0, lpRasentry);
- lpRasentry = NULL;
- }
- if(lpDevInfo) {
- HeapFree(GetProcessHeap(), 0, lpDevInfo);
- lpDevInfo = NULL;
- }
- //TODO: AccessString
- BYTE lpb[436];
- DWORD dwSizeOflpb = 0;
- bool fHaveApn = false;
- if(!newInfo.strAccessString.IsNullOrEmpty()) {
- fHaveApn = true;
- size_t szLen = strlen(newInfo.strAccessString);
- CSimpleStringW lpwczTmpVpn = CSimpleStringA2W(newInfo.strAccessString);
- int szWlen = wcslen((LPCWSTR)lpwczTmpVpn);
- dwSizeOflpb = sizeof(lpb);
- memset(lpb, 0, dwSizeOflpb);
- lpb[0]=180, lpb[1]=1, lpb[4]=180,lpb[5]=1;
- lpb[8]=180, lpb[9]=1, lpb[12]=1, lpb[16]=15;
- lpb[20]=1, lpb[24]=2, lpb[76]=1, lpb[80]=2, lpb[84]=2;
- for(int i=0,stip=0; i<szWlen; ++i, stip+=2) {
- *(lpb + 88 + stip) = (BYTE)(lpwczTmpVpn[i]);
- }
- lpb[344] = 1;
- lpb[248] = 1;
- Dbg("Have accss string: %s", (LPCTSTR)newInfo.strAccessString);
- }
- dwRet = RasSetEntryProperties(NULL, (LPCTSTR)csEntryName, &rasEntry, sizeof(rasEntry),
- fHaveApn ? lpb : NULL, dwSizeOflpb);
- if(dwRet == ERROR_SUCCESS) {
- Dbg("update entry(%s) successfully.", (LPCTSTR)csEntryName);
- } else {
- Dbg("update entry(%s) failed: %d", (LPCTSTR)csEntryName, dwRet);
- if(lpRasentry) {
- HeapFree(GetProcessHeap(), 0, lpRasentry);
- lpRasentry = NULL;
- }
- if(lpDevInfo) {
- HeapFree(GetProcessHeap(), 0, lpDevInfo);
- lpDevInfo = NULL;
- }
- m_csErrMsg = CSimpleStringA::Format("RasSetEntryProperties failed: %d", dwRet);
- return Error_Unexpect;
- }
- //RASCREDENTIALS credentials;
- //memset(&credentials, 0, sizeof(RASCREDENTIALS));
- //credentials.dwSize = sizeof(RASCREDENTIALS);
- //dwRet = RasGetCredentials(NULL, csEntryName, &credentials);
- //if(dwRet == ERROR_SUCCESS) {
- // Dbg("Old UserName: %s", credentials.szUserName);
- // Dbg("Old Password: %s", credentials.szPassword);
- // Dbg("Old Mask: 0x%X", credentials.dwMask);
- // strcpy_s(credentials.szUserName, newInfo.strUserName);
- // strcpy_s(credentials.szPassword, newInfo.strPassword);
- // strcpy_s(credentials.szDomain, "");
- // credentials.dwMask = 0;
- // credentials.dwSize = sizeof(RASCREDENTIALS);
- // dwRet = RasSetCredentials(NULL, csEntryName, &credentials, FALSE);
- // if(dwRet == 0) {
- // Dbg("RasSetCredentials succ");
- // } else {
- // Dbg("RasSetCredentials failed: %d", dwRet);
- // }
- //} else {
- // Dbg("RasGetCredentials failed: %d", dwRet);
- //}
- CSimpleStringA csUpdatedGUID;
- bool fAborted = false;
- if(fReCreate) {
- do {
- fAborted = true;
- if((dwRet = RasGetEntryProperties(NULL, csEntryName, NULL,
- &dwEntrySz, NULL, &dwDevInfoSz)) != 0) {
- if(dwRet == ERROR_BUFFER_TOO_SMALL) {
- lpRasentry = (LPRASENTRY) HeapAlloc(
- GetProcessHeap(), HEAP_ZERO_MEMORY, dwEntrySz);
- if(dwDevInfoSz != 0) {
- lpDevInfo = (LPBYTE) HeapAlloc(
- GetProcessHeap(), HEAP_ZERO_MEMORY, dwDevInfoSz);
- Dbg("dwDevInfoSz: %u", dwDevInfoSz);
- }
- lpRasentry->dwSize = sizeof(RASENTRY);
- if((dwRet = RasGetEntryProperties(NULL, (LPCTSTR)csEntryName,
- lpRasentry, &dwEntrySz, lpDevInfo, &dwDevInfoSz)) != 0) {
- Dbg("RasGetEntryProperties twice failed");
- break;
- }
- csUpdatedGUID = GuidToString(lpRasentry->guidId);
- if(!csUpdatedGUID.IsNullOrEmpty()) {
- fAborted = false;
- }
- }
- else {
- Dbg("RasGetEntryProperties3 failed : %d", dwRet);
- break;
- }
- } else {
- Dbg("RasGetEntryProperties3 improper : %d", dwRet);
- break;
- }
- } while (FALSE);
- } else {
- csUpdatedGUID = lpcszEntryGUID;
- }
- if(!fAborted) {
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- spConfigRun->WriteConfigValue(csUpdatedGUID, "Status", "Update");
- if(!fRuncfgMark || fReCreate) {
- spConfigRun->WriteConfigValue(csUpdatedGUID, "Type", "RAS");
- spConfigRun->WriteConfigValue(csUpdatedGUID, "EntryName", newInfo.strProfileDesc);
- if(fReCreate) {
- spConfigRun->WriteConfigValue(lpcszEntryGUID, "Status", "Invalid-Update-Delete");
- spConfigRun->WriteConfigValue(lpcszEntryGUID, "EntryName", "");
- spConfigRun->WriteConfigValue(lpcszEntryGUID, "PhoneNum", "");
- spConfigRun->WriteConfigValue(lpcszEntryGUID, "UserName", "");
- spConfigRun->WriteConfigValue(lpcszEntryGUID, "Password", "");
- spConfigRun->WriteConfigValue(lpcszEntryGUID, "APN", "");
- Sleep(800);
- }
- }
- spConfigRun->WriteConfigValue(csUpdatedGUID, "PhoneNum", newInfo.strPhoneNum);
- spConfigRun->WriteConfigValue(csUpdatedGUID, "UserName", newInfo.strUserName);
- #ifdef USING_ENCRYPT
- CSimpleStringA csEValue = EncryptString(newInfo.strPassword);
- spConfigRun->WriteConfigValue(csUpdatedGUID, "Password", csEValue);
- #else
- spConfigRun->WriteConfigValue(csUpdatedGUID, "Password", newInfo.strPassword);
- #endif
- spConfigRun->WriteConfigValue(csUpdatedGUID, "APN", newInfo.strAccessString);
- }
- if(lpRasentry) {
- HeapFree(GetProcessHeap(), 0, lpRasentry);
- lpRasentry = NULL;
- }
- if(lpDevInfo) {
- HeapFree(GetProcessHeap(), 0, lpDevInfo);
- lpDevInfo = NULL;
- }
- m_csErrMsg = "";
- return fAborted ? Error_Unexpect : Error_Succeed;
- }else {
- m_csErrMsg = CSimpleStringA::Format("RasGetEntryProperties failed: %d", dwRet);
- return Error_Unexpect;
- }
- }
- BOOL CMobileDialFSM::SetGlobalConnectState(LPCTSTR lpcszEntryGUID, const RASCONNSTATE state)
- {
- int cnt = g_DongleInfos.GetCount();
- int aim = -1;
- for(int i=0; i<cnt && aim == -1; ++i) {
- if(g_DongleInfos[i].usDeviceType == DEVTYPE_MODEM) {
- int cnt2 = g_DongleInfos[i].profileList.GetCount();
- if(cnt2 > 0) {
- MBNProfileList& profiles = g_DongleInfos[i].profileList;
- for(int j=0; j<cnt2; ++j) {
- if(!profiles[j].strProfileName.Compare(lpcszEntryGUID)) {
- aim = i;
- Dbg("Set the connState of entry : %s", (LPCTSTR)profiles[j].AccessInfo.strProfileDesc);
- break;
- }
- }
- }
- }
- }
- if(aim == -1) {
- return FALSE;
- }
- if(state == RASCS_Connected) {
- g_DongleInfos[aim].subInfo.mbnCntState = MBN_ACTIVATION_STATE_ACTIVATED;
- g_DongleInfos[aim].subInfo.strProfileName = lpcszEntryGUID;
- g_DongleInfos[aim].state = MBD_ACTIVATION_CONNECTED;
- } else if(g_DongleInfos[aim].state == MBD_ACTIVATION_CONNECTED) {
- if(g_DongleInfos[aim].subInfo.strProfileName.GetLength() > 0) {
- if(!g_DongleInfos[aim].subInfo.strProfileName.Compare(lpcszEntryGUID)) {
- //TODO: more various situation?
- g_DongleInfos[aim].subInfo.mbnCntState = MBN_ACTIVATION_STATE_DEACTIVATED;
- g_DongleInfos[aim].subInfo.strProfileName = "";
- g_DongleInfos[aim].state = MBD_ACTIVATION_DISCONNECTED;
- }
- }
- }
- return TRUE;
- }
- int CMobileDialFSM::Dial3GConnect()
- {
- LOG_FUNCTION();
- m_34GReserved = 3;
- if(m_34GDialSuc == 3) {
- m_34GDialSuc = 0;
- }
- if (EnumPhoneEntry() != 0) {
- Dbg("no sepecified entry(%s), begin to create it...", (LPCTSTR)m_csEntryName);
- if(CreatePhoneEntry() != 0) {
- Dbg("Create phone entry failed.");
- SetRasStatus(MBD_CREATE_ENTRY_FAILED);
- return 0;
- }else{
- Dbg("Create phone entry suc.");
- }
- }
- RASDIALPARAMS Rasparam;
- Rasparam.dwSize=sizeof(RASDIALPARAMS);
- strcpy_s(Rasparam.szPhoneNumber,m_csPhoneNum);
- strcpy_s(Rasparam.szEntryName,m_csEntryName);
- strcpy_s(Rasparam.szUserName,m_csUserName);
- strcpy_s(Rasparam.szPassword,m_csPassword);
- strcpy_s(Rasparam.szDomain, "");
- if(g_hrasconn != NULL) {
- Dbg("g_hrasconn has value !");
- RasHangUpSuffix();
- }
- DWORD dwDial = RasDial(NULL, NULL, &Rasparam, 0, /*&CustomRasDialFunc*/NULL, &g_hrasconn);
- if (dwDial == ERROR_SUCCESS) {
- Dbg("3g condition, ras dial successfully ");
- SetRasStatus(MBD_ACTIVATION_CONNECTING);
- {
- CSmartPointer<IConfigInfo> spConfigRun;
- CSimpleStringA csValue;
- CSimpleStringA csEntryGUID;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- if(Error_Succeed == spConfigRun->ReadConfigValue("RAS", "EntryGUID", csEntryGUID)
- && !csEntryGUID.IsNullOrEmpty()) {
- Dbg("Update original dial param.");
- if(Error_Succeed == spConfigRun->ReadConfigValue(csEntryGUID, "Status", csValue)
- && !csValue.Compare("Invalid-Temporary")) {
- spConfigRun->WriteConfigValue(csEntryGUID, "Type", "RAS");
- spConfigRun->WriteConfigValue(csEntryGUID, "EntryName", m_csEntryName);
- spConfigRun->WriteConfigValue(csEntryGUID, "PhoneNum", m_csPhoneNum);
- spConfigRun->WriteConfigValue(csEntryGUID, "UserName", m_csUserName);
- #ifdef USING_ENCRYPT
- CSimpleStringA csEValue = EncryptString(m_csPassword);
- spConfigRun->WriteConfigValue(csEntryGUID, "Password", csEValue);
- #else
- spConfigRun->WriteConfigValue(csEntryGUID, "Password", m_csPassword);
- #endif
- spConfigRun->WriteConfigValue(csEntryGUID, "APN", m_csVpnName);
- spConfigRun->WriteConfigValue(csEntryGUID, "Status", "Init");
- spConfigRun->WriteConfigValue("RAS", "EntryGUID", "");
- }
- }
- }
- m_34GDialSuc = 3;
- return 1;
- }
- //hardly useful.
- //Condition1: replaced by disconnect from mbn.
- //Condition2: repalced by error_socket or timeout even invalid connect from fsm.
- SetCurState(MBD_CONNECTION_FAILURE);
- _FormatRasError(dwDial);
- if(g_hrasconn != NULL) {
- RasHangUpSuffix();
- }
- SetRasStatus(MBD_CONNECTION_FAILURE);
- return 0;
- }
- int CMobileDialFSM::Dial3GConnectEx(LPCTSTR lpcszDevName, LPCTSTR lpcszEntryGUID)
- {
- LOG_FUNCTION();
-
- if(GetCurState() == MBD_ACTIVATION_CONNECTED) {
- assert(FALSE && "不应该处于已连接的状态");
- SetRasStatus(MBD_UNKNOWN);
- return 0;
- }
- m_34GReserved = 3;
- if(m_34GDialSuc == 3) {
- m_34GDialSuc = 0;
- }
- CSmartPointer<IConfigInfo> spConfigRun;
- ErrorCodeEnum rc = Error_NoDefine;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- CSimpleStringA csValue;
- CSimpleStringA csPhoneNum;
- CSimpleStringA csEntryName;
- CSimpleStringA csUserName;
- CSimpleStringA csPassword;
- CSimpleStringA csVpn;
- if(Error_Succeed == spConfigRun->ReadConfigValue(lpcszEntryGUID, "Status", csValue)
- && csValue.GetLength() > 0) {
- if(csValue.IsStartWith("Invalid")) {
- Dbg("the runcfg record for %s is invalid : %s", lpcszEntryGUID, (LPCTSTR)csValue);
- m_csErrMsg = CSimpleStringA::Format("运行时配置信息无效:%s", (LPCTSTR)csValue);
- return -1;
- }
- spConfigRun->ReadConfigValue(lpcszEntryGUID, "EntryName", csEntryName);
- spConfigRun->ReadConfigValue(lpcszEntryGUID, "PhoneNum", csPhoneNum);
- spConfigRun->ReadConfigValue(lpcszEntryGUID, "UserName", csUserName);
- #ifdef USING_ENCRYPT
- spConfigRun->ReadConfigValue(lpcszEntryGUID, "Password", csValue);
- csPassword = DecryptString(csValue);
- #else
- spConfigRun->ReadConfigValue(lpcszEntryGUID, "Password", csPassword);
- #endif
- spConfigRun->ReadConfigValue(lpcszEntryGUID, "APN", csVpn);
- }else {
- Dbg("runcfg is not exist ras record for %s", lpcszEntryGUID);
- m_csErrMsg = "在运行时配置信息中未找到拨号参数";
- SetRasStatus(MBD_RUN_ENTRY_NOTFOUND);
- return -1;
- }
- RASDIALPARAMS Rasparam;
- memset(&Rasparam, 0, sizeof(RASDIALPARAMS));
- Rasparam.dwSize=sizeof(RASDIALPARAMS);
- strcpy_s(Rasparam.szPhoneNumber, csPhoneNum);
- strcpy_s(Rasparam.szEntryName, csEntryName);
- strcpy_s(Rasparam.szUserName, csUserName);
- strcpy_s(Rasparam.szPassword, csPassword);
- strcpy_s(Rasparam.szDomain, "");
- if(g_hrasconn != NULL) {
- RasHangUpSuffix();
- }
- bool bAsyn = !!(m_hRasListenThread != NULL);
- if(bAsyn) {
- // LogEvent(Severity_Low, Error_NoDefine, "Cancel the Ras asy dial!");
- // bAsyn = false;
- }
- DWORD dwDial = RasDial(NULL, NULL, &Rasparam, 0, bAsyn ? &CustomRasDialFunc : NULL, &g_hrasconn);
- if (dwDial == ERROR_SUCCESS) {
- Dbg("3g condition, ras dial successfully bAsyn:%d", bAsyn);
- if(m_recentInfo.usDialType == CNT_INVALID
- || (m_recentInfo.strDongle.Compare(lpcszDevName) || m_recentInfo.strProfile.Compare(lpcszEntryGUID) )) {
- Dbg("Store the new dial param.");
- m_34GDialSuc = 3;
- m_recentInfo.usDialType = CNT_RAS;
- m_recentInfo.strDongle = lpcszDevName;
- m_recentInfo.strProfile = lpcszEntryGUID;
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- spConfigRun->WriteConfigValue("Recent", "Type", "RAS");
- spConfigRun->WriteConfigValue("Recent", "Dongle", m_recentInfo.strDongle);
- spConfigRun->WriteConfigValue("Recent", "Profile", m_recentInfo.strProfile);
- spConfigRun->WriteConfigValueInt("Recent", "Manual", 0);
- spConfigRun->WriteConfigValueHexInt("Recent", "RequestID", (ULONG)g_hrasconn);
- } else if(m_recentInfo.usDialType == CNT_RAS) {
- m_recentInfo.ulRequestID = (ULONG)g_hrasconn;
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- spConfigRun->WriteConfigValueHexInt("Recent", "RequestID", (ULONG)g_hrasconn);
- }
- SetRasStatus(MBD_ACTIVATION_CONNECTING);
- m_34GDialSuc = 3;
- return 1;
- }
- _FormatRasError(dwDial);
- if(g_hrasconn != NULL) {
- RasHangUpSuffix();
- }
- SetRasStatus(MBD_CONNECTION_FAILURE);
- return 0;
- }
- int CMobileDialFSM::Dial4GConnect()
- {
- m_34GReserved = 4;
- if(m_pMbn->Connect()) {
- Dbg("4g condition, mbn connect successfully");
- m_34GDialSuc = 4;
- return 1;
- }
- Dbg("4g condition, mbn connect failed.");
- return 0;
- }
- int CMobileDialFSM::Dial4GConnectEx(LPCTSTR lpcszInterface, LPCTSTR lpcszProfileName)
- {
- m_34GReserved = 4;
- if(m_34GDialSuc == 4) {
- m_34GDialSuc = 0;
- }
- ULONG ulResult = m_pMbn->ConnectEx2(lpcszInterface, lpcszProfileName);
- if(ulResult != (ULONG)-1) {
- Dbg("4g Dial4GConnectEx successfully");
- if(m_recentInfo.usDialType == CNT_INVALID
- || (m_recentInfo.strDongle.Compare(lpcszInterface) || m_recentInfo.strProfile.Compare(lpcszProfileName) )) {
- Dbg("Store the new dial param.");
- m_34GDialSuc = 4;
- m_recentInfo.usDialType = CNT_MBN;
- m_recentInfo.strDongle = lpcszInterface;
- m_recentInfo.strProfile = lpcszProfileName;
- m_recentInfo.ulRequestID = ulResult;
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- spConfigRun->WriteConfigValue("Recent", "Type", "MBN");
- spConfigRun->WriteConfigValue("Recent", "Dongle", m_recentInfo.strDongle);
- spConfigRun->WriteConfigValue("Recent", "Profile", m_recentInfo.strProfile);
- spConfigRun->WriteConfigValueInt("Recent", "Manual", 0);
- spConfigRun->WriteConfigValueHexInt("Recent", "RequestID", ulResult);
- } else if(m_recentInfo.usDialType == CNT_MBN) {
- m_recentInfo.ulRequestID = ulResult;
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- spConfigRun->WriteConfigValueHexInt("Recent", "RequestID", ulResult);
- }
- return 1;
- }
- if(m_34GDialSuc == 4) {
- m_34GDialSuc = 0;
- }
- Dbg("Dial4GConnectEx failed.");
- return 0;
- }
- int CMobileDialFSM::DialConnect()
- {
- static int s_x[MAX_BLACK_SHEEP_NUM];
- static int s_y[MAX_BLACK_SHEEP_NUM];
- static int s_z[MAX_BLACK_SHEEP_NUM];
- static int s_pt;
- LOG_FUNCTION();
- s_pt = 0;
- Dbg("---------- The first step arrived.");
- SetCurState(MBD_ACTIVATION_CONNECTING);
- auto state3G = GetRasStatus();
- auto state4G = m_pMbn->GetCurState();
- auto stateMBB = GetHWStatus();
- Dbg("[MBN#%s][RAS#%s][MBB#%s]",
- ConvertStatusToString(state4G), ConvertStatusToString(state3G), ConvertStatusToString(stateMBB));
- m_34GReserved = 0;
- if(m_nAdvancedGen == ADVANCE_MBB) {
- if(SwithMBBConnectStatus(TRUE)) {
- return ADVANCE_MBB;
- }
- return -1;
- }
- if(m_recentInfo.usDialType != CNT_INVALID) {
- if((m_recentInfo.usDialType == CNT_RAS && m_n3G > 0) || (m_recentInfo.usDialType == CNT_MBN && m_n4G > 0)) {
- Dbg("[%s]: Start to find the specified dial param.", m_recentInfo.usDialType == CNT_MBN ? "4G" : "3G");
- const int cnt = g_DongleInfos.GetCount();
- int aim = -1;
- Dbg("dongles'count: %d", cnt);
- for(int i=0; i<cnt; ++i) {
- if(!m_recentInfo.strDongle.Compare(g_DongleInfos[i].csInterfaceId)) {
- const int cnt2 = g_DongleInfos[i].profileList.GetCount();
- Dbg("%d", cnt2);
- for(int j=0; j<cnt2; ++j) {
- if(!m_recentInfo.strProfile.Compare(g_DongleInfos[i].profileList[j].strProfileName)) {
- Dbg("found connect profile: %s(%s)", (LPCTSTR)g_DongleInfos[i].csInterfaceId,
- (LPCTSTR)g_DongleInfos[i].profileList[j].AccessInfo.strProfileDesc);
- aim = i;
- break;
- }
- }
- if(aim != -1) {
- break;
- }
- }
- }
- if(aim != -1) {
- if(m_recentInfo.usDialType == CNT_RAS) {
- if(Dial3GConnectEx(m_recentInfo.strDongle, m_recentInfo.strProfile) > 0) {
- return 3;
- } else if(g_DongleInfos[aim].state == MBD_ACTIVATION_DISCONNECTED) {
- SetCurState(MBD_CONNECTION_FAILURE);
- return -1;
- }
- } else {
- if(Dial4GConnectEx(m_recentInfo.strDongle, m_recentInfo.strProfile) > 0) {
- return 4;
- } else if(g_DongleInfos[aim].state == MBD_ACTIVATION_DISCONNECTED) {
- SetCurState(MBD_CONNECTION_FAILURE);
- return -1;
- }
- }
- Dbg("Nonono, give you one more chance");
- } else {
- Dbg("[%s]: not found yet", m_recentInfo.usDialType == CNT_MBN ? "4G" : "3G");
- }
- }
- }
- Dbg("---------- The second step arrived.");
- int cnt = g_DongleInfos.GetCount();
- int aim = -1;
- bool fp3G = false, fp4G = false;
- for(int i=0; i<cnt; ++i) {
- int cnt2 = g_DongleInfos[i].profileList.GetCount();
- if(cnt2 > 0) {
- if(g_DongleInfos[i].usDeviceType == DEVTYPE_MODEM && !fp3G) { fp3G = true;}
- else if(g_DongleInfos[i].usDeviceType == DEVTYPE_INTER && !fp4G) { fp4G = true; }
- }
- if(g_DongleInfos[i].state != MBD_ACTIVATION_DISCONNECTED) {
- Dbg("Ignore it bcz Dongle[%d]'s state: %s", i, ConvertStatusToString(g_DongleInfos[i].state));
- continue;
- }
- if(cnt2 > 0) {
- for(int j=0; j<cnt2; ++j) {
- if(!g_DongleInfos[i].profileList[j].AccessInfo.IsDefault) {
- Dbg("Ignore it bcz Profiles[%d]'s un-default", j);
- // is not default but apply and can be used to connecting ?? [11/23/2019 15:15 @Gifur]
- if(cnt2 != 1) {
- continue;
- } else {
- Dbg("only one profile, try it.");
- }
- }
- {
- int aim2 = -1;
- for(int z=0; z<mBlackSheepCount; ++z) {
- if(!g_DongleInfos[i].csInterfaceId.Compare(m_blackSheep[z].strDongle)
- && !g_DongleInfos[i].profileList[j].strProfileName.Compare(m_blackSheep[z].strProfile)) {
- aim2 = z;
- break;
- }
- }
- if(aim2 != -1) {
- s_x[s_pt] = i, s_y[s_pt] = j;
- s_z[s_pt] = aim2;
- Dbg("blacksheep: [%d] [%d][%d][%d] ", s_pt, i, j, aim2);
- s_pt++;
- continue;
- }
- }
- if(g_DongleInfos[i].profileList[j].AccessInfo.usCntType == CNT_MBN) {
- if(Dial4GConnectEx(g_DongleInfos[i].csInterfaceId, g_DongleInfos[i].profileList[j].strProfileName) > 0) {
- aim = 4;
- Dbg("[MBN](%s)(%s) connect succ.", (LPCTSTR)g_DongleInfos[i].csInterfaceId,
- (LPCTSTR)g_DongleInfos[i].profileList[j].AccessInfo.strProfileDesc);
- break;
- }
- } else if(g_DongleInfos[i].profileList[j].AccessInfo.usCntType == CNT_RAS) {
- if(Dial3GConnectEx(g_DongleInfos[i].csInterfaceId, g_DongleInfos[i].profileList[j].strProfileName) > 0) {
- aim = 3;
- Dbg("[RAS](%s)(%s) connect succ.", (LPCTSTR)g_DongleInfos[i].csInterfaceId,
- (LPCTSTR)g_DongleInfos[i].profileList[j].AccessInfo.strProfileDesc);
- break;
- }
- }
- }
- }
- if(aim != -1) {
- return aim;
- }
- }
-
- if(s_pt > 0) {
- Dbg("---------- The third step arrived.");
- bool loop = true;
- int times = 0;
- do
- {
- DWORD dwMinError = (DWORD)-1;
- int aim3 = -1, k = -1;
- for(int i=0; i<s_pt; ++i) {
- if(s_z[i] < mBlackSheepCount && dwMinError > m_blackSheep[s_z[i]].dwErrCount) {
- aim3 = s_z[i];
- k = i;
- dwMinError = m_blackSheep[s_z[i]].dwErrCount;
- }
- }
- if(aim3 >= 0) {
- int i = s_x[k];
- int j = s_y[k];
- if(g_DongleInfos[i].profileList[j].AccessInfo.usCntType == CNT_MBN) {
- if(Dial4GConnectEx(g_DongleInfos[i].csInterfaceId, g_DongleInfos[i].profileList[j].strProfileName) > 0) {
- aim = 4;
- Dbg("BlackSheep#[MBN](%s)(%s) connect succ.", (LPCTSTR)g_DongleInfos[i].csInterfaceId,
- (LPCTSTR)g_DongleInfos[i].profileList[j].AccessInfo.strProfileDesc);
- }
- } else if(g_DongleInfos[i].profileList[j].AccessInfo.usCntType == CNT_RAS) {
- if(Dial3GConnectEx(g_DongleInfos[i].csInterfaceId, g_DongleInfos[i].profileList[j].strProfileName) > 0) {
- aim = 3;
- Dbg("BlackSheep#[RAS](%s)(%s) connect succ.", (LPCTSTR)g_DongleInfos[i].csInterfaceId,
- (LPCTSTR)g_DongleInfos[i].profileList[j].AccessInfo.strProfileDesc);
- }
- }
- if(aim != -1) {
- return aim;
- } else {
- times++;
- Dbg("Black sheep cannot connect(%d/%d) ?", times, s_pt);
- m_blackSheep[aim3].dwErrCount += 2;
- if(times >= s_pt) {
- break;
- }
- Sleep(1000);
- }
- } else {
- loop = false;
- }
- } while (loop);
- }
- Dbg("---------- The fourth step arrived.");
-
- if(m_n3G > 0) {
- if(!m_csEntryName.IsNullOrEmpty() && Dial3GConnect()) {
- return 3;
- }
- }
- SetCurState(MBD_CONNECTION_FAILURE);
- return -1;
- }
- int CMobileDialFSM::DisConnect(BOOL bManual)
- {
- LOG_FUNCTION();
- if(m_pMbn->GetCurState() == MBD_ACTIVATION_CONNECTED)
- {
- /*if(m_n4G > 0)*/if(m_pMbn->m_ulRequestID != ULONG(-1))
- {
- BOOL bRet = m_pMbn->DisConnect();
- // Description update... [Josephus in 14:37:06 2016/7/12]
- Dbg("4g Mbn disconnect return %d. requestID(%d)", bRet, m_pMbn->m_ulRequestID);
- }
- /*else if(m_n3G > 0)*/
- if(g_hrasconn != NULL)
- {
- DWORD dwRet = RasHangUp(g_hrasconn);
- Dbg("RasHangUp in Disconnect function returned %d", dwRet);
- if(dwRet == ERROR_SUCCESS)
- {
- RASCONNSTATUS connStatus;
- connStatus.dwSize = sizeof(RASCONNSTATUS);
- Dbg("TickCount after RasHangUp...");
- DWORD tcLast = GetTickCount() + 10000;
- while((RasGetConnectStatus(g_hrasconn, &connStatus)
- != ERROR_INVALID_HANDLE) && (tcLast > GetTickCount()))
- {
- Sleep(50);
- }
- Dbg("TickCount is done.");
- }
- }
- }
- RasHangUpSuffix();
- return 0;
- }
- BOOL CMobileDialFSM::Dis4GConnect(LPCTSTR lpcszInterface)
- {
- assert(m_pMbn->GetCurState() == MBD_ACTIVATION_CONNECTED);
- BOOL bRet = m_pMbn->DisConnect();
- return bRet;
- }
- int CMobileDialFSM::CreateCheckSocket()
- {
- int iResult = 0;
- if(m_sock != INVALID_SOCKET)
- {
- closesocket(m_sock);
- m_sock = INVALID_SOCKET;
- }
- m_sock = socket(AF_INET, SOCK_STREAM, 0);
- if (m_sock == INVALID_SOCKET)
- {
- m_dwLsErrCode = WSAGetLastError();
- Dbg("create socket failed with error: %d", m_dwLsErrCode);
- SetCurState(MBD_NETWORK_INVALID_SOCKET);
- return -1;
- }
- // Set socket into nonblocking mode to prevent its connection action from delaying too much
- //[Josephus in 17:17:48 2016/3/31]
- ULONG ul = 1;
- iResult = ioctlsocket(m_sock, FIONBIO, (unsigned long*)&ul);
- if(iResult == SOCKET_ERROR)
- {
- m_dwLsErrCode = WSAGetLastError();
- Dbg("Set socket into nonblocking mode failed %d", m_dwLsErrCode);
- SetCurState(MBD_NETWORK_INVALID_SOCKET);
- closesocket(m_sock);
- m_sock = INVALID_SOCKET;
- return -1;
- }
- return 0;
- }
- void CMobileDialFSM::BatteryNotifierTimeOut()
- {
- SYSTEM_POWER_STATUS sys_power_status;
- BOOL bRet = GetSystemPowerStatus(&sys_power_status);
- if (bRet != 0)
- {
- if (sys_power_status.ACLineStatus == 255)
- {
- Dbg("unknown AC power status.");
- m_bACPower = 2;
- }
- else
- m_bACPower = sys_power_status.ACLineStatus;
- if (sys_power_status.BatteryLifePercent == 255)
- {
- #ifndef TWINKLE_LOCAL_DEBUG
- Dbg("unknown battery power");
- #endif
- }
- else {
- m_batteryRemains = sys_power_status.BatteryLifePercent;
- }
- //Dbg("oiltest %d",m_batteryRemains);
- if (m_batteryRemains != m_batteryRemainsF || m_bACPower != m_bACPowerF)
- {
- m_batteryRemainsF = m_batteryRemains;
- m_bACPowerF = m_bACPower;
- BatteryVar evt;
- evt.battery = (m_batteryRemains<<16)+m_bACPower;
- SpSendBroadcast(m_pEntity->GetFunction(),SP_MSG_OF(BatteryVar),SP_MSG_SIG_OF(BatteryVar),evt);
- Dbg("oiltest power left %d(%x)",sys_power_status.BatteryLifePercent,evt.battery);
- }
- }
- GetEntityBase()->GetFunction()->ResetTimer(MOBILEDIAL_TIMER_ID, BATTERY_TIMER_INTERVAL);
- return;
- }
- int CMobileDialFSM::CheckConnenction(bool bUseBackup, int& nRetType)
- {
- static int iResult = 0;
- int nRes = 0;
- nRetType = 0;
- iResult = CreateCheckSocket();
- if(iResult < 0)
- {
- Dbg("Create sockect for connect operation failed %d", WSAGetLastError());
- nRes = 2;
- }
- else
- {
- // Connect to server.
- SOCKADDR_IN addrSrv;
- addrSrv.sin_family = AF_INET;
- if(bUseBackup && m_bBackupAvail)
- {
- addrSrv.sin_addr.S_un.S_addr = inet_addr(m_csIpBackup);
- addrSrv.sin_port = htons(atoi(m_csPortBackup));
- nRetType = 2;
- }
- else
- {
- addrSrv.sin_addr.S_un.S_addr = inet_addr(m_csIp);
- addrSrv.sin_port = htons(atoi(m_csPort));
- nRetType = 1;
- }
- //Dbg("prepared for connecting");
- timeval tm;
- FD_SET set;
- FD_SET exceptSet;
- iResult = connect(m_sock, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));
- m_dwLsErrCode = WSAGetLastError();
- if(iResult == SOCKET_ERROR && m_dwLsErrCode == WSAEWOULDBLOCK)
- {
- //Dbg("start to select");
- // Set config value [Josephus in 9:54:07 2016/4/6]
- tm.tv_sec = m_TimeoutSec;
- tm.tv_usec = 0;
- FD_ZERO(&set);
- FD_SET(m_sock, &set);
- FD_ZERO(&exceptSet);
- FD_SET(m_sock, &exceptSet);
- iResult = select(m_sock+1, NULL, &set, &exceptSet, &tm);
- if(iResult == 0)
- {
- Dbg("timeout(%d)...", tm.tv_sec);
- //timeout
- iResult = SOCKET_ERROR;
- SetCurState(MBD_NETWORK_TIMEOUT);
- }
- else if(iResult > 0)
- {
- if(FD_ISSET(m_sock, &set))
- {
- iResult = 0;
- SetCurState(MBD_VALID_CONNECTED);
- }
- else if(FD_ISSET(m_sock, &exceptSet))
- {
- DWORD optVal;
- int optLen = sizeof(DWORD);
- if(getsockopt(m_sock, SOL_SOCKET, SO_ERROR, (char*)&optVal, &optLen) != SOCKET_ERROR)
- {
- Dbg("find it in exceptSet(socket#%d) %d", m_sock, optVal);
- m_dwLsErrCode = optVal;
- }
- else
- {
- Dbg("find it in exceptSet(socket#%d) but getOpt failed", m_sock);
- }
- iResult = SOCKET_ERROR;
- SetCurState(MBD_NETWORK_NOTFOUND_SOCKET);
- }
- else
- {
- Dbg("didn't find it in writeset(socket#%d)", m_sock);
- iResult = SOCKET_ERROR;
- SetCurState(MBD_NETWORK_NOTFOUND_SOCKET);
- }
- }
- else
- {
- // [Josephus in 14:42:30 2016/7/12]
- Dbg("socket(%d), iResult(%d)...", m_sock, iResult);
- SetCurState(MBD_NETWORK_ERROR_SOCKET);
- m_dwLsErrCode = WSAGetLastError();
- }
- }
- if (iResult == SOCKET_ERROR)
- {
- Dbg("Set disconnect flag.");
- nRes = 0;
- }
- else
- {
- Dbg("Set connected flag.");
- nRes = 1;
- Sleep(2000);
- }
- // cleanup
- closesocket(m_sock);
- m_sock = INVALID_SOCKET;
- }
- return nRes;
- }
- void CMobileDialFSM::SendNetStatusMsg()
- {
- NetStatusVar evt;
- if(m_bPadAndFLB && isUsingNewVerAllInOne()) {
- if(m_signalVal == 0) {
- Dbg("Connected condition prior to check NetCard Set Signal default 4!!");
- m_signalVal = 4;
- }
- Dbg("FLB type pad so Send real signal value! %d ", m_signalVal);
- evt.netstatus = m_signalVal;
- SpSendBroadcast(m_pEntity->GetFunction(),SP_MSG_OF(NetStatusVar),SP_MSG_SIG_OF(NetStatusVar),evt);
- return;
- }
- if(!m_bConnected)
- {
- Dbg("Send Signal 0 !!");
- evt.netstatus = 0;
- m_signalVal = 0;
- SpSendBroadcast(m_pEntity->GetFunction(),SP_MSG_OF(NetStatusVar),SP_MSG_SIG_OF(NetStatusVar),evt);
- }
- else if(!m_bPadAndFLB)
- {
- Dbg("not pad or FLB so Send Signal default 4!!");
- evt.netstatus = 4;
- m_signalVal = 4;
- SpSendBroadcast(m_pEntity->GetFunction(),SP_MSG_OF(NetStatusVar),SP_MSG_SIG_OF(NetStatusVar),evt);
- }
- else
- {
- m_signalVal = m_pMbn->m_nSignalVal;
- if(m_signalVal == 0) {
- Dbg("Connected condition prior to check NetCard Set Signal default 4!!");
- m_signalVal = 4;
- }
- Dbg("Send Signal %d !!", m_signalVal);
- evt.netstatus = m_signalVal;
- SpSendBroadcast(m_pEntity->GetFunction(),SP_MSG_OF(NetStatusVar),SP_MSG_SIG_OF(NetStatusVar),evt);
- }
- }
- int CMobileDialFSM::SearchForCOMPorts()
- {
- int nCnt = 0;
- m_mapPort.clear();
- GUID guid = GUID_CLASS_COMPORT;
- HDEVINFO hDevInfo = SetupDiGetClassDevs(&guid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
- if(hDevInfo == INVALID_HANDLE_VALUE) {
- Dbg("SetupDiGetClassDevs failed with error %d", GetLastError());
- return -1;
- }
- SP_DEVINFO_DATA devInfoData;
- ZeroMemory(&devInfoData, sizeof(devInfoData));
- devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
- int nIndex = 0;
- while(SetupDiEnumDeviceInfo(hDevInfo, nIndex++, &devInfoData)) {
- HKEY hKey = SetupDiOpenDevRegKey(hDevInfo, &devInfoData, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_QUERY_VALUE);
- if(hKey){
- DWORD dwDataType = 0;
- char szPort[256] = {0};
- DWORD dwSize = sizeof(szPort);
- if(RegQueryValueEx(hKey, "PortName", NULL, &dwDataType, (LPBYTE)szPort, &dwSize) == ERROR_SUCCESS) {
- if(dwDataType == REG_SZ) {
- char szPortName[256] = {0};
- DWORD dwSizeName = sizeof(szPortName);
- pair<std::string, std::string> pairPort;
- pairPort.second = szPort;
- if(SetupDiGetDeviceRegistryProperty(hDevInfo, &devInfoData, SPDRP_DEVICEDESC, NULL,
- (PBYTE)szPortName, dwSizeName, &dwSizeName)) {
- pairPort.first = szPortName;
- }else {
- pairPort.first = "";
- }
- m_mapPort.insert(pairPort);
- nCnt++;
- }
- }
- RegCloseKey(hKey);
- }
- }
- SetupDiDestroyDeviceInfoList(hDevInfo);
- return nCnt;
- }
- void CMobileDialFSM::_EntriesToDongle(const RasEntryWithDevice& entry, ptMbnProfileInfo info)
- {
- InitAccessKeyInfo(&info->AccessInfo);
- info->bUserDefined = true;
- info->AccessInfo.usCntType = CNT_RAS;
- info->AccessInfo.strProfileDesc = entry.szEntryName;
- info->AccessInfo.strPhoneNum = entry.szPhoneNumber;
- info->strProfileName = entry.szGUID;
- info->AccessInfo.IsDefault = TRUE;
- Dbg("ADD: %s", (LPCTSTR)info->strProfileName);
- if((entry.dwfOptions & RASEO_RequirePAP) == RASEO_RequirePAP) {
- info->AccessInfo.usAPType |= AUPR_PAP;
- }
- if((entry.dwfOptions & RASEO_RequireCHAP) == RASEO_RequireCHAP) {
- info->AccessInfo.usAPType |= AUPR_CHAP;
- }
- if((entry.dwfOptions & RASEO_RequireMsCHAP2) == RASEO_RequireMsCHAP2) {
- info->AccessInfo.usAPType |= AUPR_MSV2;
- }
- {
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- CSimpleStringA csEntryGUID = info->strProfileName;
- CSimpleStringA csValue;
- if(Error_Succeed == spConfigRun->ReadConfigValue(csEntryGUID, "Status", csValue)
- && csValue.GetLength() > 0) {
- if(csValue.IsStartWith("Invalid")) {
- Dbg("the runcfg record for %s is invalid : %s", (LPCTSTR)csEntryGUID, (LPCTSTR)csValue);
- } else {
- spConfigRun->ReadConfigValue(csEntryGUID, "PhoneNum", info->AccessInfo.strPhoneNum);
- spConfigRun->ReadConfigValue(csEntryGUID, "UserName", info->AccessInfo.strUserName);
- #ifdef USING_ENCRYPT
- spConfigRun->ReadConfigValue(csEntryGUID, "Password", csValue);
- info->AccessInfo.strPassword = DecryptString(csValue);
- #else
- spConfigRun->ReadConfigValue(csEntryGUID, "Password", info->AccessInfo.strPassword);
- #endif
- spConfigRun->ReadConfigValue(csEntryGUID, "APN", info->AccessInfo.strAccessString);
- }
- }else {
- Dbg("runcfg is not exist ras record for %s", (LPCTSTR)csEntryGUID);
- }
- }
- }
- //int CMobileDialFSM::WriteBackDirCfgToRunCfg()
- //{
- // LOG_FUNCTION();
- // CSmartPointer<IConfigInfo> spConfigRun;
- // GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- // spConfigRun->WriteConfigValue("init", "param1", m_csPhoneNum);
- // spConfigRun->WriteConfigValue("init", "param2", m_csEntryName);
- // spConfigRun->WriteConfigValue("init", "param3", m_csUserName);
- // spConfigRun->WriteConfigValue("init", "param4", m_csPassword);
- // m_bRCfgHaveDial = true;
- // return 0;
- //}
- void CMobileDialFSM::RecordLastErrorMsg(int nLastError)
- {
- switch(nLastError)
- {
- case WSASYSNOTREADY:
- Dbg("ErrorCode(%d), Text[%s]",
- nLastError,
- "The underlying network subsystem is not ready for network communication.");
- break;
- case WSAVERNOTSUPPORTED:
- Dbg("ErrorCode(%d), Text[%s]",
- nLastError,
- "The version of Windows Sockets support requested is not provided by this particular Windows Sockets implementation");
- break;
- case WSAEINPROGRESS :
- Dbg("ErrorCode(%d), Text[%s]",
- nLastError,
- "A blocking Windows Sockets 1.1 operation is in progress.");
- break;
- case WSAEPROCLIM:
- Dbg("ErrorCode(%d), Text[%s]",
- nLastError, "A limit on the number of tasks supported by the Windows Sockets implementation has been reached.");
- break;
- case WSAEFAULT:
- Dbg("ErrorCode(%d), Text[%s]",
- nLastError,
- "The lpWSAData parameter is not a valid pointer.");
- break;
- //Above for WSAStartup
- case WSANOTINITIALISED:
- Dbg("ErrorCode(%d), Text[%s]",
- nLastError,
- "A successful WSAStartup call must occur before using this function.");
- break;
- case WSAENETDOWN:
- Dbg("ErrorCode(%d), Text[%s]",
- nLastError,
- "The network subsystem has failed.");
- break;
- //Above for WSACleanup
- default:
- Dbg("ErrorCode(%d), josephtest can not explain the text current.");
- break;
- }
- }
- void CMobileDialFSM::SelfTest(EntityTestEnum eTestType,CSmartPointer<ITransactionContext> pTransactionContext)
- {
- pTransactionContext->SendAnswer(m_ecSelfTest);
- }
- MOBILEDIAL_CONNECTION_STATE CMobileDialFSM::GetCurState()
- {
- if(m_bPadAndFLB && !isUsingNewVerAllInOne())
- {
- const MOBILEDIAL_CONNECTION_STATE st3G = GetRasStatus();
- const MOBILEDIAL_CONNECTION_STATE st4G = m_pMbn->GetCurState();
- const MOBILEDIAL_CONNECTION_STATE stHW = GetHWStatus();
- if(m_nAdvancedGen != 0) {
- if(m_nAdvancedGen == ADVANCE_RAS && st3G != MBD_ACTIVATION_CONNECTED) {
- return st3G;
- }
- if(m_nAdvancedGen == ADVANCE_MBN && st4G != MBD_ACTIVATION_CONNECTED) {
- return st4G;
- }
- if(m_nAdvancedGen == ADVANCE_MBB && stHW != MBD_ACTIVATION_CONNECTED && stHW != MBD_WLAN_CONNECTED) {
- return stHW;
- }
- } else {
- if(m_n3G > 0 || m_n4G > 0) {
- if(st3G == MBD_ACTIVATION_CONNECTED || st4G == MBD_ACTIVATION_CONNECTED) {
- if(m_34GReserved != 0){
- m_34GReserved = 0;
- }
- } else {
- if(m_n3G > 0 && m_n4G > 0) {
- if(m_34GReserved == ADVANCE_RAS) {
- Dbg("Ras status handled.1");
- return st3G;
- } else if(m_34GReserved == ADVANCE_MBN) {
- Dbg("Mbn status handled.1");
- return st4G;
- }
- if(st3G == MBD_ACTIVATION_DISCONNECTED || st4G == MBD_ACTIVATION_DISCONNECTED) {
- return MBD_ACTIVATION_DISCONNECTED;
- }
- Dbg("[MBN#%s][RAS#%s]", ConvertStatusToString(st4G), ConvertStatusToString(st3G));
- if(m_pMbn->HasAnyProfile()) {
- Dbg("Mbn status handled.3");
- return st4G;
- }
- if(st4G == MBD_NO_PROFILE && st3G == MBD_NO_ENTRY) {
- return MBD_NO_PROFILE;
- }
- return MBD_INVALID_BOTH_DONGLE;
- } else if(m_n3G > 0) {
- Dbg("Ras status handled.2");
- return st3G;
- } else {
- Dbg("Mbn status handled.2");
- return st4G;
- }
- }
- } else if(m_curState != MBD_VALID_CONNECTED) {
- if(MBD_MIFI_START < stHW && stHW < MBD_MIFI_END) {
- Dbg("hw handle.");
- return stHW;
- }
- Dbg("no any dongle ...");
- SetCurState(MBD_NO_MOBILEDONGLE);
- }
- }
- }
- Dbg("Main status handled.");
- return m_curState;
- }
- void CMobileDialFSM::OnStateTrans(int iSrcState, int iDstState)
- {
- //if(iSrcState == FSM_STATE_INIT)
- if(s1 == iSrcState && (iDstState == s4 || iDstState == s5)) m_bNotify = TRUE;
- }
- BOOL CMobileDialFSM::FormatLastError(DWORD dwCode, CSimpleStringA& csOut)
- {
- LPVOID lpMsgBuf;
- if(!FormatMessage(
- FORMAT_MESSAGE_ALLOCATE_BUFFER |
- FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_MAX_WIDTH_MASK,
- NULL,
- dwCode,
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- (LPTSTR) &lpMsgBuf,
- 0, NULL ))
- {
- return FALSE;
- }
- csOut = (LPCTSTR)lpMsgBuf;
- LocalFree(lpMsgBuf);
- return TRUE;
- }
- CSimpleStringA CMobileDialFSM::GetFurtherDetail(BOOL slvNeed)
- {
- const MOBILEDIAL_CONNECTION_STATE state = GetCurState();
- CSimpleStringA csTemp;
- CSimpleStringA csDetail;
- DWORD nSuffixCode = 0;
- BOOL fReportOrNot = TRUE;
- if(m_bConnected) {
- fReportOrNot = FALSE;
- }
- LOG_TRACE("[MBN#%s][RAS#%s][HW#%s][FSM#%s]",
- ConvertStatusToString(m_pMbn->GetCurState()),
- ConvertStatusToString(m_3gState),
- ConvertStatusToString(m_HwState),
- ConvertStatusToString(state));
- if(m_bPadAndFLB) {
- nSuffixCode = 0x01000000;
- nSuffixCode |= (m_nAdvancedGen << 20);
- if(m_n3G > 0) nSuffixCode |= (m_n3G << 18);
- if(m_n4G > 0) nSuffixCode |= (m_n4G << 16);
- }
- nSuffixCode |= state;
- //Dbg("nSuffixCode : %d(0x%08x).", nSuffixCode, nSuffixCode);
- if(state < MBD_NETWORK_SEPERATE) {
- if(state == MBD_NETWORK_TIMEOUT) {
- if(m_bPadAndFLB) {
- if(!isUsingNewVerAllInOne()) {
- if(m_nAdvancedGen == 2 && mMBBParam.connectType == MBB_CONNECT_WIFI) {
- csTemp = "WLAN已连接,但网络请求超时";
- } else {
- csTemp = "上网卡已连接,但网络请求超时";
- }
- }
- } /*else {
- csTemp = "网线已连接,但网络请求超时";
- }*/
- if(csTemp.IsNullOrEmpty()) {
- csTemp = "网络请求超时";
- }
- }
- // error!!! should be fixed in 1.9.0 [Josephus in 8:59:23 2016/9/22]
- else if(state == MBD_NETWORK_ERROR_SOCKET || state == MBD_NETWORK_NOTFOUND_SOCKET) {
- // [Josephus in 13:36:22 2016/9/6]
- CSimpleStringA csCode;
- if(m_bPadAndFLB) {
- if(FormatLastError(m_dwLsErrCode, csCode)) {
- CSimpleStringA csTest;
- if(!isUsingNewVerAllInOne()) {
- if(m_nAdvancedGen == 2 && mMBBParam.connectType == MBB_CONNECT_WIFI) {
- csTest = CSimpleStringA::Format("WLAN已连接,但网络出现错误:%s", (LPCTSTR)csCode);
- } else {
- csTest = CSimpleStringA::Format("上网卡已连接,但网络出现错误:%s", (LPCTSTR)csCode);
- }
- } else {
- csTest = CSimpleStringA::Format("网络出现错误:%s", (LPCTSTR)csCode);
- }
- LogEvent(Severity_Middle,CombineErrorCode(state), (LPCTSTR)csTest);
- }
- if(m_dwLsErrCode == 0) {
- if(!isUsingNewVerAllInOne()) {
- if(m_nAdvancedGen == 2 && mMBBParam.connectType == MBB_CONNECT_WIFI) {
- csTemp = "WLAN已连接,但网络出现错误";
- } else {
- csTemp = "上网卡已连接,但网络出现错误";
- }
- } else {
- csTemp = "网络出现错误";
- }
- } else{
- char cdString[128] = {0};
- sprintf_s(cdString, 128, "GLE=%08X", m_dwLsErrCode);
- csTemp = CSimpleStringA::Format("网络出现错误[%s]", cdString);
- }
- }
- } else if(state == MBD_NETWORK_INVALID_SOCKET) {
- csTemp = "创建套接字失败";
- } else if(state == MBD_NO_FOUND_CABLE){
- csTemp = "网线未连接,请重新连接网线或设备";
- } else {
- char cdString[128] = {0};
- sprintf_s(cdString, 128, "%08x", nSuffixCode);
- csTemp = CSimpleStringA::Format("连接上网错误[%s]", cdString);
- }
- } else {
- if(state == MBD_READY_SIM_NO_INSERT) {
- csTemp = "SIM卡未插入卡托,请检查无线宽带上网卡";
- } else if(state > MBD_READY_BAD_SIM_START && state < MBD_READY_BAD_SIM_END) {
- char cdString[128] = {0};
- sprintf_s(cdString, 128, "%08x", nSuffixCode);
- csTemp = CSimpleStringA::Format("SIM卡出现异常[%s],请尝试重连设备", cdString);
- } else if(state == MBD_READY_NO_SERVICE) {
- csTemp = "无线宽带上网卡无服务,请检查卡托或咨询相关运营商";
- } else if(state == MBD_CONNECTION_INVALID_ACCESS) {
- csTemp = "连接准入字符串设置错误,请检查配置后再重连设备";
- } else if(state == MBD_CONNECTION_INVALID_NAMEORPASSWORD) {
- csTemp = "拨号所使用的用户名或密码错误";
- } else if(state == MBD_UNKNOWN) {
- csTemp = "无线宽带上网卡状态不可用,请等候一段时间或重连设备";
- } else if(state == MBD_NO_PROFILE) {
- csTemp = "找不到拨号参数,请先对4G上网卡进行配置";
- } else if(state == MBD_NO_ENTRY){
- csTemp = "找不到拨号参数,请先对上网卡进行配置";
- } else if(state == MBD_RUN_ENTRY_NOTFOUND) {//仅3G拨号时出现的错误
- csTemp = "运行时找不到3G拨号所需数据,请更新数据";
- } else if(state == MBD_CREATE_ENTRY_FAILED) {
- csTemp = "创建拨号所需的电话簿失败";
- } else if(state == MBD_NO_MOBILEDONGLE) {
- csTemp = "未检测到无线宽带上网卡,请重连设备";
- } else if(state == MBD_CONNECTION_FAILURE || state == MBD_RASDIAL_FAILED) {//34G轮询拨号或仅4G拨号可能出现的错误
- if(!_IsMBBProfileConfiged()) {
- csTemp = "尝试拨号上网失败,请检查配置后再重连设备";
- } else {
- csTemp = "尝试拨号上网失败,请检查配置并确认是否在可用时间段";
- }
- } else if(state == MBD_ACTIVATION_CONNECTING) {
- csTemp = "无线宽带上网卡正在进行拨号";
- fReportOrNot = FALSE;
- } else if(state == MBD_ACTIVATION_DISCONNECTING) {
- csTemp = "无线宽带上网卡正在断开连接";
- fReportOrNot = FALSE;
- } else if(state == MBD_ACTIVATION_DISCONNECTED) {
- csTemp = "无线宽带上网卡未连接";
- fReportOrNot = FALSE;
- } else if(state == MBD_INVALID_BOTH_DONGLE) {
- csTemp = "上网卡出现异常,请检查配置或重连设备";
- } else if(state == MBD_WLAN_INVALID_NAMEORPASSWORD) {
- csTemp = "无效的 WLAN 连接参数";
- } else if(state == MBD_WLAN_OFF) {
- csTemp = "WLAN 被禁用";
- } else if(state == MBD_WLAN_DISCONNECTED) {
- csTemp = "WLAN 未连接";
- } else if(state == MBD_WLAN_CONNECTED) {
- csTemp = "WLAN 已连接";
- fReportOrNot = FALSE;
- } else if(state == MBD_WLAN_CONNECTING) {
- csTemp = "正在连接 WLAN...";
- fReportOrNot = FALSE;
- } else if(state == MBD_WLAN_ENTRY_NO_FOUND) {
- csTemp = "找不到指定的 SSID 名称";
- fReportOrNot = FALSE;
- } else if(state == MBD_WLAN_CONNECT_FAILED) {
- csTemp = "尝试连接 WLAN 失败";
- fReportOrNot = FALSE;
- } else if(state == MBD_WLAN_CONFIG_CHANGED) {
- csTemp = "WLAN 配置已更新";
- fReportOrNot = FALSE;
- } else if(state == MBD_NO_FOUND_CABLE) {
- csTemp = "网线未连接,请重新连接网线或设备";
- } else if(state == MBD_WLAN_CONFIG_REBOOT) {
- csTemp = "上网模式已同步更新为WLAN连接,请拔离MIFI设备并重启终端应用";
- fReportOrNot = FALSE;
- } else if(state == MBD_WLAN_DEVICE_PLUG_OFF) {
- csTemp = "上网模式已同步更新,请拔离MIFI设备,或者你可以更改为有线连接方式";
- fReportOrNot = FALSE;
- } else if(state == MBD_WLAN_CONFIG_WAIT_REBOOT) {
- csTemp = "上网模式同步更新完成,请重启终端应用或等候拨号模块自动重启";
- fReportOrNot = FALSE;
- } else if(state == MBD_MIFI_LOGIN_INVALID_NAMEORPASSWORD) {
- csTemp = "登录到MIFI设备失败,无效的用户名或密码";
- } else if(state == MBD_INTERNAL_ERROR) {
- csTemp = CSimpleStringA::Format("拨号程序执行异常[0x%08x],请尝试重连设备", m_pMbn->GetMBNCode());
- } else {
- char cdString[128] = {0};
- sprintf_s(cdString, 128, "%08x", nSuffixCode);
- csTemp = CSimpleStringA::Format("连接上网错误[%s]", cdString);
- }
- }
- if(slvNeed) {
- csDetail = CSimpleStringA::Format("%s#0x%08x", (LPCTSTR)csTemp, nSuffixCode);
- } else {
- csDetail = CSimpleStringA((LPCTSTR)csTemp.GetData());
- }
- if(fReportOrNot && !slvNeed) {
- LogError(Severity_High, Error_InvalidState, CombineErrorCode(state), csDetail.GetData());
- }
- return csDetail;
- }
- int CMobileDialFSM::CheckLANConnectStatus()
- {
- DWORD dwFlag;
- BOOL bRet = InternetGetConnectedState(&dwFlag, 0);
- Dbg("Return Status: %d, GetLastError: %d", bRet, GetLastError());
- if((dwFlag & INTERNET_CONNECTION_CONFIGURED) == INTERNET_CONNECTION_CONFIGURED)
- {
- Dbg("Local system has a valid connection to the Internet, but it might or might not be currently connected.");
- }
- if((dwFlag & INTERNET_CONNECTION_LAN) == INTERNET_CONNECTION_LAN)
- {
- Dbg("Local system uses a local area network to connect to the Internet.");
- }
- if((dwFlag & INTERNET_CONNECTION_MODEM) == INTERNET_CONNECTION_MODEM)
- {
- Dbg("Local system uses a modem to connect to the Internet.");
- }
- if((dwFlag & INTERNET_CONNECTION_MODEM_BUSY) == INTERNET_CONNECTION_MODEM_BUSY)
- {
- Dbg("No longer used: INTERNET_CONNECTION_MODEM_BUSY");
- }
- if((dwFlag & INTERNET_CONNECTION_OFFLINE) == INTERNET_CONNECTION_OFFLINE)
- {
- Dbg("Local system is in offline mode.");
- }
- if((dwFlag & INTERNET_CONNECTION_PROXY) == INTERNET_CONNECTION_PROXY)
- {
- Dbg("Local system uses a proxy server to connect to the Internet.");
- }
- if((dwFlag & INTERNET_RAS_INSTALLED) == INTERNET_RAS_INSTALLED)
- {
- Dbg("Local system has RAS installed.");
- }
- if(bRet)
- return 1;
- return 0;
- }
- void CMobileDialFSM::SendMsgToDialog(LPCTSTR errMsg, BOOL bSolvedInfor)
- {
- static char szMessage[256];
- if(errMsg != NULL) {
- memset(szMessage, 0, sizeof(szMessage));
- szMessage[0] = '\n';
- if(!bSolvedInfor) {
- strcpy_s(szMessage, errMsg);
- }
- TellDlgTheResult(bSolvedInfor ? Error_Succeed : Error_Bug ,
- WM_FATALMESSAGE_CHANGE, (LPARAM)szMessage);
- }
- }
- void CMobileDialFSM::ShowFatalError(LPCTSTR errMsg, BOOL bSolvedInfor)
- {
- static int nFatalTimes = 0;
- CSimpleStringA uiState = "";
- bool bDisplay = true;
-
- auto err = this->GetEntityBase()->GetFunction()->GetSysVar("UIState",uiState);
- if(err == Error_Succeed && uiState.GetLength() > 0 && uiState[0] != 'X'){
- bDisplay = false;
- }
- if(errMsg != NULL) {
- if(!bSolvedInfor) {
- nFatalTimes++;
- if(bDisplay) GetEntityBase()->GetFunction()->ShowFatalError(errMsg);
- else Dbg("ShowFatalError:%s", errMsg);
- } else if(nFatalTimes != 0) {
- nFatalTimes = 0;
- if(bDisplay) GetEntityBase()->GetFunction()->ShowFatalError(errMsg);
- else Dbg("ShowFatalSucceed:%s", errMsg);
- }
- SendMsgToDialog(errMsg, bSolvedInfor);
- }
- }
- void CMobileDialFSM::TryOpenWwanSvc()
- {
- ServiceStatus status = SERVICE_STATUS_UNKNOWN;
- BOOLEAN bRet = CSvcManager::GetInstance()->QueryServiceStatus(SERVICE_WWAN_AutoConfig, status);
- Dbg("The %s service query result: %d, status: %d.", SERVICE_WWAN_AutoConfig, bRet, status);
- if(bRet) {
- if(status == SERVICE_STATUS_STOPPED) {
- bRet = CSvcManager::GetInstance()->StartServiceWith(SERVICE_WWAN_AutoConfig);
- Dbg("CustomStartService %s returned %d.", SERVICE_WWAN_AutoConfig, bRet);
- if(!bRet)
- {
- LastErrorInfo infor;
- CSvcManager::GetInstance()->GetLastErrMsg(infor);
- Dbg("GetLastErr: %s.", infor.szErrMsg);
- }
- }
- else if(status == SERVICE_STATUS_PASUSED) {
- bRet = CSvcManager::GetInstance()->StopService(SERVICE_WWAN_AutoConfig);
- Dbg("StopService %s returned %d.", SERVICE_WWAN_AutoConfig, bRet);
- if(!bRet) {
- LastErrorInfo infor;
- CSvcManager::GetInstance()->GetLastErrMsg(infor);
- Dbg("GetLastErr: %s.", infor.szErrMsg);
- }
- }
- }
- }
- int CMobileDialFSM::RefreshRasEntry()
- {
- LOG_FUNCTION();
- DWORD dwCb = 0;
- DWORD dwRet = ERROR_SUCCESS;
- DWORD dwEntries = 0;
- LPRASENTRYNAME lpRasEntryName = NULL;
- m_rasEntries.Clear();
- dwRet = RasEnumEntries(NULL, NULL, lpRasEntryName, &dwCb, &dwEntries);
- if (dwRet == ERROR_BUFFER_TOO_SMALL && dwEntries > 0) {
- lpRasEntryName = (LPRASENTRYNAME) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwCb);
- if (lpRasEntryName == NULL){
- Dbg("HeapAlloc failed when RasEnumEntries");
- SetRasStatus(MBD_INTERNAL_ERROR);
- return -1;
- }
- lpRasEntryName[0].dwSize = sizeof(RASENTRYNAME);
- dwRet = RasEnumEntries(NULL, NULL, lpRasEntryName, &dwCb, &dwEntries);
- if (ERROR_SUCCESS == dwRet) {
- Dbg("The following RAS entry names were found:");
- m_rasEntries.Init(dwEntries);
- for (DWORD i = 0; i < dwEntries; i++) {
- strcpy_s(m_rasEntries[i].szEntryName, lpRasEntryName[i].szEntryName);
- m_rasEntries[i].szDeviceType[0] = '\0';
- m_rasEntries[i].szDeviceName[0] = '\0';
- m_rasEntries[i].szPhoneNumber[0] = '\0';
- m_rasEntries[i].dwfOptions = 0;
- Dbg("Refresh EntryName: %s", m_rasEntries[i].szEntryName);
- LPRASENTRY lpRasentry = NULL;
- LPBYTE lpDevInfo = NULL;
- DWORD dwEntrySz = 0, dwDevInfoSz = 0;
- dwRet = RasGetEntryProperties(NULL, lpRasEntryName[i].szEntryName, NULL, &dwEntrySz, NULL, &dwDevInfoSz);
- if(dwRet == ERROR_BUFFER_TOO_SMALL) {
- if(dwEntrySz != 0)
- lpRasentry = (LPRASENTRY)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwEntrySz);
- if(dwDevInfoSz != 0)
- lpDevInfo = (LPBYTE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwDevInfoSz);
- }
- if(lpRasentry != NULL) {
- lpRasentry->dwSize = sizeof(RASENTRY);
- dwRet = RasGetEntryProperties(NULL, lpRasEntryName[i].szEntryName, lpRasentry, &dwEntrySz, lpDevInfo, &dwDevInfoSz);
- if(dwRet != 0) {
- Dbg("RasGetEntryProperties twice failed: %d", dwRet);
- } else {
- Dbg("DeviceName: %s, DeviceType: %s", lpRasentry->szDeviceName, lpRasentry->szDeviceType);
- strcpy_s(m_rasEntries[i].szDeviceName, lpRasentry->szDeviceName);
- strcpy_s(m_rasEntries[i].szDeviceType, lpRasentry->szDeviceType);
- strcpy_s(m_rasEntries[i].szPhoneNumber, lpRasentry->szLocalPhoneNumber);
- strcpy_s(m_rasEntries[i].szGUID, (LPCTSTR)GuidToString(lpRasentry->guidId));
- Dbg("EntryGUID: %s", m_rasEntries[i].szGUID);
- m_rasEntries[i].dwfOptions = lpRasentry->dwfOptions;
- }
- }
- if(lpRasentry) {
- HeapFree(GetProcessHeap(), 0, lpRasentry);
- lpRasentry = NULL;
- }
- if(lpDevInfo) {
- HeapFree(GetProcessHeap(), 0, lpDevInfo);
- lpDevInfo = NULL;
- }
- }
- } else {
- HeapFree(GetProcessHeap(), 0, lpRasEntryName);
- lpRasEntryName = NULL;
- SetRasStatus(MBD_INTERNAL_ERROR);
- return -2;
- }
- HeapFree(GetProcessHeap(), 0, lpRasEntryName);
- lpRasEntryName = NULL;
- return dwEntries;
- }
- // There was either a problem with RAS or there are RAS entry names to enumerate
- if(dwEntries >= 1) {
- Dbg("The operation failed to acquire the buffer size.");
- SetRasStatus(MBD_INTERNAL_ERROR);
- return -3;
- }
- Dbg("There were no RAS entry names found.");
- SetRasStatus(MBD_NO_ENTRY);
- return 0;
- }
- ErrorCodeEnum CMobileDialFSM::AddNewProfile(
- const CSimpleStringA csInterfaceID, const AccessKeyInfo& newInfo, bool fApplyNow)
- {
- LOG_FUNCTION();
- ErrorCodeEnum rc = Error_NoDefine;
- //
- if(newInfo.usCntType == CNT_MBN) {
- rc = m_pMbn->AddProfile(csInterfaceID, newInfo, fApplyNow);
- if(rc == Error_Succeed) {
- }
- }else if(newInfo.usCntType == CNT_RAS) {
- rc = CreatePhoneEntryEx(csInterfaceID, &newInfo, fApplyNow) < 0 ? Error_Unexpect : Error_Succeed;
- if(rc == Error_Succeed) {
- }
- } else if(newInfo.usCntType == CNT_ANDROID) {
- int slotID = strnicmp(csInterfaceID, "MAIN", strlen("MAIN")) == 0 ? 0 : 1;
- rc = m_SafeWirelessClient->UpdateOrInsertAPN(slotID, newInfo, fApplyNow);
- } else if(newInfo.usCntType == CNT_MBB) {
- hw::apn_config_t config;
- _ConvertToMBBApnStruct(newInfo, config);
- int res = m_HwDeviceMnt->add_profile(config, fApplyNow);
- if(res == 0) {
- _StoreMBBPassword(newInfo.strProfileDesc, newInfo.strPassword);
- rc = Error_Succeed;
- } else {
- const auto tmp = MBBResult2Status(res);
- //SetHWStatus(tmp);
- m_csErrMsg = CSimpleStringA::Format("添加配置到MIFI设备失败(%s)!", ConvertStatusToString(tmp));
- rc = Error_Unexpect;
- }
- } else {
- m_csErrMsg = "不支持的连接配置方式!";
- }
- return rc;
- }
- ErrorCodeEnum CMobileDialFSM::UpdateProfile(
- const CSimpleStringA csInterfaceID, LPCTSTR lpszProfileName, const AccessKeyInfo& newInfo, bool fApplyNow)
- {
- LOG_FUNCTION();
- if(newInfo.usCntType == CNT_MBN) {
- return m_pMbn->UpdateProfile(csInterfaceID, lpszProfileName, newInfo, fApplyNow);
- } else if(newInfo.usCntType == CNT_RAS) {
- return UpdateEntryInfo(lpszProfileName, newInfo, fApplyNow);
- } else if(newInfo.usCntType == CNT_ANDROID) {
- int profileID = 0;
- if(lpszProfileName == NULL || strlen(lpszProfileName) == 0) {
- m_csErrMsg = "无效配置标识";
- return Error_Param;
- } else {
- profileID = atoi(lpszProfileName);
- }
- int slotID = strnicmp(csInterfaceID, "MAIN", strlen("MAIN")) == 0 ? 0 : 1;
- return m_SafeWirelessClient->UpdateOrInsertAPN(slotID, newInfo, fApplyNow, profileID);
- } else if(newInfo.usCntType == CNT_MBB) {
- hw::connect_profile_t config;
- _ConvertToMBBApnStruct(newInfo, config.apn_config);
- int profileID = atoi(lpszProfileName);
- config.index = profileID;
- config.is_default = fApplyNow;
- int res = m_HwDeviceMnt->update_profile(config);
- Dbg("update profile with id: %d returned %d", profileID, res);
- if(res == 0) {
- _StoreMBBPassword(newInfo.strProfileDesc, newInfo.strPassword);
- return Error_Succeed;
- } else {
- const auto tmp = MBBResult2Status(res);
- //SetHWStatus(tmp);
- m_csErrMsg = CSimpleStringA::Format("更新配置到MIFI设备失败 (%s)!", ConvertStatusToString(tmp));
- return Error_Unexpect;
- }
- }
- else {
- m_csErrMsg = "不支持的连接配置方式!";
- return Error_NotMeetCondition;
- }
- }
- ErrorCodeEnum CMobileDialFSM::DeleteProfile(int nDongleIdx, int nProfileIdx)
- {
- LOG_FUNCTION();
- if(g_DongleInfos[nDongleIdx].usDeviceType == DEVTYPE_INTER) {
- return m_pMbn->DeleteProfile(g_DongleInfos[nDongleIdx].csInterfaceId, g_DongleInfos[nDongleIdx].profileList[nProfileIdx].strProfileName);
- } else if(g_DongleInfos[nDongleIdx].usDeviceType == DEVTYPE_MODEM) {
- Dbg("DealConnctionActivity returned: %d", DealConnctionActivity(g_DongleInfos[nDongleIdx].profileList[nProfileIdx].AccessInfo.strProfileDesc));
- DWORD dwRet = RasDeleteEntry(NULL, g_DongleInfos[nDongleIdx].profileList[nProfileIdx].AccessInfo.strProfileDesc);
- if(dwRet == 0) {
- return Error_Succeed;
- } else {
- m_csErrMsg = CSimpleStringA::Format("RasDeleteEntry failed: %d", dwRet);
- Dbg("Delete entry(%s) failed : %d", (LPCTSTR)g_DongleInfos[nDongleIdx].profileList[nProfileIdx].AccessInfo.strProfileDesc, dwRet);
- return Error_Unexpect;
- }
- } else if((g_DongleInfos[nDongleIdx].usDeviceType & DEVTYPE_ANDROID_UKNOWN )
- || (g_DongleInfos[nDongleIdx].usDeviceType & DEVTYPE_MBB)) {
- int profileID = 0;
- if(!g_DongleInfos[nDongleIdx].profileList[nProfileIdx].strProfileName.IsNullOrEmpty()) {
- profileID = atoi(g_DongleInfos[nDongleIdx].profileList[nProfileIdx].strProfileName);
- }
- if(profileID == 0) {
- Dbg("invalid profile id! profileName:%s", g_DongleInfos[nDongleIdx].profileList[nProfileIdx].strProfileName.GetData());
- m_csErrMsg = "无效配置序号";
- return Error_Param;
- }
- if(g_DongleInfos[nDongleIdx].usDeviceType & DEVTYPE_ANDROID_UKNOWN) {
- return m_SafeWirelessClient->DeleteProfile(profileID);
- } else {
- int res = m_HwDeviceMnt->delete_profile_by(profileID);
- if(res == 0) {
- Dbg("delete profile succ.");
- _StoreMBBPassword(g_DongleInfos[nDongleIdx].profileList[nProfileIdx].AccessInfo.strProfileDesc, "");
- return Error_Succeed;
- } else {
- const auto tmp = MBBResult2Status(res);
- //SetHWStatus(tmp);
- m_csErrMsg = CSimpleStringA::Format("删除配置失败(%s)!", ConvertStatusToString(tmp));
- return Error_Unexpect;
- }
- }
- }
- m_csErrMsg = "不支持的连接配置文件类型";
- return Error_NoDefine;
- }
- ErrorCodeEnum CMobileDialFSM::ConnectWithDefault()
- {
- if(m_SafeWirelessClient) {
- m_csErrMsg = "";
- return m_SafeWirelessClient->ConnectWithDefault();
- }
- return Error_NotInit;
- }
- int CMobileDialFSM::RetrieveDongleInfo()
- {
- ResetDongleInfos();
- if(isUsingNewVerAllInOne()) {
- BOOL bActive = FALSE, bConnected = FALSE;
- ErrorCodeEnum ec = m_SafeWirelessClient->IsActive(bActive, bConnected);
- if(ec == Error_Succeed) {
- if(!bConnected) {
- SendMsgToDialog("当前未连接到多合一,请稍后再试!");
- return -2;
- }
- int nNum = 0;
- ec = m_SafeWirelessClient->GetAPNConfigs(-1, nNum);
- return nNum;
- } else {
- SendMsgToDialog(CSimpleStringA::Format("连接多合一管控实体失败(0x%X)", ec));
- return -1;
- }
- }
- if(m_nAdvancedGen == ADVANCE_MBB) {
- const auto hwStatus = GetHWStatus();
- //if(hwStatus == MBD_WLAN_CONNECTED) {
- // int nNum3 = RetriveMifiInfo();
- // if(nNum3 > 0) {
- // return nNum3;
- // }
- //} else {
- // m_csErrMsg = GetFurtherDetail();
- //}
- if(hwStatus == MBD_NO_MOBILEDONGLE
- || hwStatus == MBD_WLAN_DISCONNECTED
- || hwStatus == MBD_WLAN_CONNECTING
- || hwStatus == MBD_WLAN_CONNECT_FAILED) {
- m_csErrMsg = GetFurtherDetail();
- } else {
- int nNum3 = RetriveMifiInfo();
- if(nNum3 > 0) {
- return nNum3;
- }
- }
- return -500;
- }
- int nNum = m_nAdvancedGen != 3 ? m_pMbn->EnumerateInterfaces(TRUE) : 0;
- int nNum2 = m_nAdvancedGen !=4 ? EnumCurRasDevices(TRUE) : 0;
- m_n3G = nNum2;
- m_n4G = nNum;
- if(nNum >= 0 || nNum2 >= 0) {
- if(nNum2 >= 0 && nNum >= 0) {
- return nNum + nNum2;
- } else if(nNum >= 0)
- return nNum;
- else
- return nNum2;
- }
- return (nNum < 0 ? nNum : nNum2);
- }
- void CMobileDialFSM::TellDlgTheResult(ErrorCodeEnum ec, UINT uMsg, LPARAM lparam)
- {
- if(m_hMainWnd) {
- PostMessage(m_hMainWnd, uMsg, ec, (LPARAM)lparam);
- }
- }
- BOOL CMobileDialFSM::UpdateProfileInfo(int nCurSel)
- {
- LOG_FUNCTION();
- LOG_ASSERT(nCurSel >= 0);
- BOOL bRes = FALSE;
- if(g_DongleInfos[nCurSel].usDeviceType == DEVTYPE_INTER) {
- bRes = m_pMbn->SearchForProfileName(&g_DongleInfos[nCurSel]);
- if(!bRes && m_pMbn->m_tmpState == MBD_NO_PROFILE) {
- Dbg("Because there are no profile...");
- return TRUE;
- }
- } else if(g_DongleInfos[nCurSel].usDeviceType == DEVTYPE_MODEM) {
- int nEntryNum = RefreshRasEntry();
- if(nEntryNum < 0) {
- return FALSE;
- }
- int nGongleCnt = g_DongleInfos.GetCount();
- for(int i=0; i<nGongleCnt; ++i) {
- if(g_DongleInfos[i].usDeviceType == DEVTYPE_MODEM) {
- int cnt = 0;
- for(int j=0; j<nEntryNum; ++j) {
- if(!g_DongleInfos[i].subInfo.strProviderName.Compare(m_rasEntries[j].szDeviceName)) {
- cnt++;
- }
- }
- g_DongleInfos[i].profileList.Clear();
- if(cnt > 0) {
- g_DongleInfos[i].profileList.Init(cnt);
- for(int j=0, z=0; j<nEntryNum; ++j) {
- if(!g_DongleInfos[i].subInfo.strProviderName.Compare(m_rasEntries[j].szDeviceName)) {
- _EntriesToDongle(m_rasEntries[j], &g_DongleInfos[i].profileList[z]);
- z++;
- }
- }
- }
- }
- }
- return TRUE;
- } else if(g_DongleInfos[nCurSel].usDeviceType == DEVTYPE_MBB) {
- LOG_ASSERT(nCurSel == 0);
- g_DongleInfos[nCurSel].profileList.Clear();
- int nNum = _GetMBBProfiles(g_DongleInfos[nCurSel]);
- if(nNum < 0) {
- m_csErrMsg = CSimpleStringA::Format("获取配置文件失败:%d", nNum);
- return FALSE;
- }
- return TRUE;
- } else if(g_DongleInfos[nCurSel].usDeviceType & DEVTYPE_ANDROID_UKNOWN) {
- BOOL bActive = FALSE, bConnected = FALSE;
- ErrorCodeEnum ec = m_SafeWirelessClient->IsActive(bActive, bConnected);
- if(ec == Error_Succeed) {
- if(!bConnected) {
- m_csErrMsg = "当前未连接到多合一,请稍后再试!";
- return FALSE;
- }
- int nNum = 0;
- ec = m_SafeWirelessClient->GetAPNConfigsPure(nCurSel, nNum);
- if(ec == Error_Succeed) {
- return TRUE;
- }
- m_csErrMsg = CSimpleStringA::Format("调用接口 GetAPNConfigsPure 失败:%d", ec);
- return FALSE;
- } else {
- m_csErrMsg = CSimpleStringA::Format("连接多合一管控实体失败(0x%X)", ec);
- return FALSE;
- }
- } else {
- m_csErrMsg = CSimpleStringA::Format("未知连接类型:%d", g_DongleInfos[nCurSel].usDeviceType);
- }
- return bRes;
- }
- BOOL CMobileDialFSM::UpdateSubInfo(int nCurSel)
- {
- LOG_FUNCTION();
- LOG_ASSERT(nCurSel >= 0);
- if(g_DongleInfos[nCurSel].usDeviceType == DEVTYPE_INTER) {
- return m_pMbn->GetInterfaceInfo(g_DongleInfos[nCurSel].csInterfaceId,
- &g_DongleInfos[nCurSel].subInfo);
- } else if(g_DongleInfos[nCurSel].usDeviceType == DEVTYPE_MODEM) {
- return UpdateRasConnectState(true) >= 0 ? TRUE : FALSE;
- } else if(g_DongleInfos[nCurSel].usDeviceType & DEVTYPE_ANDROID_UKNOWN) {
- int slotNum = 1;
- if(g_DongleInfos[nCurSel].usDeviceType == DEVTYPE_ANDROID_MAIN) {
- slotNum = 1; // sim_slot_main
- } else if(g_DongleInfos[nCurSel].usDeviceType == DEVTYPE_ANDROID_VICE) {
- slotNum = 2; // sim_slot_vice
- } else {
- m_csErrMsg = CSimpleStringA::Format("无效卡槽序号:%d", g_DongleInfos[nCurSel].usDeviceType);
- return FALSE;
- }
- int nNum = 0;
- ErrorCodeEnum ec = m_SafeWirelessClient->GetAPNConfigs(-1, nNum, true, false);
- if(ec == Error_Succeed) {
- return TRUE;
- }
- m_csErrMsg = CSimpleStringA::Format("调用接口 GetAPNConfigs 失败:%d", ec);
- return FALSE;
- } else if(g_DongleInfos[nCurSel].usDeviceType == DEVTYPE_MBB) {
- if(_GetMBBDeviceInfo(g_DongleInfos[nCurSel]) == 0){
- return TRUE;
- }
- return FALSE;
- }
- return FALSE;
- }
- void CMobileDialFSM::StorePersistentRequetsId(ULONG ulRequestID)
- {
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- spConfigRun->WriteConfigValueHexInt("MBN", "RequestID", ulRequestID);
- //Dbg("Store RequestID: %d", ulRequestID);
- }
- BOOL CMobileDialFSM::GetPersistentRequestId(ULONG& ulRequestID)
- {
- UINT64 data;
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- if(spConfigRun->ReadConfigValueHexInt("MBN", "RequestID", data) == Error_Succeed) {
- ulRequestID = (ULONG)data;
- return TRUE;
- }
- Dbg("Read run config value for RequestID failed");
- return FALSE;
- }
- void CMobileDialFSM::EraseTheRecentInfo(const ULONG ulRequestID)
- {
- LOG_FUNCTION();
- Dbg("the coming id: %d", ulRequestID);
- Dbg("recent type: %d", m_recentInfo.usDialType);
- Dbg("recent request id: %d", m_recentInfo.ulRequestID);
- if(ulRequestID == 0) {
- return;
- }
- if(m_recentInfo.usDialType == CNT_MBN && m_recentInfo.ulRequestID == ulRequestID
- || (m_recentInfo.usDialType == CNT_RAS && m_recentInfo.ulRequestID == ulRequestID)) {
- Dbg("Start to remove recent infor : %d", m_recentInfo.usDialType == CNT_RAS);
- {
- int aim = -1;
- for(int i=0; i<mBlackSheepCount; ++i) {
- if(!m_recentInfo.strDongle.Compare(m_blackSheep[i].strDongle)
- && !m_recentInfo.strProfile.Compare(m_blackSheep[i].strProfile)) {
- aim = i;
- break;
- }
- }
- if(aim != -1) {
- m_blackSheep[aim].dwErrCount++;
- } else if(mBlackSheepCount < MAX_BLACK_SHEEP_NUM) {
- m_blackSheep[mBlackSheepCount].strDongle = m_recentInfo.strDongle;
- m_blackSheep[mBlackSheepCount].strProfile = m_recentInfo.strProfile;
- m_blackSheep[mBlackSheepCount].usDialType = m_recentInfo.usDialType;
- m_blackSheep[mBlackSheepCount].dwErrCount = 1;
- m_blackSheep[mBlackSheepCount].Flag = FALSE;
- mBlackSheepCount++;
- }
- }
- m_recentInfo.usDialType = CNT_INVALID;
- m_recentInfo.ulRequestID = 0;
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- spConfigRun->WriteConfigValue("Recent", "Type", "Invalid");
- spConfigRun->WriteConfigValue("Recent", "Dongle", "");
- spConfigRun->WriteConfigValue("Recent", "Profile", "");
- spConfigRun->WriteConfigValueInt("Recent", "Manual", 0);
- spConfigRun->WriteConfigValueHexInt("Recent", "RequestID", 0);
- } else {
- Dbg("try to erase the recent dial info failed!");
- }
- }
- void CMobileDialFSM::SetAutoManage(bool bAuto /*= true*/)
- {
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- spConfigRun->WriteConfigValueInt("init", "ManualManage", bAuto ? 0 : 1);
- if(m_bManageByUser == bAuto) {
- m_bManageByUser = !bAuto;
- if(!m_bManageByUser && GetCurrState()->id == s5) {
- Dbg("Recover and should to run...s5 entry");
- ConnectTask* task = new ConnectTask(this);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- }
- }
- }
- void CMobileDialFSM::SetAdvancedGen(int newValue)
- {
- if(newValue == 1) {
- newValue = ADVANCE_RAS;
- } else if(newValue == 2) {
- newValue = ADVANCE_MBN;
- } else if(newValue == 3) {
- newValue = 0;
- } else if(newValue == 4) {
- newValue = ADVANCE_MBB;
- } else {
- return;
- }
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- spConfigRun->WriteConfigValueInt("init", "GenAdvanced", newValue);
- //m_nAdvancedGen = newValue;
- }
- // 映射到窗体的Radio控件的顺序
- int CMobileDialFSM::GetAdvancedGen(bool fRead5RunCfg /*= false*/)
- {
- int ret = 0;
- if(!fRead5RunCfg) {
- ret = m_nAdvancedGen;
- } else {
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- spConfigRun->ReadConfigValueInt("init", "GenAdvanced", ret);
- if(ret != ADVANCE_MBB && ret != ADVANCE_MBN && ret != ADVANCE_RAS) {
- ret = 0;
- }
- }
- if(ret == ADVANCE_RAS) {
- return 1;
- } else if(ret == ADVANCE_MBN) {
- return 2;
- } else if(ret == ADVANCE_MBB) {
- return 4;
- }
- return 3;
- }
- BOOL CMobileDialFSM::isUsingNewVerAllInOne()
- {
- #if HAS_NEW_ALL_IN_ONE
- static int status = -1;
- if(status == -1) {
- if(m_SafeWirelessClient == NULL) {
- EnterCriticalSection(&m_cs4WirlessClient);
- if(m_SafeWirelessClient == NULL) {
- m_SafeWirelessClient = new MySpace::WirelessAgentSafeClient(this);
- }
- LeaveCriticalSection(&m_cs4WirlessClient);
- }
- BOOL isActive = FALSE, isConnected = FALSE;
- ErrorCodeEnum ec = m_SafeWirelessClient->IsActive(isActive, isConnected);
- if(ec == Error_Succeed) {
- if(isActive) {
- status = 1;
- } else {
- status = 0;
- }
- }
- }
- if(status == -1) {
- BOOL active = FALSE;
- CSimpleStringA strDevName;
- ErrorCodeEnum ec = SpDetectWirelessConfig(GetEntityBase(), active, strDevName);
- if(active) {
- status = 1;
- } else if(ec == 0) {
- status = 0;
- }
- }
- if(status == 1) {
- return TRUE;
- }
- #endif
- return FALSE;
- }
- ErrorCodeEnum CMobileDialFSM::SwitchDefaultSlot(int slotIdx)
- {
- return m_SafeWirelessClient->SetDefaultSlot(slotIdx);
- }
- void CMobileDialFSM::SaveMBBConfig(const MBBParams* param, BOOL autoSave)
- {
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- spConfigRun->WriteConfigValue("MBB", "Username", param->loginParam.strUsername);
- CSimpleStringA csEValue = EncryptString(param->loginParam.strPassword);
- spConfigRun->WriteConfigValue("MBB", "Password", csEValue);
- spConfigRun->WriteConfigValueInt("MBB", "ConnectType", param->connectType);
- spConfigRun->WriteConfigValue("MBB", "SSID", param->wlanConnectParam.strUsername);
- csEValue = EncryptString(param->wlanConnectParam.strPassword);
- spConfigRun->WriteConfigValue("MBB", "SharedKey", csEValue);
- spConfigRun->WriteConfigValueInt("MBB", "Hidden", param->wlanConnectParam.Flag);
- spConfigRun->WriteConfigValueInt("MBB", "Customized", autoSave ? FALSE : TRUE);
- if(!autoSave) {
- Dbg("Update MBB param from outside.");
- }
- }
- bool CMobileDialFSM::GetMBBConfig(MBBParams* param, BOOL fSetDefaultIfEmpty)
- {
- if(param == NULL) {
- return false;
- }
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- param->connectType = MBB_CONNECT_UNKONWN;
- spConfigRun->ReadConfigValueInt("MBB", "ConnectType", param->connectType);
- param->loginParam.strUsername.Clear();
- spConfigRun->ReadConfigValue("MBB", "Username", param->loginParam.strUsername);
- CSimpleStringA csEValue;
- spConfigRun->ReadConfigValue("MBB", "Password", csEValue);
- param->loginParam.strPassword.Clear();
- param->loginParam.strPassword = DecryptString(csEValue);
- param->loginParam.Flag = FALSE;
- param->wlanConnectParam.strUsername.Clear();
- spConfigRun->ReadConfigValue("MBB", "SSID", param->wlanConnectParam.strUsername);
- csEValue.Clear();
- spConfigRun->ReadConfigValue("MBB", "SharedKey", csEValue);
- param->wlanConnectParam.strPassword.Clear();
- param->wlanConnectParam.strPassword = DecryptString(csEValue);
- param->wlanConnectParam.Flag = FALSE;
- spConfigRun->ReadConfigValueInt("MBB", "Hidden", param->wlanConnectParam.Flag);
- param->customSet = FALSE;
- spConfigRun->ReadConfigValueInt("MBB", "Customized", param->customSet);
- BOOL fResetFlag = FALSE;
- if(fSetDefaultIfEmpty) {
- if(param->connectType == MBB_CONNECT_UNKONWN) {
- param->connectType = MBB_CONNECT_WIFI;
- fResetFlag = TRUE;
- }
- if(param->loginParam.strUsername.IsNullOrEmpty()
- || param->loginParam.strPassword.IsNullOrEmpty()) {
- param->loginParam.strUsername = DEFAULT_MIFI_LOGIN_USERNAME;
- param->loginParam.strPassword = DEFAULT_PASSWORD_PREFIX;
- param->loginParam.strPassword += m_strTerminalNo.SubString(0, 6);
- param->loginParam.Flag = FALSE;
- fResetFlag = TRUE;
- }
- if(param->wlanConnectParam.strUsername.IsNullOrEmpty()
- || param->wlanConnectParam.strPassword.IsNullOrEmpty()) {
- CSimpleStringA strNewSSID(m_strTerminalNo.GetData());
- strNewSSID += "-MIFI";
- CSimpleStringA strNewPassword(DEFAULT_PASSWORD_PREFIX);
- strNewPassword += m_strTerminalNo.SubString(6, m_strTerminalNo.GetLength() - 6);
- param->wlanConnectParam.strUsername = strNewSSID;
- param->wlanConnectParam.strPassword = strNewPassword;
- param->wlanConnectParam.Flag = TRUE;
- param->customSet = FALSE;
- fResetFlag = TRUE;
- }
- }
- if(param != &mMBBParam && !fResetFlag) {
- mMBBParam.connectType = param->connectType;
- mMBBParam.loginParam.strUsername = (LPCTSTR)param->loginParam.strUsername;
- mMBBParam.loginParam.strPassword = (LPCTSTR)param->loginParam.strPassword;
- mMBBParam.loginParam.Flag = param->loginParam.Flag;
- mMBBParam.wlanConnectParam.strUsername = (LPCTSTR)param->wlanConnectParam.strUsername;
- mMBBParam.wlanConnectParam.strPassword = (LPCTSTR)param->wlanConnectParam.strPassword;
- mMBBParam.wlanConnectParam.Flag = param->wlanConnectParam.Flag;
- mMBBParam.customSet = param->customSet;
- } else {
- csEValue.Clear();
- spConfigRun->ReadConfigValue("MBB", "StoredSharedKey", csEValue);
- m_strReservedPasword = DecryptString(csEValue); /*暂时没有用*/
- }
- return true;
- }
- ErrorCodeEnum CMobileDialFSM::ConnectWlan()
- {
- connect_param conn_param_;
- memset(&conn_param_, 0, sizeof(conn_param_));
- conn_param_.temporary_mode = true;
- //if(m_strReservedPasword.IsNullOrEmpty()
- // || 0 != mMBBParam.wlanConnectParam.strPassword.Compare(m_strReservedPasword.GetData())) {
- // LogEvent(Severity_Middle, 0, "Need to update password!");
- // conn_param_.rewrite_password = true;
- // strcpy_s(conn_param_.new_password, mMBBParam.wlanConnectParam.strPassword.GetData());
- //}
- conn_param_.hidden_mode = !!mMBBParam.wlanConnectParam.Flag;
- strcpy_s(conn_param_.friendly_name, mMBBParam.wlanConnectParam.strUsername.GetData());
- strcpy_s(conn_param_.password, mMBBParam.wlanConnectParam.strPassword.GetData());
- Dbg("Start to connect wifi %s", conn_param_.friendly_name);
- Dbg("hidden or not? %s", conn_param_.hidden_mode ? "true" : "false");
- if(m_dwWlanConnectTimes % 3 == 0 && !conn_param_.hidden_mode) {
- LogWarn(Severity_Low, Error_DataCheck, CombineErrorCode(MBD_WLAN_SSID_VISIBLE), "安全起见,请勿将 WLAN 设为广播模式!!");
- }
- int rc = spagent::spagent_assistor::connect_wifi_with_param(&conn_param_);
- Dbg("connect to wifi(%s) returned: %d", conn_param_.friendly_name, rc);
- if(rc != 0) {
- LogWarn(Severity_Low, Error_NetBroken, 0, (LPCTSTR)CSimpleStringA::Format("connect to %s failed, hidden mode(%s): %d",
- conn_param_.friendly_name, (conn_param_.hidden_mode ? "true" : "false"), rc));
- }
- return (ErrorCodeEnum)rc;
- }
- BOOL CMobileDialFSM::NeedToConnectWifi()
- {
- LOG_ASSERT(!mMBBParam.wlanConnectParam.strUsername.IsNullOrEmpty());
- std::string ssid;
- //Dbg("start to find out whether is connected or not..");
- int rc = spagent::spagent_assistor::is_connected(conn_tool_wifi, ssid);
- if(rc == 0) {
- Dbg("wifi is not connect !");
- } else if(rc > 0) {
- Dbg("wifi is connected and connected ssid is: %s", ssid.c_str());
- if(mMBBParam.wlanConnectParam.strUsername.Compare(ssid.c_str())) {
- //Dbg("force reconnect wifi bcz the ssid is not: %s", (LPCTSTR)mMBBParam.wlanConnectParam.strUsername);
- LogWarn(Severity_High, Error_Unexpect, CombineErrorCode(MBD_WLAN_CONNECTED_WITH_ILLEGAL_SSID),
- CSimpleStringA::Format("Unexpected wifi %s is connected, force to reconnect to %s immediately!",
- ssid.c_str(), mMBBParam.wlanConnectParam.strUsername.GetData()));
- rc = 0;
- }
- }
- return (rc == 0);
- }
- void CMobileDialFSM::UpdateWifiPassword(const CSimpleStringA& password)
- {
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- CSimpleStringA csEValue = EncryptString(password);
- spConfigRun->WriteConfigValue("MBB", "StoredSharedKey", csEValue);
- m_strReservedPasword = (LPCTSTR)password;
- }
- int CMobileDialFSM::RetriveMifiInfo()
- {
- if(m_HwDeviceMnt->detect_devices()) {
- int res = _LoginMBBDevice(mMBBParam);
- if(res != 0) {
- return res;
- }
- g_DongleInfos.Init(1);
- MbnDongleInfo& dongle = g_DongleInfos[0];
- dongle.profileList.Clear();
- res = _GetMBBDeviceInfo(dongle);
- if(res < 0) {
- return res;
- }
- _GetMBBProfiles(dongle);
- return 1;
- } else {
- SendMsgToDialog("未找到MIFI设备!");
- return 0;
- }
- }
- BOOL CMobileDialFSM::SwithMBBConnectStatus(BOOL toConnect)
- {
- if(!toConnect) {
- int res = m_HwDeviceMnt->disconnect();
- if(res == 0) {
- Dbg("disconnect mifi network succ.");
- return TRUE;
- }
- else {
- const auto tmp = MBBResult2Status(res);
- //SetHWStatus(tmp);
- m_csErrMsg = CSimpleStringA::Format("MIFI断开上网连接失败!(%s)", ConvertStatusToString(tmp));
- return FALSE;
- }
- } else {
- int res = m_HwDeviceMnt->connect();
- if(res == 0) {
- Dbg("connect mifi network succ.");
- return TRUE;
- }
- else {
- const auto tmp = MBBResult2Status(res);
- //SetHWStatus(tmp);
- m_csErrMsg = CSimpleStringA::Format("MIFI拨号上网连接失败!(%s)", ConvertStatusToString(tmp));
- return FALSE;
- }
- }
- }
- void CMobileDialFSM::CheckHWDeviceStatus()
- {
- BOOL fToExtend = FALSE;
- if(m_nAdvancedGen == ADVANCE_MBB) {
- if(mMBBParam.connectType == MBB_CONNECT_WIRE) {
- if(CheckLANConnectStatus() == 0) {
- SetHWStatus(MBD_NO_MOBILEDONGLE);
- } else {
- SetHWStatus(MBD_ACTIVATION_CONNECTED);
- fToExtend = TRUE;
- }
- } else if(mMBBParam.connectType == MBB_CONNECT_WIFI) {
- if(NeedToConnectWifi()) {
- SetHWStatus(MBD_WLAN_DISCONNECTED);
- } else {
- SetHWStatus(MBD_WLAN_CONNECTED);
- fToExtend = TRUE;
- }
- } else {
- SetHWStatus(MBD_RUN_CONFIG_INCOMPLEMENT);
- }
- Dbg("Huawei status: %s", ConvertStatusToString(GetHWStatus()));
- if(fToExtend) {
- const int res = RetriveMifiInfo();
- }
- }
- }
- void CMobileDialFSM::_ConvertToMBBApnStruct(const AccessKeyInfo& newInfo, hw::apn_config_t& config)
- {
- memset(&config, 0, sizeof(hw::apn_config_t));
- wcscpy_s(config.profile_name, spagent::util::string_util::s2w(newInfo.strProfileDesc.GetData()).c_str());
- wcscpy_s(config.apn_name, spagent::util::string_util::s2w(newInfo.strAccessString.GetData()).c_str());
- wcscpy_s(config.username, spagent::util::string_util::s2w(newInfo.strUserName.GetData()).c_str());
- wcscpy_s(config.password, spagent::util::string_util::s2w(newInfo.strPassword.GetData()).c_str());
- if(newInfo.usAPType == AUPR_PAP) {
- config.auth_mode = hw::auth_pap;
- } else if(newInfo.usAPType == AUPR_CHAP) {
- config.auth_mode = hw::auth_chap;
- } else if(newInfo.usAPType == AUPR_PAPORCHAP) {
- config.auth_mode = hw::auth_none;
- } else {
- config.auth_mode = hw::auth_auto;
- }
- if(newInfo.strIPType.Compare("IPv4") == 0) {
- config.ip_type = hw::ipv4;
- } else if(newInfo.strIPType.Compare("IPv6") == 0) {
- config.ip_type = hw::ipv6;
- } else /*if(newInfo.strIPType.Compare("IPv4v6") == 0)*/ {
- config.ip_type = hw::ipv46;
- }
- }
- int CMobileDialFSM::_GetMBBDeviceInfo(MbnDongleInfo& dongle)
- {
- InitMbnDongleSubInfo(&dongle.subInfo);
- dongle.state = MBD_ACTIVATION_DISCONNECTED;
- dongle.usDeviceType = DEVTYPE_MBB;
- hw::dev_info_t dev_info;
- Dbg("start to get dev info...");
- int res = m_HwDeviceMnt->get_dev_info(dev_info);
- if(res == 0) {
- dongle.subInfo.strProviderName = spagent::util::string_util::w2s(dev_info.dev_name).c_str();
- dongle.subInfo.strDeviceID = spagent::util::string_util::w2s(dev_info.imsi).c_str();
- dongle.subInfo.strManufacturer = spagent::util::string_util::w2s(dev_info.sn).c_str();
- dongle.subInfo.strCellularClass = spagent::util::string_util::w2s(dev_info.work_mode).c_str();
- dongle.subInfo.strFirmware = spagent::util::string_util::w2s(dev_info.hardware_version).c_str();
- dongle.subInfo.strSimIccID = spagent::util::string_util::w2s(dev_info.iccid).c_str();
- dongle.subInfo.strMode = spagent::util::string_util::w2s(dev_info.provider_name).c_str();
- dongle.csInterfaceId = spagent::util::string_util::w2s(dev_info.dev_name).c_str();
- dongle.subInfo.ulSingnal = dev_info.network_status.signal_strength;
- dongle.subInfo.mbnCntState = MBN_ACTIVATION_STATE_NONE;
- Dbg("connect status: %d", (int)dev_info.network_status.connect_status);
- if(dev_info.network_status.connect_status == hw::connected) {
- dongle.subInfo.mbnCntState = MBN_ACTIVATION_STATE_ACTIVATED;
- } else if(dev_info.network_status.connect_status == hw::connecting) {
- dongle.subInfo.mbnCntState = MBN_ACTIVATION_STATE_ACTIVATING;
- } else if(dev_info.network_status.connect_status == hw::disconnecting) {
- dongle.subInfo.mbnCntState = MBN_ACTIVATION_STATE_DEACTIVATING;
- } else if(dev_info.network_status.connect_status == hw::disconnected) {
- dongle.subInfo.mbnCntState = MBN_ACTIVATION_STATE_DEACTIVATED;
- }
- dongle.state = GetMBBConnectState(dev_info.network_status);
- SetHWStatus(dongle.state);
- Dbg("dongle connect status: %d", (int)dongle.subInfo.mbnCntState);
- } else {
- Dbg("get the mifi dev information failed: %d", res);
- const auto tmp = MBBResult2Status(res);
- //SetHWStatus(tmp);
- SendMsgToDialog(CSimpleStringA::Format("获取MIFI设备信息失败 (%s)", ConvertStatusToString(tmp)));
- res = -1;
- }
- return res;
- }
- int CMobileDialFSM::_GetMBBProfiles(MbnDongleInfo& dongle)
- {
- std::vector<hw::connect_profile_t> profiles;
- Dbg("start to get connect profile...");
- hw::connect_profile_t* profile = new hw::connect_profile_t[PROFILE_MAX_COUNT];
- memset(profile, 0, sizeof(hw::connect_profile_t)*PROFILE_MAX_COUNT);
- int profileNum = PROFILE_MAX_COUNT;
- //int nNum = m_HwDeviceMnt->get_connect_profiles(profiles);
- int nNum = m_HwDeviceMnt->get_profiles(profile, profileNum);
- Dbg("get_connect_profiles returned %d", nNum);
- if(nNum > 0) {
- dongle.profileList.Init(nNum);
- int idx = 0;
- //while(it != nullptr) {
- for(int i=0; i<nNum; ++i) {
- const hw::connect_profile_t* it = &profile[i];
- //for(auto it=profiles.cbegin(); it!=profiles.cend(); ++it) {
- MbnProfileInfo& profile = dongle.profileList[idx];
- InitAccessKeyInfo(&dongle.profileList[idx].AccessInfo);
- profile.bUserDefined = true;
- profile.AccessInfo.usCntType = CNT_MBB;
- profile.AccessInfo.strProfileDesc = spagent::util::string_util::w2s(it->apn_config.profile_name).c_str();
- profile.strProfileName = CSimpleStringA::Format("%d", it->index);
- profile.AccessInfo.IsDefault = it->is_default;
- if(it->is_default) {
- dongle.subInfo.strProfileName = profile.strProfileName.GetData();
- }
- profile.AccessInfo.strAccessString = spagent::util::string_util::w2s(it->apn_config.apn_name).c_str();
- profile.AccessInfo.strUserName = spagent::util::string_util::w2s(it->apn_config.username).c_str();
- profile.AccessInfo.strPassword = spagent::util::string_util::w2s(it->apn_config.password).c_str();
- //TODO: 新版的MIFI有给定特殊的********号字符,需要做处理,后续验证
- if(profile.AccessInfo.strPassword.IsNullOrEmpty()) {
- _RetrieveMBBPassword(profile.AccessInfo.strProfileDesc, profile.AccessInfo.strPassword);
- }
- if(it->apn_config.auth_mode == hw::auth_auto) {
- profile.AccessInfo.usAPType = AUPR_AUTO;
- } else if(it->apn_config.auth_mode == hw::auth_pap) {
- profile.AccessInfo.usAPType = AUPR_PAP;
- } else if(it->apn_config.auth_mode == hw::auth_chap) {
- profile.AccessInfo.usAPType = AUPR_CHAP;
- } else if(it->apn_config.auth_mode == hw::auth_none) {
- profile.AccessInfo.usAPType = AUPR_PAPORCHAP;
- }
- if(it->apn_config.ip_type == hw::ipv4) {
- profile.AccessInfo.strIPType = "IPv4";
- } else if(it->apn_config.ip_type == hw::ipv6) {
- profile.AccessInfo.strIPType = "IPv6";
- } else {
- profile.AccessInfo.strIPType = "IPv4v6";
- }
- idx++;
- }
- }
- else {
- const auto tmp = MBBResult2Status(nNum);
- }
- delete [] profile;
- return nNum;
- }
- void CMobileDialFSM::_StoreMBBPassword(const CSimpleStringA& profileName, const CSimpleStringA& password)
- {
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- CSimpleStringA csEValue = EncryptString(password);
- spConfigRun->WriteConfigValue(profileName, "Password", csEValue);
- }
- void CMobileDialFSM::_RetrieveMBBPassword(const CSimpleStringA& profileName, CSimpleStringA& password)
- {
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- CSimpleStringA csValue;
- spConfigRun->ReadConfigValue(profileName, "Password", csValue);
- password = DecryptString(csValue);
- }
- int CMobileDialFSM::_LoginMBBDevice(const MBBParams& newParam)
- {
- int res = 0;
- bool firstLogin = false;
- if(!m_HwDeviceMnt->has_login(firstLogin)) {
- std::wstring username = spagent::util::string_util::s2w(newParam.loginParam.strUsername.GetData());
- std::wstring password = spagent::util::string_util::s2w(newParam.loginParam.strPassword.GetData());
- //Dbg("start to login: %s, %s", (LPCTSTR)newParam.loginParam.strUsername, (LPCTSTR)newParam.loginParam.strPassword);
- Dbg("start to login: %s %d", (LPCTSTR)newParam.loginParam.strUsername, newParam.loginParam.strPassword.GetLength());
- res = m_HwDeviceMnt->login(username, password);
- const auto tmp = MBBResult2Status(res);
- if(res == -3) {
- Dbg("login failed: incorrect usrname or password!");
- SendMsgToDialog("登录密码不正确!");
- } else if(res != 0) {
- Dbg("login returned %s", ConvertStatusToString(tmp));
- //SetHWStatus(tmp);
- m_csErrMsg = CSimpleStringA::Format("登录到MIFI设备失败(%s)!", ConvertStatusToString(tmp));
- SendMsgToDialog(m_csErrMsg);
- }
- }
- return res;
- }
- int CMobileDialFSM::_UpdateMBBDualParam(int configMask, MBBParams& newParam)
- {
- /*对于MIFI3,需要先改密码然后再更新WIFI信息,否则后面的MAC过滤地址会报9003的错误*/
- if(!!(configMask & 4)) {
- std::wstring username = CSimpleStringA2W(newParam.loginParam.strUsername).GetData();
- std::wstring password = CSimpleStringA2W(newParam.loginParam.strPassword).GetData();
- const CSimpleStringA oldPassword = newParam.loginParam.strPassword;
- newParam.loginParam.strPassword = DEFAULT_PASSWORD_PREFIX;
- newParam.loginParam.strPassword += m_strTerminalNo.SubString(0, 6);
- std::wstring newPassword = CSimpleStringA2W(newParam.loginParam.strPassword).GetData();
- int res = m_HwDeviceMnt->change_password(username, password, newPassword);
- Dbg("update login password returned: %d",res);
- if(res != 0) {
- newParam.loginParam.strPassword = oldPassword;
- configMask &= (int(~4));
- const auto tmp = MBBResult2Status(res);
- Dbg("change_password failed: %s", ConvertStatusToString(tmp));
- return -1;
- }
- }
- if(!!(configMask & 1)) {
- hw::wlan_config_t new_wlan_config;
- memset(&new_wlan_config, 0, sizeof(hw::wlan_config_t));
- CSimpleStringW strUsernameW = CSimpleStringA2W(newParam.wlanConnectParam.strUsername);
- CSimpleStringW strPasswordW = CSimpleStringA2W(newParam.wlanConnectParam.strPassword);
- wcscpy_s(new_wlan_config.ssid, strUsernameW.GetData());
- wcscpy_s(new_wlan_config.password, strPasswordW.GetData());
- new_wlan_config.hidden = !!newParam.wlanConnectParam.Flag;
- int save_res = m_HwDeviceMnt->set_wlan_config(new_wlan_config, true);
- Dbg("update wlan config returned: %d", save_res);
- if(save_res != 0) {
- const auto tmp = MBBResult2Status(save_res);
- Dbg("set wlan config failed: %s", ConvertStatusToString(tmp));
- return -1;
- }
- }
- if(!!(configMask & 2) || !!(configMask & 4)) {
- Dbg("Write to the run config");
- LOG_ASSERT(!newParam.loginParam.strUsername.IsNullOrEmpty());
- LOG_ASSERT(!newParam.loginParam.strPassword.IsNullOrEmpty());
- LOG_ASSERT(!newParam.wlanConnectParam.strUsername.IsNullOrEmpty());
- LOG_ASSERT(!newParam.wlanConnectParam.strPassword.IsNullOrEmpty());
- SaveMBBConfig(&newParam);
- }
- return 0;
- }
- MOBILEDIAL_CONNECTION_STATE CMobileDialFSM::GetMBBConnectState(const hw::network_info_t& info)
- {
- if(info.sim_locked) {
- return MBD_READY_DEVICE_LOCKED;
- } else if(info.sim_status == hw::sim_not_found) {
- return MBD_READY_SIM_NO_INSERT;
- } else if(info.sim_status == hw::invalid_sim) {
- return MBD_READY_BAD_SIM;
- }
- if(info.connect_status == hw::connected) {
- return MBD_ACTIVATION_CONNECTED;
- } else if(info.connect_status == hw::connecting) {
- return MBD_ACTIVATION_CONNECTING;
- } else if(info.connect_status == hw::disconnecting) {
- return MBD_ACTIVATION_DISCONNECTING;
- } else if(info.connect_status == hw::disconnected) {
- return MBD_ACTIVATION_DISCONNECTED;
- } else if(info.connect_status == hw::connect_failed
- || info.connect_status == hw::connect_failed_with_poor) {
- return MBD_CONNECTION_FAILURE;
- } else if(info.connect_status == hw::no_service) {
- return MBD_READY_NO_SERVICE;
- } else if(info.connect_status == hw::connect_dial_up_param_failed) {
- return MBD_CONNECTION_FAILURE;
- } else {
- return MBD_ACTIVATION_NONE;
- }
- }
- ErrorCodeEnum CMobileDialFSM::_InsertLocal2MacFilter()
- {
- ErrorCodeEnum ec = Error_Succeed;
- if(mMBBParam.connectType == MBB_CONNECT_WIRE) {
- return ec;
- }
- std::vector<std::string> wlanKeys;
- wlanKeys.push_back("wlan");
- CSmartPointer<IConfigInfo> spConfigRun;
- GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
- CSimpleStringA csWlanName;
- BOOL fNeedEnum = TRUE;
- std::string strNewMac;
- LOG_ASSERT(!m_strTerminalNo.IsNullOrEmpty());
- LOG_ASSERT(!mMBBParam.wlanConnectParam.strUsername.IsNullOrEmpty());
- CSimpleStringA strTerminalxSSID = m_strTerminalNo + "x" + mMBBParam.wlanConnectParam.strUsername;
- int insertOrNot = 0;
- //spConfigRun->ReadConfigValueInt("MIFI", strTerminalxSSID, insertOrNot);
- //if(insertOrNot > 0) {
- // return Error_Succeed;
- //}
- spConfigRun->ReadConfigValue("MIFI", "WlanMacName", csWlanName);
- if(!csWlanName.IsNullOrEmpty()) {
- Dbg("add wlan name from run config: %s", csWlanName.GetData());
- CAutoArray<CSimpleStringA> csMacAddress = csWlanName.Split(':');
- if(csMacAddress.GetCount() == 6) {
- fNeedEnum = FALSE;
- strNewMac = csWlanName.GetData();
- }
- }
- if(fNeedEnum) {
- int aimIndex = -1;
- network_adapters local_adapters;
- const int count_of_adapters = spagent::spagent_assistor::get_network_adapters(local_adapters);
- for(int i=0; i<count_of_adapters; ++i) {
- std::string compare_name = local_adapters.adapters[i].friend_name;
- Dbg("wlan name[%d]: %s", i, compare_name.c_str());
- if(!csWlanName.IsNullOrEmpty()) {
- if(csWlanName.Compare(compare_name.c_str(), true) == 0) {
- aimIndex = i;
- break;
- }
- } else {
- std::string name = spagent::util::string_util::tolower(compare_name);
- for(auto it=wlanKeys.cbegin(); it!=wlanKeys.cend(); ++it) {
- if(name.find(*it) != std::string::npos) {
- aimIndex = i;
- break;
- }
- }
- if(aimIndex != -1) {
- break;
- }
- }
- }
- if(aimIndex != -1) {
- strNewMac = local_adapters.adapters[aimIndex].mac;
- Dbg("combine mac address: %s", strNewMac.c_str());
- ec = Error_Succeed;
- } else {
- ec = Error_NotExist;
- LogWarn(Severity_Middle, ec, CombineErrorCode(MBD_INTERNAL_ERROR),
- "获取不到WLAN网卡信息,请联系信息技术人员协助处理!");
- }
- }
- if(!strNewMac.empty()) {
- Dbg("s2w....");
- std::wstring wMacString = spagent::util::string_util::s2w(
- spagent::util::string_util::toupper(strNewMac));
- Dbg("insert mac filter....");
- hw::mac_filter_t filter_info;
- int res = 0;
- for(int t=1; t<=5; ++t)
- {
- memset(&filter_info, 0, sizeof(filter_info));
- wcscpy_s(filter_info.mac_filter, wMacString.c_str());
- res = m_HwDeviceMnt->insert_mac_filter(filter_info);
- Dbg("insert mac returned: %d", res);
- if(res == 0)
- break;
- Sleep(300*t);
- }
- if(res != 0) {
- //LogError(Severity_High, Error_Unexpect,
- // CombineErrorCode(MBBResult2Status(res)),
- // );
- ShowFatalError(CSimpleStringA::Format("写入MAC白名单失败:%s", ConvertStatusToString(MBBResult2Status(res))));
- } else {
- spConfigRun->WriteConfigValueInt("MIFI", strTerminalxSSID, 1);
- }
- } else {
- ShowFatalError("获取不到 WLAN 网卡信息,请联系信息技术人员协助处理!");
- }
- return ec;
- }
- void CMobileDialFSM::SetSysVal(int nFlag)
- {
- CSmartPointer<IEntityFunction> spFunction = this->GetEntityBase()->GetFunction();
- CSimpleStringA csStatus;
- CSimpleStringA csNewStatus = sysVarNetStatusEnum[NET_STATUS_UNINIT];
- ErrorCodeEnum err;
- err = spFunction->GetSysVar(SYSVAR_NET_STATUS, csStatus);
- Dbg("Current sys val of " SYSVAR_NET_STATUS " : %s(%d)", (LPCTSTR)csStatus, err);
- if(nFlag >= sizeof(sysVarNetStatusEnum)/sizeof(sysVarNetStatusEnum[0])) {
- Dbg("out range of current sys var list: %d", nFlag);
- } else {
- csNewStatus = sysVarNetStatusEnum[nFlag];
- }
- if(csNewStatus != csStatus) {
- err = spFunction->SetSysVar(SYSVAR_NET_STATUS, csNewStatus, true);
- Dbg("SetSysVar " SYSVAR_NET_STATUS " from '%s' to '%s' returned %d",
- (LPCTSTR)csStatus, (LPCTSTR)csNewStatus, err);
- } else {
- Dbg("system value is same with already one.");
- }
- return;
- }
- void CMobileDialFSM::ReportConnectType()
- {
- CSimpleStringA str(true);
- MOBILEDIAL_CONNECTION_STATE state = MBD_NOT_INITIALIZED;
- if(!m_bManufactureSignal) {
- if(m_bPadAndLIB) {
- state = MBD_CABLE_TYPE_WIRE;
- } else if(m_nAdvancedGen == ADVANCE_MBB) {
- state = MBD_CABLE_TYPE_MBB;
- } else if(m_nAdvancedGen == ADVANCE_RAS) {
- state = MBD_CABLE_TYPE_DONGLE;
- } else if(g_DongleInfos.GetCount() > 0){
- const int cnt = g_DongleInfos.GetCount();
- for(int i=0; i<cnt; ++i) {
- if(g_DongleInfos[i].state == MBD_ACTIVATION_CONNECTED) {
- if(g_DongleInfos[i].usDeviceType == DEVTYPE_MODEM) {
- state = MBD_CABLE_TYPE_DONGLE;
- } else if(g_DongleInfos[i].usDeviceType == DEVTYPE_MBB){
- state = MBD_CABLE_TYPE_MBB;
- } else if(!g_DongleInfos[i].subInfo.strManufacturer.IsNullOrEmpty()) {
- const CSimpleStringA& man = g_DongleInfos[i].subInfo.strManufacturer;
- const CSimpleStringA& mode = g_DongleInfos[i].subInfo.strMode;
- if(!man.Compare("Surface", true)
- && !mode.Compare("Surface Mobile Broadband")) {
- state = MBD_CABLE_TYPE_LTE;
- } else if(man.Compare("huawei", true) == 0) {
- state = MBD_CABLE_TYPE_DONGLE;
- } else {
- Dbg("Unrecognized: %s", man.GetData());
- state = MBD_CABLE_TYPE_DONGLE;
- }
- }
- }
- }
- } else {
- // 可能会因为有线插入可联网的华为 MIFI 触发该操作 [6/30/2020 11:06 @Gifur]
- Dbg("unknown connect type. don't know how just connected!");
- state = MBD_CABLE_TYPE_UNKNOWN;
- }
- }
- if(state != MBD_NOT_INITIALIZED) {
- LogWarn(Severity_Low, Error_NoDefine, CombineErrorCode(state), ConvertStatusToString(state));
- m_bManufactureSignal = TRUE;
- }
- }
- BOOL CMobileDialFSM::BornValidSSIDAndPsw(CSimpleStringA& strNewSSID, CSimpleStringA& strNewPsw)
- {
- strNewSSID = m_strTerminalNo.GetData();
- strNewSSID += "-MIFIX";
- strNewPsw = DEFAULT_PASSWORD_PREFIX;
- strNewPsw += m_strTerminalNo.SubString(6, m_strTerminalNo.GetLength() - 6);
- return TRUE;
- }
- void CMobileDialFSM::MBBDeviceMonitoring()
- {
- LOG_FUNCTION();
- if(m_fMBBDeviceMonitoring) {
- Dbg("the monitoring task has been setup before.");
- return;
- }
- m_fMBBDeviceMonitoring = TRUE;
- m_fMBBDeviceMonitorStop = FALSE;
- int res = 0;
- int sleepTimes = 0;
- volatile int sleepMaxTimes = 6;
- while(m_HwDeviceMnt != NULL && !m_fMBBDeviceMonitorStop) {
-
- sleepMaxTimes = 6;
- hw::network_info_t info;
- res = m_HwDeviceMnt->get_network_info(info);
- if(res == 0) {
- CSimpleStringA strNewDevName = CSimpleStringW2A(CSimpleStringW(info.dev_name));
- if(m_curMIFIDevName.IsNullOrEmpty() || m_curMIFIDevName.Compare(strNewDevName) != 0) {
- /*借来一用,反正新版多合一没戏了*/
- EnterCriticalSection(&m_cs4WirlessClient);
- m_curMIFIDevName = strNewDevName;
- LeaveCriticalSection(&m_cs4WirlessClient);
- }
- if((m_nAdvancedGen != ADVANCE_MBB || mMBBParam.connectType != MBB_CONNECT_WIRE)
- && !IsWifiConnected()) {
- Dbg("plug in status: %d", info.usb_plug_in_status ? 1 : 0);
- if(info.usb_plug_in_status) {
- if(GetCurrState()->id != CMobileDialFSM::s8
- && GetCurrState()->id != CMobileDialFSM::s2) {
-
- ShowFatalError(CSimpleStringA::Format("检测到华为MIFI设备 %s 插入", m_curMIFIDevName.GetData()));
- if(DetectMBBConfigUpdate(FALSE)) {
- Dbg("post USER_EVT_CONFIG_DETECT event.");
- FSMEvent* fsmEvent = new FSMEvent(USER_EVT_CONFIG_DETECT);
- fsmEvent->param1 = 1;
- PostEventFIFO(fsmEvent);
- }
-
- } else {
- LogEvent(Severity_Middle, CombineErrorCode(MBD_HOLD_MOBILEDONGLE),
- CSimpleStringA::Format("检测到华为MIFI: %s 设备插入", m_curMIFIDevName.GetData()));
-
- sleepMaxTimes = 20;
- }
- }
-
- } else {
- if(m_mifiBattery != (int)info.battery_percent) {
- Dbg("mifi's battery changed from %d to %d", m_mifiBattery, (int)info.battery_percent);
- if(info.battery_percent == 0) {
- LogWarn(Severity_High, Error_Hardware,
- CombineErrorCode(MBD_MIFI_LOW_BATTERY), "MIFI设备电量低!");
- }
- m_mifiBattery = (int)info.battery_percent;
- }
- const MOBILEDIAL_CONNECTION_STATE current_state = GetMBBConnectState(info);
- if(GetHWStatus() != current_state) {
- const auto old_status = SetHWStatus(current_state);
- if(current_state == MBD_ACTIVATION_CONNECTED) {
- TellDlgTheResult(Error_Succeed, WM_DIAL_RESULT, ADVANCE_MBB);
- FSMEvent* fsmEvent = new FSMEvent(USER_EVT_CONNECT_COMPLETE);
- fsmEvent->param1 = 0;
- fsmEvent->param2 = ADVANCE_MBB;
- PostEventLIFO(fsmEvent);
-
- } else if(current_state == MBD_ACTIVATION_DISCONNECTED) {
- TellDlgTheResult(Error_Succeed, WM_DIAL_DISCONNECT, ADVANCE_MBB);
- FSMEvent* fsmEvent = new FSMEvent(USER_EVT_DISCONNECT_COMPLETE);
- fsmEvent->param1 = 0;
- fsmEvent->param2 = ADVANCE_MBB;
- }
- }
- if(current_state == MBD_ACTIVATION_CONNECTED) {
- TellDlgTheResult(Error_Succeed, WM_SIGNAL_CHANGE, info.signal_strength);
- const int signalVal = (int)(0.05f * info.signal_strength / 5 * 4);
- if(signalVal != m_signalVal) {
- Dbg("mifi's network signal changed from %d to %d", m_signalVal, signalVal);
- FSMEvent* signalEvent = new FSMEvent(USER_EVT_SIGNAL);
- signalEvent->param1 = signalVal;
- PostEventFIFO(signalEvent);
- m_signalVal = signalVal;
- }
- }
- }
-
- } else if(res != -12 && res != -18 && res != -10) {
- LogWarn(Severity_Low, Error_Unexpect, CombineErrorCode(MBBResult2Status(res)),
- CSimpleStringA::Format("Try to get MBB network infor failed: %s!",
- ConvertStatusToString(MBBResult2Status(res))));
-
- } else if(m_nAdvancedGen != ADVANCE_MBB) {
- if(MBD_MIFI_START < GetHWStatus() && GetHWStatus() < MBD_MIFI_END) {
- SetHWStatus(MBD_NOT_INITIALIZED);
- }
- }
- sleepTimes = 0;
- while(!m_fMBBDeviceMonitorStop && ++sleepTimes <= sleepMaxTimes) {
- Sleep(1000);
- }
- }
- Dbg("out of while %d", m_fMBBDeviceMonitorStop);
- m_fMBBDeviceMonitoring = FALSE;
- }
- void CMobileDialFSM::BroadcastCableChangedEvent(MOBILEDIAL_CONNECTION_STATE state)
- {
- //let it empty at current time.
- bool fDeal = true;
- MOBILEDIAL_CONNECTION_STATE cur_state = state;
- if(state >= MBD_CABLE_DEVICE_REMOVE && state < MBD_CABLE_DEVICE_ARRIVAL) {
- cur_state = MBD_CABLE_DEVICE_REMOVE;
- } else if(state >= MBD_CABLE_DEVICE_ARRIVAL && state < MBD_CABLE_DIALUP_CONNETED) {
- cur_state = MBD_CABLE_DEVICE_ARRIVAL;
- } else if(state >= MBD_CABLE_DIALUP_CONNETED && state < MBD_CABLE_DIALUP_DISCONNETED) {
- cur_state = MBD_CABLE_DIALUP_CONNETED;
- } else if(state >= MBD_CABLE_DIALUP_DISCONNETED && state <= MBD_RAS_DIALUP_DISCONNETED_IN_BUSINESS) {
- cur_state = MBD_CABLE_DIALUP_DISCONNETED;
- } else {
- Dbg("unsupport event: %s", ConvertStatusToString(state));
- fDeal = false;
- }
- if(fDeal) {
- LogEvent(Severity_High, CombineErrorCode(cur_state), ConvertStatusToString(state));
- }
- }
- void CMobileDialFSM::BroadcastCableChangedFSMEvent(const FSMEvent* pEvt)
- {
- switch(pEvt->iEvt) {
- case USER_EVT_DEVICE_ARRIVAL:
- {
- if(pEvt->param2 == 3) {
- if(pEvt->param1 == 1) {
- Dbg("UserCode:0x%08X, 收到3G网卡插入的外部监听事件", CombineErrorCode(MBD_RAS_DEVICE_ARRIVAL));
- //LogEvent(Severity_Middle, CombineErrorCode(MBD_RAS_DEVICE_ARRIVAL), "收到3G网卡插入的外部监听事件");
- } else if(pEvt->param1 == 0) {
- Dbg("UserCode:0x%08X, 收到3G网卡插入的内部处理事件", CombineErrorCode(MBD_RAS_DEVICE_ARRIVAL));
- //LogEvent(Severity_Middle, CombineErrorCode(MBD_RAS_DEVICE_ARRIVAL), "收到3G网卡插入的内部处理事件");
- }
- BroadcastCableChangedEvent(MBD_RAS_DEVICE_ARRIVAL);
- } else if(pEvt->param2 == 4) {
- if(pEvt->param1 == 1) {
- Dbg("UserCode:0x%08X, 收到4G网卡插入的外部监听事件", CombineErrorCode(MBD_MBN_DEVICE_ARRIVAL));
- //LogEvent(Severity_Middle, CombineErrorCode(MBD_MBN_DEVICE_ARRIVAL), "收到4G网卡插入的外部监听事件");
- } else if(pEvt->param1 == 0) {
- Dbg("UserCode:0x%08X, 收到4G网卡插入的内部处理事件", CombineErrorCode(MBD_MBN_DEVICE_ARRIVAL));
- LogEvent(Severity_Middle, CombineErrorCode(MBD_MBN_DEVICE_ARRIVAL), "收到4G网卡插入的内部处理事件");
- }
- BroadcastCableChangedEvent(MBD_MBN_DEVICE_ARRIVAL);
- } else if(pEvt->param2 == 2) {
- LogEvent(Severity_Middle, CombineErrorCode(MBD_MBB_DEVICE_ARRIVAL), "收到有线卡托插入的外部监听事件");
- }
- }
- break;
- case USER_EVT_DEVICE_LEAVE:
- {
- if(pEvt->param2 == 3) {
- if(pEvt->param1 == 1) {
- Dbg("UserCode:0x%08X, 收到3G网卡拔离的外部监听事件", CombineErrorCode(MBD_RAS_DEVICE_REMOVE));
- //LogEvent(Severity_Middle, CombineErrorCode(MBD_RAS_DEVICE_REMOVE), "收到3G网卡拔离的外部监听事件");
- } else if(pEvt->param1 == 0) {
- Dbg("UserCode:0x%08X, 收到3G网卡拔离的内部处理事件", CombineErrorCode(MBD_RAS_DEVICE_REMOVE));
- //LogEvent(Severity_Middle, CombineErrorCode(MBD_RAS_DEVICE_REMOVE), "收到3G网卡拔离的内部处理事件");
- }
- BroadcastCableChangedEvent(MBD_RAS_DEVICE_REMOVE);
- } else if(pEvt->param2 == 4) {
- if(pEvt->param1 == 1) {
- Dbg("UserCode:0x%08X, 收到4G网卡拔离的外部监听事件", CombineErrorCode(MBD_MBN_DEVICE_REMOVE));
- //LogEvent(Severity_Middle, CombineErrorCode(MBD_MBN_DEVICE_REMOVE), "收到4G网卡拔离的外部监听事件");
- } else if(pEvt->param1 == 0) {
- Dbg("UserCode:0x%08X, 收到4G网卡拔离的内部处理事件", CombineErrorCode(MBD_MBN_DEVICE_REMOVE));
- //LogEvent(Severity_Middle, CombineErrorCode(MBD_MBN_DEVICE_REMOVE), "收到4G网卡拔离的内部处理事件");
- }
- BroadcastCableChangedEvent(MBD_MBN_DEVICE_REMOVE);
- }
- }
- break;
- case USER_EVT_CONNECT_COMPLETE:
- {
- Dbg("connect complement! param1(%d)::param2(%d)", pEvt->param1, pEvt->param2);
- if(pEvt->param2 == ADVANCE_RAS) {
- if(pEvt->param1 == 0) {
- Dbg("UserCode:0x%08X, 收到3G网卡已连接的内部处理事件", CombineErrorCode(MBD_RAS_DIALUP_CONNETED));
- //LogEvent(Severity_Middle,CombineErrorCode(MBD_RAS_DIALUP_CONNETED),"收到3G网卡已连接的内部处理事件");
- } else if(pEvt->param1 == 1) {
- Dbg("UserCode:0x%08X, 收到3G网卡已连接的外部监听事件", CombineErrorCode(MBD_RAS_DIALUP_CONNETED));
- //LogEvent(Severity_Middle,CombineErrorCode(MBD_RAS_DIALUP_CONNETED),"收到3G网卡已连接的外部监听事件");
- } else if(pEvt->param1 == -1) {
- Dbg("UserCode:0x%08X, 收到3G网卡连接失败的外部监听事件", CombineErrorCode(MBD_RAS_DIALUP_CONNETED));
- //LogEvent(Severity_Middle,CombineErrorCode(MBD_RAS_DIALUP_CONNETED),"收到3G网卡连接失败的外部监听事件");
- break;
- }
- BroadcastCableChangedEvent(MBD_RAS_DIALUP_CONNETED);
- } else if(pEvt->param2 <= 1 && pEvt->param2 >= -1) {
- if(pEvt->param1 == 0) {
- if(pEvt->param2) {
- Dbg("UserCode:0x%08X, 收到4G网卡拨号连接的 MBN 事件", CombineErrorCode(MBD_MBN_DIALUP_CONNETED));
- BroadcastCableChangedEvent(MBD_MBN_DIALUP_CONNETED);
- break;
- }
- } else if(pEvt->param1 == -1) {
- break;
- }
- BroadcastCableChangedEvent(MBD_CABLE_DIALUP_CONNETED);
- } else {
- BroadcastCableChangedEvent(MBD_CABLE_DIALUP_CONNETED);
- }
- }
- break;
- case USER_EVT_DISCONNECT_COMPLETE:
- {// let the FSM(s5) do this [4/15/2020 18:59 @Gifur]
- if(pEvt->param2 == ADVANCE_RAS && pEvt->param1 == 1) {
- Dbg("UserCode:0x%08X, 收到3G网卡连接断开的外部监听事件", CombineErrorCode(MBD_RAS_DIALUP_DISCONNETED));
- //LogEvent(Severity_Middle,CombineErrorCode(MBD_RAS_DIALUP_DISCONNETED),"收到3G网卡连接断开的外部监听事件");
- //BroadcastCableChangedEvent(MBD_RAS_DIALUP_DISCONNETED);
- } if(pEvt->param2 == ADVANCE_MBN) {
- Dbg("UserCode:0x%08X, 收到4G网卡连接断开事件", CombineErrorCode(MBD_MBN_DIALUP_DISCONNETED));
- //LogEvent(Severity_Middle,CombineErrorCode(MBD_MBN_DIALUP_DISCONNETED),"收到4G网卡连接断开事件");
- BroadcastCableChangedEvent(MBD_MBN_DIALUP_DISCONNETED);
- } else {
- //BroadcastCableChangedEvent(MBD_CABLE_DIALUP_DISCONNETED);
- }
- }
- break;
- case EVT_USER_WIRELESS_STATE:
- {
- if(pEvt->param1 == 0) {
- if(pEvt->param2 == 1)
- //LogEvent(Severity_Middle, CombineErrorCode(MBD_WLAN_DISCONNECTED), "收到指定WIFI断开连接的事件");
- LogError(Severity_Middle, Error_NetBroken, CombineErrorCode(MBD_WLAN_DISCONNECTED), "收到指定WIFI断开连接的事件");
- else if(pEvt->param2 == 2)
- LogWarn(Severity_Middle, Error_Unexpect, CombineErrorCode(MBD_WLAN_CONNECTED), "收到未知WIFI连接的事件");
- } else if(pEvt->param1 == 1) {
- LogEvent(Severity_Middle, CombineErrorCode(MBD_WLAN_CONNECTED), "收到指定WIFI连接的事件");
- }
- }
- break;
- }
- }
- int CMobileDialFSM::DealMBBConfigUpdate(BOOL fCheckOnly)
- {
- LOG_FUNCTION();
- int ec = 0;
- bool fFirstLogin = false;
- MBBParams defaultParam;
- MBBParams* paramPtr = NULL;
- if(fCheckOnly) {
- paramPtr = &defaultParam;
- } else {
- paramPtr = &mMBBParam;
- }
- // 1: write to device,
- // 2: update from device
- // 3: both save and need to update the login password.
- int nNeedConfig = 0;
- if(fCheckOnly || m_HwDeviceMnt->detect_devices()) {
- GetMBBConfig(paramPtr);
- bool fEmptyParam = false;
- if(paramPtr->loginParam.strUsername.IsNullOrEmpty() || paramPtr->loginParam.strPassword.IsNullOrEmpty()) {
- paramPtr->loginParam.strUsername = DEFAULT_MIFI_LOGIN_USERNAME;
- paramPtr->loginParam.strPassword = DEFAULT_PASSWORD_PREFIX;
- LOG_ASSERT(!m_strTerminalNo.IsNullOrEmpty());
- paramPtr->loginParam.strPassword += m_strTerminalNo.SubString(0, 6);
- Dbg("default password.");
- fEmptyParam = true;
- bool firstLogin;
- LOG_ASSERT(!m_HwDeviceMnt->has_login(firstLogin));
- }
- int res = 0;
-
- res = _LoginMBBDevice(*paramPtr);
- if(res == -10) {
- Dbg("detect it's invalid certificate.");
- Sleep(100);
- res = _LoginMBBDevice(*paramPtr);
- }
- if(res == -3) {
- if(!IsMIFI3()) {
- paramPtr->loginParam.strPassword = DEFAULT_MIFI_LOGIN_PASSWORD;
- res = _LoginMBBDevice(*paramPtr);
- //if(res == -3) {
- // Dbg("use backup default password.");
- // paramPtr->loginParam.strPassword = DEFAULT_MIFI_LOGIN_PASSWORD_BACKUP;
- // res = _LoginMBBDevice(*paramPtr);
- //}
-
-
- } else {
- // 添加对华为MIFI3初始化的处理办法 [7/23/2020 14:49 @Gifur]
- if(fCheckOnly) {
- Dbg("detect mifi3 and login failed, check flag return 1");
- return 1;
- } else {
- Dbg("open CMIFIPswDlg...");
- CMIFIPswDlg dlgMain;
- int nRet = dlgMain.DoModal();
- Dbg("open CMIFIPswDlg return: %d %d", nRet, dlgMain.m_strLoginPassword.GetLength());
- if(nRet > 0 && dlgMain.m_strLoginPassword.GetLength() != 0) {
- paramPtr->loginParam.strPassword = (LPCTSTR)dlgMain.m_strLoginPassword;
- Dbg("user input password: %s", paramPtr->loginParam.strPassword.GetData());
- res = _LoginMBBDevice(*paramPtr);
- }
- }
- }
- if(res == 0) {
- fFirstLogin = true;
- }
- }
- if(res == 0) {
- if(!fEmptyParam && !fFirstLogin && paramPtr->customSet) {
- /*如果是手工添加的配置内容,不做更新操作*/
- Dbg("stop from updating mifi config due to customized configure.");
- return 6;
- }
- hw::wlan_config_t wlan_config;
- res = m_HwDeviceMnt->get_wlan_config(wlan_config);
- if(res == 0) {
- CSimpleStringA strSSID(CSimpleStringW2A(wlan_config.ssid));
- CSimpleStringA strPassword(CSimpleStringW2A(wlan_config.password));
- BOOL fvalidSSID = FALSE;
- const BOOL fPswEmpty = strPassword.IsNullOrEmpty();
- if(strSSID.IndexOf("-") == 10) {//TODO: 判断名称是否符合要求
- fvalidSSID = TRUE;
- CSimpleStringA strThirdTerminalNo = strSSID.SubString(0, 10);
- LogEvent(Severity_Low, CombineErrorCode(MBD_HOLD_MOBILEDONGLE),
- CSimpleStringA::Format("the terminal sn in ssid: %s", strThirdTerminalNo.GetData()));
- if(fPswEmpty) {
- Dbg("wlan password is empty.");
- CSimpleStringA strNewPassword(DEFAULT_PASSWORD_PREFIX);
- strNewPassword += strThirdTerminalNo.SubString(6, strThirdTerminalNo.GetLength() - 6);
- strPassword = strNewPassword;
- Dbg("combile the existed password @1");
- //Dbg("combile the existed password: %s", strPassword.GetData());
- }
- }
- if(strSSID.IsStartWith(m_strTerminalNo.GetData())) {
- //自家的设备
- if(strPassword.IsNullOrEmpty()) {
- Dbg("wlan password is empty.");
- CSimpleStringA strNewPassword(DEFAULT_PASSWORD_PREFIX);
- strNewPassword += m_strTerminalNo.SubString(6, m_strTerminalNo.GetLength() - 6);
- strPassword = strNewPassword;
- Dbg("combile the existed password @2");
- //Dbg("combile the existed password: %s", strPassword.GetData());
- }
- if((paramPtr->wlanConnectParam.strUsername.Compare(strSSID) != 0
- || paramPtr->wlanConnectParam.strPassword.Compare(strPassword) != 0
- || wlan_config.hidden != (!!paramPtr->wlanConnectParam.Flag))) {
- //从设备中写进来
- paramPtr->wlanConnectParam.strUsername = strSSID;
- paramPtr->wlanConnectParam.strPassword = strPassword;
- paramPtr->wlanConnectParam.Flag = wlan_config.hidden ? TRUE : FALSE;
- paramPtr->connectType = MBB_CONNECT_WIFI;
- nNeedConfig = 2;
- }
-
- } else if(fvalidSSID) {
- //他家的设备
- Dbg("the third terminal sn.");
- if(strSSID.Compare(paramPtr->wlanConnectParam.strUsername) != 0
- || strPassword.Compare(paramPtr->wlanConnectParam.strPassword) != 0
- || wlan_config.hidden != (!!paramPtr->wlanConnectParam.Flag)) {
- paramPtr->wlanConnectParam.strUsername = strSSID;
- paramPtr->wlanConnectParam.strPassword = strPassword;
- paramPtr->wlanConnectParam.Flag = wlan_config.hidden ? TRUE : FALSE;
- paramPtr->connectType = MBB_CONNECT_WIFI;
- nNeedConfig = 2;
- }
- if(fPswEmpty) {
- LogWarn(Severity_Middle, Error_Unexpect, CombineErrorCode(MBD_MIFI_NO_DATA),
- "尝试获取WLAN密码失败,该设备不支持共享使用!");
- }
-
- } else {
- //新的设备(有可能)
- CSimpleStringA strNewSSID(m_strTerminalNo.GetData());
- CSimpleStringA strNewPassword(DEFAULT_PASSWORD_PREFIX);
- strNewPassword += m_strTerminalNo.SubString(6, m_strTerminalNo.GetLength() - 6);
- hw::dev_info_t dev_info;
- int get_dev_res = m_HwDeviceMnt->get_dev_info(dev_info);
- if(get_dev_res == 0) {
- CSimpleStringA strDevName(CSimpleStringW2A(dev_info.dev_name));
- const int index_dev = strDevName.IndexOf("-");
- strNewSSID += "-";
- if(index_dev != -1) {
- strNewSSID += strDevName.SubString(0, index_dev);
- } else {
- strNewSSID += strDevName;
- }
- } else {
- Dbg("get dev info faiiled: %d", get_dev_res);
- strNewSSID += "-MIFI";
- }
- paramPtr->wlanConnectParam.strUsername = strNewSSID;
- paramPtr->wlanConnectParam.strPassword = strNewPassword;
- paramPtr->wlanConnectParam.Flag = TRUE;
- Dbg("new ssid name: %s", paramPtr->wlanConnectParam.strUsername.GetData());
- //Dbg("new password: %s", paramPtr->wlanConnectParam.strPassword.GetData());
- paramPtr->connectType = MBB_CONNECT_WIFI;
- nNeedConfig = 3;
- }
- if((nNeedConfig & 2) == 0 && fEmptyParam) {
- nNeedConfig |= 2;
- }
- if(fFirstLogin) {
- //密码要更新
- nNeedConfig |= 4;
- }
- //////////////////////////////////////////////////////////////////////////
- if(!!nNeedConfig) {
- ec = 1;
- }
- if(!fCheckOnly) {
- if(0 != _UpdateMBBDualParam(nNeedConfig, *paramPtr)) {
- ec = 4;
- } else if(_InsertLocal2MacFilter() != Error_Succeed){
- //MIFI3必须在更改了密码之后才能插入过滤白名单
- //Always return Succeed.
- ec = 6;
- }
-
- } else {
- Dbg("only check this time.");
- if(fFirstLogin || fEmptyParam) {
- Dbg("logout returned: %d.", m_HwDeviceMnt->logout());
- }
- }
- } else {
- Dbg("get wlan config failed: %d", res);
- ec = 2;
- }
- } else {
- Dbg("login failed: %d", res);
- if(-17 == res) {
- //LogWarn(Severity_Middle, Error_Unexpect, CombineErrorCode(MBBResult2Status(res)),
- // "尝试登录MIFI失败次数超限,请拔离设备10分钟再试");
- ShowFatalError("尝试登录MIFI失败次数超限,请拔离设备10分钟后再试,或直接重置设备!");
- Sleep(10000);
- } else {
- LogWarn(Severity_Middle, Error_Unexpect, CombineErrorCode(MBBResult2Status(res)),
- CSimpleStringA::Format("尝试登录到 MIFI 设备失败(%s)!", ConvertStatusToString(MBBResult2Status(res))));
- }
- //SetHWStatus(MBBResult2Status(res));
- if(res == -3) {
- //SetHWStatus(MBD_MIFI_LOGIN_INVALID_NAMEORPASSWORD);
- //ShowFatalError(GetFurtherDetail());
- //SendNetStatusMsg();
- ec = 5;
- } else {
- ec = 3;
- }
- }
- } else {
- Dbg("no detect device");
- ec = 4;
- }
- return ec;
- }
- BOOL CMobileDialFSM::DetectMBBConfigUpdate(BOOL fNeedCheck)
- {
- static BOOL fFirstFlag = TRUE;
- if((m_nAdvancedGen != ADVANCE_MBB || mMBBParam.connectType != MBB_CONNECT_WIRE) && !IsWifiConnected()) {
- if(!fNeedCheck || m_HwDeviceMnt->detect_devices()) {
- int res = 1;
- if(fFirstFlag && (res = DealMBBConfigUpdate(TRUE)) == 1) {
- return TRUE;
- } else if(fFirstFlag && res == 0) {
- fFirstFlag = FALSE;
- }
- } else if(!fFirstFlag) {
- fFirstFlag = TRUE;
- }
- }
- return FALSE;
- }
- void CMobileDialFSM::ForbidAutoConnnectBySystem()
- {
- LOG_FUNCTION();
- HKEY hKey = NULL;
- HKEY hSubKey = NULL;
- HKEY hSvcKey = NULL;
- BOOL fNeedCheck = FALSE;
- BOOL fEnableSet = FALSE;
- DWORD dwFlag = KEY_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS;
- if (gArch == 64/*Win64Bit*/) {
- dwFlag |= KEY_WOW64_64KEY;
- } else {
- dwFlag |= KEY_WOW64_32KEY;
- }
- LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Policies\\Microsoft\\Windows"),
- 0, dwFlag, &hKey);
- if(lResult == ERROR_SUCCESS) {
- lResult = RegOpenKeyEx(hKey, "WwanSvc\\GroupPolicy", 0, dwFlag, &hSubKey);
- if(lResult == ERROR_FILE_NOT_FOUND) {
- DWORD dwDisposition = REG_OPENED_EXISTING_KEY;
- Dbg("Start to create \"WwanSvc\\GroupPolicy\" key...");
- lResult = RegCreateKeyEx(hKey, "WwanSvc\\GroupPolicy",
- 0, NULL,REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hSubKey, &dwDisposition);
- Dbg("Create it return %d", lResult);
- }
- if(lResult == ERROR_SUCCESS) {
- DWORD dwType = REG_DWORD;
- DWORD dwValue = 0;
- DWORD dwSize = sizeof(dwValue);
- lResult = RegQueryValueEx(hSubKey, "DisableWwanAutoConnect", NULL, &dwType, (LPBYTE)&dwValue, &dwSize);
- if(lResult == ERROR_FILE_NOT_FOUND || (lResult == ERROR_SUCCESS && dwValue == 0)) {
- fNeedCheck = TRUE;
- } else {
- Dbg("needless to check: result:%d, value:%d", lResult, dwValue);
- }
- }
- } else {
- Dbg("RegOpenKeyEx \"SOFTWARE\\Policies\\Microsoft\\Windows\" failed %d", lResult);
- }
- if(fNeedCheck) {
- lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\WwanSvc\\DisallowAutoConnectByClient"), 0, dwFlag, &hSvcKey);
- if(lResult == ERROR_FILE_NOT_FOUND) {
- fEnableSet = TRUE;
- } else if(lResult == ERROR_SUCCESS) {
- DWORD dwClass = 0;
- DWORD dwCount = 0, dwSubKeys = 0;
- lResult = RegQueryInfoKey(hSvcKey, NULL, &dwClass, NULL, &dwSubKeys, NULL, NULL, &dwCount, NULL, NULL, NULL, NULL);
- if(lResult != ERROR_SUCCESS) {
- fEnableSet = FALSE;
- }
- else if(dwCount > 0) {
- Dbg("Number of subValue: %d", dwCount);
- char szValue[128];
- DWORD dwLen = sizeof(szValue);
- DWORD dwValue = 0;
- DWORD dwSize = sizeof(dwValue);
- DWORD dwType = REG_DWORD;
- for(int i=0; lResult == ERROR_SUCCESS && i<(int)dwCount; ++i) {
- memset(szValue, 0, sizeof(szValue));
- lResult = RegEnumValue(hSvcKey, i, szValue, &dwLen, NULL, &dwType, (LPBYTE)&dwValue, &dwSize);
- if(lResult == ERROR_SUCCESS) {
- Dbg("RegEnumValue: %s - %d", szValue, dwValue);
- if(dwValue > 0) {
- Dbg("Because...");
- fEnableSet = FALSE;
- }
- }
- }
- } else {
- fEnableSet = TRUE;
- }
- }
- }
- if(fEnableSet) {
- DWORD dwType = REG_DWORD;
- DWORD dwValue = 1;
- DWORD dwSize = sizeof(dwValue);
- lResult = RegSetValueEx(hSubKey, "DisableWwanAutoConnect", 0, REG_DWORD, (const BYTE*)&dwValue, dwSize);
- if(lResult == ERROR_SUCCESS) {
- Dbg("RegSetValueEx for DisableWwanAutoConnect succ.");
- } else {
- Dbg("RegSetValueEx for DisableWwanAutoConnect failed, %d", lResult);
- }
- }
- RegCloseKey(hKey);
- RegCloseKey(hSvcKey);
- RegCloseKey(hSubKey);
- }
- const MOBILEDIAL_CONNECTION_STATE& CMobileDialFSM::GetRasStatus() const
- {
- return m_3gState;
- }
- BOOL CMobileDialFSM::RasHangUpSuffix(BOOL bOrigin)
- {
- LOG_FUNCTION();
- BOOL fResult = TRUE;
- if(g_hrasconn != NULL) {
- DWORD dwRet = 0;
- dwRet = RasHangUp(g_hrasconn);
- Dbg("RasHangUp in DisConnect returned %d", dwRet);
- if(dwRet == ERROR_SUCCESS) {
- RASCONNSTATUS connStatus;
- connStatus.dwSize = sizeof(RASCONNSTATUS);
- Dbg("TickCount allocated 3 seconds after RasHangUp...");
- //Reduce timeout tick in case occuring
- //UnLoading-Entity -Josephus@2017627 16:54:10
- DWORD tcLast = GetTickCount() + 3 * 1100;
- while((( dwRet = RasGetConnectStatus(g_hrasconn, &connStatus))
- != ERROR_INVALID_HANDLE) && (tcLast > GetTickCount())) {
- Sleep(0);
- }
- fResult = (dwRet == ERROR_INVALID_HANDLE);
- Dbg("Cycle is done %snormally", fResult ? "" : "ab");
- }
- else {
- if(dwRet == ERROR_INVALID_HANDLE) {
- Dbg("to RasHandup: The handle specified in RashandUp is invalid.");
- }
- else if(dwRet == ERROR_NO_CONNECTION) {
- Dbg("to RasHandup: The connection was dropped.");
- }
- else {
- Dbg("Invoke RasHangUp failed returned: %d", dwRet);
- }
- fResult = FALSE;
- }
- g_hrasconn = NULL;
- } else {
- m_csErrMsg = "RAS句柄不存在";
- fResult = FALSE;
- }
- return fResult;
- }
- int CMobileDialFSM::EnumCurRasDevices(BOOL bUpdate)
- {
- if(m_nAdvancedGen == 4 || m_nAdvancedGen == 2) {
- return 0;
- }
- LOG_FUNCTION();
- Dbg("bUpdate: %d", bUpdate);
- int nRes = 0;
- DWORD dwCb = 0;
- DWORD dwRet = ERROR_SUCCESS;
- DWORD dwDevices = 0;
- LPRASDEVINFO lpRasDevInfo = NULL;
- dwRet = RasEnumDevices(lpRasDevInfo, &dwCb, &dwDevices);
- if (dwRet == ERROR_BUFFER_TOO_SMALL) {
- lpRasDevInfo = (LPRASDEVINFO)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwCb);
- if (lpRasDevInfo == NULL) {
- Dbg("HeapAlloc failed when enuming ras devices.");
- SetRasStatus(MBD_INTERNAL_ERROR);
- return -1;
- }
- lpRasDevInfo[0].dwSize = sizeof(RASDEVINFO);
- dwRet = RasEnumDevices(lpRasDevInfo, &dwCb, &dwDevices);
- if (ERROR_SUCCESS == dwRet) {
- for (DWORD i = 0; i < dwDevices; i++) {
- if(!_strnicmp(lpRasDevInfo[i].szDeviceType, RASDT_Modem, strlen(RASDT_Modem))) {
- nRes++;
- if(!bUpdate) {
- Dbg("%s <%s>",lpRasDevInfo[i].szDeviceName,lpRasDevInfo[i].szDeviceType);
- }
- }
- }
- Dbg("The above RAS devices were found(%d)", nRes);
- if(nRes > 0) {
- if(bUpdate) {
- int nEntryNum = RefreshRasEntry();
- Dbg("nEntryNum(%d) vs Count(%d)", nEntryNum, m_rasEntries.GetCount());
- DongleList donglist;
- donglist.Init(nRes);
- Dbg("Dream device count: %d", nRes);
- bool fHasCfg = false;
- DWORD k = 0;
- for (DWORD i = 0; i < dwDevices; i++) {
- if(!_strnicmp(lpRasDevInfo[i].szDeviceType, RASDT_Modem, strlen(RASDT_Modem))) {
- Dbg("%s <%s>",lpRasDevInfo[i].szDeviceName,lpRasDevInfo[i].szDeviceType);
- memset(&donglist[k], 0, sizeof(MbnDongleInfo));
- donglist[k].usDeviceType = DEVTYPE_MODEM;
- //TODO:
- donglist[k].csInterfaceId = lpRasDevInfo[i].szDeviceName;
- InitMbnDongleSubInfo(&donglist[k].subInfo);
- donglist[k].subInfo.ulSingnal = 0xFFFFFFFF;
- donglist[k].subInfo.strProviderName = lpRasDevInfo[i].szDeviceName;
- donglist[k].subInfo.mbnCntState = MBN_ACTIVATION_STATE_DEACTIVATED;
- donglist[k].subInfo.strProfileName = "";
- donglist[k].state = /*MBD_NOT_INITIALIZED*/MBD_ACTIVATION_DISCONNECTED;
- int num = 0;
- for(int j=0; j<nEntryNum; ++j) {
- if(!strcmp(lpRasDevInfo[i].szDeviceName, m_rasEntries[j].szDeviceName)) {
- num++;
- }
- }
- if(num > 0) {
- donglist[k].profileList.Init(num);
- for(int j=0, z=0; j<nEntryNum; ++j) {
- if(!strcmp(lpRasDevInfo[i].szDeviceName, m_rasEntries[j].szDeviceName)) {
- _EntriesToDongle(m_rasEntries[j], &donglist[k].profileList[z]);
- z++;
- }
- }
- fHasCfg = true;
- } else {
- donglist[k].state = MBD_NO_ENTRY;
- }
- k++;
- }
- }
- LOG_ASSERT(k == nRes);
- g_DongleInfos.Append(donglist);
- if(fHasCfg) {
- UpdateRasConnectState();
- } else {
- SetRasStatus(MBD_NO_ENTRY);
- }
- }
- } else {
- SetRasStatus(MBD_NO_MOBILEDONGLE);
- }
- } else {
- SetRasStatus(MBD_INTERNAL_ERROR);
- Dbg("RasEnumDevices failed.");
- HeapFree(GetProcessHeap(), 0, lpRasDevInfo);
- lpRasDevInfo = NULL;
- return -1;
- }
- HeapFree(GetProcessHeap(), 0, lpRasDevInfo);
- lpRasDevInfo = NULL;
- return nRes;
- }
- if (dwDevices >= 1)
- {
- Dbg("The operation failed to acquire the buffer size.");
- SetRasStatus(MBD_INTERNAL_ERROR);
- return -1;
- }
- Dbg("There were no RAS devices found.");
- SetRasStatus(MBD_NO_MOBILEDONGLE);
- return 0;
- }
- BOOL CMobileDialFSM::Init3GComponent()
- {
- bool bContinue = true;
- for(int i=0; i<RasEventCount; ++i)
- {
- if(g_RasEvents[i] == NULL) {
- if((g_RasEvents[i] = CreateEventA(NULL, FALSE, FALSE, NULL)) == NULL){
- Dbg("CreateEvent[%d] failed with error %u.", i, GetLastError());
- bContinue = false;
- }
- }
- }
- if(!bContinue) {
- Dbg("Cancel to create listern thread");
- return FALSE;
- }
- if(m_hRasListenThread != NULL) {
- TerminateThread(m_hRasListenThread, -1);
- CloseHandle(m_hRasListenThread);
- m_hRasListenThread = NULL;
- }
- m_hRasListenThread = (HANDLE)_beginthreadex(NULL, 0, RasEventThreadFunc, (void*)this, 0, NULL);
- if(m_hRasListenThread == INVALID_HANDLE_VALUE || m_hRasListenThread == NULL) {
- LogError(Severity_None, Error_Unexpect, 0, "Create thread for 3G RasDial disconnect failed !");
- m_hRasListenThread = NULL;
- return FALSE;
- }
- DWORD dwRet = RasConnectionNotification((HRASCONN)INVALID_HANDLE_VALUE, g_RasEvents[1], RASCN_Disconnection);
- if(dwRet == ERROR_SUCCESS) {
- Dbg("RasConnectionNotification for disconnect succ.");
- } else {
- Dbg("RasConnectionNotification for disconnect failed : %d", dwRet);
- }
- dwRet = RasConnectionNotification((HRASCONN)INVALID_HANDLE_VALUE,
- g_RasEvents[0], RASCN_Connection);
- if(dwRet == ERROR_SUCCESS) {
- Dbg("RasConnectionNotification for connect succ.");
- } else {
- Dbg("RasConnectionNotification for connect failed : %d", dwRet);
- }
- dwRet = RasConnectionNotification((HRASCONN)INVALID_HANDLE_VALUE,
- g_RasEvents[3], RASCN_BandwidthAdded);
- if(dwRet == ERROR_SUCCESS) {
- Dbg("RasConnectionNotification for add succ.");
- } else {
- Dbg("RasConnectionNotification for add failed : %d", dwRet);
- }
- dwRet = RasConnectionNotification((HRASCONN)INVALID_HANDLE_VALUE,
- g_RasEvents[4], RASCN_BandwidthRemoved);
- if(dwRet == ERROR_SUCCESS) {
- Dbg("RasConnectionNotification for remove succ.");
- } else {
- Dbg("RasConnectionNotification for remove failed : %d", dwRet);
- }
- return TRUE;
- }
- BOOL CMobileDialFSM::Init4GComponent()
- {
- //ForbidAutoConnnectBySystem();
- if(m_pMbn) {
- m_pMbn->AdviseCntMnrEvent();
- m_pMbn->AdviseConnectEvent();
- m_pMbn->AdviseSignalEvent();
- m_pMbn->AdviseCntProfileMnrEvent();
- m_pMbn->AdviseCntProfileEvent();
- }
- return TRUE;
- }
- BOOL CMobileDialFSM::InitHuaweiComponent()
- {
- GetMBBConfig(&mMBBParam);
- Dbg("connect type: %d", mMBBParam.connectType);
- Dbg("username: %s", (LPCTSTR)mMBBParam.loginParam.strUsername);
- Dbg("ssid: %s", (LPCTSTR)mMBBParam.wlanConnectParam.strUsername);
- if(m_WifiChangedEvt == NULL) {
- spagent::spagent_assistor::init("mobile");
- m_WifiChangedEvt = new WifiChangeEvent(this);
- if(mMBBParam.connectType == MBB_CONNECT_WIRE) {
- spagent::spagent_assistor::disconnect(conn_tool_wifi, true);
- }
- }
- if(!m_WifiChangedEvt->m_bRegistered) {
- int rc = spagent::spagent_assistor::register_notification_events(conn_tool_wifi, m_WifiChangedEvt);
- Dbg("Register wifi changed event return: %d", rc);
- m_WifiChangedEvt->m_bRegistered = rc == 0 ? TRUE : FALSE;
- }
- return TRUE;
- }
- BOOL CMobileDialFSM::IsWifiConnected()
- {
- std::string ssid;
- return spagent::spagent_assistor::is_connected(conn_tool_wifi, ssid) ? TRUE : FALSE;
- }
- void CMobileDialFSM::_FormatRasError(DWORD dwRasCode)
- {
- DWORD cBufSize = 256;
- char lpszBuf[256] = {0};
- DWORD dwRetVal = RasGetErrorString((UINT)dwRasCode, lpszBuf, cBufSize);
- if(dwRetVal == ERROR_SUCCESS) {
- LogError(Severity_Middle, Error_Unrecover, CombineErrorCode(MBD_RASDIAL_FAILED),
- CSimpleStringA::Format("错误 %d:%s", dwRasCode, lpszBuf));
- m_csErrMsg = CSimpleStringA::Format("%s : %d", lpszBuf, dwRasCode);
- }else {
- m_csErrMsg = CSimpleStringA::Format("RasDial failed: %u", dwRasCode);
- LogError(Severity_Middle, Error_Unrecover, CombineErrorCode(MBD_RASDIAL_FAILED), CSimpleStringA::Format("3G拨号失败:%u", dwRasCode));
- }
- }
- int CMobileDialFSM::CheckNetSituationWithPing()
- {
- int nRes = 0;
- if((ping1 == NULL || !ping1->IsValid()) && (ping2 == NULL || !ping2->IsValid()))
- return -1;
- int t1 = 0, t2 = 0;
- const int max_times = 4;
- if(ping1 != NULL && ping1->IsValid())
- {
- for(t1=0; t1<max_times; ++t1)
- {
- if(ping1->PingOnce() == 0)
- {
- nRes += 1;
- break;
- }
- Sleep(1000);
- }
- }
- if(ping2 != NULL && ping2->IsValid())
- {
- for(t2=0; t2<max_times; ++t2)
- {
- Sleep(1000);
- if(ping2->PingOnce() == 0)
- {
- nRes += 2;
- break;
- }
- }
- }
- return nRes;
- }
|