main.c 224 KB

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