main.c 299 KB

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