main.c 235 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324
  1. #include "define.h"
  2. #include "main.h"
  3. //#define CDFA_CERTIFICATE // Only enable for CDFA certificate to send receipt by Phihong back end API
  4. //==========================
  5. // System basic sample constant
  6. //==========================
  7. #define is_error(ptr) ((unsigned long)ptr > (unsigned long)-4000L)
  8. #define ARRAY_SIZE(A) (sizeof(A) / sizeof(A[0]))
  9. #define PASS 1
  10. #define FAIL -1
  11. #define YES 1
  12. #define NO 0
  13. #define ON 1
  14. #define OFF 0
  15. #define BUFFER_SIZE 128
  16. //==========================
  17. // Timeout constant define
  18. //==========================
  19. #define TIMEOUT_SPEC_HANDSHAKING 180
  20. #define TIMEOUT_SPEC_AUTH 15
  21. #define TIMEOUT_SPEC_HANDSHAKING_LED 185
  22. #define TIMEOUT_SPEC_LOGPPRINTOUT 30
  23. #define TIMEOUT_SPEC_PROFILE_PREPARE 60
  24. #define TIMEOUT_SPEC_BS_HLC_HANDSHAKE 60
  25. #define TIMEOUT_SPEC_EV_READY 30
  26. #define TIMEOUT_SPEC_CCS_HEARTBEAT_COUNT_RESET 10
  27. #define TIMEOUT_SPEC_CCS_HANDSHAKE 120
  28. #define TIMEOUT_SPEC_PWN_CHANGE 5
  29. #define TIMEOUT_SPEC_POWERSAVING_LCD 120
  30. #define TIMEOUT_SPEC_POWERSAVING_RFID 120
  31. #define TIMEOUT_SPEC_POWERSAVING_METER 120
  32. #define TIMEOUT_SPEC_POWERSAVING_LED_STATUS 120
  33. #define TIMEOUT_SPEC_CEHCK_POWER_CONSUMPTION 15
  34. #define TIMEOUT_SPEC_UPGRADE 300
  35. //==========================
  36. // GPIO constant define
  37. //==========================
  38. #define GPIO_OUT_RST_RFID 62
  39. #define GPIO_OUT_RST_4G 114
  40. #define GPIO_OUT_RST_QCA 115
  41. #define GPIO_OUT_RST_ETH 89
  42. #define GPIO_IN_WAKEUP 63
  43. #define MtdBlockSize 0x300000
  44. #define DB_FILE "/Storage/ChargeLog/localCgargingRecord.db"
  45. //==========================
  46. // Declare method
  47. //==========================
  48. void trim(char *s);
  49. int mystrcmp(char *p1,char *p2);
  50. void substr(char *dest, const char* src, unsigned int start, unsigned int cnt);
  51. void split(char **arr, char *str, const char *del);
  52. int isReachableInternet();
  53. int isRouteFail();
  54. int InitRfidPort(void);
  55. int GetCardSerialNumber();
  56. void setLedMotion(unsigned char gun_index,unsigned char led_mode);
  57. void setRequest(unsigned char gun_index,unsigned char isOn);
  58. void setSpeaker(unsigned char isOn, unsigned char speaker_mode);
  59. //==========================
  60. // Declare RFID module type
  61. //==========================
  62. #define MODULE_EWT 0
  63. int wtdFd = -1;
  64. int rfidFd = -1;
  65. char* rfidPortName = "/dev/ttyS2";
  66. RFID rfid;
  67. char *valid_Internet[2] = {"8.8.8.8", "180.76.76.76"};
  68. //==========================
  69. // Declare share memory
  70. //==========================
  71. struct SysConfigAndInfo *ShmSysConfigAndInfo;
  72. struct StatusCodeData *ShmStatusCodeData;
  73. struct PsuData *ShmPsuData;
  74. struct CHAdeMOData *ShmCHAdeMOData;
  75. struct CcsData *ShmCcsData;
  76. struct PrimaryMcuData *ShmPrimaryMcuData;
  77. struct FanModuleData *ShmFanModuleData;
  78. struct RelayModuleData *ShmRelayModuleData;
  79. struct OCPP16Data *ShmOCPP16Data;
  80. struct OCPP20Data *ShmOCPP20Data;
  81. struct Charger *ShmCharger;
  82. struct DISPENSER *ShmDispenser;
  83. struct timespec startTime[AC_QUANTITY][TMR_IDX_CNT];
  84. struct timespec startChargingTime[AC_QUANTITY];
  85. struct timespec endChargingTime[AC_QUANTITY];
  86. sqlite3 *localDb;
  87. struct SysConfigData SysConfigOrg;
  88. ParsingRatedCur modelnameInfo={0};
  89. //=================================
  90. // Common routine
  91. //=================================
  92. void trim(char *s)
  93. {
  94. int i=0, j, k, l=0;
  95. while((s[i]==' ')||(s[i]=='\t')||(s[i]=='\n'))
  96. i++;
  97. j = strlen(s)-1;
  98. while((s[j]==' ')||(s[j]=='\t')||(s[j]=='\n'))
  99. j--;
  100. if(i==0 && j==strlen(s)-1) { }
  101. else if(i==0) s[j+1] = '\0';
  102. else {
  103. for(k=i; k<=j; k++) s[l++] = s[k];
  104. s[l] = '\0';
  105. }
  106. }
  107. int mystrcmp(char *p1,char *p2)
  108. {
  109. while(*p1==*p2)
  110. {
  111. if(*p1=='\0' || *p2=='\0')
  112. break;
  113. p1++;
  114. p2++;
  115. }
  116. if(*p1=='\0' && *p2=='\0')
  117. return(PASS);
  118. else
  119. return(FAIL);
  120. }
  121. void substr(char *dest, const char* src, unsigned int start, unsigned int cnt)
  122. {
  123. strncpy(dest, src + start, cnt);
  124. dest[cnt] = 0;
  125. }
  126. void split(char **arr, char *str, const char *del)
  127. {
  128. char *s = strtok(str, del);
  129. while(s != NULL)
  130. {
  131. *arr++ = s;
  132. s = strtok(NULL, del);
  133. }
  134. }
  135. int StoreLogMsg(const char *fmt, ...)
  136. {
  137. char Buf[4096+256];
  138. char buffer[4096];
  139. time_t CurrentTime;
  140. struct tm *tm;
  141. struct timeval tv;
  142. va_list args;
  143. va_start(args, fmt);
  144. int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
  145. va_end(args);
  146. memset(Buf,0,sizeof(Buf));
  147. CurrentTime = time(NULL);
  148. tm=localtime(&CurrentTime);
  149. gettimeofday(&tv, NULL); // get microseconds, 10^-6
  150. if((ShmSysConfigAndInfo->SysConfig.ModelName != NULL) && (ShmSysConfigAndInfo->SysConfig.SerialNumber != NULL) && (strlen((char*)ShmSysConfigAndInfo->SysConfig.ModelName) >= 14))
  151. {
  152. sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/SystemLog/[%04d.%02d]%s_%s_SystemLog",
  153. tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec,
  154. buffer,
  155. tm->tm_year+1900,tm->tm_mon+1,
  156. ShmSysConfigAndInfo->SysConfig.ModelName,
  157. ShmSysConfigAndInfo->SysConfig.SerialNumber);
  158. }
  159. else
  160. {
  161. sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/SystemLog/[%04d.%02d]SystemLog",
  162. tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec,
  163. buffer,
  164. tm->tm_year+1900,tm->tm_mon+1);
  165. }
  166. #ifdef SystemLogMessage
  167. system(Buf);
  168. #endif
  169. #ifdef ConsloePrintLog
  170. printf("[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec, buffer);
  171. #endif
  172. return rc;
  173. }
  174. void refreshStartTimer(struct timespec *timer)
  175. {
  176. clock_gettime(CLOCK_MONOTONIC, timer);
  177. }
  178. int getDiffSecNow(struct timespec timer)
  179. {
  180. struct timespec timerNow;
  181. clock_gettime(CLOCK_MONOTONIC, &timerNow);
  182. return (int)((((unsigned long)(timerNow.tv_sec - timer.tv_sec) * 1000) + ((unsigned long)((timerNow.tv_nsec / 1000000) - (timer.tv_nsec / 1000000))))/1000);
  183. }
  184. int getDiffSecBetween(struct timespec start, struct timespec end)
  185. {
  186. return (int)((((unsigned long)(end.tv_sec - start.tv_sec) * 1000) + ((unsigned long)((end.tv_nsec / 1000000) - (start.tv_nsec / 1000000))))/1000);
  187. }
  188. long long DiffTimebWithNow(struct timeb ST)
  189. {
  190. //return milli-second
  191. struct timeb ET;
  192. long long StartTime,StopTime;
  193. ftime(&ET);
  194. StartTime=(long long)ST.time;
  195. StopTime=(long long)ET.time;
  196. return ((StopTime-StartTime)*1000) + (ET.millitm-ST.millitm);
  197. }
  198. long long DiffTimeb(struct timeb ST, struct timeb ET)
  199. {
  200. //return milli-second
  201. long long StartTime,StopTime;
  202. StartTime=(long long)ST.time;
  203. StopTime=(long long)ET.time;
  204. return ((StopTime-StartTime)*1000) + (ET.millitm-ST.millitm);
  205. }
  206. int DiffTimebWithNowSec(struct timeb ST)
  207. {
  208. //return milli-second
  209. struct timeb ET;
  210. unsigned int StartTime,StopTime;
  211. ftime(&ET);
  212. StartTime=(unsigned int)ST.time;
  213. StopTime=(unsigned int)ET.time;
  214. return (StopTime-StartTime);
  215. }
  216. int isOvertNow(uint8_t *start)
  217. {
  218. int result = YES;
  219. struct ParsingResult
  220. {
  221. int result;
  222. int scanedElement;
  223. int year;
  224. int month;
  225. int mday;
  226. int hour;
  227. int min;
  228. int sec;
  229. int tz_hour;
  230. int tz_min;
  231. float minSec;
  232. }parsingResult;
  233. struct tm tmStart;
  234. struct timeb tbStart;
  235. memset(&parsingResult, 0x00, sizeof(struct ParsingResult));
  236. if(strstr((char*)start, ".") != NULL)
  237. {
  238. // Original data with mini second
  239. if(strstr((char*)start, "Z") != NULL)
  240. {
  241. // Original data with Z
  242. parsingResult.scanedElement = sscanf((char*)start, "%d-%d-%dT%d:%d:%d.%fZ",
  243. &parsingResult.year,
  244. &parsingResult.month,
  245. &parsingResult.mday,
  246. &parsingResult.hour,
  247. &parsingResult.min,
  248. &parsingResult.sec,
  249. &parsingResult.minSec);
  250. }
  251. else
  252. {
  253. // Original data without Z
  254. parsingResult.scanedElement = sscanf((char*)start, "%d-%d-%dT%d:%d:%d.%f%d:%d",
  255. &parsingResult.year,
  256. &parsingResult.month,
  257. &parsingResult.mday,
  258. &parsingResult.hour,
  259. &parsingResult.min,
  260. &parsingResult.sec,
  261. &parsingResult.minSec,
  262. &parsingResult.tz_hour,
  263. &parsingResult.tz_min);
  264. }
  265. }
  266. else
  267. {
  268. // Original data without mini second
  269. if(strstr((char*)start, "Z") != NULL)
  270. {
  271. // Original data with Z
  272. parsingResult.scanedElement = sscanf((char*)start, "%d-%d-%dT%d:%d:%dZ",
  273. &parsingResult.year,
  274. &parsingResult.month,
  275. &parsingResult.mday,
  276. &parsingResult.hour,
  277. &parsingResult.min,
  278. &parsingResult.sec);
  279. }
  280. else
  281. {
  282. // Original data without Z
  283. parsingResult.scanedElement = sscanf((char*)start, "%d-%d-%dT%d:%d:%d%d:%d",
  284. &parsingResult.year,
  285. &parsingResult.month,
  286. &parsingResult.mday,
  287. &parsingResult.hour,
  288. &parsingResult.min,
  289. &parsingResult.sec,
  290. &parsingResult.tz_hour,
  291. &parsingResult.tz_min);
  292. }
  293. }
  294. if(parsingResult.scanedElement >= 6)
  295. {
  296. tmStart.tm_year = parsingResult.year - 1900;
  297. tmStart.tm_mon = parsingResult.month - 1;
  298. tmStart.tm_mday = parsingResult.mday;
  299. tmStart.tm_hour = parsingResult.hour;
  300. tmStart.tm_min = parsingResult.min;
  301. tmStart.tm_sec = parsingResult.sec;
  302. tmStart.tm_gmtoff = 0;
  303. tbStart.time = mktime(&tmStart);
  304. tbStart.timezone = 0;
  305. tbStart.millitm = 0;
  306. tbStart.time -= (parsingResult.tz_hour*3600) + (parsingResult.tz_min*60*(parsingResult.tz_hour>=0?1:-1));
  307. if(DiffTimebWithNowSec(tbStart) <= 0)
  308. result = NO;
  309. else
  310. result = YES;
  311. }
  312. else
  313. {
  314. DEBUG_WARN("Start date parsing error.\n");
  315. }
  316. return result;
  317. }
  318. void getDateTimeString(char* result)
  319. {
  320. time_t CurrentTime;
  321. struct tm *tm;
  322. CurrentTime = time(NULL);
  323. tm=localtime(&CurrentTime);
  324. sprintf(result, "%04d.%02d.%02d %02d:%02d:%02d", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec);
  325. }
  326. int getCurrentYear()
  327. {
  328. int result = 0;
  329. time_t CurrentTime;
  330. struct tm *tm;
  331. CurrentTime = time(NULL);
  332. tm=localtime(&CurrentTime);
  333. result = (tm->tm_year + 1900);
  334. return result;
  335. }
  336. unsigned long long getAvailableMemory()
  337. {
  338. long pages = sysconf(_SC_AVPHYS_PAGES);
  339. long page_size = sysconf(_SC_PAGE_SIZE);
  340. return pages * page_size;
  341. }
  342. unsigned int isKernelSupportNAT()
  343. {
  344. unsigned int result = NO;
  345. unsigned int version = 0;
  346. FILE *fp;
  347. char cmd[256];
  348. char buf[512];
  349. // Get IP address & net mask
  350. strcpy(cmd, "uname -v");
  351. fp = popen(cmd, "r");
  352. if(fp != NULL)
  353. {
  354. if(fgets(buf, sizeof(buf), fp) != NULL)
  355. {
  356. sscanf(buf, "#%d", &version);
  357. //DEBUG_INFO("Kernel version: %d\n", version);
  358. if(version >= 30)
  359. result = YES;
  360. }
  361. }
  362. pclose(fp);
  363. return result;
  364. }
  365. int getEth0MacAddress()
  366. {
  367. int result = PASS;
  368. FILE *fp;
  369. char cmd[256];
  370. char buf[512];
  371. char tmp[512];
  372. strcpy(cmd, "ifconfig eth0");
  373. fp = popen(cmd, "r");
  374. if(fp != NULL)
  375. {
  376. while(fgets(buf, sizeof(buf), fp) != NULL)
  377. {
  378. if(strstr(buf, "eth0") > 0)
  379. {
  380. result = PASS;
  381. }
  382. if(strstr(buf, "eth0 Link encap:Ethernet HWaddr") > 0)
  383. {
  384. sscanf(buf, "%*s%*s%*s%*s%s", tmp);
  385. strcpy((char*)ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthMacAddress, tmp);
  386. }
  387. }
  388. }
  389. pclose(fp);
  390. return result;
  391. }
  392. //======================================================
  393. // OCPP routine
  394. //======================================================
  395. void ocpp_process_start()
  396. {
  397. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  398. system("/root/OcppBackend &");
  399. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  400. system("/root/OcppBackend20 &");
  401. }
  402. uint8_t ocpp_get_isRemoteStartWait()
  403. {
  404. uint8_t result = OFF;
  405. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  406. {
  407. result = ShmOCPP16Data->MsMsg.bits.isRemoteStartWaitReq;
  408. }
  409. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  410. {
  411. result = ShmOCPP20Data->MsMsg.bits.isRemoteStartWaitReq;
  412. }
  413. return result;
  414. }
  415. uint8_t ocpp_get_connection_status()
  416. {
  417. uint8_t result = OFF;
  418. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  419. {
  420. result = ShmOCPP16Data->OcppConnStatus;
  421. }
  422. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  423. {
  424. result = ShmOCPP20Data->OcppConnStatus;
  425. }
  426. return result;
  427. }
  428. uint16_t ocpp_get_connection_timeout()
  429. {
  430. uint16_t result = TIMEOUT_SPEC_HANDSHAKING;
  431. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  432. {
  433. if(strcmp((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData,"") != 0)
  434. {
  435. result = atoi((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData);
  436. }
  437. }
  438. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  439. {
  440. if(strcmp((char *)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_EVConnectionTimeOut].variableAttribute[0].value,"") != 0)
  441. {
  442. result = atoi((char *)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_EVConnectionTimeOut].variableAttribute[0].value);
  443. }
  444. }
  445. return result;
  446. }
  447. uint8_t ocpp_get_update_firmware_req()
  448. {
  449. uint8_t result = NO;
  450. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  451. {
  452. result = ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq;
  453. }
  454. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  455. {
  456. result = ShmOCPP20Data->MsMsg.bits.UpdateFirmwareReq;
  457. }
  458. return result;
  459. }
  460. uint8_t ocpp_get_reset_req()
  461. {
  462. uint8_t result = NO;
  463. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  464. {
  465. result = ShmOCPP16Data->MsMsg.bits.ResetReq;
  466. }
  467. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  468. {
  469. result = ShmOCPP20Data->MsMsg.bits.ResetReq;
  470. }
  471. return result;
  472. }
  473. void ocpp_boot_info_sync()
  474. {
  475. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  476. {
  477. memcpy((char*)ShmOCPP16Data->OcppServerURL, (char*)ShmSysConfigAndInfo->SysConfig.OcppServerURL, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.OcppServerURL));
  478. memcpy((char*)ShmOCPP16Data->ChargeBoxId, (char*)ShmSysConfigAndInfo->SysConfig.ChargeBoxId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.ChargeBoxId));
  479. sprintf((char*)ShmOCPP16Data->BootNotification.CpFwVersion, (char*)ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev);
  480. sprintf((char*)ShmOCPP16Data->BootNotification.CpMeterSerialNumber, "N/A");
  481. switch(ShmSysConfigAndInfo->SysConfig.ModelName[3])
  482. {
  483. case 'M':
  484. case 'Z':
  485. sprintf((char*)ShmOCPP16Data->BootNotification.CpMeterType, "MID");
  486. break;
  487. case 'P':
  488. sprintf((char*)ShmOCPP16Data->BootNotification.CpMeterType, "PTB");
  489. break;
  490. case 'I':
  491. sprintf((char*)ShmOCPP16Data->BootNotification.CpMeterType, "TIC");
  492. break;
  493. case 'U':
  494. sprintf((char*)ShmOCPP16Data->BootNotification.CpMeterType, "UL");
  495. break;
  496. default:
  497. sprintf((char*)ShmOCPP16Data->BootNotification.CpMeterType, "N/A");
  498. break;
  499. }
  500. }
  501. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  502. {
  503. memcpy((char*)ShmOCPP20Data->OcppServerURL, (char*)ShmSysConfigAndInfo->SysConfig.OcppServerURL, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.OcppServerURL));
  504. memcpy((char*)ShmOCPP20Data->ChargeBoxId, (char*)ShmSysConfigAndInfo->SysConfig.ChargeBoxId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.ChargeBoxId));
  505. sprintf((char*)ShmOCPP20Data->BootNotification.chargingStation.firmwareVersion, (char*)ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev);
  506. }
  507. }
  508. void ocpp_set_remotestart(uint8_t gun_index, uint8_t status)
  509. {
  510. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  511. {
  512. if(ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStartTransactionReq != status)
  513. ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStartTransactionReq = status;
  514. }
  515. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  516. {
  517. if(ShmOCPP20Data->CsMsg.bits[gun_index].RequestStartTransactionReq != status)
  518. ShmOCPP20Data->CsMsg.bits[gun_index].RequestStartTransactionReq = status;
  519. }
  520. }
  521. void ocpp_set_remotestop(uint8_t gun_index, uint8_t status)
  522. {
  523. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  524. {
  525. if(ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStopTransactionReq != status)
  526. ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStopTransactionReq = status;
  527. }
  528. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  529. {
  530. if(ShmOCPP20Data->CsMsg.bits[gun_index].RequestStopTransactionReq != status)
  531. ShmOCPP20Data->CsMsg.bits[gun_index].RequestStopTransactionReq = status;
  532. }
  533. }
  534. uint8_t ocpp_get_remotestart(uint8_t gun_index)
  535. {
  536. uint8_t result = OFF;
  537. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  538. {
  539. result = ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStartTransactionReq;
  540. }
  541. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  542. {
  543. result = ShmOCPP20Data->CsMsg.bits[gun_index].RequestStartTransactionReq;
  544. }
  545. return result;
  546. }
  547. void ocpp_copy_userid_from_remotestart(uint8_t gun_index)
  548. {
  549. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  550. {
  551. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmOCPP16Data->RemoteStartTransaction[gun_index].IdTag, ARRAY_SIZE(ShmOCPP16Data->RemoteStartTransaction[gun_index].IdTag));
  552. }
  553. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  554. {
  555. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmOCPP20Data->RequestStartTransaction[gun_index].idToken.idToken, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  556. }
  557. }
  558. uint8_t ocpp_get_remotestop(uint8_t gun_index)
  559. {
  560. uint8_t result = OFF;
  561. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  562. {
  563. result = ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStopTransactionReq;
  564. }
  565. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  566. {
  567. result = ShmOCPP20Data->CsMsg.bits[gun_index].RequestStopTransactionReq;
  568. }
  569. return result;
  570. }
  571. void ocpp_set_auth_req(uint8_t status, ...)
  572. {
  573. va_list args;
  574. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  575. {
  576. if(ShmOCPP16Data->SpMsg.bits.AuthorizeReq != status)
  577. {
  578. if(status == ON)
  579. memset(ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status, 0x00, ARRAY_SIZE(ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status));
  580. ShmOCPP16Data->SpMsg.bits.AuthorizeReq = status;
  581. }
  582. }
  583. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  584. {
  585. if(ShmOCPP20Data->SpMsg.bits.AuthorizeReq != status)
  586. {
  587. if(status == ON)
  588. {
  589. memset(&ShmOCPP20Data->Authorize.Response_idTokenInfo, 0x00, sizeof(struct IdTokenInfoType));
  590. va_start(args, status);
  591. sprintf((char*)ShmOCPP20Data->Authorize.idToken.type, "%s", va_arg(args, char*));
  592. va_end(args);
  593. }
  594. ShmOCPP20Data->SpMsg.bits.AuthorizeReq = status;
  595. }
  596. }
  597. }
  598. uint8_t ocpp_get_auth_req()
  599. {
  600. uint8_t result = OFF;
  601. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  602. {
  603. result = ShmOCPP16Data->SpMsg.bits.AuthorizeReq;
  604. }
  605. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  606. {
  607. result = ShmOCPP20Data->SpMsg.bits.AuthorizeReq;
  608. }
  609. return result;
  610. }
  611. void ocpp_set_auth_conf(uint8_t status)
  612. {
  613. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  614. {
  615. if(ShmOCPP16Data->SpMsg.bits.AuthorizeConf != status)
  616. ShmOCPP16Data->SpMsg.bits.AuthorizeConf = status;
  617. }
  618. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  619. {
  620. if(ShmOCPP20Data->SpMsg.bits.AuthorizeConf != status)
  621. ShmOCPP20Data->SpMsg.bits.AuthorizeConf = status;
  622. }
  623. }
  624. uint8_t ocpp_get_auth_conf()
  625. {
  626. uint8_t result = OFF;
  627. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  628. {
  629. result = ShmOCPP16Data->SpMsg.bits.AuthorizeConf;
  630. }
  631. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  632. {
  633. result = ShmOCPP20Data->SpMsg.bits.AuthorizeConf;
  634. }
  635. return result;
  636. }
  637. uint8_t ocpp_get_auth_result(uint8_t isValidParent, ...)
  638. {
  639. uint8_t result = OFF;
  640. va_list args;
  641. uint8_t gun_index;
  642. if(isValidParent)
  643. {
  644. va_start(args, isValidParent);
  645. gun_index = va_arg(args, int);
  646. va_end(args);
  647. switch(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus)
  648. {
  649. case SYS_MODE_AUTHORIZING:
  650. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  651. {
  652. if((strcmp((char*)ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status, "Accepted")==0))
  653. result = PASS;
  654. }
  655. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  656. {
  657. if((strcmp((char*)ShmOCPP20Data->Authorize.Response_idTokenInfo.status, "Accepted")==0))
  658. result = PASS;
  659. }
  660. break;
  661. case SYS_MODE_CHARGING:
  662. case SYS_MODE_TERMINATING:
  663. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  664. {
  665. /*
  666. DEBUG_INFO("==========================================\n");
  667. DEBUG_INFO("=== OCPP GETTING AUTHORIZE RESULT 1.6 ====\n");
  668. DEBUG_INFO("==========================================\n");
  669. DEBUG_INFO("Authorize.ResponseIdTagInfo.ParentIdTag : %s \n", ShmOCPP16Data->Authorize.ResponseIdTagInfo.ParentIdTag);
  670. DEBUG_INFO("StartTransaction[%d].ResponseIdTagInfo.ParentIdTag : %s \n", gun_index ,ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.ParentIdTag);
  671. */
  672. if((strcmp((char*)ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status, "Accepted")==0) &&
  673. (strcmp((char*)ShmOCPP16Data->Authorize.ResponseIdTagInfo.ParentIdTag, (char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.ParentIdTag)==0))
  674. result = PASS;
  675. }
  676. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  677. {
  678. /*
  679. DEBUG_INFO("==========================================\n");
  680. DEBUG_INFO("=== OCPP GETTING AUTHORIZE RESULT 2.0 ====\n");
  681. DEBUG_INFO("==========================================\n");
  682. DEBUG_INFO("Authorize.Response_idTokenInfo.groupIdToken.idToken : %s \n", ShmOCPP20Data->Authorize.Response_idTokenInfo.groupIdToken.idToken);
  683. DEBUG_INFO("TransactionEvent[%d].Response_idTokenInfo.groupIdToken.idToken : %s \n", gun_index, ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.groupIdToken.idToken);
  684. */
  685. if((strcmp((char*)ShmOCPP20Data->Authorize.Response_idTokenInfo.status, "Accepted")==0) &&
  686. (strcmp((char*)ShmOCPP20Data->Authorize.Response_idTokenInfo.groupIdToken.idToken, (char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.groupIdToken.idToken)==0))
  687. result = PASS;
  688. }
  689. break;
  690. default:
  691. break;
  692. }
  693. }
  694. else
  695. {
  696. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  697. {
  698. if((strcmp((char*)ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status, "Accepted")==0))
  699. result = PASS;
  700. }
  701. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  702. {
  703. if((strcmp((char*)ShmOCPP20Data->Authorize.Response_idTokenInfo.status, "Accepted")==0))
  704. result = PASS;
  705. }
  706. }
  707. //DEBUG_INFO("Authorize result : %s \n", ((result == PASS)?"Pass":"Fail"));
  708. return result;
  709. }
  710. uint8_t ocpp_get_unlocker_req(uint8_t gun_index)
  711. {
  712. uint8_t result = OFF;
  713. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  714. {
  715. result = ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor;
  716. }
  717. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  718. {
  719. result = ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor;
  720. }
  721. return result;
  722. }
  723. void ocpp_set_unlocker_req(uint8_t gun_index, uint8_t status)
  724. {
  725. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  726. {
  727. if(ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor != status)
  728. ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor = status;
  729. }
  730. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  731. {
  732. if(ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor != status)
  733. ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor = status;
  734. }
  735. }
  736. void ocpp_set_starttransaction_req(uint8_t gun_index, uint8_t status)
  737. {
  738. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  739. {
  740. if(ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionReq != status)
  741. ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionReq = status;
  742. }
  743. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  744. {
  745. if(ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventReq != status)
  746. ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventReq = status;
  747. }
  748. }
  749. void ocpp_set_starttransaction_conf(uint8_t gun_index, uint8_t status)
  750. {
  751. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  752. {
  753. if(ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionConf != status)
  754. ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionConf = status;
  755. }
  756. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  757. {
  758. if(ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventConf != status)
  759. ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventConf = status;
  760. }
  761. }
  762. void ocpp_set_stoptransaction_req(uint8_t gun_index, uint8_t status)
  763. {
  764. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  765. {
  766. if(ShmOCPP16Data->CpMsg.bits[gun_index].StopTransactionReq != status)
  767. ShmOCPP16Data->CpMsg.bits[gun_index].StopTransactionReq = status;
  768. }
  769. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  770. {
  771. if(ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventReq != status)
  772. ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventReq = status;
  773. }
  774. }
  775. void ocpp_set_stoptransaction_conf(uint8_t gun_index, uint8_t status)
  776. {
  777. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  778. {
  779. if(ShmOCPP16Data->CpMsg.bits[gun_index].StopTransactionConf != status)
  780. {
  781. ShmOCPP16Data->CpMsg.bits[gun_index].StopTransactionConf = status;
  782. }
  783. }
  784. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  785. {
  786. if(ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventConf != status)
  787. {
  788. ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventConf = status;
  789. }
  790. }
  791. }
  792. void ocpp_copy_userid_to_starttransaction(uint8_t gun_index)
  793. {
  794. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  795. {
  796. memcpy((char*)ShmOCPP16Data->StartTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmOCPP16Data->StartTransaction[gun_index].IdTag));
  797. }
  798. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  799. {
  800. memcpy((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId));
  801. }
  802. }
  803. uint8_t ocpp_get_starttransaction_result(uint8_t gun_index)
  804. {
  805. uint8_t result = PASS;
  806. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  807. {
  808. if(strstr((char*)ShmOCPP16Data->ConfigurationTable.CoreProfile[StopTransactionOnInvalidId].ItemData, "TRUE"))
  809. {
  810. if((strcmp((char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Blocked")==0) ||
  811. (strcmp((char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Expired")==0) ||
  812. (strcmp((char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Invalid")==0))
  813. result = NO;
  814. }
  815. }
  816. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  817. {
  818. if(strstr((char*)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_StopTxOnInvalidId].variableAttribute[0].value, "TRUE"))
  819. {
  820. if((strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Blocked")==0) ||
  821. (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Expired")==0) ||
  822. (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Invalid")==0) ||
  823. (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NoCredit")==0) ||
  824. (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NotAllowedTypeEVSE")==0) ||
  825. (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NotAtThisLocation")==0) ||
  826. (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NotAtThisTime")==0) ||
  827. (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Unknown")==0))
  828. result = NO;
  829. }
  830. }
  831. return result;
  832. }
  833. uint8_t ocpp_get_smartcharging_profileId(uint8_t gun_index)
  834. {
  835. uint8_t result = 0;
  836. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  837. {
  838. result = ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfileId;
  839. }
  840. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  841. {
  842. result = ShmOCPP20Data->SmartChargingProfile[gun_index].id;
  843. }
  844. return result;
  845. }
  846. void ocpp_reset_smartcharging_profileId(uint8_t gun_index)
  847. {
  848. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  849. {
  850. ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfileId = 0;
  851. }
  852. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  853. {
  854. ShmOCPP20Data->SmartChargingProfile[gun_index].id = 0;
  855. }
  856. }
  857. uint8_t ocpp_get_profile_req(uint8_t gun_index)
  858. {
  859. uint8_t result = OFF;
  860. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  861. {
  862. result = ShmOCPP16Data->CSUMsg.bits[gun_index].ChargingProfileReq;
  863. }
  864. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  865. {
  866. result = ShmOCPP20Data->CSUMsg.bits[gun_index].ChargingProfileReq;
  867. }
  868. return result;
  869. }
  870. void ocpp_set_profile_req(uint8_t gun_index, uint8_t status)
  871. {
  872. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  873. {
  874. if(ShmOCPP16Data->CSUMsg.bits[gun_index].ChargingProfileReq != status)
  875. ShmOCPP16Data->CSUMsg.bits[gun_index].ChargingProfileReq = status;
  876. }
  877. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  878. {
  879. if(ShmOCPP20Data->CSUMsg.bits[gun_index].ChargingProfileReq != status)
  880. ShmOCPP20Data->CSUMsg.bits[gun_index].ChargingProfileReq = status;
  881. }
  882. }
  883. uint8_t ocpp_get_profile_conf(uint8_t gun_index)
  884. {
  885. uint8_t result = OFF;
  886. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  887. {
  888. result = ShmOCPP16Data->CSUMsg.bits[gun_index].ChargingProfileConf;
  889. }
  890. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  891. {
  892. result = ShmOCPP20Data->CSUMsg.bits[gun_index].ChargingProfileConf;
  893. }
  894. return result;
  895. }
  896. void ocpp_set_profile_conf(uint8_t gun_index, uint8_t status)
  897. {
  898. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  899. {
  900. if(ShmOCPP16Data->CSUMsg.bits[gun_index].ChargingProfileConf != status)
  901. ShmOCPP16Data->CSUMsg.bits[gun_index].ChargingProfileConf = status;
  902. }
  903. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  904. {
  905. if(ShmOCPP20Data->CSUMsg.bits[gun_index].ChargingProfileConf != status)
  906. ShmOCPP20Data->CSUMsg.bits[gun_index].ChargingProfileConf = status;
  907. }
  908. }
  909. uint8_t ocpp_get_StopTransactionOnEVSideDisconnect()
  910. {
  911. uint8_t result = OFF;
  912. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  913. {
  914. if(strcmp((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[StopTransactionOnEVSideDisconnect].ItemData, "TRUE") == 0)
  915. result = ON;
  916. }
  917. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  918. {
  919. if(strcmp((char *)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_StopTxOnEVSideDisconnect].variableAttribute[0].value, "TRUE") == 0)
  920. result = ON;
  921. }
  922. return result;
  923. }
  924. uint8_t ocpp_get_cancelreservation_req(uint8_t gun_index)
  925. {
  926. uint8_t result = OFF;
  927. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  928. {
  929. result = ShmOCPP16Data->CsMsg.bits[gun_index].CancelReservationReq;
  930. }
  931. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  932. {
  933. result = ShmOCPP20Data->CsMsg.bits[gun_index].CancelReservationReq;
  934. }
  935. return result;
  936. }
  937. void ocpp_set_cancelreservation_req(uint8_t gun_index, uint8_t status)
  938. {
  939. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  940. {
  941. if(ShmOCPP16Data->CsMsg.bits[gun_index].CancelReservationReq != status)
  942. ShmOCPP16Data->CsMsg.bits[gun_index].CancelReservationReq = status;
  943. if(ShmOCPP16Data->CsMsg.bits[gun_index].CancelReservationReq == OFF)
  944. ShmOCPP16Data->CsMsg.bits[gun_index].CancelReservationConf = ON;
  945. }
  946. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  947. {
  948. if(ShmOCPP20Data->CsMsg.bits[gun_index].CancelReservationReq != status)
  949. ShmOCPP20Data->CsMsg.bits[gun_index].CancelReservationReq = status;
  950. if(ShmOCPP20Data->CsMsg.bits[gun_index].CancelReservationReq == OFF)
  951. ShmOCPP20Data->CsMsg.bits[gun_index].CancelReservationConf = ON;
  952. }
  953. }
  954. uint8_t ocpp_compare_reserve_id_with_user(uint8_t gun_index)
  955. {
  956. uint8_t result = OFF;
  957. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  958. {
  959. if(strcmp((char*)ShmSysConfigAndInfo->SysConfig.UserId, (char*)ShmOCPP16Data->ReserveNow[gun_index].IdTag) == 0)
  960. result = ON;
  961. }
  962. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  963. {
  964. if(strcmp((char*)ShmSysConfigAndInfo->SysConfig.UserId, (char*)ShmOCPP20Data->ReserveNow[gun_index].idToken.idToken) == 0)
  965. result = ON;
  966. }
  967. return result;
  968. }
  969. uint8_t ocpp_compare_reserve_id_with_remote_user(uint8_t gun_index)
  970. {
  971. uint8_t result = OFF;
  972. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  973. {
  974. if(strcmp((char*)ShmOCPP16Data->RemoteStartTransaction[gun_index].IdTag, (char*)ShmOCPP16Data->ReserveNow[gun_index].IdTag) == 0)
  975. {
  976. result = ON;
  977. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmOCPP16Data->RemoteStartTransaction[gun_index].IdTag, ARRAY_SIZE(ShmOCPP16Data->RemoteStartTransaction[gun_index].IdTag));
  978. }
  979. }
  980. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  981. {
  982. if(strcmp((char*)ShmOCPP20Data->RequestStartTransaction[gun_index].idToken.idToken, (char*)ShmOCPP20Data->ReserveNow[gun_index].idToken.idToken) == 0)
  983. {
  984. result = ON;
  985. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmOCPP20Data->RequestStartTransaction[gun_index].idToken.idToken, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  986. }
  987. }
  988. return result;
  989. }
  990. uint8_t ocpp_isAuthorizeRemoteStart()
  991. {
  992. uint8_t result = NO;
  993. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  994. {
  995. if(strstr((char*)ShmOCPP16Data->ConfigurationTable.CoreProfile[AuthorizeRemoteTxRequests].ItemData, "TRUE"))
  996. {
  997. result = YES;
  998. }
  999. }
  1000. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  1001. {
  1002. if(strstr((char*)ShmOCPP20Data->ControllerComponentVariable[AuthCtrlr_AuthorizeRemoteStart].variableAttribute[0].value, "TRUE"))
  1003. {
  1004. result = YES;
  1005. }
  1006. }
  1007. return result;
  1008. }
  1009. //======================================================
  1010. // Check interface status
  1011. //======================================================
  1012. int isInterfaceUp(const char *interface)
  1013. {
  1014. int result = FAIL;
  1015. FILE *fp;
  1016. char cmd[256];
  1017. char buf[512];
  1018. strcpy(cmd, "ifconfig");;
  1019. fp = popen(cmd, "r");
  1020. if(fp != NULL)
  1021. {
  1022. while(fgets(buf, sizeof(buf), fp) != NULL)
  1023. {
  1024. if(strstr(buf, interface) > 0)
  1025. {
  1026. result = PASS;
  1027. }
  1028. }
  1029. }
  1030. pclose(fp);
  1031. return result;
  1032. }
  1033. //======================================================
  1034. // Create all share memory
  1035. //======================================================
  1036. int CreatShareMemory()
  1037. {
  1038. int result = PASS;
  1039. int MeterSMId;
  1040. //creat ShmSysConfigAndInfo
  1041. if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo), IPC_CREAT | 0777)) < 0)
  1042. {
  1043. DEBUG_ERROR("shmget ShmSysConfigAndInfo NG\n");
  1044. result = FAIL;
  1045. }
  1046. else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  1047. {
  1048. DEBUG_ERROR("shmat ShmSysConfigAndInfo NG\n");
  1049. result = FAIL;
  1050. }
  1051. memset(ShmSysConfigAndInfo,0,sizeof(struct SysConfigAndInfo));
  1052. //creat ShmPsuData
  1053. if ((MeterSMId = shmget(ShmPsuKey, sizeof(struct PsuData), IPC_CREAT | 0777)) < 0)
  1054. {
  1055. DEBUG_ERROR("shmget ShmPsuData NG\n");
  1056. result = FAIL;
  1057. }
  1058. else if ((ShmPsuData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  1059. {
  1060. DEBUG_ERROR("shmat ShmPsuData NG\n");
  1061. result = FAIL;
  1062. }
  1063. else
  1064. {}
  1065. //creat ShmStatusCodeData
  1066. if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData), IPC_CREAT | 0777)) < 0)
  1067. {
  1068. DEBUG_ERROR("shmget ShmStatusCodeData NG\n");
  1069. result = FAIL;
  1070. }
  1071. else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  1072. {
  1073. DEBUG_ERROR("shmat ShmStatusCodeData NG\n");
  1074. result = FAIL;
  1075. }
  1076. memset(ShmStatusCodeData, 0, sizeof(struct StatusCodeData));
  1077. //creat ShmPrimaryMcuData
  1078. if ((MeterSMId = shmget(ShmPrimaryMcuKey, sizeof(struct PrimaryMcuData), IPC_CREAT | 0777)) < 0)
  1079. {
  1080. DEBUG_ERROR("shmget ShmPrimaryMcuData NG\n");
  1081. result = FAIL;
  1082. }
  1083. else if ((ShmPrimaryMcuData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  1084. {
  1085. DEBUG_ERROR("shmat ShmPrimaryMcuData NG\n");
  1086. result = FAIL;
  1087. }
  1088. memset(ShmPrimaryMcuData,0,sizeof(struct PrimaryMcuData));
  1089. //creat ShmOCPP16Data
  1090. if ((MeterSMId = shmget(ShmOcppModuleKey, sizeof(struct OCPP16Data), IPC_CREAT | 0777)) < 0)
  1091. {
  1092. DEBUG_ERROR("shmget ShmOCPP16Data NG\n");
  1093. result = FAIL;
  1094. }
  1095. else if ((ShmOCPP16Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  1096. {
  1097. DEBUG_ERROR("shmat ShmOCPP16Data NG\n");
  1098. result = FAIL;
  1099. }
  1100. memset(ShmOCPP16Data,0,sizeof(struct OCPP16Data));
  1101. //creat ShmOCPP20Data
  1102. if ((MeterSMId = shmget(ShmOcpp20ModuleKey, sizeof(struct OCPP20Data), IPC_CREAT | 0777)) < 0)
  1103. {
  1104. DEBUG_ERROR("shmget OCPP20Data NG\n");
  1105. result = FAIL;
  1106. }
  1107. else if ((ShmOCPP20Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  1108. {
  1109. DEBUG_ERROR("shmat OCPP20Data NG\n");
  1110. result = FAIL;
  1111. }
  1112. memset(ShmOCPP20Data,0,sizeof(struct OCPP20Data));
  1113. //creat ShmCharger
  1114. if ((MeterSMId = shmget(ShmChargerKey, sizeof(struct Charger), IPC_CREAT | 0777)) < 0)
  1115. {
  1116. DEBUG_ERROR("shmget ShmCharger NG\n");
  1117. result = FAIL;
  1118. }
  1119. else if ((ShmCharger = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  1120. {
  1121. DEBUG_ERROR("shmat ShmCharger NG\n");
  1122. result = FAIL;
  1123. }
  1124. memset(ShmCharger,0,sizeof(struct Charger));
  1125. //creat ShmDispenser
  1126. if ((MeterSMId = shmget(ShmDispenserKey, sizeof(struct DISPENSER), IPC_CREAT | 0777)) < 0)
  1127. {
  1128. DEBUG_ERROR("shmget ShmDispenser NG\n");
  1129. result = FAIL;
  1130. }
  1131. else if ((ShmDispenser = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  1132. {
  1133. DEBUG_ERROR("shmat ShmDispenser NG\n");
  1134. result = FAIL;
  1135. }
  1136. memset(ShmDispenser,0,sizeof(struct DISPENSER));
  1137. ShmSysConfigAndInfo->SysInfo.InternetConn = OFF;
  1138. return result;
  1139. }
  1140. //======================================================
  1141. // Call WEBAPI to mail receipt (Only for CDFA verify)
  1142. //======================================================
  1143. #ifdef CDFA_CERTIFICATE
  1144. int sendReceiptMail(char *startDateTime, char *stopDateTime, char *receiptInfo)
  1145. {
  1146. int result = FAIL;
  1147. char reciever[128];
  1148. char subject[128];
  1149. char content[8192];
  1150. char priceDetail[4098]={0};
  1151. char cmdBuf[8192];
  1152. double totalEnergy;
  1153. double totalPrice;
  1154. json_object *detailPrice = json_tokener_parse(receiptInfo);
  1155. if(!is_error(detailPrice))
  1156. {
  1157. if(json_object_object_get(detailPrice, "totalChargedEnergy") != NULL)
  1158. totalEnergy = json_object_get_double(json_object_object_get(detailPrice, "totalChargedEnergy"));
  1159. if(json_object_object_get(detailPrice, "totalPrice") != NULL)
  1160. totalPrice = json_object_get_double(json_object_object_get(detailPrice, "totalPrice"));
  1161. if(json_object_object_get(detailPrice, "receiptDetail") != NULL)
  1162. {
  1163. for(int idx=0;idx<json_object_array_length(json_object_object_get(detailPrice, "receiptDetail"));idx++)
  1164. {
  1165. sprintf(priceDetail, "%s---%02d:00, %.4f KWH @ $ %.2f = $ %.2f<br/>\n", priceDetail
  1166. , json_object_get_int(json_object_object_get(json_object_array_get_idx(json_object_object_get(detailPrice, "receiptDetail"), idx), "hour"))
  1167. , json_object_get_double(json_object_object_get(json_object_array_get_idx(json_object_object_get(detailPrice, "receiptDetail"), idx), "chargedEnergy"))
  1168. , json_object_get_double(json_object_object_get(json_object_array_get_idx(json_object_object_get(detailPrice, "receiptDetail"), idx), "unitPrice"))
  1169. , json_object_get_double(json_object_object_get(json_object_array_get_idx(json_object_object_get(detailPrice, "receiptDetail"), idx), "periodPrice")));
  1170. }
  1171. }
  1172. }
  1173. json_object_put(detailPrice);
  1174. // Generate mail content
  1175. sprintf(reciever, "folus_wen@phihong.com.tw");
  1176. sprintf(subject, "Charging Receipt From %s", ShmSysConfigAndInfo->SysConfig.chargePointVendor);
  1177. sprintf(content, "<img src=\"https://www.phihong.com/images/logo.png\"/><br/>\n"
  1178. "<h1>Receipt of charging on %s</h1><br/>\n"
  1179. "<b>Location Name:</b> CDFA Lab<br/>\n"
  1180. "<b>Location Address:</b> xxxxxxxxxxx<br/>\n"
  1181. "<b>EVSE ID:</b> %s<br/>\n"
  1182. "<b>Maximum Rate of Energy Transfer:</b> 11.5 KW AC<br/>\n"
  1183. "<b>Charging start date time:</b> %s<br/>\n"
  1184. "<b>Charging stop date time:</b> %s<br/>\n"
  1185. "<b>Energy Delivered:</b> %.4f KWH<br/>\n"
  1186. "<b>Cost of Charging:</b><br/>\n"
  1187. "%s"
  1188. "***Total charged cost: $ %.2f<br/>\n"
  1189. "<br/>\n"
  1190. "<br/>\n"
  1191. "%s<br/>\n"
  1192. "47800 Fremont Blvd.<br/>\n"
  1193. "Fremont, CA 94538, USA<br/>\n", startDateTime
  1194. , ShmSysConfigAndInfo->SysConfig.ChargeBoxId
  1195. , startDateTime
  1196. , stopDateTime
  1197. , totalEnergy
  1198. , priceDetail
  1199. , totalPrice
  1200. , ShmSysConfigAndInfo->SysConfig.chargePointVendor);
  1201. json_object *post = json_object_new_object();
  1202. json_object_object_add(post, "Receiver", json_object_new_string(reciever));
  1203. json_object_object_add(post, "Subject", json_object_new_string(subject));
  1204. json_object_object_add(post, "Body", json_object_new_string(content));
  1205. json_object_object_add(post, "UseHtml", json_object_new_boolean(1));
  1206. // Call WEBAPI
  1207. sprintf(cmdBuf, "curl -X POST -k -d '%s' -H \"Content-Type: application/json\" https://ocpp.phihong.com.tw:5014/api/Notification/ &", json_object_to_json_string_ext(post, JSON_C_TO_STRING_PLAIN));
  1208. system(cmdBuf);
  1209. //DEBUG_INFO("cmdBuf: %s\n", cmdBuf);
  1210. json_object_put(post);
  1211. return result;
  1212. }
  1213. #endif /* CDFA_CERTIFICATE */
  1214. //======================================================
  1215. // SQLite3 related routine
  1216. //======================================================
  1217. int getReceiptInfo(uint8_t gun_index, char *receiptInfo)
  1218. {
  1219. int result = PASS;
  1220. double totalEnergy=0.0;
  1221. double totalPrice=0.0;
  1222. json_object *receipt = json_object_new_object();
  1223. json_object *receiptAry = json_object_new_array();
  1224. for(uint8_t idxHour=0;idxHour<ARRAY_SIZE(ShmCharger->gun_info[gun_index].presentChargedEnergyPeriod);idxHour++)
  1225. {
  1226. json_object *receiptDetail = json_object_new_object();
  1227. json_object_object_add(receiptDetail, "hour", json_object_new_int(idxHour));
  1228. json_object_object_add(receiptDetail, "chargedEnergy", json_object_new_double(ShmCharger->gun_info[gun_index].presentChargedEnergyPeriod[idxHour]));
  1229. json_object_object_add(receiptDetail, "unitPrice", json_object_new_double(ShmSysConfigAndInfo->SysConfig.BillingData.Fee[idxHour]));
  1230. json_object_object_add(receiptDetail, "periodPrice", json_object_new_double(ShmCharger->gun_info[gun_index].presentChargedEnergyPeriod[idxHour]*ShmSysConfigAndInfo->SysConfig.BillingData.Fee[idxHour]));
  1231. totalEnergy += ShmCharger->gun_info[gun_index].presentChargedEnergyPeriod[idxHour];
  1232. totalPrice += ShmCharger->gun_info[gun_index].presentChargedEnergyPeriod[idxHour]*ShmSysConfigAndInfo->SysConfig.BillingData.Fee[idxHour];
  1233. json_object_array_add(receiptAry, receiptDetail);
  1234. }
  1235. json_object_object_add(receipt, "receiptDetail", receiptAry);
  1236. json_object_object_add(receipt, "totalChargedEnergy", json_object_new_double(totalEnergy));
  1237. json_object_object_add(receipt, "totalPrice", json_object_new_double(totalPrice));
  1238. json_object_object_add(receipt, "serviceProvider", json_object_new_string((char*)ShmSysConfigAndInfo->SysConfig.chargePointVendor));
  1239. json_object_object_add(receipt, "serviceProviderAddress", json_object_new_string("Address"));
  1240. json_object_object_add(receipt, "serviceProviderTel", json_object_new_string("TEL"));
  1241. json_object_object_add(receipt, "chargerBoxId", json_object_new_string((char*)ShmSysConfigAndInfo->SysConfig.ChargeBoxId));
  1242. sprintf(receiptInfo, "%s", json_object_to_json_string_ext(receipt, JSON_C_TO_STRING_PLAIN));
  1243. json_object_put(receipt);
  1244. //DEBUG_INFO("receiptInfo: %s\n", receiptInfo);
  1245. return result;
  1246. }
  1247. int DB_Open(sqlite3 *db)
  1248. {
  1249. int result = PASS;
  1250. char* errMsg = NULL;
  1251. char* createRecordSql="CREATE TABLE IF NOT EXISTS charging_record("
  1252. "idx integer primary key AUTOINCREMENT, "
  1253. "reservationId text, "
  1254. "transactionId text, "
  1255. "startMethod text, "
  1256. "userId text, "
  1257. "dateTimeStart text, "
  1258. "dateTimeStop text,"
  1259. "socStart text, "
  1260. "socStop text, "
  1261. "chargeEnergy text, "
  1262. "stopReason text, "
  1263. "finalCost text"
  1264. ");";
  1265. char* createRecordBufSql="CREATE TABLE IF NOT EXISTS charging_record_buffer("
  1266. "reservationId text, "
  1267. "transactionId text, "
  1268. "startMethod text, "
  1269. "userId text, "
  1270. "dateTimeStart text, "
  1271. "dateTimeStop text,"
  1272. "socStart text, "
  1273. "socStop text, "
  1274. "chargeEnergy text, "
  1275. "stopReason text, "
  1276. "finalCost text"
  1277. ");";
  1278. char* createCfgSql="CREATE TABLE IF NOT EXISTS `config` ( "
  1279. "`idx` INTEGER PRIMARY KEY AUTOINCREMENT, "
  1280. "`item` TEXT NOT NULL, "
  1281. "`connector` INTEGER NOT NULL, "
  1282. "`val` TEXT NOT NULL, unique(item,connector) on conflict replace);";
  1283. //sqlite3_config(SQLITE_CONFIG_URI, 1);
  1284. if(sqlite3_open(DB_FILE, &db))
  1285. {
  1286. result = FAIL;
  1287. DEBUG_ERROR( "Can't open database: %s\n", sqlite3_errmsg(db));
  1288. sqlite3_close(db);
  1289. }
  1290. else
  1291. {
  1292. DEBUG_INFO( "Local charging record database open successfully.\n");
  1293. if (sqlite3_exec(db, createRecordSql, 0, 0, &errMsg) != SQLITE_OK)
  1294. {
  1295. result = FAIL;
  1296. DEBUG_ERROR( "Create local charging record table error message: %s\n", errMsg);
  1297. }
  1298. else
  1299. {
  1300. DEBUG_INFO( "Opened local charging record table successfully\n");
  1301. }
  1302. if (sqlite3_exec(db, createRecordBufSql, 0, 0, &errMsg) != SQLITE_OK)
  1303. {
  1304. result = FAIL;
  1305. DEBUG_ERROR( "Create local charging record buffer table error message: %s\n", errMsg);
  1306. }
  1307. else
  1308. {
  1309. DEBUG_INFO( "Opened local charging record buffer table successfully\n");
  1310. }
  1311. if (sqlite3_exec(db, createCfgSql, 0, 0, &errMsg) != SQLITE_OK)
  1312. {
  1313. result = FAIL;
  1314. DEBUG_ERROR( "Create local config table error message: %s\n", errMsg);
  1315. }
  1316. else
  1317. {
  1318. DEBUG_INFO( "Opened local config table successfully\n");
  1319. }
  1320. sqlite3_close(db);
  1321. }
  1322. return result;
  1323. }
  1324. int DB_Check_Record_Buf(sqlite3 *db, int gun_index)
  1325. {
  1326. int result = PASS;
  1327. char* errMsg = NULL;
  1328. char sqlStr[4096];
  1329. char **rs;
  1330. int rows, cols;
  1331. if(sqlite3_open(DB_FILE, &db))
  1332. {
  1333. result = FAIL;
  1334. DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
  1335. sqlite3_close(db);
  1336. }
  1337. else
  1338. {
  1339. sqlite3_get_table(db, "select * from charging_record_buffer", &rs, &rows, &cols, &errMsg);
  1340. if(rows>0)
  1341. {
  1342. // Copy record buffer
  1343. for(int idxRow=1;idxRow<=rows;idxRow++)
  1344. {
  1345. if(strcmp(rs[(idxRow*cols)+3], "0") == 0)
  1346. {
  1347. result = false;
  1348. }
  1349. sprintf(sqlStr, "insert into charging_record(reservationId, transactionId, startMethod, userId, dateTimeStart, dateTimeStop, socStart, socStop, chargeEnergy, stopReason, finalCost) "
  1350. "values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');",
  1351. rs[(idxRow*cols)+0],
  1352. rs[(idxRow*cols)+1],
  1353. rs[(idxRow*cols)+2],
  1354. rs[(idxRow*cols)+3],
  1355. rs[(idxRow*cols)+4],
  1356. rs[(idxRow*cols)+5],
  1357. rs[(idxRow*cols)+6],
  1358. rs[(idxRow*cols)+7],
  1359. rs[(idxRow*cols)+8],
  1360. rs[(idxRow*cols)+9],
  1361. rs[(idxRow*cols)+10]);
  1362. if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
  1363. {
  1364. result = FAIL;
  1365. DEBUG_INFO( "Copy local charging record buffer error message: %s\n", errMsg);
  1366. }
  1367. else
  1368. {
  1369. DEBUG_INFO( "Copy local charging record buffer successfully\n");
  1370. }
  1371. #ifdef CDFA_CERTIFICATE
  1372. // Only for CDFA certificate
  1373. sendReceiptMail(rs[(idxRow*cols)+4],
  1374. rs[(idxRow*cols)+5],
  1375. rs[(idxRow*cols)+10]);
  1376. #endif /* CDFA_CERTIFICATE */
  1377. }
  1378. // Delete buffer
  1379. if (sqlite3_exec(db, "delete from charging_record_buffer", 0, 0, &errMsg) != SQLITE_OK)
  1380. {
  1381. result = FAIL;
  1382. DEBUG_INFO( "Delete local charging record buffer error message: %s\n", errMsg);
  1383. }
  1384. else
  1385. {
  1386. DEBUG_INFO( "Delete local charging record buffer successfully\n");
  1387. }
  1388. }
  1389. else
  1390. {
  1391. DEBUG_INFO("There is not any charging record buffer.\n", gun_index);
  1392. }
  1393. sqlite3_free_table(rs);
  1394. sqlite3_close(db);
  1395. }
  1396. return result;
  1397. }
  1398. int DB_Update_Record_Buf(sqlite3 *db, int gun_index)
  1399. {
  1400. int result = PASS;
  1401. char* errMsg = NULL;
  1402. char sqlStr[4096];
  1403. char receiptInfo[2048];
  1404. getReceiptInfo(gun_index, receiptInfo);
  1405. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  1406. {
  1407. sprintf(sqlStr, "insert into charging_record_buffer(reservationId, transactionId, startMethod, userId, dateTimeStart, dateTimeStop, socStart, socStop, chargeEnergy, stopReason, finalCost) "
  1408. "values('%d', '%d', '%d', '%s', '%s', '%s', '%d', '%d', '%f', '%s', '%s');",
  1409. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId,
  1410. ShmOCPP16Data->StartTransaction[gun_index].ResponseTransactionId,
  1411. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod,
  1412. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId,
  1413. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime,
  1414. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime,
  1415. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
  1416. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
  1417. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy,
  1418. "Power Loss",
  1419. #ifdef CDFA_CERTIFICATE
  1420. receiptInfo);// Only for CDFA certificate
  1421. #else
  1422. ShmOCPP16Data->Cost.FinalCost[gun_index].description);
  1423. #endif /* CDFA_CERTIFICATE */
  1424. }
  1425. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  1426. {
  1427. sprintf(sqlStr, "insert into charging_record_buffer(reservationId, transactionId, startMethod, userId, dateTimeStart, dateTimeStop, socStart, socStop, chargeEnergy, stopReason, finalCost) "
  1428. #ifdef CDFA_CERTIFICATE
  1429. "values('%d', '%s', '%d', '%s', '%s', '%s', '%d', '%d', '%f', '%s', '%s');",
  1430. #else
  1431. "values('%d', '%s', '%d', '%s', '%s', '%s', '%d', '%d', '%f', '%s', '%f');",
  1432. #endif /* CDFA_CERTIFICATE */
  1433. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId,
  1434. ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.transactionId,
  1435. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod,
  1436. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId,
  1437. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime,
  1438. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime,
  1439. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
  1440. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
  1441. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy,
  1442. "Power Loss",
  1443. #ifdef CDFA_CERTIFICATE
  1444. //receiptInfo);// Only for CDFA certificate
  1445. #else
  1446. ShmOCPP20Data->CostUpdated.totalCost);
  1447. #endif /* CDFA_CERTIFICATE */
  1448. }
  1449. if(sqlite3_open(DB_FILE, &db))
  1450. {
  1451. result = FAIL;
  1452. DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
  1453. sqlite3_close(db);
  1454. }
  1455. else
  1456. {
  1457. // Delete buffer
  1458. if (sqlite3_exec(db, "delete from charging_record_buffer", 0, 0, &errMsg) != SQLITE_OK)
  1459. {
  1460. result = FAIL;
  1461. DEBUG_INFO( "Delete local charging record buffer error message: %s\n", errMsg);
  1462. }
  1463. else
  1464. {
  1465. //DEBUG_INFO( "Delete local charging record buffer successfully\n");
  1466. }
  1467. // Insert record buffer
  1468. if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
  1469. {
  1470. result = FAIL;
  1471. DEBUG_INFO( "Insert local charging record buffer error message: %s\n", errMsg);
  1472. }
  1473. else
  1474. {
  1475. //DEBUG_INFO( "Insert local charging record buffer successfully\n");
  1476. }
  1477. sqlite3_close(db);
  1478. }
  1479. return result;
  1480. }
  1481. int DB_Insert_Record(sqlite3 *db, int gun_index)
  1482. {
  1483. int result = PASS;
  1484. char* errMsg = NULL;
  1485. char sqlStr[4096];
  1486. char receiptInfo[2048];
  1487. getReceiptInfo(gun_index, receiptInfo);
  1488. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  1489. {
  1490. sprintf(sqlStr, "insert into charging_record(reservationId, transactionId, startMethod, userId, dateTimeStart, dateTimeStop, socStart, socStop, chargeEnergy, stopReason, finalCost) "
  1491. "values('%d', '%d', '%d', '%s', '%s', '%s', '%d', '%d', '%f', '%s', '%s');",
  1492. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId,
  1493. ShmOCPP16Data->StartTransaction[gun_index].ResponseTransactionId,
  1494. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod,
  1495. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId,
  1496. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime,
  1497. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime,
  1498. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
  1499. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
  1500. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy,
  1501. ShmOCPP16Data->StopTransaction[gun_index].StopReason,
  1502. #ifdef CDFA_CERTIFICATE
  1503. receiptInfo);// Only for CDFA certificate
  1504. #else
  1505. ShmOCPP16Data->Cost.FinalCost[gun_index].description);
  1506. #endif /* CDFA_CERTIFICATE */
  1507. }
  1508. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  1509. {
  1510. sprintf(sqlStr, "insert into charging_record(reservationId, transactionId, startMethod, userId, dateTimeStart, dateTimeStop, socStart, socStop, chargeEnergy, stopReason, finalCost) "
  1511. #ifdef CDFA_CERTIFICATE
  1512. "values('%d', '%s', '%d', '%s', '%s', '%s', '%d', '%d', '%f', '%s', '%s');",
  1513. #else
  1514. "values('%d', '%s', '%d', '%s', '%s', '%s', '%d', '%d', '%f', '%s', '%f');",
  1515. #endif /* CDFA_CERTIFICATE */
  1516. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId,
  1517. ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.transactionId,
  1518. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod,
  1519. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId,
  1520. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime,
  1521. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime,
  1522. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
  1523. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
  1524. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy,
  1525. ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason,
  1526. #ifdef CDFA_CERTIFICATE
  1527. receiptInfo);// Only for CDFA certificate
  1528. #else
  1529. ShmOCPP20Data->CostUpdated.totalCost);
  1530. #endif /* CDFA_CERTIFICATE */
  1531. }
  1532. //DEBUG_INFO("sqlStr= %s\n", sqlStr);
  1533. if(sqlite3_open(DB_FILE, &db))
  1534. {
  1535. result = FAIL;
  1536. DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
  1537. sqlite3_close(db);
  1538. }
  1539. else
  1540. {
  1541. // Delete buffer
  1542. if (sqlite3_exec(db, "delete from charging_record_buffer", 0, 0, &errMsg) != SQLITE_OK)
  1543. {
  1544. result = FAIL;
  1545. DEBUG_INFO( "Delete local charging record buffer error message: %s\n", errMsg);
  1546. }
  1547. else
  1548. {
  1549. DEBUG_INFO( "Delete local charging record buffer successfully\n");
  1550. }
  1551. // Insert charging record
  1552. if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
  1553. {
  1554. result = FAIL;
  1555. DEBUG_INFO( "Insert local charging record error message: %s\n", errMsg);
  1556. }
  1557. else
  1558. {
  1559. DEBUG_INFO( "Insert local charging record successfully\n");
  1560. }
  1561. sprintf(sqlStr, "delete from charging_record where (idx < (select idx from charging_record order by idx desc limit 1)-2000) and (dateTimeStop < '%04d.01.01 00:00:00');", (getCurrentYear()-3));
  1562. if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
  1563. {
  1564. result = FAIL;
  1565. DEBUG_INFO( "delete local charging error message: %s\n", errMsg);
  1566. }
  1567. else
  1568. {
  1569. DEBUG_INFO( "delete local charging record successfully\n");
  1570. }
  1571. sqlite3_close(db);
  1572. }
  1573. #ifdef CDFA_CERTIFICATE
  1574. // Only for CDFA certificate
  1575. sendReceiptMail((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime,
  1576. (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime,
  1577. receiptInfo);
  1578. #endif
  1579. return result;
  1580. }
  1581. int DB_Update_Operactive(sqlite3 *db, uint8_t gun_index, uint8_t isOperactive)
  1582. {
  1583. uint8_t result = false;
  1584. char* errMsg = NULL;
  1585. char sqlStr[1024];
  1586. srand(time(NULL));
  1587. if(sqlite3_open(DB_FILE, &db))
  1588. {
  1589. result = FAIL;
  1590. DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
  1591. sqlite3_close(db);
  1592. }
  1593. else
  1594. {
  1595. sprintf(sqlStr, "insert or replace into config (item, connector, val) values('isOperactive', %d, %d);", gun_index, isOperactive);
  1596. //DEBUG_INFO("sqlStr= %s\n", sqlStr);
  1597. if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
  1598. {
  1599. result = FAIL;
  1600. DEBUG_INFO( "update config error message: %s\n", errMsg);
  1601. }
  1602. else
  1603. {
  1604. DEBUG_INFO("update connector-%d config item isOperactive to %d\n", gun_index, isOperactive);
  1605. }
  1606. sqlite3_close(db);
  1607. }
  1608. return result;
  1609. }
  1610. int DB_Get_Operactive(sqlite3 *db, uint8_t gun_index)
  1611. {
  1612. uint8_t result = true;
  1613. char* errMsg = NULL;
  1614. char sqlStr[1024];
  1615. char **rs;
  1616. int rows, cols;
  1617. sprintf(sqlStr, "select * from config where item='isOperactive' and connector=%d;", gun_index);
  1618. //DEBUG_INFO("sqlStr= %s\n", sqlStr);
  1619. if(sqlite3_open(DB_FILE, &db))
  1620. {
  1621. result = FAIL;
  1622. DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
  1623. sqlite3_close(db);
  1624. }
  1625. else
  1626. {
  1627. sqlite3_get_table(db, sqlStr, &rs, &rows, &cols, &errMsg);
  1628. if(rows>0)
  1629. {
  1630. for(int idxRow=1;idxRow<=rows;idxRow++)
  1631. {
  1632. if(strcmp(rs[(idxRow*cols)+3], "0") == 0)
  1633. {
  1634. result = false;
  1635. }
  1636. DEBUG_INFO("Query connector-%d isOperactive: %s\n", gun_index, rs[(idxRow*cols)+3]);
  1637. }
  1638. }
  1639. else
  1640. {
  1641. DEBUG_INFO("Query connector-%d fail, default value as operactive.\n", gun_index);
  1642. }
  1643. sqlite3_free_table(rs);
  1644. sqlite3_close(db);
  1645. }
  1646. return result;
  1647. }
  1648. //======================================================
  1649. // Peripheral initial
  1650. //======================================================
  1651. int InitWatchDog()
  1652. {
  1653. int fd;
  1654. int timeout = 330;
  1655. system("/usr/bin/fuser -k /dev/watchdog");
  1656. sleep(1);
  1657. system("echo V > /dev/watchdog");
  1658. sleep(1);
  1659. fd=open("/dev/watchdog", O_RDWR);
  1660. if(fd<=0)
  1661. {
  1662. DEBUG_ERROR("System watch dog initial fail.\n");
  1663. }
  1664. ioctl(fd, _IOWR('W', 6, int), &timeout);
  1665. return fd;
  1666. }
  1667. void InitGPIO()
  1668. {
  1669. /*****************0~3, 4 bank, bank x 32+ num*********************/
  1670. /***************************************************************/
  1671. /*************** INPUT PIN ***************************************/
  1672. /***************************************************************/
  1673. /***************************************************************/
  1674. /*************** OUTPUT PIN ************************************/
  1675. /***************************************************************/
  1676. /*MCU request:GPIO3_20 => H:ON; L:OFF*/
  1677. system("echo 116 > /sys/class/gpio/export");
  1678. system("echo \"out\" > /sys/class/gpio/gpio116/direction");
  1679. system("echo 0 > /sys/class/gpio/gpio116/value");
  1680. /*Rfid:GPIO0_19 => Reset_PING H:ON; L:OFF*/
  1681. system("echo 19 > /sys/class/gpio/export");
  1682. system("echo \"out\" > /sys/class/gpio/gpio19/direction");
  1683. system("echo 1 > /sys/class/gpio/gpio19/value");
  1684. /*Speaker:GPIO2_1 => H:ON; L:OFF*/
  1685. system("echo 65 > /sys/class/gpio/export");
  1686. system("echo \"out\" > /sys/class/gpio/gpio65/direction");
  1687. system("echo 0 > /sys/class/gpio/gpio65/value");
  1688. /*Ethernet RST:GPIO2_25 => H:ON; L:OFF*/
  1689. system("echo 89 > /sys/class/gpio/export");
  1690. system("echo \"out\" > /sys/class/gpio/gpio89/direction");
  1691. system("echo 0 > /sys/class/gpio/gpio89/value");
  1692. sleep(1);
  1693. system("echo 1 > /sys/class/gpio/gpio89/value");
  1694. /*4G/Wifi RST:GPIO3_18 => H:ON; L:OFF*/
  1695. system("echo 114 > /sys/class/gpio/export");
  1696. system("echo \"out\" > /sys/class/gpio/gpio114/direction");
  1697. system("echo 1 > /sys/class/gpio/gpio114/value");
  1698. sleep(1);
  1699. system("echo 0 > /sys/class/gpio/gpio114/value");
  1700. /*RFID ICC:GPIO0_20 => H:ON; L:OFF*/
  1701. system("echo 20 > /sys/class/gpio/export");
  1702. system("echo \"in\" > /sys/class/gpio/gpio20/direction");
  1703. /*QCA7000 interrupt:GPIO2_00 => H:ON; L:OFF*/
  1704. system("echo 64 > /sys/class/gpio/export");
  1705. system("echo \"in\" > /sys/class/gpio/gpio64/direction");
  1706. /*QCA7000 Reset:GPIO3_19 => H:ON; L:OFF*/
  1707. system("echo 115 > /sys/class/gpio/export");
  1708. system("echo \"out\" > /sys/class/gpio/gpio115/direction");
  1709. system("echo 0 > /sys/class/gpio/gpio115/value");
  1710. sleep(1);
  1711. system("echo 1 > /sys/class/gpio/gpio115/value");
  1712. /*RFID RST: GPIO1_30 => H:OFF; L:ON*/
  1713. system("echo 62 > /sys/class/gpio/export");
  1714. system("echo \"out\" > /sys/class/gpio/gpio62/direction");
  1715. system("echo 0 > /sys/class/gpio/gpio62/value");
  1716. /*Wake up button GPIO1_31 => H:OFF; L:ON*/
  1717. system("echo 63 > /sys/class/gpio/export");
  1718. system("echo \"in\" > /sys/class/gpio/gpio64/direction");
  1719. sleep(1);
  1720. DEBUG_INFO("Initial GPIO OK\n");
  1721. }
  1722. int LoadSysConfigAndInfo(struct SysConfigData *ptr)
  1723. {
  1724. int fd,wrd;
  1725. unsigned char *buf;
  1726. unsigned int ChkSum,ChkSumOrg;
  1727. if((buf=malloc(MtdBlockSize))==NULL)
  1728. {
  1729. DEBUG_ERROR("malloc buffer NG,rebooting..\n");
  1730. if(ShmStatusCodeData!=NULL)
  1731. {
  1732. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
  1733. }
  1734. sleep(5);
  1735. system("reboot -f");
  1736. sleep(5);
  1737. system("reboot -f");
  1738. }
  1739. memset(buf, 0, MtdBlockSize);
  1740. //================================================
  1741. // Load configuration from mtdblock10
  1742. //================================================
  1743. system("nanddump /dev/mtd10 -f /mnt/EvseConfig.bin");
  1744. fd = open("/mnt/EvseConfig.bin", O_RDWR);
  1745. if (fd < 0)
  1746. {
  1747. free(buf);
  1748. DEBUG_ERROR("open mtdblock10 NG,rebooting..\n");
  1749. if(ShmStatusCodeData!=NULL)
  1750. {
  1751. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
  1752. }
  1753. sleep(5);
  1754. system("reboot -f");
  1755. sleep(5);
  1756. system("reboot -f");
  1757. }
  1758. wrd=read(fd, buf, MtdBlockSize);
  1759. close(fd);
  1760. if(wrd<MtdBlockSize)
  1761. {
  1762. free(buf);
  1763. DEBUG_ERROR("read SysConfigData data NG,rebooting..\n");
  1764. if(ShmStatusCodeData!=NULL)
  1765. {
  1766. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
  1767. }
  1768. sleep(5);
  1769. system("reboot -f");
  1770. sleep(5);
  1771. system("reboot -f");
  1772. }
  1773. ChkSum=0;
  1774. for(wrd=ARRAY_SIZE(ptr->CsuBootLoadFwRev);wrd<MtdBlockSize-4;wrd++)
  1775. {
  1776. ChkSum+=buf[wrd];
  1777. }
  1778. memcpy(&ChkSumOrg,buf+(MtdBlockSize-4),sizeof(ChkSumOrg));
  1779. memcpy(&ptr->ModelName,buf+(ARRAY_SIZE(ptr->CsuBootLoadFwRev)),ARRAY_SIZE(ptr->ModelName));
  1780. memcpy(&ptr->SerialNumber,buf+(ARRAY_SIZE(ptr->CsuBootLoadFwRev)+ARRAY_SIZE(ptr->ModelName)+ARRAY_SIZE(ptr->AcModelName)),ARRAY_SIZE(ptr->SerialNumber));
  1781. //================================================
  1782. // Load configuration from mtdblock11
  1783. //================================================
  1784. if(ChkSum!=ChkSumOrg)
  1785. {
  1786. DEBUG_ERROR("Primary SysConfigData checksum NG, read backup\n");
  1787. system("nanddump /dev/mtd11 -f /mnt/EvseConfig.bin");
  1788. fd = open("/mnt/EvseConfig.bin", O_RDWR);
  1789. if (fd < 0)
  1790. {
  1791. free(buf);
  1792. DEBUG_ERROR("open mtdblock11 (backup) NG,rebooting..\n");
  1793. if(ShmStatusCodeData!=NULL)
  1794. {
  1795. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
  1796. }
  1797. sleep(5);
  1798. system("reboot -f");
  1799. sleep(5);
  1800. system("reboot -f");
  1801. }
  1802. memset(buf, 0, MtdBlockSize);
  1803. wrd=read(fd, buf,MtdBlockSize);
  1804. close(fd);
  1805. if(wrd<MtdBlockSize)
  1806. {
  1807. free(buf);
  1808. DEBUG_ERROR("read backup SysConfigData data NG,rebooting..\n");
  1809. if(ShmStatusCodeData!=NULL)
  1810. {
  1811. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
  1812. }
  1813. sleep(5);
  1814. system("reboot -f");
  1815. sleep(5);
  1816. system("reboot -f");
  1817. }
  1818. ChkSum=0;
  1819. for(wrd=ARRAY_SIZE(ptr->CsuBootLoadFwRev);wrd<MtdBlockSize-4;wrd++)
  1820. {
  1821. ChkSum+=buf[wrd];
  1822. }
  1823. memcpy(&ChkSumOrg,buf+(MtdBlockSize-4),sizeof(ChkSumOrg));
  1824. //================================================
  1825. // Load configuration from mtdblock12 (Factory default)
  1826. //================================================
  1827. if(ChkSum!=ChkSumOrg)
  1828. {
  1829. DEBUG_WARN("backup SysConfigData checksum NG, read Factory default\n");
  1830. system("nanddump /dev/mtd12 -f /mnt/EvseConfig.bin");
  1831. fd = open("/mnt/EvseConfig.bin", O_RDWR);
  1832. if (fd < 0)
  1833. {
  1834. DEBUG_ERROR("open mtdblock12 (Factory default) NG,rebooting..\n");
  1835. free(buf);
  1836. if(ShmStatusCodeData!=NULL)
  1837. {
  1838. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
  1839. }
  1840. sleep(5);
  1841. system("reboot -f");
  1842. sleep(5);
  1843. system("reboot -f");
  1844. }
  1845. memset(buf, 0, MtdBlockSize);
  1846. wrd=read(fd, buf,MtdBlockSize);
  1847. close(fd);
  1848. if(wrd<MtdBlockSize)
  1849. {
  1850. DEBUG_ERROR("read factory default SysConfigData data NG,rebooting..\n");
  1851. free(buf);
  1852. if(ShmStatusCodeData!=NULL)
  1853. {
  1854. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
  1855. }
  1856. sleep(5);
  1857. system("reboot -f");
  1858. sleep(5);
  1859. system("reboot -f");
  1860. }
  1861. ChkSum=0;
  1862. for(wrd=ARRAY_SIZE(ptr->CsuBootLoadFwRev);wrd<MtdBlockSize-4;wrd++)
  1863. {
  1864. ChkSum+=buf[wrd];
  1865. }
  1866. memcpy(&ChkSumOrg,buf+(MtdBlockSize-4),sizeof(ChkSumOrg));
  1867. memcpy(buf+(ARRAY_SIZE(ptr->CsuBootLoadFwRev)), &ptr->ModelName, ARRAY_SIZE(ptr->ModelName));
  1868. memcpy(buf+(ARRAY_SIZE(ptr->CsuBootLoadFwRev)+ARRAY_SIZE(ptr->ModelName)+ARRAY_SIZE(ptr->AcModelName)), &ptr->SerialNumber, ARRAY_SIZE(ptr->SerialNumber));
  1869. if(ChkSum!=ChkSumOrg)
  1870. {
  1871. DEBUG_WARN("factory default SysConfigData checksum NG, restore factory default\n");
  1872. free(buf);
  1873. system("cd /root;./Module_FactoryConfig -m");
  1874. system("rm -f /Storage/OCPP/OCPPConfiguration");
  1875. system("sync");
  1876. sleep(5);
  1877. system("reboot -f");
  1878. sleep(5);
  1879. system("reboot -f");
  1880. return FAIL;
  1881. }
  1882. }
  1883. }
  1884. //load OK
  1885. memcpy((struct SysConfigData *)ptr,buf,sizeof(struct SysConfigData));
  1886. free(buf);
  1887. system("rm -f /mnt/EvseConfig.bin");
  1888. // SysConfig in flash is empty (0xffffffff)
  1889. if((strlen((char*)ShmSysConfigAndInfo->SysConfig.ModelName) > ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.ModelName)) ||
  1890. (strlen((char*)ShmSysConfigAndInfo->SysConfig.SerialNumber) > ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SerialNumber)) ||
  1891. (strlen((char*)ShmSysConfigAndInfo->SysConfig.SystemId) > ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SystemId)) ||
  1892. (ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient == 0xff))
  1893. {
  1894. if(strlen((char*)ShmSysConfigAndInfo->SysConfig.ModelName) > ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.ModelName))
  1895. {
  1896. memset(ShmSysConfigAndInfo->SysConfig.ModelName, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.ModelName));
  1897. }
  1898. if(strlen((char*)ShmSysConfigAndInfo->SysConfig.SerialNumber) > ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SerialNumber))
  1899. {
  1900. memset(ShmSysConfigAndInfo->SysConfig.SerialNumber, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SerialNumber));
  1901. }
  1902. if(strlen((char*)ShmSysConfigAndInfo->SysConfig.SystemId) > ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SystemId))
  1903. {
  1904. memset(ShmSysConfigAndInfo->SysConfig.SystemId, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SystemId));
  1905. }
  1906. if(ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient == 0xff)
  1907. {
  1908. DEBUG_INFO("Ethernet dhcp config is null.\n");
  1909. }
  1910. if(strlen((char*)ShmSysConfigAndInfo->SysConfig.ModelName) == 0x00)
  1911. {
  1912. DEBUG_INFO("Model name over length.\n");
  1913. }
  1914. if(strlen((char*)ShmSysConfigAndInfo->SysConfig.SerialNumber) == 0x00)
  1915. {
  1916. DEBUG_INFO("Model serial number over length.\n");
  1917. }
  1918. if(strlen((char*)ShmSysConfigAndInfo->SysConfig.SystemId) == 0x00)
  1919. {
  1920. DEBUG_INFO("SystemId over length.\n");
  1921. }
  1922. system("cd /root;./Module_FactoryConfig -m");
  1923. sleep(3);
  1924. system("/usr/bin/run_evse_restart.sh");
  1925. }
  1926. DEBUG_INFO("Load SysConfigData OK\n");
  1927. ShmCharger->isCcsEnable = OFF;
  1928. for(uint8_t idx=0;idx<3;idx++)
  1929. {
  1930. if(ShmSysConfigAndInfo->SysConfig.ModelName[7+idx] == '7')
  1931. ShmCharger->isCcsEnable = ON;
  1932. }
  1933. ShmSysConfigAndInfo->SysConfig.AcPhaseCount = ((ShmSysConfigAndInfo->SysConfig.ModelName[2]=='Y') ||
  1934. (ShmSysConfigAndInfo->SysConfig.ModelName[2]=='D') ||
  1935. (ShmSysConfigAndInfo->SysConfig.ModelName[2]=='W')
  1936. ?3:1);
  1937. RatedCurrentParsing((char*)ShmSysConfigAndInfo->SysConfig.ModelName, &modelnameInfo);
  1938. DEBUG_INFO("Model name parsing gun count: %d\n", modelnameInfo.GetGunCount);
  1939. return PASS;
  1940. }
  1941. int StoreUsrConfigData(struct SysConfigData *UsrData)
  1942. {
  1943. int result = PASS;
  1944. int fd,wrd;
  1945. unsigned int i,Chk;
  1946. unsigned char *ptr, *BufTmp;
  1947. Chk=0;
  1948. ptr=(unsigned char *)UsrData;
  1949. if((BufTmp=malloc(MtdBlockSize))!=NULL)
  1950. {
  1951. memset(BufTmp,0,MtdBlockSize);
  1952. memcpy(BufTmp,ptr,sizeof(struct SysConfigData));
  1953. for(i=0;i<MtdBlockSize-4;i++)
  1954. Chk+=*(BufTmp+i);
  1955. memcpy(BufTmp+MtdBlockSize-4, &Chk, 4);
  1956. // Output configuration to file.
  1957. fd = open("/mnt/EvseConfig.bin", O_RDWR|O_CREAT);
  1958. if (fd < 0)
  1959. {
  1960. DEBUG_ERROR("open /mnt/EvseConfig.bin NG\n");
  1961. free(BufTmp);
  1962. return 0;
  1963. }
  1964. wrd=write(fd, BufTmp, MtdBlockSize);
  1965. close(fd);
  1966. if(wrd<MtdBlockSize)
  1967. {
  1968. DEBUG_ERROR("write /mnt/EvseConfig.bin NG\n");
  1969. free(BufTmp);
  1970. return 0;
  1971. }
  1972. DEBUG_INFO("EvseConfig write to file in /mnt OK.\n");
  1973. DEBUG_INFO("Erase /dev/mtd10.\n");
  1974. runShellCmd("flash_erase /dev/mtd10 0 0");
  1975. DEBUG_INFO("Write /dev/mtd10.\n");
  1976. runShellCmd("nandwrite -p /dev/mtd10 /mnt/EvseConfig.bin");
  1977. DEBUG_INFO("Erase /dev/mtd11.\n");
  1978. runShellCmd("flash_erase /dev/mtd11 0 0");
  1979. DEBUG_INFO("Write /dev/mtd11.\n");
  1980. runShellCmd("nandwrite -p /dev/mtd11 /mnt/EvseConfig.bin");
  1981. system("rm -f /mnt/EvseConfig.bin");
  1982. DEBUG_INFO("EvseConfig write to flash OK\n");
  1983. }
  1984. else
  1985. {
  1986. DEBUG_ERROR("alloc BlockSize NG\r\n");
  1987. result = FAIL;
  1988. }
  1989. if(BufTmp!=NULL)
  1990. free(BufTmp);
  1991. return result;
  1992. }
  1993. void InitEthernet()
  1994. {
  1995. pid_t pid;
  1996. uint8_t cnt_pingDNS_Fail;
  1997. char tmpbuf[256];
  1998. unsigned int natInterface = 0;
  1999. //Init Eth0 for internet
  2000. memset(tmpbuf,0,256);
  2001. sprintf(tmpbuf,"/sbin/ifconfig eth0 %s netmask %s up &",
  2002. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress,
  2003. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress);
  2004. DEBUG_INFO("eth0 config as ip: %s, netmask: %s\n", ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress,
  2005. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress);
  2006. system(tmpbuf);
  2007. memset(tmpbuf,0,256);
  2008. sprintf(tmpbuf,"route add default gw %s eth0 &",
  2009. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthGatewayAddress);
  2010. system(tmpbuf);
  2011. system("ifconfig lo up &");
  2012. system("/sbin/ifconfig eth0:1 192.168.201.201 netmask 255.255.255.248 up &");
  2013. //system("/sbin/ethtool -s eth0 speed 10 duplex full autoneg off");
  2014. //Run DHCP client if enabled
  2015. system("killall udhcpc");
  2016. system("rm -rf /etc/resolv.conf");
  2017. system("echo nameserver 8.8.8.8 >> /etc/resolv.conf"); //Google DNS server
  2018. system("echo nameserver 180.76.76.76 >> /etc/resolv.conf"); //Baidu DNS server
  2019. if(ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient==0)
  2020. {
  2021. sprintf(tmpbuf, "/sbin/udhcpc -i eth0 -x hostname:CSU3_%s -s /root/dhcp_script/eth0.script > /dev/null &", ShmSysConfigAndInfo->SysConfig.SystemId);
  2022. system(tmpbuf);
  2023. }
  2024. // Upgrade system id to /etc/hostname
  2025. sprintf(tmpbuf, "echo %s > /etc/hostname", ShmSysConfigAndInfo->SysConfig.SystemId);
  2026. system(tmpbuf);
  2027. // Ethernet MAC address
  2028. getEth0MacAddress();
  2029. //check internet status
  2030. pid = fork();
  2031. if(pid == 0)
  2032. {
  2033. for(;;)
  2034. {
  2035. if(ShmDispenser->gun_info.primaryMcuState.rotatory_switch != ROTARY_SWITCH_E_DISPENSER)
  2036. {
  2037. if(isRouteFail())
  2038. {
  2039. //DEBUG_ERROR("eth0 not in route, restart eth0.\n");
  2040. system("/sbin/ifconfig eth0 down;/sbin/ifconfig eth0 up");
  2041. if((ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient==0))
  2042. {
  2043. system("pgrep -f \"udhcpc -i eth0\" | xargs kill");
  2044. sprintf(tmpbuf, "/sbin/udhcpc -i eth0 -x hostname:CSU3_%s -s /root/dhcp_script/eth0.script > /dev/null &", ShmSysConfigAndInfo->SysConfig.SystemId);
  2045. system(tmpbuf);
  2046. }
  2047. else
  2048. {
  2049. system("pgrep -f \"udhcpc -i eth0\" | xargs kill");
  2050. memset(tmpbuf,0,256);
  2051. sprintf(tmpbuf,"/sbin/ifconfig eth0 %s netmask %s up &",
  2052. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress,
  2053. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress);
  2054. system(tmpbuf);
  2055. memset(tmpbuf,0,256);
  2056. sprintf(tmpbuf,"route add default gw %s eth0 &",
  2057. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthGatewayAddress);
  2058. system(tmpbuf);
  2059. }
  2060. }
  2061. if(isReachableInternet() == PASS)
  2062. {
  2063. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet=OFF;
  2064. cnt_pingDNS_Fail = 0;
  2065. }
  2066. else
  2067. {
  2068. if(cnt_pingDNS_Fail >= 3)
  2069. {
  2070. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet=ON;
  2071. if((ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient==0))
  2072. {
  2073. system("pgrep -f \"udhcpc -i eth0\" | xargs kill");
  2074. sprintf(tmpbuf, "/sbin/udhcpc -i eth0 -x hostname:CSU3_%s -s /root/dhcp_script/eth0.script > /dev/null &", ShmSysConfigAndInfo->SysConfig.SystemId);
  2075. system(tmpbuf);
  2076. }
  2077. else
  2078. {
  2079. system("pgrep -f \"udhcpc -i eth0\" | xargs kill");
  2080. memset(tmpbuf,0,256);
  2081. sprintf(tmpbuf,"/sbin/ifconfig eth0 %s netmask %s up &",
  2082. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress,
  2083. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress);
  2084. system(tmpbuf);
  2085. memset(tmpbuf,0,256);
  2086. sprintf(tmpbuf,"route add default gw %s eth0 &",
  2087. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthGatewayAddress);
  2088. system(tmpbuf);
  2089. }
  2090. cnt_pingDNS_Fail = 0;
  2091. }
  2092. else
  2093. {
  2094. cnt_pingDNS_Fail++;
  2095. }
  2096. }
  2097. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet &&
  2098. ((ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode == 0) || ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi) &&
  2099. ((ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomEnabled == 0) || ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi))
  2100. {
  2101. ShmSysConfigAndInfo->SysInfo.InternetConn = OFF;
  2102. }
  2103. else
  2104. {
  2105. ShmSysConfigAndInfo->SysInfo.InternetConn = ON;
  2106. }
  2107. //============================================================
  2108. // Priority for internet 0 : First / 1 : Second / 2: Third
  2109. //============================================================
  2110. if(!ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet)
  2111. {
  2112. system("/sbin/ifmetric eth0 0");
  2113. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  2114. {
  2115. system("/sbin/ifmetric mlan0 1");
  2116. }
  2117. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  2118. {
  2119. system("/sbin/ifmetric ppp0 2");
  2120. }
  2121. if(isKernelSupportNAT() == YES)
  2122. {
  2123. if(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode == 2)
  2124. {
  2125. if(natInterface != 1)
  2126. {
  2127. system("/sbin/iptables -t nat -F");
  2128. system("/sbin/iptables -A POSTROUTING -t nat -s 192.168.10.0/24 -o eth0 -j MASQUERADE");
  2129. natInterface = 1;
  2130. }
  2131. }
  2132. else
  2133. {
  2134. system("/sbin/iptables -t nat -F");
  2135. }
  2136. }
  2137. }
  2138. else if(!ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi)
  2139. {
  2140. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  2141. {
  2142. system("/sbin/ifmetric eth0 1");
  2143. system("/sbin/ifmetric mlan0 0");
  2144. }
  2145. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  2146. {
  2147. system("/sbin/ifmetric ppp0 2");
  2148. }
  2149. }
  2150. else if(!ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi)
  2151. {
  2152. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  2153. {
  2154. system("/sbin/ifmetric mlan0 2");
  2155. }
  2156. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  2157. {
  2158. system("/sbin/ifmetric eth0 1");
  2159. system("/sbin/ifmetric ppp0 0");
  2160. }
  2161. if(isKernelSupportNAT() == YES)
  2162. {
  2163. if(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode == 2)
  2164. {
  2165. if(natInterface != 2)
  2166. {
  2167. system("/sbin/iptables -t nat -F");
  2168. system("/sbin/iptables -A POSTROUTING -t nat -s 192.168.10.0/24 -o ppp0 -j MASQUERADE");
  2169. natInterface = 2;
  2170. }
  2171. }
  2172. else
  2173. {
  2174. system("/sbin/iptables -t nat -F");
  2175. }
  2176. }
  2177. }
  2178. else
  2179. {
  2180. if(isKernelSupportNAT() == YES)
  2181. {
  2182. if(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode == 2)
  2183. {
  2184. system("/sbin/iptables -t nat -F");
  2185. natInterface = 0;
  2186. }
  2187. }
  2188. }
  2189. }
  2190. else
  2191. {
  2192. if(ShmDispenser->gun_info.mcuFlag.isReadFwVerPass ||
  2193. ShmDispenser->gun_info.mcuFlag.isSetModelNamePass ||
  2194. ShmDispenser->gun_info.mcuFlag.isSetSerialNumberPass)
  2195. {
  2196. system("pgrep -f \"udhcpc -i eth0\" | xargs kill");
  2197. system("/sbin/ifconfig eth0:1 192.168.201.202 netmask 255.255.255.248 up &");
  2198. }
  2199. }
  2200. sleep(5);
  2201. }
  2202. }
  2203. DEBUG_INFO("Initial Ethernet OK\n");
  2204. }
  2205. int SpawnTask()
  2206. {
  2207. system ("pkill Module_");
  2208. system ("pkill OcppBackend");
  2209. /*
  2210. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  2211. {
  2212. system("/root/Module_4g &");
  2213. }
  2214. if(ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W' || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  2215. {
  2216. system("/root/Module_Wifi &");
  2217. }*/
  2218. system("/root/Module_EventLogging &");
  2219. ocpp_process_start();
  2220. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0)
  2221. DEBUG_INFO("OCPP URL is empty, need to create a configuration table !!!\n");
  2222. //system ("/root/Module_AlarmDetect &");
  2223. system ("/root/Module_InternalComm &");
  2224. //system ("/root/Module_Speaker &");
  2225. system ("/root/Module_ProduceUtils &");
  2226. //system ("/root/Module_LcmControl &");
  2227. system ("/root/Module_Cabinet &");
  2228. system ("/root/Module_Dispenser &");
  2229. return PASS;
  2230. }
  2231. int InitQca7000()
  2232. {
  2233. int result = PASS;
  2234. system("/sbin/rmmod qcaspi");
  2235. if(isKernelSupportNAT() == YES)
  2236. system("/sbin/insmod /lib/qcaspi_nat.ko");
  2237. else
  2238. system("/sbin/insmod /lib/qcaspi.ko");
  2239. sleep(2);
  2240. system("/sbin/ifconfig eth1 192.168.253.11 netmask 255.255.255.0 up");
  2241. sleep(1);
  2242. return result;
  2243. }
  2244. int Initialization(uint8_t gun_index)
  2245. {
  2246. int result = PASS;
  2247. InitGPIO();
  2248. InitEthernet();
  2249. if(InitQca7000() != PASS)
  2250. {
  2251. DEBUG_ERROR("QCA7000 initial fail.\n");
  2252. result = FAIL;
  2253. }
  2254. if(DB_Open(localDb) != PASS)
  2255. {
  2256. DEBUG_ERROR("Local database initial fail.\n");
  2257. result = FAIL;
  2258. }
  2259. if((rfidFd = InitRfidPort()) == FAIL)
  2260. {
  2261. DEBUG_ERROR("RFID port initial fail.\n");
  2262. result = FAIL;
  2263. }
  2264. if((wtdFd = InitWatchDog()) == FAIL)
  2265. {
  2266. DEBUG_ERROR("Watchdog initial fail.\n");
  2267. result = FAIL;
  2268. }
  2269. if(result == PASS)
  2270. DEBUG_INFO("Initialization OK.\n");
  2271. else
  2272. DEBUG_INFO("Initialization Fail.\n");
  2273. ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
  2274. return result;
  2275. }
  2276. //=====================================================
  2277. // Common routine
  2278. //=====================================================
  2279. char* getSystemModeName(unsigned char mode)
  2280. {
  2281. char* result;
  2282. switch(mode)
  2283. {
  2284. case SYS_MODE_BOOTING:
  2285. result = "booting";
  2286. break;
  2287. case SYS_MODE_IDLE:
  2288. result = "idle";
  2289. break;
  2290. case SYS_MODE_AUTHORIZING:
  2291. result = "authorizing";
  2292. break;
  2293. case SYS_MODE_PREPARING:
  2294. result = "preparing";
  2295. break;
  2296. case SYS_MODE_CHARGING:
  2297. result = "charging";
  2298. break;
  2299. case SYS_MODE_TERMINATING:
  2300. result = "terminating";
  2301. break;
  2302. case SYS_MODE_COMPLETE:
  2303. result = "complete";
  2304. break;
  2305. case SYS_MODE_ALARM:
  2306. result = "alarm";
  2307. break;
  2308. case SYS_MODE_FAULT:
  2309. result = "fault";
  2310. break;
  2311. case SYS_MODE_MAINTAIN:
  2312. result = "maintain";
  2313. break;
  2314. case SYS_MODE_RESERVATION:
  2315. result = "reservation";
  2316. break;
  2317. case SYS_MODE_BOOKING:
  2318. result = "booking";
  2319. break;
  2320. case SYS_MODE_DEBUG:
  2321. result = "debug";
  2322. break;
  2323. case SYS_MODE_UPDATE:
  2324. result = "upgrade";
  2325. break;
  2326. default:
  2327. result = "unknown";
  2328. break;
  2329. }
  2330. return result;
  2331. }
  2332. void setChargerMode(unsigned char gun_index, unsigned char mode)
  2333. {
  2334. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus = ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus;
  2335. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus = mode;
  2336. DEBUG_INFO("Gun-%02d mode switch from %s to %s\n", gun_index, getSystemModeName(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus), getSystemModeName(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus));
  2337. }
  2338. unsigned char isMode(unsigned char gun_index, unsigned char mode)
  2339. {
  2340. return ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == mode)?YES:NO);
  2341. }
  2342. unsigned char isModeChange(unsigned char gun_index)
  2343. {
  2344. unsigned char result = NO;
  2345. if(!isMode(gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus))
  2346. {
  2347. result = YES;
  2348. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus = ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus;
  2349. }
  2350. return result;
  2351. }
  2352. int isGpioInitialized(unsigned int gpio)
  2353. {
  2354. int result = FAIL;
  2355. char gpioPath[64];
  2356. sprintf(gpioPath, "/sys/class/gpio/gpio%d/value", gpio);
  2357. if((access(gpioPath, F_OK)) != -1)
  2358. {
  2359. result = PASS;
  2360. }
  2361. return result;
  2362. }
  2363. void gpio_set_value(unsigned int gpio, unsigned int value)
  2364. {
  2365. int fd;
  2366. char buf[256];
  2367. sprintf(buf, "/sys/class/gpio/gpio%d/value", gpio);
  2368. fd = open(buf, O_WRONLY);
  2369. if (fd < 0)
  2370. {
  2371. DEBUG_ERROR("GPIO-%d set %d fail.\n", gpio, value);
  2372. return;
  2373. }
  2374. if (value)
  2375. write(fd, "1", 2);
  2376. else
  2377. write(fd, "0", 2);
  2378. close(fd);
  2379. }
  2380. int gpio_get_value(unsigned int gpio)
  2381. {
  2382. int fd;
  2383. char buf[256];
  2384. char ch;
  2385. int8_t result = FAIL;
  2386. sprintf(buf, "/sys/class/gpio/gpio%d/value", gpio);
  2387. fd = open(buf, O_RDONLY);
  2388. if (fd < 0)
  2389. {
  2390. DEBUG_ERROR("GPIO-%d get fail\n", gpio);
  2391. return result;
  2392. }
  2393. read(fd, &ch, 1);
  2394. if (ch != '0')
  2395. result = 1;
  2396. else
  2397. result = 0;
  2398. close(fd);
  2399. return result;
  2400. }
  2401. int presentChargedEnergyClear(unsigned char gun_index)
  2402. {
  2403. int result = FAIL;
  2404. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy = 0;
  2405. memset(ShmCharger->gun_info[gun_index].presentChargedEnergyPeriod, 0x00, ARRAY_SIZE(ShmCharger->gun_info[gun_index].presentChargedEnergyPeriod)*sizeof(float));
  2406. result = PASS;
  2407. return result;
  2408. }
  2409. float presentChargedEnergyTotal(unsigned char gun_index)
  2410. {
  2411. float result = 0.0f;
  2412. for(int idx=0;idx<ARRAY_SIZE(ShmCharger->gun_info[gun_index].presentChargedEnergyPeriod);idx++)
  2413. {
  2414. result += ShmCharger->gun_info[gun_index].presentChargedEnergyPeriod[idx];
  2415. }
  2416. return result;
  2417. }
  2418. int presentChargedEnergyUpdate(unsigned char gun_index)
  2419. {
  2420. int result = FAIL;
  2421. time_t CurrentTime;
  2422. struct tm *tm;
  2423. CurrentTime = time(NULL);
  2424. tm=localtime(&CurrentTime);
  2425. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==1)
  2426. {
  2427. // Resolution: 0.0001 kwh
  2428. ShmCharger->gun_info[gun_index].presentChargedEnergyPeriod[tm->tm_hour] += (((float)(ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption - ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption_at_start))/10000.0) - presentChargedEnergyTotal(gun_index);
  2429. }
  2430. else
  2431. {
  2432. // Resolution: 0.0001 kwh
  2433. ShmCharger->gun_info[gun_index].presentChargedEnergyPeriod[tm->tm_hour] += ((((float)(ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption - ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption_at_start))/10000.0) +
  2434. (((float)(ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption - ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption_at_start))/10000.0) +
  2435. (((float)(ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption - ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption_at_start))/10000.0))
  2436. - presentChargedEnergyTotal(gun_index);
  2437. }
  2438. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy = presentChargedEnergyTotal(gun_index);
  2439. return result;
  2440. }
  2441. //===============================================
  2442. // Get firmware version
  2443. //===============================================
  2444. void get_firmware_version(unsigned char gun_index)
  2445. {
  2446. FILE *fp;
  2447. char cmd[512];
  2448. char buf[512];
  2449. if(gun_index == 0)
  2450. {
  2451. // Get CSU hardware version
  2452. sprintf((char*)ShmSysConfigAndInfo->SysInfo.CsuHwRev, "REV.XXXXXXX");
  2453. // Get CSU boot loader version
  2454. memcpy(ShmSysConfigAndInfo->SysInfo.CsuBootLoadFwRev, ShmSysConfigAndInfo->SysConfig.CsuBootLoadFwRev, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.CsuBootLoadFwRev));
  2455. // Get CSU kernel version
  2456. sprintf(cmd, "/bin/uname -r");
  2457. fp = popen(cmd, "r");
  2458. if(fp == NULL)
  2459. sprintf((char*)ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev, "Unknown version");
  2460. else
  2461. {
  2462. while(fgets(buf, sizeof(buf), fp) != NULL)
  2463. {
  2464. memcpy(ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev, buf, strlen(buf)-1);
  2465. }
  2466. }
  2467. // Get MCU firmware version
  2468. strcpy((char*)ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev, ShmCharger->gun_info[gun_index].ver.Version_FW);
  2469. // Get CSU root file system version
  2470. sprintf((char*)ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev, "D0.01.00.0000.00");
  2471. // Get AC connector type from model name
  2472. for(uint8_t idx=0;idx<3;idx++)
  2473. {
  2474. switch(ShmSysConfigAndInfo->SysConfig.ModelName[7+idx])
  2475. {
  2476. case '1':
  2477. // J1772 Plug
  2478. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '4';
  2479. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '4';
  2480. break;
  2481. case '2':
  2482. // J1772 Socket
  2483. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '1';
  2484. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '1';
  2485. break;
  2486. case '3':
  2487. // CE Plug
  2488. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '5';
  2489. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '5';
  2490. break;
  2491. case '4':
  2492. // CE Socket
  2493. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '2';
  2494. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '2';
  2495. break;
  2496. case '5':
  2497. // GB Plug
  2498. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '6';
  2499. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '6';
  2500. break;
  2501. case '6':
  2502. // GB Socket
  2503. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '3';
  2504. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '3';
  2505. break;
  2506. }
  2507. }
  2508. // Get network option from model name
  2509. switch(ShmSysConfigAndInfo->SysConfig.ModelName[10])
  2510. {
  2511. case 'B':
  2512. case 'U':
  2513. //Blue tooth
  2514. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '3';
  2515. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[9] = '3';
  2516. break;
  2517. case 'W':
  2518. // WIFI
  2519. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '1';
  2520. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[9] = '1';
  2521. break;
  2522. case 'T':
  2523. // 3G/4G
  2524. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '2';
  2525. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[9] = '2';
  2526. break;
  2527. case 'D':
  2528. // WIFI + 4G
  2529. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '5';
  2530. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[9] = '5';
  2531. break;
  2532. default:
  2533. // LAN
  2534. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '0';
  2535. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[9] = '0';
  2536. break;
  2537. }
  2538. // Get rating power from model name
  2539. memcpy(&ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[10], &ShmSysConfigAndInfo->SysConfig.ModelName[4], 0x03);
  2540. memcpy(&ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[10], &ShmSysConfigAndInfo->SysConfig.ModelName[4], 0x03);
  2541. // Get vender code from model name
  2542. memcpy(&ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[14], &ShmSysConfigAndInfo->SysConfig.ModelName[12], 0x02);
  2543. memcpy(&ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[14], &ShmSysConfigAndInfo->SysConfig.ModelName[12], 0x02);
  2544. DEBUG_INFO("========================================\n");
  2545. DEBUG_INFO("------------- Cabinet info -------------\n");
  2546. DEBUG_INFO("Model: %s\n", ShmSysConfigAndInfo->SysConfig.ModelName);
  2547. DEBUG_INFO("CSU hardware version: %s\n", ShmSysConfigAndInfo->SysInfo.CsuHwRev);
  2548. DEBUG_INFO("CSU boot loader version: %s\n", ShmSysConfigAndInfo->SysInfo.CsuBootLoadFwRev);
  2549. DEBUG_INFO("CSU kernel version: %s\n", ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev);
  2550. DEBUG_INFO("CSU root file system version: %s\n", ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev);
  2551. DEBUG_INFO("========================================\n");
  2552. }
  2553. //===========================================
  2554. // Put info to dispenser share memory
  2555. //===========================================
  2556. // Get CSU boot loader version
  2557. memcpy(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuBootLoadFwRev, ShmSysConfigAndInfo->SysConfig.CsuBootLoadFwRev, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.CsuBootLoadFwRev));
  2558. // Get CSU kernel version
  2559. sprintf(cmd, "/bin/uname -r");
  2560. fp = popen(cmd, "r");
  2561. if(fp == NULL)
  2562. sprintf((char*)ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuKernelFwRev, "Unknown version");
  2563. else
  2564. {
  2565. while(fgets(buf, sizeof(buf), fp) != NULL)
  2566. {
  2567. memcpy(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuKernelFwRev, buf, strlen(buf)-1);
  2568. }
  2569. }
  2570. // Get MCU firmware version
  2571. strcpy((char*)ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev, ShmCharger->gun_info[gun_index].ver.Version_FW);
  2572. // Get CSU root file system version
  2573. sprintf((char*)ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev, "D0.01.00.0000.00");
  2574. // Get AC connector type from model name
  2575. for(uint8_t idx=0;idx<3;idx++)
  2576. {
  2577. switch(ShmDispenser->ConfigData.ModelName[7+idx])
  2578. {
  2579. case '1':
  2580. // J1772 Plug
  2581. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[6] = '4';
  2582. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[6] = '4';
  2583. break;
  2584. case '2':
  2585. // J1772 Socket
  2586. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[6] = '1';
  2587. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[6] = '1';
  2588. break;
  2589. case '3':
  2590. // CE Plug
  2591. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[6] = '5';
  2592. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[6] = '5';
  2593. break;
  2594. case '4':
  2595. // CE Socket
  2596. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[6] = '2';
  2597. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[6] = '2';
  2598. break;
  2599. case '5':
  2600. // GB Plug
  2601. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[6] = '6';
  2602. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[6] = '6';
  2603. break;
  2604. case '6':
  2605. // GB Socket
  2606. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[6] = '3';
  2607. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[6] = '3';
  2608. break;
  2609. }
  2610. }
  2611. // Get network option from model name
  2612. switch(ShmDispenser->ConfigData.ModelName[10])
  2613. {
  2614. case 'B':
  2615. case 'U':
  2616. //Blue tooth
  2617. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[9] = '3';
  2618. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[9] = '3';
  2619. break;
  2620. case 'W':
  2621. // WIFI
  2622. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[9] = '1';
  2623. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[9] = '1';
  2624. break;
  2625. case 'T':
  2626. // 3G/4G
  2627. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[9] = '2';
  2628. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[9] = '2';
  2629. break;
  2630. case 'D':
  2631. // WIFI + 4G
  2632. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[9] = '5';
  2633. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[9] = '5';
  2634. break;
  2635. default:
  2636. // LAN
  2637. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[9] = '0';
  2638. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[9] = '0';
  2639. break;
  2640. }
  2641. // Get rating power from model name
  2642. memcpy(&ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[10], &ShmDispenser->ConfigData.ModelName[4], 0x03);
  2643. memcpy(&ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[10], &ShmDispenser->ConfigData.ModelName[4], 0x03);
  2644. // Get vender code from model name
  2645. memcpy(&ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[14], &ShmDispenser->ConfigData.ModelName[12], 0x02);
  2646. memcpy(&ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[14], &ShmDispenser->ConfigData.ModelName[12], 0x02);
  2647. DEBUG_INFO("========================================\n");
  2648. DEBUG_INFO("----------- Dispenser-%01d info -----------\n", (gun_index+1));
  2649. DEBUG_INFO("CSU boot loader version: %s\n", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuBootLoadFwRev);
  2650. DEBUG_INFO("CSU kernel version: %s\n", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuKernelFwRev);
  2651. DEBUG_INFO("CSU root file system version: %s\n", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev);
  2652. DEBUG_INFO("CSU MCU firmware version: %s\n", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev);
  2653. DEBUG_INFO("========================================\n");
  2654. }
  2655. //===============================================
  2656. // Upgrade firmware
  2657. //===============================================
  2658. int upgrade_check()
  2659. {
  2660. int result = PASS;
  2661. int fd;
  2662. DIR *dir;
  2663. struct dirent *file;
  2664. char cmd[512];
  2665. long int MaxLen=48*1024*1024, ImageLen=0, wrd;
  2666. if ((dir = opendir ("/mnt")) != NULL)
  2667. {
  2668. refreshStartTimer(&startTime[0][TMR_IDX_UPGRADE]);
  2669. /* print all the files and directories within directory */
  2670. while ((file = readdir (dir)) != NULL)
  2671. {
  2672. if((strlen(file->d_name)>2))
  2673. {
  2674. // Wait for MCU upgrade finish.
  2675. while(ShmCharger->gun_info[0].mcuFlag.isMcuUpgradeReq || (modelnameInfo.GetGunCount>1?ShmCharger->gun_info[1].mcuFlag.isMcuUpgradeReq:FALSE))sleep(1);
  2676. // Wait for LCM upgrade finish.
  2677. while(ShmCharger->isUpgradeLcmReq)sleep(1);
  2678. memset(&ShmCharger->fwUpgradeInfo, 0xFF, sizeof(Fw_Upgrade_Info));
  2679. DEBUG_INFO("New firmware file: %s\n", file->d_name);
  2680. sprintf(ShmCharger->fwUpgradeInfo.location, "/mnt/%s", file->d_name);
  2681. if((fd=open(ShmCharger->fwUpgradeInfo.location, O_RDONLY)) >= 0)
  2682. {
  2683. unsigned char *ptr = malloc(MaxLen); //-48 is take out the header
  2684. memset(ptr, 0xFF, MaxLen); //-48 is take out the header
  2685. ImageLen = read(fd, ptr, MaxLen);
  2686. close(fd);
  2687. ShmCharger->fwUpgradeInfo.fwType = ((ptr[0x13]<<0) | (ptr[0x12]<<8) | (ptr[0x11]<<16) | (ptr[0x10]<<24));
  2688. substr(ShmCharger->fwUpgradeInfo.modelName, (char *)ptr, 0, 0x10);
  2689. DEBUG_INFO("New firmware type: %X\n", ShmCharger->fwUpgradeInfo.fwType);
  2690. DEBUG_INFO("New firmware model name: %s, %s\n", ShmCharger->fwUpgradeInfo.modelName, ShmSysConfigAndInfo->SysConfig.ModelName);
  2691. if((ShmCharger->fwUpgradeInfo.modelName[0] == ShmSysConfigAndInfo->SysConfig.ModelName[0]) &&
  2692. (ShmCharger->fwUpgradeInfo.modelName[1] == ShmSysConfigAndInfo->SysConfig.ModelName[1]) &&
  2693. (ShmCharger->fwUpgradeInfo.modelName[7] == ShmSysConfigAndInfo->SysConfig.ModelName[7]) &&
  2694. (ShmCharger->fwUpgradeInfo.modelName[8] == ShmSysConfigAndInfo->SysConfig.ModelName[8]) &&
  2695. (ShmCharger->fwUpgradeInfo.modelName[9] == ShmSysConfigAndInfo->SysConfig.ModelName[9]) &&
  2696. (ShmCharger->fwUpgradeInfo.modelName[11] == ShmSysConfigAndInfo->SysConfig.ModelName[11]) &&
  2697. (ShmCharger->fwUpgradeInfo.modelName[12] == ShmSysConfigAndInfo->SysConfig.ModelName[12]) &&
  2698. (ShmCharger->fwUpgradeInfo.modelName[13] == ShmSysConfigAndInfo->SysConfig.ModelName[13]) &&
  2699. (ShmCharger->fwUpgradeInfo.fwType>0))
  2700. {
  2701. switch(ShmCharger->fwUpgradeInfo.fwType)
  2702. {
  2703. case CSU_MLO:
  2704. case CSU_BOOTLOADER:
  2705. case CSU_KERNEL_CONFIGURATION:
  2706. case CSU_KERNEL_IMAGE:
  2707. case CSU_ROOT_FILE_SYSTEM:
  2708. case CSU_USER_CONFIGURATION:
  2709. case CSU_PRIMARY_CONTROLLER:
  2710. case AC_WALLMOUNT_CONTROLLER:
  2711. // Put image file
  2712. for(uint8_t gun_index=0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  2713. {
  2714. char cmd[768];
  2715. if(gun_index>0)
  2716. {
  2717. sprintf(cmd, "ftpput -u root -p y42j/4cj84 192.168.201.%d /mnt/%s %s", (201+gun_index), file->d_name, file->d_name);
  2718. if(system(cmd) != 0)
  2719. {
  2720. DEBUG_ERROR("FTP put %s to dispenser-%d fail\n", file->d_name, gun_index);
  2721. result = FAIL;
  2722. }
  2723. else
  2724. {
  2725. DEBUG_INFO("FTP put %s to dispenser-%d finish\n", file->d_name, gun_index);
  2726. }
  2727. }
  2728. }
  2729. break;
  2730. case LCM:
  2731. fd = open("/mnt/lcm.zip", O_RDWR | O_CREAT | O_EXCL);
  2732. if (fd < 0)
  2733. {
  2734. DEBUG_ERROR("Can not create lcm.zip file.\n");
  2735. result = FAIL;
  2736. }
  2737. else
  2738. {
  2739. // Write image to flash
  2740. DEBUG_INFO("Writing data to lcm.zip file...\n");
  2741. wrd=write(fd, ptr+48, ImageLen-48);
  2742. close(fd);
  2743. DEBUG_INFO(">> lcm.zip Written length: 0x%x\n", wrd);
  2744. if(wrd != (ImageLen-48))
  2745. {
  2746. result = FAIL;
  2747. }
  2748. else
  2749. {
  2750. runShellCmd("mkdir -p /mnt/lcd");
  2751. runShellCmd("unzip /mnt/lcm.zip -d /mnt/lcd");
  2752. sprintf(cmd, "yes|rm %s", ShmCharger->fwUpgradeInfo.location);
  2753. system(cmd);
  2754. system("rm -f /mnt/lcm.zip");
  2755. result = PASS;
  2756. }
  2757. }
  2758. ShmCharger->isUpgradeLcmReq = ON;
  2759. sleep(10);
  2760. break;
  2761. default:
  2762. result = FAIL;
  2763. DEBUG_WARN("Image file is unknown type.\n");
  2764. sprintf(cmd, "yes|rm %s", ShmCharger->fwUpgradeInfo.location);
  2765. system(cmd);
  2766. break;
  2767. }
  2768. }
  2769. else
  2770. {
  2771. result = FAIL;
  2772. DEBUG_ERROR("Model name and Firmware type error.\n");
  2773. sprintf(cmd, "yes|rm %s", ShmCharger->fwUpgradeInfo.location);
  2774. system(cmd);
  2775. }
  2776. free(ptr);
  2777. }
  2778. else
  2779. {
  2780. result = FAIL;
  2781. DEBUG_ERROR("New firmware open error.\n");
  2782. }
  2783. }
  2784. else
  2785. {
  2786. if(strlen(file->d_name) >= 3)
  2787. {
  2788. result = FAIL;
  2789. DEBUG_ERROR("File name error.\n");
  2790. }
  2791. else
  2792. {
  2793. DEBUG_ERROR("Searching file.\n");
  2794. }
  2795. }
  2796. }
  2797. closedir (dir);
  2798. // Wait dispenser upgrade result
  2799. if(result != FAIL)
  2800. {
  2801. uint8_t isCompleted = ON;
  2802. for(uint8_t gun_index=0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  2803. ShmCharger->gun_info[gun_index].isUpgradeReq = ON;
  2804. do
  2805. {
  2806. isCompleted = ON;
  2807. for(uint8_t gun_index=0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  2808. {
  2809. isCompleted &= ShmCharger->gun_info[gun_index].isUpgradeEnd;
  2810. }
  2811. sleep(1);
  2812. }while((getDiffSecNow(startTime[0][TMR_IDX_UPGRADE]) < TIMEOUT_SPEC_UPGRADE) && !isCompleted);
  2813. for(uint8_t gun_index=0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  2814. {
  2815. result &= ShmCharger->gun_info[gun_index].isUpgradePASS;
  2816. }
  2817. result &= (getDiffSecNow(startTime[0][TMR_IDX_UPGRADE]) <= TIMEOUT_SPEC_UPGRADE);
  2818. if(getDiffSecNow(startTime[0][TMR_IDX_UPGRADE]) > TIMEOUT_SPEC_UPGRADE)DEBUG_INFO("Upgrade process timeout.\n");
  2819. }
  2820. }
  2821. else
  2822. {
  2823. result = FAIL;
  2824. DEBUG_ERROR("/mnt does not valid.\n");
  2825. }
  2826. return result;
  2827. }
  2828. //===============================================
  2829. // Check RFID is match with start user
  2830. //===============================================
  2831. int isMatchStartUser(unsigned char gun_index)
  2832. {
  2833. uint8_t tmpUser[32];
  2834. if(ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian)
  2835. {
  2836. // Big endian
  2837. switch(rfid.snType)
  2838. {
  2839. case RFID_SN_TYPE_6BYTE:
  2840. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5]);
  2841. break;
  2842. case RFID_SN_TYPE_7BYTE:
  2843. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6]);
  2844. break;
  2845. case RFID_SN_TYPE_10BYTE:
  2846. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6], rfid.currentCard[7], rfid.currentCard[8], rfid.currentCard[9]);
  2847. break;
  2848. case RFID_SN_TYPE_4BYTE:
  2849. default:
  2850. sprintf((char*)tmpUser, "%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3]);
  2851. break;
  2852. }
  2853. }
  2854. else
  2855. {
  2856. // Little endian
  2857. switch(rfid.snType)
  2858. {
  2859. case RFID_SN_TYPE_6BYTE:
  2860. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  2861. break;
  2862. case RFID_SN_TYPE_7BYTE:
  2863. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  2864. break;
  2865. case RFID_SN_TYPE_10BYTE:
  2866. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[9], rfid.currentCard[8], rfid.currentCard[7], rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  2867. break;
  2868. case RFID_SN_TYPE_4BYTE:
  2869. default:
  2870. sprintf((char*)tmpUser, "%02X%02X%02X%02X", rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  2871. break;
  2872. }
  2873. }
  2874. DEBUG_INFO("==== isMatchStartUser ==== \n");
  2875. DEBUG_INFO("tmpUser : %s \n", tmpUser);
  2876. DEBUG_INFO("StartUserId : %s \n", ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId);
  2877. DEBUG_INFO("========================== \n");
  2878. return ((strcmp((char*)tmpUser, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId)==0)?YES:NO);
  2879. }
  2880. int isMatchPresentUser()
  2881. {
  2882. uint8_t tmpUser[32];
  2883. if(ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian)
  2884. {
  2885. // Big endian
  2886. switch(rfid.snType)
  2887. {
  2888. case RFID_SN_TYPE_6BYTE:
  2889. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5]);
  2890. break;
  2891. case RFID_SN_TYPE_7BYTE:
  2892. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6]);
  2893. break;
  2894. case RFID_SN_TYPE_10BYTE:
  2895. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6], rfid.currentCard[7], rfid.currentCard[8], rfid.currentCard[9]);
  2896. break;
  2897. case RFID_SN_TYPE_4BYTE:
  2898. default:
  2899. sprintf((char*)tmpUser, "%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3]);
  2900. break;
  2901. }
  2902. }
  2903. else
  2904. {
  2905. // Little endian
  2906. switch(rfid.snType)
  2907. {
  2908. case RFID_SN_TYPE_6BYTE:
  2909. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  2910. break;
  2911. case RFID_SN_TYPE_7BYTE:
  2912. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  2913. break;
  2914. case RFID_SN_TYPE_10BYTE:
  2915. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[9], rfid.currentCard[8], rfid.currentCard[7], rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  2916. break;
  2917. case RFID_SN_TYPE_4BYTE:
  2918. default:
  2919. sprintf((char*)tmpUser, "%02X%02X%02X%02X", rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  2920. break;
  2921. }
  2922. }
  2923. DEBUG_INFO("==== isMatchPresentUser ==== \n");
  2924. DEBUG_INFO("tmpUser : %s \n", tmpUser);
  2925. DEBUG_INFO("UserId : %s \n", ShmSysConfigAndInfo->SysConfig.UserId);
  2926. DEBUG_INFO("============================ \n");
  2927. return ((strcmp((char*)tmpUser, (char*)ShmSysConfigAndInfo->SysConfig.UserId)==0)?YES:NO);
  2928. }
  2929. //===============================================
  2930. // Read RFID Serial Number
  2931. //===============================================
  2932. int GetCardSerialNumber()
  2933. {
  2934. int isSuccess = FAIL;
  2935. int module_type = MODULE_EWT;
  2936. if(getRequestCardSN(rfidFd,module_type,&rfid))
  2937. {
  2938. if(rfid.cardType == ISO14443A)
  2939. {
  2940. if(rfid.snType == RFID_SN_TYPE_4BYTE)
  2941. {
  2942. isSuccess = PASS;
  2943. }
  2944. else if (rfid.snType == RFID_SN_TYPE_7BYTE)
  2945. {
  2946. isSuccess = PASS;
  2947. }
  2948. sethaltCard(rfidFd,module_type);
  2949. }
  2950. else if(rfid.cardType == IS014443B)
  2951. {
  2952. isSuccess = PASS;
  2953. }
  2954. else if(rfid.cardType == FELICA)
  2955. {
  2956. isSuccess = PASS;
  2957. }
  2958. else
  2959. {}
  2960. }
  2961. else
  2962. {}
  2963. return isSuccess;
  2964. }
  2965. //===============================================
  2966. // Set led motion
  2967. //===============================================
  2968. void setLedMotion(unsigned char gun_index,unsigned char led_mode)
  2969. {
  2970. switch(led_mode)
  2971. {
  2972. case LED_ACTION_INIT:
  2973. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_INIT;
  2974. break;
  2975. case LED_ACTION_IDLE:
  2976. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_IDLE;
  2977. break;
  2978. case LED_ACTION_AUTHED:
  2979. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_AUTHED;
  2980. break;
  2981. case LED_ACTION_CONNECTED:
  2982. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_CONNECTED;
  2983. break;
  2984. case LED_ACTION_CHARGING:
  2985. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_CHARGING;
  2986. break;
  2987. case LED_ACTION_STOP:
  2988. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_STOP;
  2989. break;
  2990. case LED_ACTION_ALARM:
  2991. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_ALARM;
  2992. break;
  2993. case LED_ACTION_MAINTAIN:
  2994. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_MAINTAIN;
  2995. break;
  2996. case LED_ACTION_RFID_PASS:
  2997. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_RFID_PASS;
  2998. break;
  2999. case LED_ACTION_RFID_FAIL:
  3000. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_RFID_FAIL;
  3001. break;
  3002. case LED_ACTION_BLE_CONNECT:
  3003. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_BLE_CONNECT;
  3004. break;
  3005. case LED_ACTION_BLE_DISABLE:
  3006. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_BLE_DISABLE;
  3007. break;
  3008. case LED_ACTION_DEBUG:
  3009. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_DEBUG;
  3010. break;
  3011. case LED_ACTION_ALL_OFF:
  3012. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_ALL_OFF;
  3013. break;
  3014. case LED_RELAY_ON:
  3015. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_RELAY_ON;
  3016. break;
  3017. case LED_RELAY_OFF:
  3018. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_RELAY_OFF;
  3019. break;
  3020. case LED_ACTION_HANDSHAKE_FAIL:
  3021. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_HANDSHAKE_FAIL;
  3022. break;
  3023. case LED_ACTION_INTERNET_DISCONNECT:
  3024. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_INTERNET_DISCONNECT;
  3025. break;
  3026. case LED_ACTION_RESTORE_SETTING:
  3027. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_RESTORE_SETTING;
  3028. break;
  3029. case LED_ACTION_IDLE_BACKEND_CONNECTED:
  3030. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_IDLE_BACKEND_CONNECTED;
  3031. break;
  3032. case LED_ACTION_IDLE_BACKEND_CONNECTED_SLEEP:
  3033. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_IDLE_BACKEND_CONNECTED_SLEEP;
  3034. break;
  3035. case LED_ACTION_IDLE_BACKEND_DISCONNECTED:
  3036. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_IDLE_BACKEND_DISCONNECTED;
  3037. break;
  3038. case LED_ACTION_IDLE_BACKEND_DISCONNECTED_SLEEP:
  3039. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_IDLE_BACKEND_DISCONNECTED_SLEEP;
  3040. break;
  3041. case LED_ACTION_RESERVATION_MODE:
  3042. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_RESERVATION_MODE;
  3043. break;
  3044. }
  3045. }
  3046. //===============================================
  3047. // Request on/off set
  3048. //===============================================
  3049. void setRequest(unsigned char gun_index,unsigned char isOn)
  3050. {
  3051. if(isOn == ON)
  3052. {
  3053. if(ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest == OFF)
  3054. {
  3055. ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest = ON;
  3056. DEBUG_INFO("Gun-%d permission request: ON \n",gun_index);
  3057. }
  3058. }
  3059. else
  3060. {
  3061. if(ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest == ON)
  3062. {
  3063. ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest = OFF;
  3064. DEBUG_INFO("Gun-%d permission request: OFF \n",gun_index);
  3065. }
  3066. }
  3067. }
  3068. //===============================================
  3069. // Request on/off get
  3070. //===============================================
  3071. int getRequest(unsigned char gun_index)
  3072. {
  3073. return ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest;
  3074. }
  3075. //===============================================
  3076. // Relay on/off set
  3077. //===============================================
  3078. void setRelay(unsigned char gun_index,unsigned char isOn)
  3079. {
  3080. if(isOn == ON)
  3081. {
  3082. if(ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn == OFF)
  3083. {
  3084. switch(ShmCharger->gun_info[gun_index].chargingMode)
  3085. {
  3086. case CHARGING_MODE_BS:
  3087. case CHARGING_MODE_HLC:
  3088. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = ON;
  3089. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][0] = 0x01;
  3090. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][1] = 0x01;
  3091. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][2] = 0x01;
  3092. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  3093. DEBUG_INFO("Gun-%d Output relay status: ON. [CHARGING_MODE_BS] \n",gun_index);
  3094. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  3095. DEBUG_INFO("Gun-%d Output relay status: ON. [CHARGING_MODE_HLC] \n",gun_index);
  3096. break;
  3097. case CHARGING_MODE_SOCKETE:
  3098. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = ON;
  3099. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][3] = 0x01;
  3100. DEBUG_INFO("Gun-%d Output relay status: ON. [CHARGING_MODE_SOCKETE] \n",gun_index);
  3101. break;
  3102. default:
  3103. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = ON;
  3104. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][0] = 0x01;
  3105. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][1] = 0x01;
  3106. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][2] = 0x01;
  3107. DEBUG_INFO("Gun-%d Output relay status: ON. [DEFFAULT] \n",gun_index);
  3108. break;
  3109. }
  3110. }
  3111. }
  3112. else
  3113. {
  3114. if(ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn == ON)
  3115. {
  3116. switch(ShmCharger->gun_info[gun_index].chargingMode)
  3117. {
  3118. case CHARGING_MODE_BS:
  3119. case CHARGING_MODE_HLC:
  3120. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = OFF;
  3121. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][0] = 0;
  3122. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][1] = 0;
  3123. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][2] = 0;
  3124. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  3125. DEBUG_INFO("Gun-%d Output relay status: OFF. [CHARGING_MODE_BS] \n",gun_index);
  3126. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  3127. DEBUG_INFO("Gun-%d Output relay status: OFF. [CHARGING_MODE_HLC] \n",gun_index);
  3128. break;
  3129. case CHARGING_MODE_SOCKETE:
  3130. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = OFF;
  3131. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][3] = 0;
  3132. DEBUG_INFO("Gun-%d Output relay status: OFF. [CHARGING_MODE_SOCKETE] \n",gun_index);
  3133. break;
  3134. default:
  3135. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = OFF;
  3136. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][0] = 0;
  3137. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][1] = 0;
  3138. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][2] = 0;
  3139. DEBUG_INFO("Gun-%d Output relay status: OFF. [DEFFAULT] \n",gun_index);
  3140. break;
  3141. }
  3142. }
  3143. }
  3144. }
  3145. //===============================================
  3146. // Relay on/off get
  3147. //===============================================
  3148. int getRelay(unsigned char gun_index)
  3149. {
  3150. return ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn;
  3151. }
  3152. //===============================================
  3153. // Set speaker on/off request
  3154. //===============================================
  3155. void setSpeaker(unsigned char isOn, unsigned char speaker_mode)
  3156. {
  3157. if(isOn == ON)
  3158. {
  3159. ShmCharger->isSpeakerOn = ON;
  3160. ShmCharger->speaker_type = speaker_mode;
  3161. }
  3162. }
  3163. //===============================================
  3164. // Initialization RFID communication port
  3165. //===============================================
  3166. int InitRfidPort()
  3167. {
  3168. int uartO2 = open(rfidPortName, O_RDWR);
  3169. struct termios tios;
  3170. if (uartO2 != FAIL)
  3171. {
  3172. ioctl (uartO2, TCGETS, &tios);
  3173. tios.c_cflag = B19200 | CS8 | CLOCAL | CREAD;
  3174. tios.c_lflag = 0;
  3175. tios.c_iflag = 0;
  3176. tios.c_oflag = 0;
  3177. tios.c_cc[VMIN] = 0;
  3178. tios.c_cc[VTIME] = (unsigned char) 1;
  3179. tios.c_lflag = 0;
  3180. tcflush(uartO2, TCIFLUSH);
  3181. ioctl(uartO2, TCSETS, &tios);
  3182. }
  3183. if (uartO2 < 0)
  3184. {
  3185. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RfidModuleCommFail = 1;
  3186. }
  3187. return uartO2;
  3188. }
  3189. //===============================================
  3190. // Check internet access status
  3191. //===============================================
  3192. int isReachableInternet()
  3193. {
  3194. int result = FAIL;
  3195. FILE *fp;
  3196. char cmd[256];
  3197. char buf[512];
  3198. char tmp[512];
  3199. // Get ip address & net mask
  3200. strcpy(cmd, "ifconfig eth0");
  3201. fp = popen(cmd, "r");
  3202. if (fp != NULL)
  3203. {
  3204. while(fgets(buf, sizeof(buf), fp) != NULL)
  3205. {
  3206. if (strstr(buf, "inet addr:") > 0)
  3207. {
  3208. sscanf(buf, "%*s%s", tmp);
  3209. substr(tmp, tmp, strspn(tmp, "addr:"), strlen(buf)-strspn(tmp, "addr:"));
  3210. if (strcmp(tmp, (char *)ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress) != 0)
  3211. {
  3212. strcpy((char *) ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress, tmp);
  3213. }
  3214. sscanf(buf, "%*s%*s%*s%s", tmp);
  3215. substr(tmp, tmp, strspn(tmp, "Mask:"), strlen(buf)-strspn(tmp, "Mask:"));
  3216. if (strcmp(tmp, (char *)ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress) != 0)
  3217. {
  3218. strcpy((char *) ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress, tmp);
  3219. }
  3220. }
  3221. }
  3222. }
  3223. pclose(fp);
  3224. memset(buf, 0x00, sizeof(buf));
  3225. // Get gateway
  3226. fp = popen("ip route", "r");
  3227. if(fp == NULL)
  3228. result = FAIL;
  3229. else
  3230. {
  3231. while(fgets(buf, sizeof(buf), fp) != NULL)
  3232. {
  3233. if((strstr(buf, "default") != NULL) && (strstr(buf, "eth0") != NULL))
  3234. break;
  3235. }
  3236. if(strstr(buf, "default") != NULL)
  3237. {
  3238. sscanf(buf, "%*s%*s%s", tmp);
  3239. substr((char*)ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthGatewayAddress, tmp, 0, strlen(tmp));
  3240. }
  3241. }
  3242. pclose(fp);
  3243. memset(buf, 0x00, sizeof(buf));
  3244. for(int idx=0;idx<ARRAY_SIZE(valid_Internet);idx++)
  3245. {
  3246. sprintf(cmd, "ping -c 1 -w 3 -I eth0 %s", valid_Internet[idx]);
  3247. fp = popen(cmd, "r");
  3248. if(fp != NULL)
  3249. {
  3250. while(fgets(buf, sizeof(buf), fp) != NULL)
  3251. {
  3252. if(strstr(buf, "transmitted") > 0)
  3253. {
  3254. //sscanf(buf, "%*s%*s%*s%*s%*s%*s%s", tmp);
  3255. if(strstr(buf,"100%") != NULL)
  3256. {
  3257. }
  3258. else
  3259. {
  3260. result = PASS;
  3261. }
  3262. //DEBUG_INFO("%s",buf);
  3263. //DEBUG_INFO("%s\n",tmp);
  3264. }
  3265. }
  3266. }
  3267. pclose(fp);
  3268. }
  3269. return result;
  3270. }
  3271. int isRouteFail()
  3272. {
  3273. int result = YES;
  3274. FILE *fp;
  3275. char buf[512];
  3276. fp = popen("route -n", "r");
  3277. if(fp != NULL)
  3278. {
  3279. while(fgets(buf, sizeof(buf), fp) != NULL)
  3280. {
  3281. if(strstr(buf, "eth0") != NULL)
  3282. result = NO;
  3283. }
  3284. }
  3285. pclose(fp);
  3286. return result;
  3287. }
  3288. //===============================================
  3289. // Check reservation date is expired
  3290. //===============================================
  3291. int isReservationExpired(unsigned char gun_index)
  3292. {
  3293. int result = NO;
  3294. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3295. {
  3296. if(isOvertNow(ShmOCPP16Data->ReserveNow[gun_index].ExpiryDate))
  3297. result = YES;
  3298. }
  3299. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3300. {
  3301. if(isOvertNow(ShmOCPP20Data->ReserveNow[gun_index].expiryDateTime))
  3302. result = YES;
  3303. }
  3304. return result;
  3305. }
  3306. //===============================================
  3307. // Check charging profile related date routine
  3308. //===============================================
  3309. int isProfileValid(uint8_t gun_index)
  3310. {
  3311. int result = NO;
  3312. struct tm tmFrom, tmTo;
  3313. struct timeb tbFrom, tbTo;
  3314. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3315. {
  3316. if((sscanf((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ValidFrom, "%4d-%2d-%2dT%2d:%2d:%2d", &tmFrom.tm_year, &tmFrom.tm_mon, &tmFrom.tm_mday, &tmFrom.tm_hour, &tmFrom.tm_min, &tmFrom.tm_sec) == 6) &&
  3317. (sscanf((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ValidTo, "%4d-%2d-%2dT%2d:%2d:%2d", &tmTo.tm_year, &tmTo.tm_mon, &tmTo.tm_mday, &tmTo.tm_hour, &tmTo.tm_min, &tmTo.tm_sec) == 6))
  3318. {
  3319. tmFrom.tm_year -= 1900;
  3320. tmFrom.tm_mon -= 1;
  3321. tbFrom.time = mktime(&tmFrom);
  3322. tmTo.tm_year -= 1900;
  3323. tmTo.tm_mon -= 1;
  3324. tbTo.time = mktime(&tmTo);
  3325. DEBUG_INFO("Valid from compare Now: %d\n", DiffTimebWithNow(tbFrom));
  3326. DEBUG_INFO("Valid to compare Now: %d\n", DiffTimebWithNow(tbTo));
  3327. if((DiffTimebWithNow(tbFrom)>=0) && (DiffTimebWithNow(tbTo)<=0))
  3328. {
  3329. result = YES;
  3330. }
  3331. }
  3332. else
  3333. {
  3334. DEBUG_WARN("ValidFrom or ValidTo date parsing error.\n");
  3335. }
  3336. }
  3337. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3338. {
  3339. if((sscanf((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].validFrom, "%4d-%2d-%2dT%2d:%2d:%2d", &tmFrom.tm_year, &tmFrom.tm_mon, &tmFrom.tm_mday, &tmFrom.tm_hour, &tmFrom.tm_min, &tmFrom.tm_sec) == 6) &&
  3340. (sscanf((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].validTo, "%4d-%2d-%2dT%2d:%2d:%2d", &tmTo.tm_year, &tmTo.tm_mon, &tmTo.tm_mday, &tmTo.tm_hour, &tmTo.tm_min, &tmTo.tm_sec) == 6))
  3341. {
  3342. tmFrom.tm_year -= 1900;
  3343. tmFrom.tm_mon -= 1;
  3344. tbFrom.time = mktime(&tmFrom);
  3345. tmTo.tm_year -= 1900;
  3346. tmTo.tm_mon -= 1;
  3347. tbTo.time = mktime(&tmTo);
  3348. DEBUG_INFO("Valid from compare Now: %d\n", DiffTimebWithNow(tbFrom));
  3349. DEBUG_INFO("Valid to compare Now: %d\n", DiffTimebWithNow(tbTo));
  3350. if((DiffTimebWithNow(tbFrom)>=0) && (DiffTimebWithNow(tbTo)<=0))
  3351. {
  3352. result = YES;
  3353. }
  3354. }
  3355. else
  3356. {
  3357. DEBUG_WARN("ValidFrom or ValidTo date parsing error.\n");
  3358. }
  3359. }
  3360. return result;
  3361. }
  3362. int getScheduleStart(int gun_index)
  3363. {
  3364. int result = -1;
  3365. struct tm tmScheduleStart;;
  3366. struct timeb tbScheduleStart;
  3367. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3368. {
  3369. if((sscanf((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.StartSchedule, "%4d-%2d-%2dT%2d:%2d:%2d", &tmScheduleStart.tm_year, &tmScheduleStart.tm_mon, &tmScheduleStart.tm_mday, &tmScheduleStart.tm_hour, &tmScheduleStart.tm_min, &tmScheduleStart.tm_sec) == 6))
  3370. {
  3371. tmScheduleStart.tm_year -= 1900;
  3372. tmScheduleStart.tm_mon -= 1;
  3373. tbScheduleStart.time = mktime(&tmScheduleStart);
  3374. tbScheduleStart.millitm = 0;
  3375. result = DiffTimebWithNow(tbScheduleStart)/1000;
  3376. //DEBUG_INFO("Schedule start compare Now(seconds): %d\n", result);
  3377. }
  3378. else
  3379. {
  3380. DEBUG_WARN("Schedule start date parsing error.\n");
  3381. }
  3382. }
  3383. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3384. {
  3385. if((sscanf((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].startSchedule, "%4d-%2d-%2dT%2d:%2d:%2d", &tmScheduleStart.tm_year, &tmScheduleStart.tm_mon, &tmScheduleStart.tm_mday, &tmScheduleStart.tm_hour, &tmScheduleStart.tm_min, &tmScheduleStart.tm_sec) == 6))
  3386. {
  3387. tmScheduleStart.tm_year -= 1900;
  3388. tmScheduleStart.tm_mon -= 1;
  3389. tbScheduleStart.time = mktime(&tmScheduleStart);
  3390. tbScheduleStart.millitm = 0;
  3391. result = DiffTimebWithNow(tbScheduleStart)/1000;
  3392. //DEBUG_INFO("Schedule start compare Now(seconds): %d\n", result);
  3393. }
  3394. else
  3395. {
  3396. DEBUG_WARN("Schedule start date parsing error.\n");
  3397. }
  3398. }
  3399. return result;
  3400. }
  3401. int getStartSinceToday()
  3402. {
  3403. int result = -1;
  3404. time_t t;
  3405. struct tm *tmStartToday;
  3406. struct timeb tbStartToday;
  3407. t=time(NULL);
  3408. tmStartToday=localtime(&t);
  3409. tmStartToday->tm_hour = 0;
  3410. tmStartToday->tm_min = 0;
  3411. tmStartToday->tm_sec = 0;
  3412. tbStartToday.time = mktime(tmStartToday);
  3413. result = DiffTimebWithNow(tbStartToday)/1000;
  3414. //DEBUG_INFO("Start today compare Now(seconds): %d\n", result);
  3415. return result;
  3416. }
  3417. int getStartSinceWeek()
  3418. {
  3419. int result = -1;
  3420. time_t t;
  3421. struct tm *tmStartWeek;
  3422. struct timeb tbStartWeek;
  3423. t=time(NULL);
  3424. tmStartWeek=localtime(&t);
  3425. t-=86400*tmStartWeek->tm_wday;
  3426. tmStartWeek=localtime(&t);
  3427. tmStartWeek->tm_hour = 0;
  3428. tmStartWeek->tm_min = 0;
  3429. tmStartWeek->tm_sec = 0;
  3430. tbStartWeek.time = mktime(tmStartWeek);
  3431. result = DiffTimebWithNow(tbStartWeek)/1000;
  3432. //DEBUG_INFO("Start week compare Now(seconds): %d\n", result);
  3433. return result;
  3434. }
  3435. //===============================================
  3436. // Valid from local white list
  3437. //===============================================
  3438. int isValidLocalWhiteCard()
  3439. {
  3440. uint8_t result = FAIL;
  3441. for(uint8_t idx=0;idx<ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.LocalWhiteCard);idx++)
  3442. {
  3443. if(strcmp((char*)ShmSysConfigAndInfo->SysConfig.UserId, (char*)ShmSysConfigAndInfo->SysConfig.LocalWhiteCard[idx]) == 0)
  3444. {
  3445. result = PASS;
  3446. }
  3447. }
  3448. return result;
  3449. }
  3450. //==========================================
  3451. // Check routine
  3452. //==========================================
  3453. void checkTask()
  3454. {
  3455. /*
  3456. * TODO:
  3457. * 1. Rotary switch define change with system specification
  3458. */
  3459. // Task run only on cabinet
  3460. if(ShmDispenser->gun_info.primaryMcuState.rotatory_switch != ROTARY_SWITCH_E_DISPENSER)
  3461. {
  3462. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  3463. {
  3464. if(system("pidof -s Module_4g > /dev/null") != 0)
  3465. {
  3466. DEBUG_INFO("Module_4g not running, restart it.\n");
  3467. system("/root/Module_4g &");
  3468. }
  3469. }
  3470. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  3471. {
  3472. if(system("pidof -s Module_Wifi > /dev/null") != 0)
  3473. {
  3474. DEBUG_INFO("Module_Wifi not running, restart it.\n");
  3475. system("/root/Module_Wifi &");
  3476. }
  3477. }
  3478. if((strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") != 0) && !ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharging)
  3479. {
  3480. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3481. {
  3482. if((time((time_t*)NULL) - ShmOCPP16Data->procDogTime) > 180)
  3483. {
  3484. DEBUG_WARN("OcppBackend watch dog timeout task restart.\n");
  3485. ShmOCPP16Data->procDogTime = time((time_t*)NULL);
  3486. system("pkill OcppBackend");
  3487. sleep(3);
  3488. ocpp_process_start();
  3489. }
  3490. if(system("pidof -s OcppBackend > /dev/null") != 0)
  3491. {
  3492. DEBUG_INFO("OcppBackend not running, restart it.\n");
  3493. ocpp_process_start();
  3494. }
  3495. }
  3496. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3497. {
  3498. if((time((time_t*)NULL) - ShmOCPP20Data->procDogTime) > 180)
  3499. {
  3500. DEBUG_WARN("OcppBackend20 watch dog timeout task restart.\n");
  3501. ShmOCPP20Data->procDogTime = time((time_t*)NULL);
  3502. system("pkill OcppBackend20");
  3503. sleep(3);
  3504. ocpp_process_start();
  3505. }
  3506. if(system("pidof -s OcppBackend20 > /dev/null") != 0)
  3507. {
  3508. DEBUG_INFO("OcppBackend20 not running, restart it.\n");
  3509. ocpp_process_start();
  3510. }
  3511. }
  3512. }
  3513. if(system("pidof -s Module_Speaker > /dev/null") != 0)
  3514. {
  3515. DEBUG_INFO("Module_Speaker not running, restart it.\n");
  3516. system("/root/Module_Speaker &");
  3517. }
  3518. if(system("pidof -s Module_LcmControl > /dev/null") != 0)
  3519. {
  3520. DEBUG_INFO("Module_LcmControl not running, restart it.\n");
  3521. system ("/root/Module_LcmControl &");
  3522. }
  3523. if((system("pidof -s Module_PowerSharing > /dev/null") != 0) &&
  3524. ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharging)
  3525. {
  3526. DEBUG_INFO("Module_PowerSharing not running, restart it.\n");
  3527. system ("/root/Module_PowerSharing &");
  3528. }
  3529. if((system("pidof -s Module_InitUpgrade > /dev/null") != 0) &&
  3530. ShmSysConfigAndInfo->SysConfig.isReqFirstUpgrade)
  3531. {
  3532. DEBUG_INFO("Module_InitUpgrade not running, restart it.\n");
  3533. system ("/root/Module_InitUpgrade &");
  3534. }
  3535. if(system("pidof -s Module_AlarmDetect > /dev/null") != 0)
  3536. {
  3537. DEBUG_INFO("Module_AlarmDetect not running, restart it.\n");
  3538. system("/root/Module_AlarmDetect &");
  3539. }
  3540. }
  3541. // Task run both on cabinet and dispenser
  3542. if(system("pidof -s Module_EventLogging > /dev/null") != 0)
  3543. {
  3544. DEBUG_INFO("Module_EventLogging not running, restart it.\n");
  3545. system("/root/Module_EventLogging &");
  3546. }
  3547. if(system("pidof -s Module_InternalComm > /dev/null") != 0)
  3548. {
  3549. DEBUG_INFO("Module_InternalComm not running, restart it.\n");
  3550. system("/root/Module_InternalComm &");
  3551. }
  3552. if(system("pidof -s Module_ProduceUtils > /dev/null") != 0)
  3553. {
  3554. DEBUG_INFO("Module_ProduceUtils not running, restart it.\n");
  3555. system ("/root/Module_ProduceUtils &");
  3556. }
  3557. if((system("pidof -s Module_Cabinet > /dev/null") != 0))
  3558. {
  3559. DEBUG_INFO("Module_Cabinet not running, restart it.\n");
  3560. system ("/root/Module_Cabinet &");
  3561. }
  3562. if((system("pidof -s Module_Dispenser > /dev/null") != 0))
  3563. {
  3564. DEBUG_INFO("Module_Dispenser not running, restart it.\n");
  3565. system ("/root/Module_Dispenser &");
  3566. }
  3567. }
  3568. void checkConnectionTimeout()
  3569. {
  3570. if((system("pidof -s OcppBackend > /dev/null") != 0) && (system("pidof -s OcppBackend20 > /dev/null") != 0))
  3571. {
  3572. ShmCharger->timeoutSpec.Present_Timeout_Spec = TIMEOUT_SPEC_HANDSHAKING;
  3573. //DEBUG_INFO("Handshaking timeout specification follow by initial setting : %d s \n", TIMEOUT_SPEC_HANDSHAKING/1000);
  3574. }
  3575. else
  3576. {
  3577. ShmCharger->timeoutSpec.Setting_Timeout_Spec = ocpp_get_connection_timeout();
  3578. if((ShmCharger->timeoutSpec.Setting_Timeout_Spec) < TIMEOUT_SPEC_BS_HLC_HANDSHAKE)
  3579. {
  3580. ShmCharger->timeoutSpec.Present_Timeout_Spec = (TIMEOUT_SPEC_BS_HLC_HANDSHAKE+10);
  3581. //DEBUG_INFO("Handshaking timeout specification follow by OCPP Configuration : Fail. Value can't be zero or less than zero.\n.");
  3582. }
  3583. else
  3584. {
  3585. ShmCharger->timeoutSpec.Present_Timeout_Spec = (ShmCharger->timeoutSpec.Setting_Timeout_Spec);
  3586. //DEBUG_INFO("Handshaking timeout specification follow by OCPP Configuration : Pass...\n.");
  3587. }
  3588. //DEBUG_INFO("Handshaking timeout specification follow by OCPP Configuration : %s s \n.",ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData);
  3589. }
  3590. }
  3591. void checkReset()
  3592. {
  3593. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3594. {
  3595. if(ShmOCPP16Data->MsMsg.bits.ResetReq)
  3596. {
  3597. if((!isMode(0, SYS_MODE_CHARGING) && !isMode(0, SYS_MODE_TERMINATING) && !isMode(0, SYS_MODE_COMPLETE)) &&
  3598. ((modelnameInfo.GetGunCount==2)?(!isMode(1, SYS_MODE_CHARGING) && !isMode(1, SYS_MODE_TERMINATING) && !isMode(1, SYS_MODE_COMPLETE)):TRUE) &&
  3599. ((modelnameInfo.GetGunCount==3)?(!isMode(2, SYS_MODE_CHARGING) && !isMode(2, SYS_MODE_TERMINATING) && !isMode(2, SYS_MODE_COMPLETE)):TRUE))
  3600. {
  3601. ShmOCPP16Data->MsMsg.bits.ResetReq = OFF;
  3602. sprintf((char*)ShmOCPP16Data->Reset.ResponseStatus, "Accepted");
  3603. ShmOCPP16Data->MsMsg.bits.ResetConf = ON;
  3604. DEBUG_INFO("%s reset request by OCPP.\n", ShmOCPP16Data->Reset.Type);
  3605. if(strcmp((char*)ShmOCPP16Data->Reset.Type, "Hard") == 0)
  3606. {
  3607. for(int gun_index=0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  3608. {
  3609. ShmCharger->gun_info[gun_index].isResetHardReq = ON;
  3610. setLedMotion(gun_index,LED_ACTION_INIT);
  3611. }
  3612. }
  3613. else
  3614. {
  3615. for(int gun_index=0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  3616. {
  3617. ShmCharger->gun_info[gun_index].isResetSoftReq = ON;
  3618. setLedMotion(gun_index,LED_ACTION_INIT);
  3619. }
  3620. }
  3621. sleep(2);
  3622. }
  3623. }
  3624. }
  3625. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3626. {
  3627. if(ShmOCPP20Data->MsMsg.bits.ResetReq)
  3628. {
  3629. if((!isMode(0, SYS_MODE_CHARGING) && !isMode(0, SYS_MODE_TERMINATING) && !isMode(0, SYS_MODE_COMPLETE)) &&
  3630. ((modelnameInfo.GetGunCount==2)?(!isMode(1, SYS_MODE_CHARGING) && !isMode(1, SYS_MODE_TERMINATING) && !isMode(1, SYS_MODE_COMPLETE)):TRUE) &&
  3631. ((modelnameInfo.GetGunCount==3)?(!isMode(2, SYS_MODE_CHARGING) && !isMode(2, SYS_MODE_TERMINATING) && !isMode(2, SYS_MODE_COMPLETE)):TRUE))
  3632. {
  3633. ShmOCPP20Data->MsMsg.bits.ResetReq = OFF;
  3634. sprintf((char*)ShmOCPP20Data->Reset.Response_status, "Accepted");
  3635. ShmOCPP20Data->MsMsg.bits.ResetConf = ON;
  3636. DEBUG_INFO("%s reset request by OCPP.\n", ShmOCPP20Data->Reset.type);
  3637. if(strcmp((char*)ShmOCPP20Data->Reset.type, "Immediate") == 0)
  3638. {
  3639. for(int gun_index=0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  3640. {
  3641. ShmCharger->gun_info[gun_index].isResetHardReq = ON;
  3642. setLedMotion(gun_index,LED_ACTION_INIT);
  3643. }
  3644. }
  3645. else
  3646. {
  3647. for(int gun_index=0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  3648. {
  3649. ShmCharger->gun_info[gun_index].isResetSoftReq = ON;
  3650. setLedMotion(gun_index,LED_ACTION_INIT);
  3651. }
  3652. }
  3653. sleep(2);
  3654. }
  3655. }
  3656. }
  3657. if(ShmDispenser->gun_info.isResetHardReq)
  3658. {
  3659. system("sync");
  3660. sleep(5);
  3661. system("reboot -f");
  3662. sleep(5);
  3663. system("reboot -f");
  3664. }
  3665. else if(ShmDispenser->gun_info.isResetSoftReq)
  3666. {
  3667. sleep(5);
  3668. close(wtdFd);
  3669. system("/usr/bin/run_evse_restart.sh");
  3670. }
  3671. }
  3672. void checkReservation(uint8_t gun_index)
  3673. {
  3674. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3675. {
  3676. if(ShmOCPP16Data->CsMsg.bits[gun_index].ReserveNowReq)
  3677. {
  3678. ShmOCPP16Data->CsMsg.bits[gun_index].ReserveNowReq = OFF;
  3679. ShmOCPP16Data->CsMsg.bits[gun_index].ReserveNowConf = ON;
  3680. if(isMode(gun_index, SYS_MODE_IDLE) && !isReservationExpired(gun_index))
  3681. {
  3682. sleep(5);
  3683. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId = ShmOCPP16Data->ReserveNow[gun_index].ReservationId;
  3684. setChargerMode(gun_index, SYS_MODE_RESERVATION);
  3685. }
  3686. DEBUG_INFO("Reservation request on gun-%d.\n", gun_index);
  3687. }
  3688. }
  3689. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3690. {
  3691. if(ShmOCPP20Data->CsMsg.bits[gun_index].ReserveNowReq)
  3692. {
  3693. ShmOCPP20Data->CsMsg.bits[gun_index].ReserveNowReq = OFF;
  3694. ShmOCPP20Data->CsMsg.bits[gun_index].ReserveNowConf = ON;
  3695. if(isMode(gun_index, SYS_MODE_IDLE) && !isReservationExpired(gun_index))
  3696. {
  3697. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId = ShmOCPP20Data->ReserveNow[gun_index].id;
  3698. setChargerMode(gun_index, SYS_MODE_RESERVATION);
  3699. }
  3700. DEBUG_INFO("Reservation request on gun-%d.\n", gun_index);
  3701. }
  3702. }
  3703. }
  3704. void checkUnlocker(uint8_t gun_index)
  3705. {
  3706. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3707. {
  3708. if(ShmOCPP16Data->CsMsg.bits[gun_index].UnlockConnectorReq == ON)
  3709. {
  3710. ShmOCPP16Data->CsMsg.bits[gun_index].UnlockConnectorReq = OFF;
  3711. sprintf((char*)ShmOCPP16Data->UnlockConnector[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].ResponseStatus, "NotSupported");
  3712. ShmOCPP16Data->CsMsg.bits[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].UnlockConnectorConf = ON;
  3713. ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor = ON;
  3714. }
  3715. }
  3716. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3717. {
  3718. if(ShmOCPP20Data->CsMsg.bits[gun_index].UnlockConnectorReq == ON)
  3719. {
  3720. ShmOCPP20Data->CsMsg.bits[gun_index].UnlockConnectorReq = OFF;
  3721. sprintf((char*)ShmOCPP20Data->UnlockConnector[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].Response_status, "UnlockFailed");
  3722. ShmOCPP20Data->CsMsg.bits[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].UnlockConnectorConf = ON;
  3723. ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor = ON;
  3724. }
  3725. }
  3726. }
  3727. void checkAvailability(uint8_t gun_index)
  3728. {
  3729. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3730. {
  3731. if(ShmOCPP16Data->CsMsg.bits[gun_index].ChangeAvailabilityReq)
  3732. {
  3733. if(strcmp((char*)ShmOCPP16Data->ChangeAvailability[gun_index].Type, "Operative") == 0)
  3734. {
  3735. DB_Update_Operactive(localDb, gun_index, true);
  3736. ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
  3737. }
  3738. else
  3739. {
  3740. DB_Update_Operactive(localDb, gun_index, false);
  3741. ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
  3742. }
  3743. ShmOCPP16Data->CsMsg.bits[gun_index].ChangeAvailabilityReq = OFF;
  3744. }
  3745. }
  3746. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3747. {
  3748. if(ShmOCPP20Data->CsMsg.bits[gun_index].ChangeAvailabilityReq)
  3749. {
  3750. if(strcmp((char*)ShmOCPP20Data->ChangeAvailability[gun_index].operationalStatus, "Operative") == 0)
  3751. {
  3752. DB_Update_Operactive(localDb, gun_index, true);
  3753. ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
  3754. }
  3755. else
  3756. {
  3757. DB_Update_Operactive(localDb, gun_index, false);
  3758. ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
  3759. }
  3760. ShmOCPP20Data->CsMsg.bits[gun_index].ChangeAvailabilityReq = OFF;
  3761. }
  3762. }
  3763. }
  3764. void checkChargingProfileLimit(uint8_t gun_index)
  3765. {
  3766. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3767. {
  3768. if((ocpp_get_smartcharging_profileId(gun_index) > 0) &&
  3769. (ocpp_get_profile_req(gun_index) != ON) &&
  3770. (((strlen((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ValidFrom)>0) && (strlen((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ValidTo)>0)) ? isProfileValid(gun_index) : ON))
  3771. {
  3772. // Debug information
  3773. if(getDiffSecNow(startTime[gun_index][TMR_IDX_LOGPPRINTOUT]) > TIMEOUT_SPEC_LOGPPRINTOUT)
  3774. {
  3775. DEBUG_INFO("===============================================================\n");
  3776. DEBUG_INFO("Profile ID found: %d\n", ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfileId);
  3777. DEBUG_INFO("Valid from: %s\n", ShmOCPP16Data->SmartChargingProfile[gun_index].ValidFrom);
  3778. DEBUG_INFO("Valid to: %s\n", ShmOCPP16Data->SmartChargingProfile[gun_index].ValidTo);
  3779. DEBUG_INFO("Start schedule: %s\n", ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.StartSchedule);
  3780. DEBUG_INFO("Profile kind: %s\n", ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfileKind);
  3781. DEBUG_INFO("RecurrencyKind: %s\n", ShmOCPP16Data->SmartChargingProfile[gun_index].RecurrencyKind);
  3782. DEBUG_INFO("Profile purpose: %s\n", ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfilePurpose);
  3783. DEBUG_INFO("Transaction ID: %d\n", ShmOCPP16Data->SmartChargingProfile[gun_index].TransactionId);
  3784. DEBUG_INFO("ChargingRateUnit: %s\n", ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingRateUnit);
  3785. DEBUG_INFO("===============================================================\n");
  3786. }
  3787. // Checking profile kind
  3788. if((mystrcmp((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfileKind, "Absolute") == PASS))
  3789. {
  3790. // Absolute profile
  3791. if(((mystrcmp((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfilePurpose, "TxProfile") == PASS) && (ShmOCPP16Data->SmartChargingProfile[gun_index].TransactionId == ShmOCPP16Data->StartTransaction[gun_index].ResponseTransactionId)) ||
  3792. (mystrcmp((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfilePurpose, "TxProfile") == FAIL))
  3793. {
  3794. // Checking limitation
  3795. for(uint8_t idx_period=0;idx_period<ARRAY_SIZE(ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod);idx_period++)
  3796. {
  3797. if((getScheduleStart(gun_index) > ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod[idx_period].StartPeriod) &&
  3798. ((idx_period == 0) || (ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod[idx_period].StartPeriod > 0))
  3799. )
  3800. {
  3801. ShmCharger->gun_info[gun_index].targetCurrent = (mystrcmp((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingRateUnit,"W")==PASS?ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod[idx_period].Limit/(220*ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod[idx_period].NumberPhases):ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod[idx_period].Limit);
  3802. //DEBUG_INFO("ShmCharger->gun_info[%d].targetCurrent on period[%d]: %d\n", gun_index, idx_period, ShmCharger->gun_info[gun_index].targetCurrent);
  3803. }
  3804. else
  3805. break;
  3806. }
  3807. }
  3808. }
  3809. }
  3810. else if((ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfileId == 0) && (ShmOCPP16Data->CSUMsg.bits[gun_index].ChargingProfileReq != ON))
  3811. {
  3812. ShmCharger->gun_info[gun_index].targetCurrent = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
  3813. }
  3814. }
  3815. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3816. {
  3817. if((ocpp_get_smartcharging_profileId(gun_index) > 0) &&
  3818. (ocpp_get_profile_req(gun_index) != ON) &&
  3819. (((strlen((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].validFrom)>0) && (strlen((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].validTo)>0)) ? isProfileValid(gun_index) : ON))
  3820. {
  3821. // Debug information
  3822. if(getDiffSecNow(startTime[gun_index][TMR_IDX_LOGPPRINTOUT]) > TIMEOUT_SPEC_LOGPPRINTOUT)
  3823. {
  3824. DEBUG_INFO("===============================================================\n");
  3825. DEBUG_INFO("Profile ID found: %d\n", ShmOCPP20Data->SmartChargingProfile[gun_index].id);
  3826. DEBUG_INFO("Valid from: %s\n", ShmOCPP20Data->SmartChargingProfile[gun_index].validFrom);
  3827. DEBUG_INFO("Valid to: %s\n", ShmOCPP20Data->SmartChargingProfile[gun_index].validTo);
  3828. DEBUG_INFO("Start schedule: %s\n", ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].startSchedule);
  3829. DEBUG_INFO("Profile kind: %s\n", ShmOCPP20Data->SmartChargingProfile[gun_index].chargingProfileKind);
  3830. DEBUG_INFO("RecurrencyKind: %s\n", ShmOCPP20Data->SmartChargingProfile[gun_index].recurrencyKind);
  3831. DEBUG_INFO("Profile purpose: %s\n", ShmOCPP20Data->SmartChargingProfile[gun_index].chargingProfilePurpose);
  3832. DEBUG_INFO("Transaction ID: %d\n", ShmOCPP20Data->SmartChargingProfile[gun_index].transactionId);
  3833. DEBUG_INFO("ChargingRateUnit: %s\n", ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingRateUnit);
  3834. DEBUG_INFO("===============================================================\n");
  3835. }
  3836. // Checking profile kind
  3837. if((mystrcmp((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].chargingProfileKind, "Absolute") == PASS))
  3838. {
  3839. // Absolute profile
  3840. if(((mystrcmp((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].chargingProfilePurpose, "TxProfile") == PASS) && (ShmOCPP20Data->SmartChargingProfile[gun_index].transactionId == ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.transactionId)) ||
  3841. (mystrcmp((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].chargingProfilePurpose, "TxProfile") == FAIL))
  3842. {
  3843. // Checking limitation
  3844. for(uint8_t idx_period=0;idx_period<ARRAY_SIZE(ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod);idx_period++)
  3845. {
  3846. if((getScheduleStart(gun_index) > ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod[idx_period].startPeriod) &&
  3847. ((idx_period == 0) || (ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod[idx_period].startPeriod > 0))
  3848. )
  3849. {
  3850. ShmCharger->gun_info[gun_index].targetCurrent = (mystrcmp((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingRateUnit,"W")==PASS?ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod[idx_period].limit/(220*ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod[idx_period].numberPhases):ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod[idx_period].limit);
  3851. DEBUG_INFO("ShmCharger->gun_info[%d].targetCurrent on period[%d]: %d\n", gun_index, idx_period, ShmCharger->gun_info[gun_index].targetCurrent);
  3852. }
  3853. else
  3854. break;
  3855. }
  3856. }
  3857. }
  3858. }
  3859. else if((ShmOCPP20Data->SmartChargingProfile[gun_index].id == 0) && (ShmOCPP20Data->CSUMsg.bits[gun_index].ChargingProfileReq != ON))
  3860. {
  3861. ShmCharger->gun_info[gun_index].targetCurrent = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
  3862. }
  3863. }
  3864. }
  3865. void checkStopReason(uint8_t gun_index)
  3866. {
  3867. sleep(2);
  3868. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3869. {
  3870. memset(ShmOCPP16Data->StopTransaction[gun_index].IdTag, 0x00, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  3871. if(!ocpp_get_starttransaction_result(gun_index))
  3872. {
  3873. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "DeAuthorized");
  3874. }
  3875. else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_EMERGENCY_STOP)
  3876. {
  3877. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EmergencyStop");
  3878. }
  3879. else if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)
  3880. {
  3881. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EVDisconnected");
  3882. }
  3883. else if(ShmOCPP16Data->MsMsg.bits.ResetReq)
  3884. {
  3885. if(strcmp((char*)ShmOCPP16Data->Reset.Type, "Hard")==0)
  3886. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "HardReset");
  3887. else
  3888. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "SoftReset");
  3889. }
  3890. else if(ShmCharger->gun_info[gun_index].rfidReq || ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop)
  3891. {
  3892. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
  3893. if(!isMatchStartUser(gun_index))
  3894. {
  3895. memcpy((char*)ShmOCPP16Data->StopTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  3896. }
  3897. else
  3898. {
  3899. memcpy((char*)ShmOCPP16Data->StopTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  3900. }
  3901. DEBUG_INFO("Gun-%d [ IdTag ] : %s \n", gun_index, ShmOCPP16Data->StopTransaction[gun_index].IdTag);
  3902. }
  3903. else if(ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStopTransactionReq)
  3904. {
  3905. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Remote");
  3906. }
  3907. else if(ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor == ON)
  3908. {
  3909. sprintf((char*)ShmOCPP16Data->StopTransaction[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].StopReason, "UnlockCommand");
  3910. }
  3911. else
  3912. {
  3913. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Other");
  3914. }
  3915. DEBUG_INFO("Gun-%d : StopReason [ %s ]...\n",gun_index,ShmOCPP16Data->StopTransaction[gun_index].StopReason);
  3916. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  3917. presentChargedEnergyUpdate(gun_index);
  3918. DEBUG_INFO("PresentChargedEnergy Gun-[%d] : %.4f \n",gun_index ,ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy);
  3919. ShmOCPP16Data->CpMsg.bits[gun_index].StopTransactionReq = ON;
  3920. }
  3921. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3922. {
  3923. memset(ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, 0x00, ARRAY_SIZE(ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken));
  3924. if(!ocpp_get_starttransaction_result(gun_index))
  3925. {
  3926. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "DeAuthorized");
  3927. }
  3928. else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_EMERGENCY_STOP)
  3929. {
  3930. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "EmergencyStop");
  3931. }
  3932. else if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)
  3933. {
  3934. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "EVDisconnected");
  3935. }
  3936. else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_GROUND_FAIL)
  3937. {
  3938. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "GroundFault");
  3939. }
  3940. else if(ShmOCPP20Data->MsMsg.bits.ResetReq)
  3941. {
  3942. if(strcmp((char*)ShmOCPP20Data->Reset.type, "Immediate")==0)
  3943. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "ImmediateReset");
  3944. else
  3945. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "OnIdle");
  3946. }
  3947. else if(ShmCharger->gun_info[gun_index].rfidReq || ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop)
  3948. {
  3949. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Local");
  3950. if(!isMatchStartUser(gun_index))
  3951. {
  3952. memcpy((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, (char*)ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken));
  3953. }
  3954. else
  3955. {
  3956. memcpy((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId));
  3957. }
  3958. DEBUG_INFO("Gun-%d [ idToken ] : %s \n", gun_index, ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken);
  3959. }
  3960. else if((ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_L1_OVER_CURRENT) ||
  3961. (ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_L2_OVER_CURRENT) ||
  3962. (ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_L3_OVER_CURRENT))
  3963. {
  3964. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "OvercurrentFault");
  3965. }
  3966. else if(ShmOCPP20Data->CsMsg.bits[gun_index].RequestStopTransactionReq)
  3967. {
  3968. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Remote");
  3969. }
  3970. else if(ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor == ON)
  3971. {
  3972. sprintf((char*)ShmOCPP20Data->TransactionEvent[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].transactionInfo.stoppedReason, "UnlockCommand");
  3973. }
  3974. else
  3975. {
  3976. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Other");
  3977. }
  3978. DEBUG_INFO("Gun-%d : StopReason [ %s ]...\n", gun_index, ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason);
  3979. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  3980. presentChargedEnergyUpdate(gun_index);
  3981. DEBUG_INFO("PresentChargedEnergy Gun-[%d] : %.4f \n",gun_index ,ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy);
  3982. ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventReq = ON;
  3983. }
  3984. }
  3985. void checkRemoteUpgradeStatus()
  3986. {
  3987. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3988. {
  3989. if(strcmp((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "DownloadFailed")==0)
  3990. {
  3991. DEBUG_INFO("Firmware remote upgraded fail...\n");
  3992. ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq = OFF;
  3993. ShmCharger->isUpdateSuccess = NO;
  3994. }
  3995. else if(strcmp((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Downloaded")==0)
  3996. {
  3997. DEBUG_INFO("Firmware remote upgrading...\n");
  3998. sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installing");
  3999. sleep(1);
  4000. ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  4001. ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq = OFF;
  4002. if(upgrade_check() == PASS)
  4003. {
  4004. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == ON)
  4005. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = OFF;
  4006. ShmCharger->isUpdateSuccess = YES;
  4007. DEBUG_INFO("Remote update success.\n");
  4008. }
  4009. else
  4010. {
  4011. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == OFF)
  4012. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = ON;
  4013. ShmCharger->isUpdateSuccess = NO;
  4014. DEBUG_INFO("Remote update fail.\n");
  4015. }
  4016. }
  4017. else
  4018. {}
  4019. }
  4020. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  4021. {
  4022. if(strcmp((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "DownloadFailed")==0)
  4023. {
  4024. DEBUG_INFO("Firmware remote upgraded fail...\n");
  4025. ShmOCPP20Data->MsMsg.bits.UpdateFirmwareReq = OFF;
  4026. ShmCharger->isUpdateSuccess = NO;
  4027. }
  4028. else if(strcmp((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "Downloaded")==0)
  4029. {
  4030. DEBUG_INFO("Firmware remote upgrading...\n");
  4031. sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installing");
  4032. ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  4033. ShmOCPP20Data->MsMsg.bits.UpdateFirmwareReq = OFF;
  4034. if(upgrade_check() == PASS)
  4035. {
  4036. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == ON)
  4037. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = OFF;
  4038. ShmCharger->isUpdateSuccess = YES;
  4039. DEBUG_INFO("Remote update success.\n");
  4040. }
  4041. else
  4042. {
  4043. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == OFF)
  4044. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = ON;
  4045. ShmCharger->isUpdateSuccess = NO;
  4046. DEBUG_INFO("Remote update fail.\n");
  4047. }
  4048. }
  4049. else
  4050. {}
  4051. }
  4052. }
  4053. void checkRfidAuthrize()
  4054. {
  4055. static uint8_t isCheckdResult = FALSE;
  4056. if(!ShmCharger->isAuthrizing)
  4057. {
  4058. // Read RFID
  4059. if(GetCardSerialNumber() != FAIL)
  4060. {
  4061. uint8_t isSnStart = FALSE;
  4062. uint8_t bufferRFID[ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId)];
  4063. if(ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian)
  4064. {
  4065. // Big endian
  4066. switch(rfid.snType)
  4067. {
  4068. case RFID_SN_TYPE_6BYTE:
  4069. sprintf((char*)bufferRFID, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5]);
  4070. break;
  4071. case RFID_SN_TYPE_7BYTE:
  4072. sprintf((char*)bufferRFID, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6]);
  4073. break;
  4074. case RFID_SN_TYPE_10BYTE:
  4075. sprintf((char*)bufferRFID, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6], rfid.currentCard[7], rfid.currentCard[8], rfid.currentCard[9]);
  4076. break;
  4077. case RFID_SN_TYPE_4BYTE:
  4078. default:
  4079. sprintf((char*)bufferRFID, "%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3]);
  4080. break;
  4081. }
  4082. }
  4083. else
  4084. {
  4085. // Little endian
  4086. switch(rfid.snType)
  4087. {
  4088. case RFID_SN_TYPE_6BYTE:
  4089. sprintf((char*)bufferRFID, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  4090. break;
  4091. case RFID_SN_TYPE_7BYTE:
  4092. sprintf((char*)bufferRFID, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  4093. break;
  4094. case RFID_SN_TYPE_10BYTE:
  4095. sprintf((char*)bufferRFID, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[9], rfid.currentCard[8], rfid.currentCard[7], rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  4096. break;
  4097. case RFID_SN_TYPE_4BYTE:
  4098. default:
  4099. sprintf((char*)bufferRFID, "%02X%02X%02X%02X", rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  4100. break;
  4101. }
  4102. }
  4103. DEBUG_INFO("Authorize request User Id : %s\n", bufferRFID);
  4104. //DEBUG_INFO("Authorize request User Id : %s\n", ShmSysConfigAndInfo->SysConfig.UserId);
  4105. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4106. ShmCharger->gun_info[gun_index].resultAuthorization = UNKNOW_RFID;
  4107. // Check SN already start
  4108. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4109. {
  4110. if(isMatchStartUser(gun_index) || (isMatchPresentUser(gun_index) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_PREPARING)))
  4111. {
  4112. DEBUG_INFO("%s running on connector-%02d.\n", ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, gun_index);
  4113. isSnStart = TRUE;
  4114. ShmCharger->gun_info[gun_index].rfidReq = ON;
  4115. ocpp_set_auth_conf(ON);
  4116. setLedMotion(gun_index,LED_ACTION_RFID_PASS);
  4117. setSpeaker(ON, SPEAKER_SHORT);
  4118. sleep(3);
  4119. break;
  4120. }
  4121. }
  4122. // Request authorize if isSnStart is false
  4123. if(!isSnStart)
  4124. {
  4125. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, bufferRFID, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  4126. refreshStartTimer(&startTime[0][TMR_IDX_AUTH]);
  4127. ocpp_set_auth_conf(OFF);
  4128. ocpp_set_auth_req(ON, "ISO14443");
  4129. setLedMotion(0,LED_ACTION_AUTHED);
  4130. ShmCharger->isAuthrizing = TRUE;
  4131. ShmCharger->isGetAuthResult = FALSE;
  4132. isCheckdResult = FALSE;
  4133. sleep(1);
  4134. }
  4135. }
  4136. }
  4137. else
  4138. {
  4139. // Wait authorize result
  4140. if(!ocpp_get_auth_conf() && (getDiffSecNow(startTime[0][TMR_IDX_AUTH]) > TIMEOUT_SPEC_AUTH))
  4141. {
  4142. // Authorization timeout process.
  4143. DEBUG_WARN("Authorize timeout !!!\n");
  4144. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4145. {
  4146. ShmCharger->gun_info[gun_index].resultAuthorization = UNVALIDATED_RFID;
  4147. setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
  4148. }
  4149. setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
  4150. sleep(3);
  4151. ShmCharger->isAuthrizing = FALSE;
  4152. }
  4153. else
  4154. {
  4155. if(ocpp_get_auth_conf() ||
  4156. (!ocpp_get_connection_status() && ((ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE) || (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_NOCHARGE))) ||
  4157. (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST) && (getDiffSecNow(startTime[0][TMR_IDX_AUTH]) > 2))
  4158. )
  4159. {
  4160. if(ocpp_get_auth_result(NO) ||
  4161. (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE)) ||
  4162. (!ocpp_get_connection_status() && (isValidLocalWhiteCard() == PASS) && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST)))
  4163. {
  4164. if(!isCheckdResult)
  4165. {
  4166. DEBUG_INFO("Authorize pass.\n");
  4167. setSpeaker(ON, SPEAKER_SHORT);
  4168. refreshStartTimer(&startTime[0][TMR_IDX_GUN_DETECT]);
  4169. ShmCharger->isGetAuthResult = TRUE;
  4170. isCheckdResult = TRUE;
  4171. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0)
  4172. {
  4173. ocpp_set_auth_conf(ON);
  4174. }
  4175. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4176. ShmCharger->gun_info[gun_index].resultAuthorization = VALIDATED_RFID;
  4177. }
  4178. if(getDiffSecNow(startTime[0][TMR_IDX_GUN_DETECT]) < ocpp_get_connection_timeout())
  4179. {
  4180. if(GetCardSerialNumber() != FAIL)
  4181. {
  4182. if(isMatchPresentUser())
  4183. {
  4184. DEBUG_INFO("Cancel present user.\n");
  4185. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4186. {
  4187. setLedMotion(gun_index,LED_ACTION_IDLE);
  4188. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  4189. }
  4190. ShmCharger->isAuthrizing = FALSE;
  4191. }
  4192. }
  4193. else
  4194. {
  4195. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4196. {
  4197. if(getDiffSecNow(startTime[0][TMR_IDX_GUN_DETECT]) < 3)
  4198. setLedMotion(gun_index,LED_ACTION_RFID_PASS);
  4199. else
  4200. setLedMotion(gun_index,LED_ACTION_AUTHED);
  4201. if((((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_IDLE) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_RESERVATION)) && (((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)) || (ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn == ON))) ||
  4202. ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_PREPARING) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B) && (ShmCharger->gun_selectd == gun_index)) ||
  4203. (((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_CHARGING) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_TERMINATING)) && (ShmCharger->gun_selectd == gun_index))
  4204. )
  4205. {
  4206. DEBUG_INFO("Connector-%02d action detect.\n", gun_index);
  4207. ShmCharger->isAuthrizing = FALSE;
  4208. ShmCharger->gun_info[gun_index].rfidReq = ON;
  4209. break;
  4210. }
  4211. }
  4212. }
  4213. }
  4214. else
  4215. {
  4216. DEBUG_INFO("Connector action detect timeout.\n");
  4217. ShmCharger->isAuthrizing = FALSE;
  4218. ShmCharger->isGetAuthResult = TRUE;
  4219. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4220. {
  4221. setLedMotion(gun_index,LED_ACTION_IDLE);
  4222. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  4223. }
  4224. }
  4225. }
  4226. else
  4227. {
  4228. DEBUG_INFO("Authorize fail.\n");
  4229. ShmCharger->isAuthrizing = FALSE;
  4230. ShmCharger->isGetAuthResult = TRUE;
  4231. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4232. {
  4233. ShmCharger->gun_info[gun_index].resultAuthorization = UNVALIDATED_RFID;
  4234. setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
  4235. }
  4236. setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
  4237. sleep(3);
  4238. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4239. {
  4240. setLedMotion(gun_index,LED_ACTION_IDLE);
  4241. }
  4242. }
  4243. }
  4244. }
  4245. }
  4246. }
  4247. //======================================================
  4248. // Main process
  4249. //======================================================
  4250. int main(void)
  4251. {
  4252. //==================================================
  4253. // Create all share memory
  4254. //==================================================
  4255. if(CreatShareMemory()==0)
  4256. {
  4257. DEBUG_ERROR("CreatShareMemory NG\n");
  4258. if(ShmStatusCodeData!=NULL)
  4259. {
  4260. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=1;
  4261. }
  4262. sleep(5);
  4263. system("reboot -f");
  4264. sleep(5);
  4265. system("reboot -f");
  4266. }
  4267. else
  4268. {
  4269. LoadSysConfigAndInfo(&ShmSysConfigAndInfo->SysConfig);
  4270. DEBUG_INFO("CreatShareMemory OK\n");
  4271. }
  4272. if(SpawnTask() != PASS)
  4273. {
  4274. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = ON;
  4275. DEBUG_ERROR("Task spawn fail.\n");
  4276. }
  4277. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  4278. {
  4279. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus = 0xff;
  4280. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].Index = 0xff;
  4281. ShmCharger->gun_info[gun_index].primaryMcuState.rotatory_switch = 0xff;
  4282. ShmCharger->gun_info[gun_index].mcuResetRequest.isMcuResetRequest = ON;
  4283. ShmCharger->gun_info[gun_index].isSetBreatheLedTiming = OFF;
  4284. ShmCharger->gun_info[gun_index].isSetLedBrightness = OFF;
  4285. ShmCharger->gun_selectd = 0;
  4286. }
  4287. //==================================================
  4288. // Main loop
  4289. //==================================================
  4290. for(;;)
  4291. {
  4292. //==============================================
  4293. // Period check for 10 seconds
  4294. //==============================================
  4295. if(getDiffSecNow(startTime[0][TMR_IDX_CHECK_TASK]) > 10)
  4296. {
  4297. //==============================================
  4298. // Check task processing
  4299. //==============================================
  4300. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[0].SystemStatus != SYS_MODE_BOOTING)
  4301. checkTask();
  4302. //==============================================
  4303. // Check connection timeout specification
  4304. //==============================================
  4305. checkConnectionTimeout();
  4306. refreshStartTimer(&startTime[0][TMR_IDX_CHECK_TASK]);
  4307. }
  4308. //==============================================
  4309. // Check remote reset request
  4310. //==============================================
  4311. checkReset();
  4312. //==============================================
  4313. // Connector loop
  4314. //==============================================
  4315. /*
  4316. * TODO:
  4317. * 1. Rotary switch define change with system specification
  4318. */
  4319. // Only process main logic on cabinet
  4320. if(ShmDispenser->gun_info.primaryMcuState.rotatory_switch != ROTARY_SWITCH_E_DISPENSER)
  4321. {
  4322. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4323. {
  4324. //==============================================
  4325. // Synchronize share memory from OCPP struct
  4326. //==============================================
  4327. ShmSysConfigAndInfo->SysInfo.OcppConnStatus = ocpp_get_connection_status();
  4328. //==============================================
  4329. // Check RFID authorization
  4330. //==============================================
  4331. // The user is not allowed to use RFID when the system change to under those modes.
  4332. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_ALARM) &&
  4333. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_FAULT) &&
  4334. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_DEBUG) &&
  4335. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_UPDATE) &&
  4336. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_BOOTING) &&
  4337. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_COMPLETE) &&
  4338. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_MAINTAIN))
  4339. {
  4340. checkRfidAuthrize();
  4341. }
  4342. //==============================================
  4343. // Something need run in Idle mode
  4344. //==============================================
  4345. if(((ShmSysConfigAndInfo->SysInfo.AcChargingData[0].SystemStatus==SYS_MODE_IDLE) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[0].SystemStatus==SYS_MODE_ALARM) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[0].SystemStatus==SYS_MODE_DEBUG)) &&
  4346. ((modelnameInfo.GetGunCount==2)?((ShmSysConfigAndInfo->SysInfo.AcChargingData[1].SystemStatus==SYS_MODE_IDLE) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[1].SystemStatus==SYS_MODE_ALARM) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[1].SystemStatus==SYS_MODE_DEBUG)):true) &&
  4347. ((modelnameInfo.GetGunCount==3)?((ShmSysConfigAndInfo->SysInfo.AcChargingData[2].SystemStatus==SYS_MODE_IDLE) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[2].SystemStatus==SYS_MODE_ALARM) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[2].SystemStatus==SYS_MODE_DEBUG)):true))
  4348. {
  4349. // Check restore factory setting request
  4350. if(ShmSysConfigAndInfo->SysInfo.FactoryConfiguration)
  4351. {
  4352. // Set led to initial
  4353. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4354. {
  4355. setLedMotion(gun_index,LED_ACTION_INIT);
  4356. }
  4357. sleep(5);
  4358. system("cd /root;./Module_FactoryConfig -m");
  4359. system("rm -f /Storage/OCPP/OCPPConfiguration");
  4360. system("sync");
  4361. sleep(5);
  4362. system("reboot -f");
  4363. sleep(5);
  4364. system("reboot -f");
  4365. }
  4366. // Check upgrade firmware request
  4367. if(ShmSysConfigAndInfo->SysInfo.FirmwareUpdate ||
  4368. ocpp_get_update_firmware_req())
  4369. {
  4370. // If available memory too small, free memory cache first
  4371. if(getAvailableMemory() < (200*1024*1024))
  4372. {
  4373. DEBUG_INFO("Available memory (%.2f Bytes) less than 200 MBytes, free cache first.\n", getAvailableMemory()/(1024*1024.0));
  4374. system("echo 3 > /proc/sys/vm/drop_caches");
  4375. }
  4376. ShmCharger->isUpdateSuccess = NO;
  4377. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4378. {
  4379. setLedMotion(gun_index,LED_ACTION_MAINTAIN);
  4380. setChargerMode(gun_index, SYS_MODE_UPDATE);
  4381. }
  4382. }
  4383. }
  4384. //==========================================
  4385. // Power saving logic
  4386. //==========================================
  4387. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus > SYS_MODE_BOOTING)
  4388. {
  4389. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)
  4390. {
  4391. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_STATE_B]);
  4392. }
  4393. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_ALARM) ||
  4394. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_FAULT) ||
  4395. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_UPDATE) ||
  4396. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_MAINTAIN) ||
  4397. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_CHARGING) ||
  4398. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_TERMINATING) ||
  4399. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_COMPLETE))
  4400. {
  4401. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
  4402. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_RFID]);
  4403. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_METER]);
  4404. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]);
  4405. }
  4406. else
  4407. {
  4408. if((gpio_get_value(GPIO_IN_WAKEUP) == OFF) ||
  4409. (ShmCharger->gun_info[gun_index].GPIO_Input.Button_Mode_Switch == ON) ||
  4410. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus != ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus) ||
  4411. (((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_IDLE) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_PREPARING) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_RESERVATION)) &&
  4412. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B) &&
  4413. (getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_STATE_B]) < 10)))
  4414. {
  4415. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
  4416. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_RFID]);
  4417. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_METER]);
  4418. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]);
  4419. if(((gpio_get_value(GPIO_IN_WAKEUP) == OFF) || (ShmCharger->gun_info[gun_index].GPIO_Input.Button_Mode_Switch == ON)) &&
  4420. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_IDLE) &&
  4421. (getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_CHECK_POWER_CONSUMPTION]) > TIMEOUT_SPEC_CEHCK_POWER_CONSUMPTION))
  4422. {
  4423. ShmCharger->gun_info[gun_index].isCheckPowerConsumption = YES;
  4424. refreshStartTimer(&startTime[gun_index][TMR_IDX_LCM_POWER_CONSUMPTION]);
  4425. }
  4426. }
  4427. else
  4428. {
  4429. refreshStartTimer(&startTime[gun_index][TMR_IDX_CHECK_POWER_CONSUMPTION]);
  4430. if((getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_LCM_POWER_CONSUMPTION]) > TIMEOUT_SPEC_CEHCK_POWER_CONSUMPTION))
  4431. {
  4432. ShmCharger->gun_info[gun_index].isCheckPowerConsumption = NO;
  4433. }
  4434. }
  4435. }
  4436. if(getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_LCD]) > TIMEOUT_SPEC_POWERSAVING_LCD)
  4437. {
  4438. if(ShmCharger->isLcdOn == ON)
  4439. {
  4440. DEBUG_INFO("LCD into power saving...%d\n", getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_LCD]));
  4441. ShmCharger->isLcdOn = OFF;
  4442. }
  4443. }
  4444. else
  4445. {
  4446. if(ShmCharger->isLcdOn == OFF)
  4447. {
  4448. DEBUG_INFO("LCD exit power saving...%d\n", getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_LCD]));
  4449. ShmCharger->isLcdOn = ON;
  4450. }
  4451. }
  4452. if(getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_RFID]) > TIMEOUT_SPEC_POWERSAVING_RFID)
  4453. {
  4454. if(gpio_get_value(GPIO_OUT_RST_RFID) == ON)
  4455. {
  4456. DEBUG_INFO("RFID into power saving...%d\n", getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_RFID]));
  4457. gpio_set_value(GPIO_OUT_RST_RFID, OFF);
  4458. }
  4459. }
  4460. else
  4461. {
  4462. if(gpio_get_value(GPIO_OUT_RST_RFID) == OFF)
  4463. {
  4464. DEBUG_INFO("RFID exit power saving...%d\n", getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_RFID]));
  4465. gpio_set_value(GPIO_OUT_RST_RFID, ON);
  4466. }
  4467. }
  4468. if(getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_METER]) > TIMEOUT_SPEC_POWERSAVING_METER)
  4469. {
  4470. if(ShmCharger->gun_info[gun_index].isMeterOn)
  4471. {
  4472. DEBUG_INFO("Meter into power saving...%d\n", getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_METER]));
  4473. ShmCharger->gun_info[gun_index].isMeterOn = OFF;
  4474. }
  4475. }
  4476. else
  4477. {
  4478. if(!ShmCharger->gun_info[gun_index].isMeterOn)
  4479. {
  4480. DEBUG_INFO("Meter exit power saving...%d\n", getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_METER]));
  4481. ShmCharger->gun_info[gun_index].isMeterOn = ON;
  4482. }
  4483. }
  4484. if(getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]) > TIMEOUT_SPEC_POWERSAVING_LED_STATUS)
  4485. {
  4486. if(ShmCharger->gun_info[gun_index].isSleepOn == NO)
  4487. {
  4488. DEBUG_INFO("LED status into power saving...%d\n", getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]));
  4489. ShmCharger->gun_info[gun_index].isSleepOn = YES;
  4490. }
  4491. }
  4492. else
  4493. {
  4494. if(ShmCharger->gun_info[gun_index].isSleepOn == YES)
  4495. {
  4496. DEBUG_INFO("LED status exit power saving...%d\n", getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]));
  4497. ShmCharger->gun_info[gun_index].isSleepOn = NO;
  4498. }
  4499. }
  4500. }
  4501. //==========================================
  4502. // Synchronize current rating value from MCU
  4503. //==========================================
  4504. ShmSysConfigAndInfo->SysConfig.RatingCurrent = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
  4505. //==========================================
  4506. // Assign connector location index for OCPP
  4507. //==========================================
  4508. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].Index = gun_index;
  4509. //==========================================
  4510. // Synchronize present charging power
  4511. //==========================================
  4512. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount == 1)
  4513. {
  4514. if(ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON)
  4515. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingVoltage*ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrent)/1000.0;
  4516. else
  4517. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = 0;
  4518. }
  4519. else
  4520. {
  4521. if(ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON)
  4522. {
  4523. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = (((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingVoltage*ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrent)/1000.0) +
  4524. ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingVoltageL2*ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrentL2)/1000.0) +
  4525. ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingVoltageL3*ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrentL3)/1000.0));
  4526. }
  4527. else
  4528. {
  4529. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = 0;
  4530. }
  4531. }
  4532. //==========================================
  4533. // Check initialization "PASS" or "FAIL"
  4534. //==========================================
  4535. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[0].SystemStatus != SYS_MODE_BOOTING)
  4536. {
  4537. // Alarm event check
  4538. if((ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode>0))
  4539. {
  4540. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_ALARM)
  4541. {
  4542. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_UPDATE)
  4543. {
  4544. setChargerMode(gun_index, SYS_MODE_ALARM);
  4545. }
  4546. }
  4547. }
  4548. }
  4549. //==========================================
  4550. // Reservation request check
  4551. //==========================================
  4552. checkReservation(gun_index);
  4553. //==========================================
  4554. // Change availability check
  4555. //==========================================
  4556. checkAvailability(gun_index);
  4557. if(ShmCharger->gun_info[gun_index].isOperactive)
  4558. {
  4559. if(isMode(gun_index, SYS_MODE_MAINTAIN))
  4560. {
  4561. setChargerMode(gun_index, SYS_MODE_IDLE);
  4562. }
  4563. }
  4564. else
  4565. {
  4566. if(isMode(gun_index, SYS_MODE_IDLE))
  4567. {
  4568. setChargerMode(gun_index, SYS_MODE_MAINTAIN);
  4569. }
  4570. }
  4571. //==========================================
  4572. // Unlock Connector signal check
  4573. //==========================================
  4574. checkUnlocker(gun_index);
  4575. //==========================================
  4576. // Connector process
  4577. //==========================================
  4578. switch(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus)
  4579. {
  4580. case SYS_MODE_BOOTING:
  4581. if(isModeChange(gun_index))
  4582. {
  4583. setLedMotion(gun_index,LED_ACTION_INIT);
  4584. //CSU Initialization & task spawn
  4585. if(Initialization(gun_index) != PASS)
  4586. {
  4587. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = ON;
  4588. }
  4589. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
  4590. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_RFID]);
  4591. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_METER]);
  4592. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_STATE_B]);
  4593. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]);
  4594. refreshStartTimer(&startTime[gun_index][TMR_IDX_LCM_POWER_CONSUMPTION]);
  4595. }
  4596. if(ShmCharger->gun_info[gun_index].mcuFlag.isReadFwVerPass &&
  4597. ShmCharger->gun_info[gun_index].mcuFlag.isSetModelNamePass &&
  4598. ShmCharger->gun_info[gun_index].mcuFlag.isSetSerialNumberPass)
  4599. {
  4600. // OCPP BootNotification info set
  4601. DEBUG_INFO("==========================================\n");
  4602. DEBUG_INFO("System ID: %s\n",ShmSysConfigAndInfo->SysConfig.SystemId);
  4603. DEBUG_INFO("==========================================\n");
  4604. DEBUG_INFO("=== OCPP BootNotification information ====\n");
  4605. ocpp_boot_info_sync();
  4606. DEBUG_INFO("OcppServerURL: %s\n",ShmSysConfigAndInfo->SysConfig.OcppServerURL);
  4607. DEBUG_INFO("ChargeBoxId: %s\n",ShmSysConfigAndInfo->SysConfig.ChargeBoxId);
  4608. DEBUG_INFO("ChargePointVendor: %s\n",ShmSysConfigAndInfo->SysConfig.chargePointVendor);
  4609. DEBUG_INFO("==========================================\n");
  4610. DEBUG_INFO("========== Set Wifi information ==========\n");
  4611. DEBUG_INFO("Wifi mode: %d\n", ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode);
  4612. DEBUG_INFO("Wifi SSID: %s\n", ShmSysConfigAndInfo->SysConfig.AthInterface.WifiSsid);
  4613. DEBUG_INFO("Wifi password: %s\n", ShmSysConfigAndInfo->SysConfig.AthInterface.WifiPassword);
  4614. DEBUG_INFO("==========================================\n");
  4615. // Set max current to rating current
  4616. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
  4617. // Default Ethernet / Wifi / 4G to 1:disconnected
  4618. switch(ShmSysConfigAndInfo->SysConfig.ModelName[10])
  4619. {
  4620. case 'E':
  4621. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
  4622. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = OFF;
  4623. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = OFF;
  4624. break;
  4625. case 'W':
  4626. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
  4627. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = ON;
  4628. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = OFF;
  4629. break;
  4630. case 'T':
  4631. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
  4632. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = OFF;
  4633. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = ON;
  4634. break;
  4635. case 'D':
  4636. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
  4637. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = ON;
  4638. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = ON;
  4639. break;
  4640. }
  4641. // Default LCM brightness to 100
  4642. ShmCharger->isLcdOn = ON;
  4643. // Defaule led status to not sleep mode
  4644. ShmCharger->gun_info[gun_index].isSleepOn = NO;
  4645. // If Web Server OPCC URL is empty kill Module_OcppBackend
  4646. if((strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0) || ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharging)
  4647. {
  4648. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0)
  4649. DEBUG_INFO("URL is empty kill Module_OcppBackend...\n");
  4650. if(ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharging)
  4651. DEBUG_INFO("Local power sharing enable kill Module_OcppBackend...\n");
  4652. system ("pkill OcppBackend");
  4653. }
  4654. // If rotate switch equal zero, the system needs to change Debug mode
  4655. if(ShmCharger->gun_info[gun_index].primaryMcuState.rotatory_switch == 0)
  4656. setChargerMode(gun_index, SYS_MODE_DEBUG);
  4657. else
  4658. {
  4659. if((isGpioInitialized(GPIO_OUT_RST_RFID) == PASS) &&
  4660. (isGpioInitialized(GPIO_IN_WAKEUP) == PASS) &&
  4661. (isGpioInitialized(GPIO_OUT_RST_ETH) == PASS) &&
  4662. (isGpioInitialized(GPIO_OUT_RST_4G) == PASS) &&
  4663. (isGpioInitialized(GPIO_OUT_RST_QCA) == PASS))
  4664. {
  4665. //==================================================
  4666. // Get firmware version
  4667. //==================================================
  4668. sleep(3);
  4669. get_firmware_version(gun_index);
  4670. setChargerMode(gun_index, SYS_MODE_IDLE);
  4671. }
  4672. }
  4673. }
  4674. break;
  4675. case SYS_MODE_IDLE:
  4676. if(isModeChange(gun_index))
  4677. {
  4678. setLedMotion(gun_index,LED_ACTION_IDLE);
  4679. setRelay(gun_index, OFF);
  4680. setRequest(gun_index,OFF);
  4681. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  4682. ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart = OFF;
  4683. ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop = OFF;
  4684. ocpp_set_remotestart(gun_index, OFF);
  4685. ocpp_set_remotestop(gun_index, OFF);
  4686. ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode = 0x00;
  4687. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = 0;
  4688. presentChargedEnergyClear(gun_index);
  4689. ShmCharger->gun_info[gun_index].targetCurrent = 0xFF;
  4690. ocpp_set_unlocker_req(gun_index, OFF);
  4691. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId = -1;
  4692. // Response StopTransactionConf
  4693. ocpp_set_stoptransaction_conf(gun_index, OFF);
  4694. memset(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId));
  4695. ShmCharger->gun_info[gun_index].isDoEvReadyOnce = OFF;
  4696. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  4697. DB_Check_Record_Buf(localDb, gun_index);
  4698. }
  4699. // LED status in Idle mode
  4700. if(!ShmCharger->isAuthrizing)
  4701. {
  4702. if(ocpp_get_isRemoteStartWait())
  4703. {
  4704. ShmCharger->gun_info[gun_index].isSleepOn = OFF;
  4705. setLedMotion(gun_index, LED_ACTION_AUTHED);
  4706. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
  4707. }
  4708. else
  4709. {
  4710. if(ShmSysConfigAndInfo->SysInfo.OcppConnStatus == ON)
  4711. {
  4712. if(ShmCharger->gun_info[gun_index].rfidReq == OFF)
  4713. {
  4714. if(ShmCharger->gun_info[gun_index].isSleepOn == NO)
  4715. setLedMotion(gun_index, LED_ACTION_IDLE_BACKEND_CONNECTED);
  4716. else
  4717. setLedMotion(gun_index, LED_ACTION_IDLE_BACKEND_CONNECTED_SLEEP);
  4718. }
  4719. }
  4720. else
  4721. {
  4722. if(ShmCharger->gun_info[gun_index].rfidReq == OFF)
  4723. {
  4724. if(ShmCharger->gun_info[gun_index].isSleepOn == NO)
  4725. setLedMotion(gun_index, LED_ACTION_IDLE_BACKEND_DISCONNECTED);
  4726. else
  4727. setLedMotion(gun_index, LED_ACTION_IDLE_BACKEND_DISCONNECTED_SLEEP);
  4728. }
  4729. }
  4730. }
  4731. }
  4732. if(((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B)) ||
  4733. ((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)) ||
  4734. ((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) && (ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn == ON)) ||
  4735. (ShmCharger->gun_info[gun_index].rfidReq == ON) ||
  4736. (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart == ON) ||
  4737. (ocpp_get_remotestart(gun_index) == ON) ||
  4738. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStart == ON))
  4739. {
  4740. if((ShmCharger->gun_info[gun_index].rfidReq == ON))
  4741. {
  4742. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_RFID;
  4743. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_ISO14443;
  4744. DEBUG_INFO("Start Method : RFID...\n");
  4745. }
  4746. else if(ocpp_get_remotestart(gun_index))
  4747. {
  4748. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_BACKEND;
  4749. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_Central;
  4750. ocpp_copy_userid_from_remotestart(gun_index);
  4751. setSpeaker(ON, SPEAKER_SHORT);
  4752. DEBUG_INFO("Start Method : BACKEND...\n");
  4753. }
  4754. else if(ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart == ON)
  4755. {
  4756. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_BLE;
  4757. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_Local;
  4758. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmCharger->gun_info[gun_index].bleLoginCentralId.id, ARRAY_SIZE(ShmCharger->gun_info[gun_index].bleLoginCentralId.id));
  4759. setSpeaker(ON, SPEAKER_SHORT);
  4760. DEBUG_INFO("Start Method : BLE...\n");
  4761. }
  4762. else
  4763. {
  4764. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_FREE;
  4765. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_NoAuthorization;
  4766. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmSysConfigAndInfo->SysConfig.SerialNumber, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SerialNumber));
  4767. setSpeaker(ON, SPEAKER_SHORT);
  4768. DEBUG_INFO("Start Method : FREE...\n");
  4769. }
  4770. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  4771. ocpp_set_remotestart(gun_index, OFF);
  4772. ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart = OFF;
  4773. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStart = OFF;
  4774. // Get target current
  4775. ocpp_set_profile_req(gun_index, ON);
  4776. sleep(1);
  4777. checkChargingProfileLimit(gun_index);
  4778. if(ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent == 0)
  4779. {
  4780. ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmCharger->gun_info[gun_index].primaryMcuState.rating_current)?ShmCharger->gun_info[gun_index].primaryMcuState.rating_current:ShmCharger->gun_info[gun_index].targetCurrent);
  4781. }
  4782. else
  4783. {
  4784. ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent)?ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent:ShmCharger->gun_info[gun_index].targetCurrent);
  4785. }
  4786. setChargerMode(gun_index, SYS_MODE_AUTHORIZING);
  4787. }
  4788. else
  4789. {}
  4790. break;
  4791. case SYS_MODE_AUTHORIZING:
  4792. if(isModeChange(gun_index))
  4793. {
  4794. refreshStartTimer(&startTime[gun_index][TMR_IDX_AUTH]);
  4795. if(ocpp_isAuthorizeRemoteStart() && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod == START_METHOD_BACKEND))
  4796. {
  4797. DEBUG_INFO("Remote start request authorize.\n");
  4798. ocpp_set_auth_req(ON, "ISO14443");
  4799. }
  4800. }
  4801. if(getDiffSecNow(startTime[gun_index][TMR_IDX_AUTH]) > TIMEOUT_SPEC_AUTH)
  4802. {
  4803. // Authorization timeout process.
  4804. setSpeaker(ON, SPEAKER_INTERVAL_3COUNT);
  4805. setLedMotion(gun_index, LED_ACTION_RFID_FAIL);
  4806. sleep(3);
  4807. setChargerMode(gun_index, SYS_MODE_IDLE);
  4808. DEBUG_WARN("Authorize timeout !!!\n");
  4809. }
  4810. else
  4811. {
  4812. switch(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod)
  4813. {
  4814. case START_METHOD_BACKEND:
  4815. if(ocpp_isAuthorizeRemoteStart())
  4816. {
  4817. if(ocpp_get_auth_conf())
  4818. {
  4819. if(ocpp_get_auth_result(gun_index))
  4820. {
  4821. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  4822. DEBUG_INFO("Authorize pass.\n");
  4823. setSpeaker(ON, SPEAKER_SHORT);
  4824. setLedMotion(gun_index, LED_ACTION_RFID_PASS);
  4825. setChargerMode(gun_index, SYS_MODE_PREPARING);
  4826. }
  4827. else
  4828. {
  4829. DEBUG_INFO("Authorize fail.\n");
  4830. setSpeaker(ON, SPEAKER_INTERVAL_3COUNT);
  4831. setLedMotion(gun_index, LED_ACTION_RFID_FAIL);
  4832. sleep(3);
  4833. setChargerMode(gun_index, SYS_MODE_IDLE);
  4834. }
  4835. ocpp_set_auth_conf(OFF);
  4836. }
  4837. }
  4838. else
  4839. {
  4840. setChargerMode(gun_index, SYS_MODE_PREPARING);
  4841. }
  4842. break;
  4843. case START_METHOD_RFID:
  4844. case START_METHOD_BLE:
  4845. case START_METHOD_FREE:
  4846. default:
  4847. setChargerMode(gun_index, SYS_MODE_PREPARING);
  4848. break;
  4849. }
  4850. }
  4851. break;
  4852. case SYS_MODE_PREPARING:
  4853. if(isModeChange(gun_index))
  4854. {
  4855. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  4856. setLedMotion(gun_index, LED_ACTION_AUTHED);
  4857. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  4858. if(ShmCharger->isCcsEnable)refreshStartTimer(&startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]);
  4859. }
  4860. // If control pilot detect Bx, skip watch dog time out.
  4861. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B) ||
  4862. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C))
  4863. {
  4864. if(!getRequest(gun_index))
  4865. {
  4866. setRequest(gun_index, ON);
  4867. setLedMotion(gun_index, LED_ACTION_CONNECTED);
  4868. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  4869. DEBUG_INFO("Set Request On.\n");
  4870. }
  4871. switch(ShmCharger->gun_info[gun_index].ccsHandshakeState)
  4872. {
  4873. case HANDSHAKE_DUTY_5:
  4874. break;
  4875. case HANDSHAKE_DUTY_5_CHECK:
  4876. refreshStartTimer(&startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]);
  4877. DEBUG_INFO("HLC slac handshake start.\n");
  4878. break;
  4879. case HANDSHAKE_CCS:
  4880. //CCS handshake timeout
  4881. if(getDiffSecNow(startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]) > TIMEOUT_SPEC_BS_HLC_HANDSHAKE)
  4882. {
  4883. DEBUG_INFO("HLC %d secs slac handshake timeout.\n", TIMEOUT_SPEC_BS_HLC_HANDSHAKE);
  4884. }
  4885. if((ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission == OFF) && (ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty != CCS_PWM_DUTY_5))
  4886. {
  4887. DEBUG_INFO("Wait CCS give up negotiagting.\n");
  4888. }
  4889. //CCS status check
  4890. if((16 < ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus) && (ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus < 254))
  4891. {
  4892. DEBUG_INFO("Enter HLC Mode charging.\n");
  4893. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  4894. }
  4895. break;
  4896. case HANDSHAKE_CP_STATE_E:
  4897. //if(ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)
  4898. {
  4899. // restore normal CP PWM duty
  4900. // Determine max charging current to MCU
  4901. DEBUG_INFO("Determine max charging current to MCU.\n");
  4902. ocpp_set_profile_req(gun_index, ON);
  4903. sleep(1);
  4904. checkChargingProfileLimit(gun_index);
  4905. if(ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent == 0)
  4906. {
  4907. ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmCharger->gun_info[gun_index].primaryMcuState.rating_current)?ShmCharger->gun_info[gun_index].primaryMcuState.rating_current:ShmCharger->gun_info[gun_index].targetCurrent);
  4908. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmCharger->gun_info[gun_index].primaryMcuState.rating_current)?ShmCharger->gun_info[gun_index].primaryMcuState.rating_current:ShmCharger->gun_info[gun_index].targetCurrent);
  4909. }
  4910. else
  4911. {
  4912. ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent)?ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent:ShmCharger->gun_info[gun_index].targetCurrent);
  4913. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent)?ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent:ShmCharger->gun_info[gun_index].targetCurrent);
  4914. }
  4915. refreshStartTimer(&startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]);
  4916. }
  4917. break;
  4918. case HANDSHAKE_SET_MAX_CURRENT:
  4919. //if(ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)
  4920. {
  4921. DEBUG_INFO("Enter BS Mode charging.\n");
  4922. //for EV READY 30 secs didn't start charging to STATE E
  4923. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  4924. }
  4925. break;
  4926. case HANDSHAKE_BS_MODE:
  4927. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  4928. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)
  4929. setRelay(gun_index,ON);
  4930. if((ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON))
  4931. {
  4932. ocpp_set_unlocker_req(gun_index, OFF);
  4933. presentChargedEnergyClear(gun_index);
  4934. getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime);
  4935. ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption;
  4936. ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption;
  4937. ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption;
  4938. ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption;
  4939. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==1)
  4940. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  4941. else
  4942. {
  4943. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[0] = (ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption/10000.0);
  4944. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[1] = (ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption/10000.0);
  4945. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[2] = (ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption/10000.0);
  4946. }
  4947. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  4948. ocpp_copy_userid_to_starttransaction(gun_index);
  4949. ocpp_set_starttransaction_req(gun_index, ON);
  4950. refreshStartTimer(&startChargingTime[gun_index]);
  4951. setChargerMode(gun_index, SYS_MODE_CHARGING);
  4952. }
  4953. break;
  4954. case HANDSHAKE_HLC_MODE:
  4955. if(ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_START_MODE)
  4956. {
  4957. setRelay(gun_index,ON);
  4958. ShmCharger->gun_info[gun_index].isCCSStartTransation = ON;
  4959. }
  4960. if((ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON) &&
  4961. (ShmCharger->gun_info[gun_index].isCCSStartTransation == ON))
  4962. {
  4963. ocpp_set_unlocker_req(gun_index, OFF);
  4964. presentChargedEnergyClear(gun_index);
  4965. getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime);
  4966. ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption;
  4967. ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption;
  4968. ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption;
  4969. ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption;
  4970. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==1)
  4971. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  4972. else
  4973. {
  4974. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[0] = (ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption/10000.0);
  4975. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[1] = (ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption/10000.0);
  4976. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[2] = (ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption/10000.0);
  4977. }
  4978. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  4979. ocpp_copy_userid_to_starttransaction(gun_index);
  4980. ocpp_set_starttransaction_req(gun_index, ON);
  4981. ShmCharger->gun_info[gun_index].isCCSStartTransation = OFF;
  4982. setChargerMode(gun_index, SYS_MODE_CHARGING);
  4983. refreshStartTimer(&startChargingTime[gun_index]);
  4984. refreshStartTimer(&startTime[gun_index][TMR_IDX_CCS_HEARTBEAT_COUNT_RESET]);
  4985. }
  4986. //120 sec timeout
  4987. if(getDiffSecNow(startTime[gun_index][TMR_IDX_HANDSHAKING]) > TIMEOUT_SPEC_CCS_HANDSHAKE)
  4988. {
  4989. setLedMotion(gun_index, LED_ACTION_HANDSHAKE_FAIL);
  4990. if(getDiffSecNow(startTime[gun_index][TMR_IDX_HANDSHAKING]) > (TIMEOUT_SPEC_CCS_HANDSHAKE+5))
  4991. {
  4992. DEBUG_INFO("CCS 120 secs handshake timeout, change to BS Mode...\n");
  4993. if((ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission == OFF) && (ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty != CCS_PWM_DUTY_5))
  4994. {
  4995. DEBUG_INFO("Wait CCS give up negotiagting.\n");
  4996. }
  4997. }
  4998. }
  4999. break;
  5000. default:
  5001. break;
  5002. }
  5003. }
  5004. else if(ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEMode)
  5005. {
  5006. DEBUG_INFO("Enter Socket-E Mode charging.\n");
  5007. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_SOCKETE;
  5008. if(ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn == ON)
  5009. setRelay(gun_index,ON);
  5010. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  5011. ocpp_copy_userid_to_starttransaction(gun_index);
  5012. ocpp_set_starttransaction_req(gun_index, ON);
  5013. refreshStartTimer(&startChargingTime[gun_index]);
  5014. setChargerMode(gun_index, SYS_MODE_CHARGING);
  5015. }
  5016. // Unplug charging gun to Idle mode
  5017. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A) && (ShmCharger->gun_info[gun_index].isGunPlugged == YES))
  5018. {
  5019. DEBUG_INFO("Charging gun is plugged before.\n");
  5020. }
  5021. // Use RFID card to stop handshaking
  5022. if((ShmCharger->gun_info[gun_index].rfidReq == ON) && isMatchPresentUser(gun_index))
  5023. {
  5024. DEBUG_INFO("Use RFID card to stop handshaking.\n");
  5025. }
  5026. else
  5027. {
  5028. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  5029. }
  5030. if(getDiffSecNow(startTime[gun_index][TMR_IDX_HANDSHAKING]) > ShmCharger->timeoutSpec.Present_Timeout_Spec)
  5031. {
  5032. setLedMotion(gun_index, LED_ACTION_HANDSHAKE_FAIL);
  5033. if(getDiffSecNow(startTime[gun_index][TMR_IDX_HANDSHAKING]) > (ShmCharger->timeoutSpec.Present_Timeout_Spec+5))
  5034. {
  5035. DEBUG_INFO("Handshaking timeout...\n");
  5036. setChargerMode(gun_index, SYS_MODE_IDLE);
  5037. }
  5038. }
  5039. break;
  5040. case SYS_MODE_CHARGING:
  5041. if(isModeChange(gun_index))
  5042. {
  5043. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  5044. //ftime(&startChargingTime[gun_index]);
  5045. refreshStartTimer(&startTime[gun_index][TMR_IDX_LOGPPRINTOUT]);
  5046. refreshStartTimer(&startTime[gun_index][TMR_IDX_PROFILE_PREPARE]);
  5047. refreshStartTimer(&startTime[gun_index][TMR_IDX_PWN_CHANGE]);
  5048. ocpp_set_auth_req(OFF);
  5049. ocpp_reset_smartcharging_profileId(gun_index);
  5050. ocpp_set_profile_req(gun_index, ON);
  5051. ShmCharger->gun_info[gun_index].isChargerStopByCondition = NO;
  5052. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  5053. }
  5054. //if time up, clear CCS MSG count
  5055. if((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) &&
  5056. (getDiffSecNow(startTime[gun_index][TMR_IDX_CCS_HEARTBEAT_COUNT_RESET]) > TIMEOUT_SPEC_CCS_HEARTBEAT_COUNT_RESET))
  5057. {
  5058. refreshStartTimer(&startTime[gun_index][TMR_IDX_CCS_HEARTBEAT_COUNT_RESET]);
  5059. if(ShmCharger->gun_info[gun_index].acCcsInfo.CcsHeartBeat > 0)
  5060. {
  5061. ShmCharger->gun_info[gun_index].acCcsInfo.CcsHeartBeat = 0;
  5062. }
  5063. else
  5064. {
  5065. DEBUG_INFO("CCS could not get MSG from car.\n");
  5066. }
  5067. }
  5068. if((ShmCharger->gun_info[gun_index].rfidReq == ON) ||
  5069. (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop == ON) ||
  5070. ocpp_get_remotestop(gun_index) ||
  5071. (ocpp_get_connection_status() && !ocpp_get_starttransaction_result(gun_index)) ||
  5072. ((ShmCharger->gun_info[gun_index].chargingMode != CHARGING_MODE_SOCKETE) && ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState != CP_STATE_C) ||
  5073. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE) && !ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn) ||
  5074. ocpp_get_reset_req() ||
  5075. ocpp_get_unlocker_req(gun_index) ||
  5076. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop == ON) ||
  5077. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && (ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_STOP_MODE)) ||
  5078. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_RENEGOTIATE_MODE) ||
  5079. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_STANDBY_MODE))
  5080. {
  5081. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  5082. }
  5083. else
  5084. {
  5085. // Charging session info calculation
  5086. setLedMotion(gun_index,LED_ACTION_CHARGING);
  5087. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==1)
  5088. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  5089. else
  5090. {
  5091. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[0] = (ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption/10000.0);
  5092. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[1] = (ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption/10000.0);
  5093. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[2] = (ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption/10000.0);
  5094. }
  5095. refreshStartTimer(&endChargingTime[gun_index]);
  5096. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = getDiffSecBetween(startChargingTime[gun_index], endChargingTime[gun_index]);
  5097. presentChargedEnergyUpdate(gun_index);
  5098. // Response StartTransactionConf
  5099. ocpp_set_starttransaction_conf(gun_index, OFF);
  5100. // Charging profile preparation
  5101. if(getDiffSecNow(startTime[gun_index][TMR_IDX_PROFILE_PREPARE]) > TIMEOUT_SPEC_PROFILE_PREPARE)
  5102. {
  5103. if(!ocpp_get_profile_conf(gun_index))
  5104. {
  5105. ocpp_set_profile_req(gun_index, ON);
  5106. refreshStartTimer(&startTime[gun_index][TMR_IDX_PROFILE_PREPARE]);
  5107. }
  5108. else
  5109. {
  5110. ocpp_set_profile_conf(gun_index, OFF);
  5111. }
  5112. }
  5113. // Checking profile id > 0 and current time is between charging profile validFrom & validTo
  5114. checkChargingProfileLimit(gun_index);
  5115. // Charging session target current check if OCPP disconnect and power sharing server connected
  5116. if(!ocpp_get_connection_status() && ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharging)
  5117. {
  5118. if(ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer)
  5119. ShmCharger->gun_info[gun_index].targetCurrent = ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent;
  5120. else
  5121. {
  5122. if(ShmCharger->gun_info[gun_index].targetCurrent != 0)
  5123. DEBUG_WARN("Disconnect from power sharing server, target current set to 0.\n");
  5124. ShmCharger->gun_info[gun_index].targetCurrent = 0;
  5125. }
  5126. }
  5127. // Determine max charging current to MCU
  5128. if(ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent == 0)
  5129. {
  5130. ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmCharger->gun_info[gun_index].primaryMcuState.rating_current)?ShmCharger->gun_info[gun_index].primaryMcuState.rating_current:ShmCharger->gun_info[gun_index].targetCurrent);
  5131. if((ShmCharger->gun_info[gun_index].targetCurrent != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current) ||
  5132. (ShmCharger->gun_info[gun_index].primaryMcuState.current_limit != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current))
  5133. {
  5134. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  5135. {
  5136. if(getDiffSecNow(startTime[gun_index][TMR_IDX_PWN_CHANGE]) > TIMEOUT_SPEC_PWN_CHANGE)
  5137. {
  5138. if((6 <= ShmCharger->gun_info[gun_index].targetCurrent))
  5139. {
  5140. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmCharger->gun_info[gun_index].primaryMcuState.rating_current)?ShmCharger->gun_info[gun_index].primaryMcuState.rating_current:ShmCharger->gun_info[gun_index].targetCurrent);
  5141. }
  5142. else if((1 <= ShmCharger->gun_info[gun_index].targetCurrent) && (ShmCharger->gun_info[gun_index].targetCurrent < 6))
  5143. {
  5144. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = 6;
  5145. }
  5146. else
  5147. {
  5148. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = 100;
  5149. }
  5150. refreshStartTimer(&startTime[gun_index][TMR_IDX_PWN_CHANGE]);
  5151. }
  5152. }
  5153. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  5154. {
  5155. ShmCharger->gun_info[gun_index].acCcsInfo.EVSEMaxCurrent = (float)((ShmCharger->gun_info[gun_index].targetCurrent > ShmCharger->gun_info[gun_index].primaryMcuState.rating_current)?ShmCharger->gun_info[gun_index].primaryMcuState.rating_current:ShmCharger->gun_info[gun_index].targetCurrent);
  5156. }
  5157. }
  5158. }
  5159. else
  5160. {
  5161. ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent)?ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent:ShmCharger->gun_info[gun_index].targetCurrent);
  5162. if((ShmCharger->gun_info[gun_index].targetCurrent != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current) ||
  5163. (ShmCharger->gun_info[gun_index].primaryMcuState.current_limit != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current))
  5164. {
  5165. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  5166. {
  5167. if(getDiffSecNow(startTime[gun_index][TMR_IDX_PWN_CHANGE]) > TIMEOUT_SPEC_PWN_CHANGE)
  5168. {
  5169. if((6 <= ShmCharger->gun_info[gun_index].targetCurrent))
  5170. {
  5171. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent)?ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent:ShmCharger->gun_info[gun_index].targetCurrent);
  5172. }
  5173. else if((1 <= ShmCharger->gun_info[gun_index].targetCurrent) && (ShmCharger->gun_info[gun_index].targetCurrent < 6))
  5174. {
  5175. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = 6;
  5176. }
  5177. else
  5178. {
  5179. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = 100;
  5180. }
  5181. refreshStartTimer(&startTime[gun_index][TMR_IDX_PWN_CHANGE]);
  5182. }
  5183. }
  5184. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  5185. {
  5186. ShmCharger->gun_info[gun_index].acCcsInfo.EVSEMaxCurrent = (float)((ShmCharger->gun_info[gun_index].targetCurrent > ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent)?ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent:ShmCharger->gun_info[gun_index].targetCurrent);
  5187. }
  5188. }
  5189. }
  5190. // Charging session local limit condition check
  5191. if(ocpp_get_connection_status())
  5192. {
  5193. // On-line max condition check
  5194. if((ShmSysConfigAndInfo->SysConfig.MaxChargingDuration > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60)))
  5195. {
  5196. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  5197. {
  5198. setRelay(gun_index, OFF);
  5199. ShmCharger->gun_info[gun_index].isChargerStopByCondition = YES;
  5200. }
  5201. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  5202. {
  5203. setRelay(gun_index, OFF);
  5204. }
  5205. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  5206. DEBUG_INFO("Connector-%d charging duration(%d) already over max duration(%d) in second.\n", gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration, (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60));
  5207. }
  5208. else if((ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy)))
  5209. {
  5210. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  5211. {
  5212. setRelay(gun_index, OFF);
  5213. ShmCharger->gun_info[gun_index].isChargerStopByCondition = YES;
  5214. }
  5215. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  5216. {
  5217. setRelay(gun_index, OFF);
  5218. }
  5219. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  5220. DEBUG_INFO("Connector-%d charging energy(%.2f) already over max energy(%.2f) in KWH.\n", gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy, ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy));
  5221. }
  5222. else
  5223. {
  5224. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  5225. {
  5226. ShmCharger->gun_info[gun_index].isChargerStopByCondition = NO;
  5227. if(ShmCharger->gun_info[gun_index].targetCurrent>0)
  5228. setRelay(gun_index, ON);
  5229. else
  5230. setRelay(gun_index, OFF);
  5231. }
  5232. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  5233. {
  5234. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)
  5235. setRelay(gun_index, ON);
  5236. }
  5237. }
  5238. }
  5239. else
  5240. {
  5241. // Off-line max condition check
  5242. if((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) ||
  5243. ((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_ENABLE) && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy != OFF_POLICY_NOCHARGE)))
  5244. {
  5245. if(((ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeDuration > 0) ? (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeDuration*60)) : (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60))))
  5246. {
  5247. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  5248. {
  5249. setRelay(gun_index, OFF);
  5250. ShmCharger->gun_info[gun_index].isChargerStopByCondition = YES;
  5251. }
  5252. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  5253. {
  5254. setRelay(gun_index, OFF);
  5255. }
  5256. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  5257. DEBUG_INFO("Connector-%d charging duration(%d) already over off-line max duration(%d) in second.\n", gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration, (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60));
  5258. }
  5259. else if(((ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy > 0) ? (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy)) : (ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy))))
  5260. {
  5261. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  5262. {
  5263. setRelay(gun_index, OFF);
  5264. ShmCharger->gun_info[gun_index].isChargerStopByCondition = YES;
  5265. }
  5266. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  5267. {
  5268. setRelay(gun_index, OFF);
  5269. }
  5270. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  5271. DEBUG_INFO("Connector-%d charging energy(%.2f) already over off-line max energy(%.2f) in KWH.\n", gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy, ((float)ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy));
  5272. }
  5273. else
  5274. {
  5275. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  5276. {
  5277. ShmCharger->gun_info[gun_index].isChargerStopByCondition = NO;
  5278. if(ShmCharger->gun_info[gun_index].targetCurrent>0)
  5279. setRelay(gun_index, ON);
  5280. else
  5281. setRelay(gun_index, OFF);
  5282. }
  5283. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  5284. {
  5285. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)
  5286. setRelay(gun_index, ON);
  5287. }
  5288. }
  5289. }
  5290. else
  5291. {
  5292. if(ShmCharger->gun_info[gun_index].primaryMcuState.relay_state > 0)
  5293. DEBUG_INFO("Connector-%d can not charging in off line\n", gun_index);
  5294. setRelay(gun_index, OFF);
  5295. }
  5296. }
  5297. // Debug information
  5298. if(getDiffSecNow(startTime[gun_index][TMR_IDX_LOGPPRINTOUT]) > TIMEOUT_SPEC_LOGPPRINTOUT)
  5299. {
  5300. DEBUG_INFO("==============================================================\n");
  5301. DEBUG_INFO("ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent: %d \n", ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent);
  5302. DEBUG_INFO("ShmCharger->gun_info[%d].primaryMcuCp_Pwn_Duty.max_current: %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current);
  5303. DEBUG_INFO("ShmCharger->gun_info[%d].targetCurrent: %d\n", gun_index, ShmCharger->gun_info[gun_index].targetCurrent);
  5304. DEBUG_INFO("==============================================================\n");
  5305. refreshStartTimer(&startTime[gun_index][TMR_IDX_LOGPPRINTOUT]);
  5306. getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime);
  5307. DB_Update_Record_Buf(localDb, gun_index);
  5308. }
  5309. }
  5310. break;
  5311. case SYS_MODE_TERMINATING:
  5312. if(isModeChange(gun_index))
  5313. {
  5314. if(!ShmCharger->gun_info[gun_index].primaryMcuState.relay_state)
  5315. {
  5316. setLedMotion(gun_index, LED_ACTION_STOP);
  5317. }
  5318. else
  5319. {}
  5320. getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime);
  5321. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  5322. }
  5323. refreshStartTimer(&endChargingTime[gun_index]);
  5324. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration != 0)
  5325. {
  5326. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = getDiffSecBetween(startChargingTime[gun_index], endChargingTime[gun_index]);
  5327. }
  5328. // End authorize pass
  5329. if(((ShmCharger->gun_info[gun_index].rfidReq == ON) &&isMatchStartUser(gun_index)) ||
  5330. ((ShmCharger->gun_info[gun_index].rfidReq == ON) && ocpp_get_auth_result(YES, gun_index)) ||
  5331. (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE) && (ShmCharger->gun_info[gun_index].rfidReq == ON)) ||
  5332. (!ocpp_get_connection_status() && (isValidLocalWhiteCard() == PASS) && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST) && (ShmCharger->gun_info[gun_index].rfidReq == ON)) ||
  5333. (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop == ON) ||
  5334. ocpp_get_remotestop(gun_index) ||
  5335. (ocpp_get_connection_status() && !ocpp_get_starttransaction_result(gun_index)) ||
  5336. ((ShmCharger->gun_info[gun_index].chargingMode != CHARGING_MODE_SOCKETE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A) && ocpp_get_StopTransactionOnEVSideDisconnect()) ||
  5337. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE) && !ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn) ||
  5338. ocpp_get_reset_req() ||
  5339. ocpp_get_unlocker_req(gun_index) ||
  5340. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop == ON) ||
  5341. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && (ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_STOP_MODE)))
  5342. {
  5343. //setRelay(gun_index, OFF);
  5344. setLedMotion(gun_index, LED_ACTION_STOP);
  5345. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  5346. {
  5347. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  5348. sleep(1);
  5349. checkStopReason(gun_index);
  5350. setChargerMode(gun_index, SYS_MODE_COMPLETE);
  5351. }
  5352. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  5353. {
  5354. //setChargerMode(gun_index, SYS_MODE_COMPLETE);
  5355. //Cancel CCS task negotiating
  5356. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  5357. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  5358. setRelay(gun_index,OFF);
  5359. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = ON;
  5360. }
  5361. else
  5362. {
  5363. setChargerMode(gun_index, SYS_MODE_COMPLETE);
  5364. }
  5365. }
  5366. else
  5367. {
  5368. // If the charger stops charging, the led should be stoped blink
  5369. if(!ShmCharger->gun_info[gun_index].primaryMcuState.relay_state)
  5370. {
  5371. setLedMotion(gun_index, LED_ACTION_STOP);
  5372. }
  5373. // Charging profile preparation
  5374. if(getDiffSecNow(startTime[gun_index][TMR_IDX_PROFILE_PREPARE]) > TIMEOUT_SPEC_PROFILE_PREPARE)
  5375. {
  5376. if(!ocpp_get_profile_conf(gun_index))
  5377. {
  5378. ocpp_set_profile_req(gun_index, ON);
  5379. refreshStartTimer(&startTime[gun_index][TMR_IDX_PROFILE_PREPARE]);
  5380. }
  5381. else
  5382. {
  5383. ocpp_set_profile_conf(gun_index, OFF);
  5384. }
  5385. }
  5386. // Checking profile id > 0 and current time is between charging profile validFrom & validTo
  5387. checkChargingProfileLimit(gun_index);
  5388. // Determine max charging current to MCU
  5389. if(ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent == 0)
  5390. {
  5391. ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmCharger->gun_info[gun_index].primaryMcuState.rating_current)?ShmCharger->gun_info[gun_index].primaryMcuState.rating_current:ShmCharger->gun_info[gun_index].targetCurrent);
  5392. }
  5393. else
  5394. {
  5395. ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent)?ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent:ShmCharger->gun_info[gun_index].targetCurrent);
  5396. }
  5397. // Debug information
  5398. if(getDiffSecNow(startTime[gun_index][TMR_IDX_LOGPPRINTOUT]) > TIMEOUT_SPEC_LOGPPRINTOUT)
  5399. {
  5400. DEBUG_INFO("=============================================================\n");
  5401. DEBUG_INFO("ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent: %d\n", ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent);
  5402. DEBUG_INFO("ShmCharger->gun_info[%d].primaryMcuCp_Pwn_Duty.max_current: %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current);
  5403. DEBUG_INFO("ShmCharger->gun_info[%d].targetCurrent: %d\n", gun_index, ShmCharger->gun_info[gun_index].targetCurrent);
  5404. DEBUG_INFO("=============================================================\n");
  5405. refreshStartTimer(&startTime[gun_index][TMR_IDX_LOGPPRINTOUT]);
  5406. }
  5407. if(!ocpp_get_auth_result(YES, gun_index))
  5408. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  5409. if((((ShmCharger->gun_info[gun_index].chargingMode != CHARGING_MODE_SOCKETE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)) || ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE) && ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn)) &&
  5410. (ShmCharger->gun_info[gun_index].rfidReq != ON) &&
  5411. (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop != ON) &&
  5412. !ocpp_get_remotestop(gun_index) &&
  5413. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop != ON) &&
  5414. !ocpp_get_reset_req() &&
  5415. ocpp_get_starttransaction_result(gun_index) &&
  5416. !(ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60))) &&
  5417. !(ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy))) &&
  5418. !(!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy != OFF_POLICY_NOCHARGE) && ((ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeDuration > 0) ? (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeDuration*60)) : (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60)))) &&
  5419. !(!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy != OFF_POLICY_NOCHARGE) && ((ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy > 0) ? (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy)) : (ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy)))) &&
  5420. (((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && (ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_START_MODE)) || (ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS))
  5421. )
  5422. {
  5423. setChargerMode(gun_index, SYS_MODE_CHARGING);
  5424. }
  5425. }
  5426. if((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) &&
  5427. (ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty == ON) &&
  5428. (ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty == CCS_PWM_DUTY_100))
  5429. {
  5430. DEBUG_INFO("Set PWM duty 100%% go to SYS_MODE_TERMINATING.\n");
  5431. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = OFF;
  5432. sleep(1);
  5433. checkStopReason(gun_index);
  5434. setChargerMode(gun_index, SYS_MODE_COMPLETE);
  5435. }
  5436. break;
  5437. case SYS_MODE_COMPLETE:
  5438. if(isModeChange(gun_index))
  5439. {
  5440. setLedMotion(gun_index, LED_ACTION_STOP);
  5441. sleep(6);
  5442. setRelay(gun_index, OFF);
  5443. setRequest(gun_index, OFF);
  5444. sleep(13);
  5445. }
  5446. if(((ShmCharger->gun_info[gun_index].chargingMode != CHARGING_MODE_SOCKETE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)) ||
  5447. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE) && (!ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn)) ||
  5448. ocpp_get_reset_req())
  5449. {
  5450. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  5451. ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop = OFF;
  5452. ocpp_set_remotestop(gun_index, OFF);
  5453. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop = OFF;
  5454. DB_Insert_Record(localDb, gun_index);
  5455. setChargerMode(gun_index, SYS_MODE_IDLE);
  5456. }
  5457. break;
  5458. case SYS_MODE_ALARM:
  5459. setLedMotion(gun_index,LED_ACTION_ALARM);
  5460. setRelay(gun_index, OFF);
  5461. if((ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode == 0))
  5462. {
  5463. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus == SYS_MODE_CHARGING) ||
  5464. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus == SYS_MODE_TERMINATING))
  5465. {
  5466. setChargerMode(gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus);
  5467. }
  5468. else
  5469. {
  5470. setChargerMode(gun_index, SYS_MODE_IDLE);
  5471. }
  5472. }
  5473. break;
  5474. case SYS_MODE_FAULT:
  5475. if(isModeChange(gun_index))
  5476. {}
  5477. break;
  5478. case SYS_MODE_MAINTAIN:
  5479. if(isModeChange(gun_index))
  5480. {
  5481. setLedMotion(gun_index,LED_ACTION_MAINTAIN);
  5482. }
  5483. break;
  5484. case SYS_MODE_UPDATE:
  5485. if(isModeChange(gun_index))
  5486. {
  5487. setLedMotion(gun_index,LED_ACTION_MAINTAIN);
  5488. }
  5489. //======================================
  5490. // Check local upgrade firmware request
  5491. //======================================
  5492. if(ShmSysConfigAndInfo->SysInfo.FirmwareUpdate)
  5493. {
  5494. DEBUG_INFO("Firmware local upgrading...\n");
  5495. ShmSysConfigAndInfo->SysInfo.FirmwareUpdate = OFF;
  5496. if(upgrade_check() == PASS)
  5497. {
  5498. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == ON)
  5499. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = OFF;
  5500. ShmCharger->isUpdateSuccess = YES;
  5501. DEBUG_INFO("Local update success.\n");
  5502. }
  5503. else
  5504. {
  5505. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == OFF)
  5506. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = ON;
  5507. ShmCharger->isUpdateSuccess = NO;
  5508. DEBUG_INFO("Local update fail.\n");
  5509. }
  5510. }
  5511. else if(ocpp_get_update_firmware_req())
  5512. {
  5513. //======================================
  5514. // Check remote upgrade firmware request
  5515. //======================================
  5516. checkRemoteUpgradeStatus();
  5517. }
  5518. else
  5519. {
  5520. //======================================
  5521. // Upgrade complete reboot system
  5522. //======================================
  5523. if(!ShmCharger->gun_info[gun_index].mcuFlag.isMcuUpgradeReq && ((modelnameInfo.GetGunCount>1)?!ShmCharger->gun_info[gun_index^1].mcuFlag.isMcuUpgradeReq:YES) && !ShmCharger->isUpgradeLcmReq)
  5524. {
  5525. if(ShmCharger->isUpdateSuccess == YES)
  5526. {
  5527. sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installed");
  5528. ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  5529. sprintf((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "Installed");
  5530. ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  5531. DEBUG_WARN("Firmware upgrade success.\n");
  5532. sleep(5);
  5533. DEBUG_INFO("Firmware upgraded, reboot...\n");
  5534. system("reboot -f");
  5535. sleep(5);
  5536. system("reboot -f");
  5537. }
  5538. else
  5539. {
  5540. sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "InstallationFailed");
  5541. ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  5542. sprintf((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "InstallationFailed");
  5543. ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  5544. DEBUG_WARN("Firmware upgrade fail.\n");
  5545. sleep(5);
  5546. system("rm -rvf /mnt/* ");
  5547. close(wtdFd);
  5548. system("/usr/bin/run_evse_restart.sh");
  5549. }
  5550. }
  5551. }
  5552. break;
  5553. case SYS_MODE_RESERVATION:
  5554. if(isModeChange(gun_index))
  5555. {}
  5556. setLedMotion(gun_index,LED_ACTION_RESERVATION_MODE);
  5557. if(isReservationExpired(gun_index))
  5558. {
  5559. DEBUG_INFO("Reservation: Time's up...\n");
  5560. setChargerMode(gun_index, SYS_MODE_IDLE);
  5561. }
  5562. else if(ocpp_get_cancelreservation_req(gun_index))
  5563. {
  5564. DEBUG_INFO("Reservation: Cancel reservation...\n");
  5565. setChargerMode(gun_index, SYS_MODE_IDLE);
  5566. ocpp_set_cancelreservation_req(gun_index, OFF);
  5567. }
  5568. else
  5569. {
  5570. // Check is there RFID or back end request start
  5571. if((ShmCharger->gun_info[gun_index].rfidReq == ON) ||
  5572. ocpp_get_remotestart(gun_index))
  5573. {
  5574. if((ShmCharger->gun_info[gun_index].rfidReq == ON))
  5575. {
  5576. if(ocpp_compare_reserve_id_with_user(gun_index))
  5577. {
  5578. DEBUG_INFO("Start Method in reservation : RFID...\n");
  5579. DEBUG_INFO("Start request User Id : %s\n", ShmSysConfigAndInfo->SysConfig.UserId);
  5580. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_RFID;
  5581. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_ISO14443;
  5582. setChargerMode(gun_index, SYS_MODE_AUTHORIZING);
  5583. }
  5584. else
  5585. {
  5586. setLedMotion(gun_index,LED_ACTION_IDLE);
  5587. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  5588. DEBUG_INFO("It's not reserve user id.\n");
  5589. }
  5590. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  5591. }
  5592. else if(ocpp_get_remotestart(gun_index))
  5593. {
  5594. if(ocpp_compare_reserve_id_with_remote_user(gun_index))
  5595. {
  5596. DEBUG_INFO("Start Method in reservation: BACKEND...\n");
  5597. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_BACKEND;
  5598. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_Central;
  5599. setChargerMode(gun_index, SYS_MODE_AUTHORIZING);
  5600. }
  5601. ocpp_set_remotestop(gun_index, OFF);
  5602. }
  5603. }
  5604. }
  5605. break;
  5606. case SYS_MODE_BOOKING:
  5607. if(isModeChange(gun_index))
  5608. {}
  5609. break;
  5610. case SYS_MODE_DEBUG:
  5611. if(isModeChange(gun_index))
  5612. {
  5613. setLedMotion(gun_index,LED_ACTION_DEBUG);
  5614. }
  5615. break;
  5616. }
  5617. }
  5618. }
  5619. // System watch dog reset
  5620. write(wtdFd, "a", 1);
  5621. usleep(50000);
  5622. }
  5623. return FAIL;
  5624. }