main.c 298 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773
  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.63.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*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  4356. //memcpy((char*)ShmOCPP16Data->StopTransaction[gun_index].IdTag, (char*)ShmOCPP16Data->StartTransaction[gun_index].IdTag, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  4357. }
  4358. else if(ShmOCPP16Data->MsMsg.bits.ResetReq)
  4359. {
  4360. if(strcmp((char*)ShmOCPP16Data->Reset.Type, "Hard")==0)
  4361. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "HardReset");
  4362. else
  4363. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "SoftReset");
  4364. }
  4365. else if(ShmCharger->gun_info[gun_index].rfidReq || ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop)
  4366. {
  4367. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
  4368. if(!isMatchStartUser(gun_index))
  4369. {
  4370. memcpy((char*)ShmOCPP16Data->StopTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  4371. }
  4372. else
  4373. {
  4374. memcpy((char*)ShmOCPP16Data->StopTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  4375. }
  4376. DEBUG_INFO("Gun-[%d] : IdTag [ %s ].\n", gun_index, ShmOCPP16Data->StopTransaction[gun_index].IdTag);
  4377. }
  4378. else if(ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStopTransactionReq)
  4379. {
  4380. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Remote");
  4381. memcpy((char*)ShmOCPP16Data->StopTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  4382. }
  4383. else if(ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor == ON)
  4384. {
  4385. sprintf((char*)ShmOCPP16Data->StopTransaction[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].StopReason, "UnlockCommand");
  4386. }
  4387. else
  4388. {
  4389. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Other");
  4390. }
  4391. DEBUG_INFO("Gun-[%d] : StopReason [ %s ].\n",gun_index,ShmOCPP16Data->StopTransaction[gun_index].StopReason);
  4392. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  4393. presentChargedEnergyUpdate(gun_index);
  4394. DEBUG_INFO("Gun-[%d] : PresentChargedEnergy [ %.4f ].\n",gun_index ,ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy);
  4395. ShmOCPP16Data->CpMsg.bits[gun_index].StopTransactionReq = ON;
  4396. }
  4397. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  4398. {
  4399. memset(ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, 0x00, ARRAY_SIZE(ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken));
  4400. if(!ocpp_get_starttransaction_result(gun_index))
  4401. {
  4402. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "DeAuthorized");
  4403. }
  4404. else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_EMERGENCY_STOP)
  4405. {
  4406. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "EmergencyStop");
  4407. }
  4408. else if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A) || (ShmCharger->gun_info[gun_index].isGunUnpluggedBefore == YES))
  4409. {
  4410. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "EVDisconnected");
  4411. memcpy((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId));
  4412. }
  4413. else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_GROUND_FAIL)
  4414. {
  4415. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "GroundFault");
  4416. }
  4417. else if((ShmOCPP20Data->MsMsg.bits.ResetReq) && (strcmp((char*)ShmOCPP20Data->Reset.type, "Immediate")==0))
  4418. {
  4419. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "ImmediateReset");
  4420. }
  4421. else if(ShmCharger->gun_info[gun_index].rfidReq || ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop)
  4422. {
  4423. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Local");
  4424. if(!isMatchStartUser(gun_index))
  4425. {
  4426. memcpy((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, (char*)ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken));
  4427. }
  4428. else
  4429. {
  4430. memcpy((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId));
  4431. }
  4432. DEBUG_INFO("Gun-[%d] : idToken [ %s ].\n", gun_index, ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken);
  4433. }
  4434. else if((ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_L1_OVER_CURRENT) ||
  4435. (ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_L2_OVER_CURRENT) ||
  4436. (ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_L3_OVER_CURRENT))
  4437. {
  4438. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "OvercurrentFault");
  4439. }
  4440. else if(ShmOCPP20Data->CsMsg.bits[gun_index].RequestStopTransactionReq)
  4441. {
  4442. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Remote");
  4443. memcpy((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId));
  4444. }
  4445. else if(ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor == ON)
  4446. {
  4447. sprintf((char*)ShmOCPP20Data->TransactionEvent[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].transactionInfo.stoppedReason, "UnlockCommand");
  4448. }
  4449. else
  4450. {
  4451. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Other");
  4452. }
  4453. DEBUG_INFO("Gun-[%d] : StopReason [ %s ].\n", gun_index, ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason);
  4454. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  4455. presentChargedEnergyUpdate(gun_index);
  4456. DEBUG_INFO("Gun-[%d] : PresentChargedEnergy [ %.4f ].\n",gun_index ,ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy);
  4457. ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventReq = ON;
  4458. }
  4459. // Maintain server
  4460. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.MaintainServerURL,"") != 0)
  4461. {
  4462. memcpy(ShmOCPP16DataPH->StopTransaction[gun_index].StopReason, ShmOCPP16Data->StopTransaction[gun_index].StopReason, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].StopReason));
  4463. memcpy(ShmOCPP16DataPH->StopTransaction[gun_index].IdTag, ShmOCPP16Data->StopTransaction[gun_index].IdTag, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  4464. ShmOCPP16DataPH->CpMsg.bits[gun_index].StopTransactionReq = ON;
  4465. }
  4466. }
  4467. void checkRemoteUpgradeStatus()
  4468. {
  4469. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  4470. {
  4471. if(strcmp((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "DownloadFailed")==0)
  4472. {
  4473. DEBUG_INFO("Firmware remote upgraded fail...\n");
  4474. ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq = OFF;
  4475. ShmCharger->isUpdateSuccess = NO;
  4476. }
  4477. else if((strcmp((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Downloaded")==0))
  4478. {
  4479. DEBUG_INFO("Firmware remote upgrading...\n");
  4480. sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installing");
  4481. sleep(1);
  4482. ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  4483. ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq = OFF;
  4484. int result = upgrade_check();
  4485. DEBUG_INFO("Remote update Result: %s... \n",((result == PASS)?"Pass": "Fail"));
  4486. if(result == PASS)
  4487. {
  4488. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == ON)
  4489. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = OFF;
  4490. ShmCharger->isUpdateSuccess = YES;
  4491. DEBUG_INFO("Remote update success...\n");
  4492. }
  4493. else
  4494. {
  4495. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == OFF)
  4496. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = ON;
  4497. ShmCharger->isUpdateSuccess = NO;
  4498. DEBUG_INFO("Remote update unsuccess...\n");
  4499. }
  4500. }
  4501. else if((strcmp((char*)ShmOCPP16Data->SignedFirmwareStatusNotification.status, "SignatureVerified")==0))
  4502. {
  4503. DEBUG_INFO("Signature firmware remote upgrading...\n");
  4504. ShmOCPP16Data->SignedFirmwareStatusNotification.requestId = ShmOCPP16Data->SignedUpdateFirmware.requestId;
  4505. sprintf((char*)ShmOCPP16Data->SignedFirmwareStatusNotification.status, "Installing");
  4506. sleep(1);
  4507. ShmOCPP16Data->SpMsg.bits.SignedFirmwareStatusNotificationReq = ON;
  4508. ShmOCPP16Data->MsMsg.bits.SignedUpdateFirmwareReq = OFF;
  4509. if(upgrade_check() == PASS)
  4510. {
  4511. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == ON)
  4512. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = OFF;
  4513. ShmCharger->isUpdateSuccess = YES;
  4514. DEBUG_INFO("Remote update success.\n");
  4515. }
  4516. else
  4517. {
  4518. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == OFF)
  4519. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = ON;
  4520. ShmCharger->isUpdateSuccess = NO;
  4521. DEBUG_INFO("Remote update fail.\n");
  4522. }
  4523. }
  4524. else
  4525. {}
  4526. }
  4527. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  4528. {
  4529. if(strcmp((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "DownloadFailed")==0)
  4530. {
  4531. DEBUG_INFO("Firmware remote upgraded fail...\n");
  4532. ShmOCPP20Data->MsMsg.bits.UpdateFirmwareReq = OFF;
  4533. ShmCharger->isUpdateSuccess = NO;
  4534. }
  4535. else if((strcmp((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "Downloaded")==0))
  4536. {
  4537. DEBUG_INFO("Firmware remote upgrading...\n");
  4538. sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installing");
  4539. ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  4540. ShmOCPP20Data->MsMsg.bits.UpdateFirmwareReq = OFF;
  4541. int result = upgrade_check();
  4542. DEBUG_INFO("Remote update Result: %s... \n",((result == PASS)?"Pass": "Fail"));
  4543. if(result == PASS)
  4544. {
  4545. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == ON)
  4546. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = OFF;
  4547. ShmCharger->isUpdateSuccess = YES;
  4548. DEBUG_INFO("Remote update success...\n");
  4549. }
  4550. else
  4551. {
  4552. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == OFF)
  4553. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = ON;
  4554. ShmCharger->isUpdateSuccess = NO;
  4555. DEBUG_INFO("Remote update unsuccess...\n");
  4556. }
  4557. }
  4558. else
  4559. {}
  4560. }
  4561. }
  4562. void checkHandshakeCountdown(uint8_t gun_index)
  4563. {
  4564. switch(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus)
  4565. {
  4566. case SYS_MODE_IDLE:
  4567. if(ShmCharger->gun_info[ShmCharger->gun_selectd].isHandshakeTimerRefresh == YES)
  4568. refreshStartTimer(&startTime[0][TMR_IDX_GUN_DETECT]);
  4569. else
  4570. ShmCharger->timeoutSpec.Handshake_Timeout = ((ocpp_get_connection_timeout()) - (getDiffSecNow(startTime[0][TMR_IDX_GUN_DETECT])));
  4571. if(!ShmCharger->isAuthrizing)
  4572. {
  4573. if(ocpp_get_isRemoteStartWait())
  4574. ShmCharger->timeoutSpec.Handshake_Timeout = ((ocpp_get_connection_timeout()) - (getDiffSecNow(startTime[0][TMR_IDX_GUN_DETECT])));
  4575. else
  4576. refreshStartTimer(&startTime[0][TMR_IDX_GUN_DETECT]);
  4577. }
  4578. break;
  4579. case SYS_MODE_PREPARING:
  4580. if(ShmCharger->gun_info[ShmCharger->gun_selectd].isHandshakeTimerRefresh == YES)
  4581. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  4582. else
  4583. ShmCharger->timeoutSpec.Handshake_Timeout = ((ocpp_get_connection_timeout()) - getDiffSecNow(startTime[gun_index][TMR_IDX_HANDSHAKING]));
  4584. break;
  4585. case SYS_MODE_RESERVATION:
  4586. if(ShmCharger->gun_info[ShmCharger->gun_selectd].isHandshakeTimerRefresh == YES)
  4587. refreshStartTimer(&startTime[0][TMR_IDX_GUN_DETECT]);
  4588. else
  4589. ShmCharger->timeoutSpec.Handshake_Timeout = ((ocpp_get_connection_timeout()) - (getDiffSecNow(startTime[0][TMR_IDX_GUN_DETECT])));
  4590. break;
  4591. }
  4592. }
  4593. void checkRfidAuthrize()
  4594. {
  4595. static uint8_t isCheckdResult = FALSE;
  4596. static uint8_t isReadable = TRUE;
  4597. static uint8_t lastIdtag[ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId)];
  4598. uint8_t isStartByWrongReservation = NO;
  4599. if(!ShmCharger->isAuthrizing)
  4600. {
  4601. // Read RFID
  4602. if(GetCardSerialNumber() != FAIL)
  4603. {
  4604. if(isReadable == TRUE)
  4605. {
  4606. uint8_t isSnStart = FALSE;
  4607. uint8_t bufferRFID[ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId)];
  4608. if(ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian)
  4609. {
  4610. // Big endian
  4611. switch(rfid.snType)
  4612. {
  4613. case RFID_SN_TYPE_8BYTE:
  4614. 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]);
  4615. break;
  4616. case RFID_SN_TYPE_7BYTE:
  4617. 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]);
  4618. break;
  4619. case RFID_SN_TYPE_10BYTE:
  4620. 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]);
  4621. break;
  4622. case RFID_SN_TYPE_4BYTE:
  4623. default:
  4624. sprintf((char*)bufferRFID, "%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3]);
  4625. break;
  4626. }
  4627. }
  4628. else
  4629. {
  4630. // Little endian
  4631. switch(rfid.snType)
  4632. {
  4633. case RFID_SN_TYPE_8BYTE:
  4634. 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]);
  4635. break;
  4636. case RFID_SN_TYPE_7BYTE:
  4637. 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]);
  4638. break;
  4639. case RFID_SN_TYPE_10BYTE:
  4640. 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]);
  4641. break;
  4642. case RFID_SN_TYPE_4BYTE:
  4643. default:
  4644. sprintf((char*)bufferRFID, "%02X%02X%02X%02X", rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  4645. break;
  4646. }
  4647. }
  4648. DEBUG_INFO("Authorize request User Id : %s\n", bufferRFID);
  4649. //DEBUG_INFO("Authorize request User Id : %s\n", ShmSysConfigAndInfo->SysConfig.UserId);
  4650. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4651. ShmCharger->gun_info[gun_index].resultAuthorization = UNKNOW_RFID;
  4652. // Check SN already start
  4653. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4654. {
  4655. if(isMatchStartUser(gun_index) || (isMatchPresentUser(gun_index) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_PREPARING)))
  4656. {
  4657. DEBUG_INFO("%s running on connector-%02d.\n", ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, gun_index);
  4658. isSnStart = TRUE;
  4659. ShmCharger->gun_info[gun_index].rfidReq = ON;
  4660. ocpp_set_auth_conf(ON);
  4661. setLedMotion(gun_index,LED_ACTION_RFID_PASS);
  4662. setSpeaker(ON, SPEAKER_SHORT);
  4663. sleep(3);
  4664. break;
  4665. }
  4666. }
  4667. // Request authorize if isSnStart is false
  4668. if(!isSnStart)
  4669. {
  4670. memcpy(lastIdtag, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  4671. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, bufferRFID, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  4672. refreshStartTimer(&startTime[0][TMR_IDX_AUTH]);
  4673. ocpp_set_auth_req(ON, "ISO14443");
  4674. setLedMotion(0,LED_ACTION_AUTHED);
  4675. ShmCharger->isAuthrizing = TRUE;
  4676. ShmCharger->isGetAuthResult = FALSE;
  4677. isCheckdResult = FALSE;
  4678. }
  4679. isReadable = FALSE;
  4680. }
  4681. }
  4682. else
  4683. {
  4684. isReadable = TRUE;
  4685. }
  4686. }
  4687. else
  4688. {
  4689. // Wait authorize result
  4690. if(!ocpp_get_auth_conf() && (getDiffSecNow(startTime[0][TMR_IDX_AUTH]) > TIMEOUT_SPEC_AUTH))
  4691. {
  4692. // Authorization timeout process.
  4693. DEBUG_WARN("Authorize timeout !!!\n");
  4694. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4695. {
  4696. ShmCharger->gun_info[gun_index].resultAuthorization = UNVALIDATED_RFID;
  4697. setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
  4698. }
  4699. setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
  4700. sleep(3);
  4701. ShmCharger->isAuthrizing = FALSE;
  4702. }
  4703. else
  4704. {
  4705. if(ocpp_get_auth_conf() ||
  4706. (!ocpp_get_connection_status() && ((ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE) || (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_NOCHARGE))) ||
  4707. (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST) && (getDiffSecNow(startTime[0][TMR_IDX_AUTH]) > 2))
  4708. )
  4709. {
  4710. if(ocpp_get_auth_result(NO) ||
  4711. (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE)) ||
  4712. (!ocpp_get_connection_status() && (isValidLocalWhiteCard() == PASS) && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST)))
  4713. {
  4714. if(!isCheckdResult)
  4715. {
  4716. refreshStartTimer(&startTime[0][TMR_IDX_GUN_DETECT]);
  4717. ShmCharger->isGetAuthResult = TRUE;
  4718. isCheckdResult = TRUE;
  4719. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0)
  4720. {
  4721. ocpp_set_auth_conf(ON);
  4722. }
  4723. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4724. {
  4725. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_RESERVATION) &&
  4726. (ocpp_compare_reserve_id_with_user(gun_index) != YES) &&
  4727. (ocpp_get_auth_result(YES, gun_index) != PASS))
  4728. {
  4729. isStartByWrongReservation = YES;
  4730. ShmCharger->gun_info[gun_index].resultAuthorization = UNVALIDATED_RFID;
  4731. DEBUG_INFO("================================================== \n");
  4732. DEBUG_INFO("UserId: [ %s ]\n", ShmSysConfigAndInfo->SysConfig.UserId);
  4733. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  4734. {
  4735. DEBUG_INFO("Gun-%d IdTag: [ %s ]\n", gun_index, ShmOCPP16Data->ReserveNow[gun_index].IdTag);
  4736. DEBUG_INFO("Authorize response ParentIdTag: [ %s ]. \n", ShmOCPP16Data->Authorize.ResponseIdTagInfo.ParentIdTag);
  4737. DEBUG_INFO("Gun-%d Reserve ParentIdTag: [ %s ]. \n", gun_index, ShmOCPP16Data->ReserveNow[gun_index].ParentIdTag);
  4738. }
  4739. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  4740. {
  4741. DEBUG_INFO("Gun-%d idToken: [ %s ]\n", gun_index, ShmOCPP20Data->ReserveNow[gun_index].idToken.idToken);
  4742. DEBUG_INFO("Authorize response groupIdToken idToken: [ %s ]\n", ShmOCPP20Data->Authorize.Response_idTokenInfo.groupIdToken.idToken);
  4743. DEBUG_INFO("Gun-%d Reserve groupIdToken idToken: [ %s]\n", ShmOCPP20Data->ReserveNow[gun_index].groupIdToken.idToken);
  4744. }
  4745. DEBUG_INFO("================================================== \n");
  4746. DEBUG_INFO("Authorize fail.\n");
  4747. setSpeaker(ON, SPEAKER_INTERVAL_3COUNT);
  4748. }
  4749. else
  4750. {
  4751. ShmCharger->gun_info[gun_index].resultAuthorization = VALIDATED_RFID;
  4752. DEBUG_INFO("Authorize pass.\n");
  4753. setSpeaker(ON, SPEAKER_SHORT);
  4754. }
  4755. }
  4756. }
  4757. // Check handshake timeout
  4758. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4759. checkHandshakeCountdown(gun_index);
  4760. if((getDiffSecNow(startTime[0][TMR_IDX_GUN_DETECT]) < (ocpp_get_connection_timeout())) && (isStartByWrongReservation != YES))
  4761. {
  4762. if(GetCardSerialNumber() != FAIL)
  4763. {
  4764. if(isReadable == TRUE)
  4765. {
  4766. if(isMatchPresentUser())
  4767. {
  4768. DEBUG_INFO("Cancel present user.\n");
  4769. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4770. {
  4771. setLedMotion(gun_index,LED_ACTION_IDLE);
  4772. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  4773. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_PREPARING)
  4774. ShmCharger->gun_info[gun_index].rfidReq = ON;
  4775. }
  4776. setSpeaker(ON, SPEAKER_SHORT);
  4777. ShmCharger->isAuthrizing = FALSE;
  4778. }
  4779. isReadable = FALSE;
  4780. }
  4781. }
  4782. else
  4783. {
  4784. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4785. {
  4786. if(getDiffSecNow(startTime[0][TMR_IDX_GUN_DETECT]) < 3)
  4787. setLedMotion(gun_index,LED_ACTION_RFID_PASS);
  4788. else
  4789. setLedMotion(gun_index,LED_ACTION_AUTHED);
  4790. 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))) ||
  4791. ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_PREPARING) && (ShmCharger->gun_selectd == gun_index)) ||
  4792. (((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_CHARGING) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_TERMINATING)) && (ShmCharger->gun_selectd == gun_index))
  4793. )
  4794. {
  4795. DEBUG_INFO("Connector-%02d action detect.\n", gun_index);
  4796. ShmCharger->isAuthrizing = FALSE;
  4797. ShmCharger->gun_info[gun_index].rfidReq = ON;
  4798. break;
  4799. }
  4800. }
  4801. isReadable = TRUE;
  4802. }
  4803. }
  4804. else
  4805. {
  4806. if(isStartByWrongReservation != YES)
  4807. DEBUG_INFO("Connector action detect timeout.\n");
  4808. else
  4809. DEBUG_INFO("Start by wrong reservation user. \n");
  4810. ShmCharger->isAuthrizing = FALSE;
  4811. ShmCharger->isGetAuthResult = TRUE;
  4812. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4813. {
  4814. if(isStartByWrongReservation != YES)
  4815. {
  4816. setLedMotion(gun_index,LED_ACTION_HANDSHAKE_FAIL);
  4817. sleep(6);
  4818. }
  4819. else
  4820. {
  4821. setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
  4822. sleep(3);
  4823. }
  4824. setLedMotion(gun_index,LED_ACTION_IDLE);
  4825. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  4826. }
  4827. }
  4828. }
  4829. else
  4830. {
  4831. DEBUG_INFO("Authorize fail.\n");
  4832. ShmCharger->isAuthrizing = FALSE;
  4833. ShmCharger->isGetAuthResult = TRUE;
  4834. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4835. {
  4836. ShmCharger->gun_info[gun_index].resultAuthorization = UNVALIDATED_RFID;
  4837. setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
  4838. }
  4839. setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
  4840. sleep(3);
  4841. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4842. {
  4843. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_PREPARING))
  4844. setLedMotion(gun_index,LED_ACTION_AUTHED);
  4845. else
  4846. setLedMotion(gun_index,LED_ACTION_IDLE);
  4847. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_PREPARING) && (ShmCharger->gun_selectd == gun_index))
  4848. {
  4849. switch(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod)
  4850. {
  4851. case START_METHOD_BACKEND:
  4852. ocpp_copy_userid_from_remotestart(gun_index);
  4853. break;
  4854. default:
  4855. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, lastIdtag, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  4856. DEBUG_INFO("==========================================\n");
  4857. DEBUG_INFO("Copy lastIdtag into UserId. \n");
  4858. DEBUG_INFO("lastIdtag : [%s] ---> UserId : [%s] . \n", lastIdtag, ShmSysConfigAndInfo->SysConfig.UserId);
  4859. DEBUG_INFO("==========================================\n");
  4860. break;
  4861. }
  4862. }
  4863. }
  4864. }
  4865. }
  4866. }
  4867. }
  4868. }
  4869. void setPtbMeterPermission(uint8_t gun_index, uint8_t permission)
  4870. {
  4871. switch(permission)
  4872. {
  4873. case PREMISSION_DEFAULT:
  4874. // Changed permission to [Default]
  4875. ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.PtbMeterPermissionStatus = PREMISSION_DEFAULT;
  4876. DEBUG_INFO("Set PTB meter permission to [ PREMISSION_DEFAULT ] \n");
  4877. break;
  4878. case PERMISSION_START_CHARGING:
  4879. // Changed permission to [Start Charging]
  4880. if((ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.PtbMeterPermissionStatus != PERMISSION_START_CHARGING) &&
  4881. (ShmCharger->gun_info[gun_index].isSetPtbMeterPermisson != ON))
  4882. {
  4883. ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.PtbMeterPermissionStatus = PERMISSION_START_CHARGING;
  4884. ShmCharger->gun_info[gun_index].isSetPtbMeterPermisson = ON;
  4885. DEBUG_INFO("Set PTB meter permission to [ PERMISSION_START_CHARGING ] \n");
  4886. DB_Update_Meter_Permission(localDb, gun_index, PERMISSION_START_CHARGING);
  4887. }
  4888. break;
  4889. case PERMISSION_END_CHARGING:
  4890. // Changed permission to [End Charging]
  4891. if((ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.PtbMeterPermissionStatus != PERMISSION_END_CHARGING) &&
  4892. (ShmCharger->gun_info[gun_index].isSetPtbMeterPermisson != ON))
  4893. {
  4894. ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.PtbMeterPermissionStatus = PERMISSION_END_CHARGING;
  4895. ShmCharger->gun_info[gun_index].isSetPtbMeterPermisson = ON;
  4896. DEBUG_INFO("Set PTB meter permission to [ PERMISSION_END_CHARGING ] \n");
  4897. DB_Update_Meter_Permission(localDb, gun_index, PERMISSION_END_CHARGING);
  4898. }
  4899. break;
  4900. }
  4901. }
  4902. void proccessEndOfChargingForPtbMeter(uint8_t gun_index)
  4903. {
  4904. if(getDiffSecNow(startTime[gun_index][TMR_IDX_PTB_METER_MESSAGE]) >= 12)
  4905. {
  4906. if((ocpp_set_ocmf_data_transfer(gun_index) == YES))
  4907. {
  4908. checkStopReason(gun_index);
  4909. if(ShmOCPP16Data->OcmfData[gun_index].SendOcmfDataReq != ON)
  4910. ShmOCPP16Data->OcmfData[gun_index].SendOcmfDataReq = ON;
  4911. ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.isUpLoad = YES;
  4912. setChargerMode(gun_index, SYS_MODE_COMPLETE);
  4913. }
  4914. else
  4915. {
  4916. checkStopReason(gun_index);
  4917. ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.isUpLoad = NO;
  4918. setChargerMode(gun_index, SYS_MODE_COMPLETE);
  4919. }
  4920. }
  4921. else
  4922. {
  4923. setPtbMeterPermission(gun_index, PERMISSION_END_CHARGING);
  4924. if((getDiffSecNow(startTime[gun_index][TMR_IDX_PTB_METER_MESSAGE]) >= 6) && (getDiffSecNow(startTime[gun_index][TMR_IDX_PTB_METER_MESSAGE]) <= 9))
  4925. ShmCharger->gun_info[gun_index].isGetPtbMeterMessage = ON;
  4926. }
  4927. }
  4928. void checkMissingPtbMeterMessage(uint8_t gun_index)
  4929. {
  4930. if((ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.PtbMeterPermissionStatus == PERMISSION_START_CHARGING))
  4931. {
  4932. // Trigger get PTB meter message
  4933. if((getDiffSecNow(startTime[gun_index][TMR_IDX_PTB_METER_SEND]) > 0) && (getDiffSecNow(startTime[gun_index][TMR_IDX_PTB_METER_SEND]) <= 5))
  4934. {
  4935. ShmCharger->gun_info[gun_index].isGetPtbMeterMessage = ON;
  4936. }
  4937. // 5 seconds for MCU & PTB communcation + 5 seconds for CSU & MCU get PTB messages.
  4938. if((getDiffSecNow(startTime[gun_index][TMR_IDX_PTB_METER_SEND]) >= 12))
  4939. {
  4940. if((ShmCharger->gun_info[gun_index].isGetPtbMeterMessage != ON))
  4941. {
  4942. if((ocpp_set_ocmf_data_transfer(gun_index) == YES))
  4943. {
  4944. if(ShmOCPP16Data->OcmfData[gun_index].SendOcmfDataReq != ON)
  4945. ShmOCPP16Data->OcmfData[gun_index].SendOcmfDataReq = ON;
  4946. ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.isUpLoad = YES;
  4947. ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.PtbMeterPermissionStatus = PERMISSION_END_CHARGING;
  4948. DB_Update_Meter_Permission(localDb, gun_index, PERMISSION_END_CHARGING);
  4949. DB_Insert_Record(localDb, gun_index);
  4950. DEBUG_INFO("Meter data send to the backend system. \n");
  4951. }
  4952. else
  4953. {
  4954. ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.isUpLoad = NO;
  4955. ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.PtbMeterPermissionStatus = PERMISSION_END_CHARGING;
  4956. DB_Update_Meter_Permission(localDb, gun_index, PERMISSION_END_CHARGING);
  4957. DEBUG_INFO("No data to send. \n");
  4958. }
  4959. }
  4960. else
  4961. {}
  4962. }
  4963. else
  4964. {}
  4965. }
  4966. else
  4967. {
  4968. refreshStartTimer(&startTime[gun_index][TMR_IDX_PTB_METER_SEND]);
  4969. }
  4970. }
  4971. //======================================================
  4972. // Main process
  4973. //======================================================
  4974. int main(void)
  4975. {
  4976. //==================================================
  4977. // Create all share memory
  4978. //==================================================
  4979. if(CreatShareMemory()==0)
  4980. {
  4981. DEBUG_ERROR("CreatShareMemory NG\n");
  4982. if(ShmStatusCodeData!=NULL)
  4983. {
  4984. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=1;
  4985. }
  4986. sleep(5);
  4987. system("reboot -f");
  4988. sleep(5);
  4989. system("reboot -f");
  4990. }
  4991. else
  4992. {
  4993. DEBUG_INFO("CreatShareMemory OK\n");
  4994. }
  4995. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  4996. {
  4997. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus = 0xff;
  4998. ShmCharger->gun_info[gun_index].primaryMcuState.rotatory_switch = 0xff;
  4999. ShmCharger->gun_info[gun_index].mcuResetRequest.isMcuResetRequest = ON;
  5000. ShmCharger->gun_info[gun_index].isSetBreatheLedTiming = OFF;
  5001. ShmCharger->gun_info[gun_index].isSetLedBrightness = OFF;
  5002. }
  5003. //==================================================
  5004. // Main loop
  5005. //==================================================
  5006. for(;;)
  5007. {
  5008. //==============================================
  5009. // Synchronize share memory from OCPP struct
  5010. //==============================================
  5011. ShmSysConfigAndInfo->SysInfo.OcppConnStatus = ocpp_get_connection_status();
  5012. //==============================================
  5013. // Period check for 10 seconds
  5014. //==============================================
  5015. if((getDiffSecNow(startTime[0][TMR_IDX_CHECK_TASK]) > 10) || (getDiffSecNow(startTime[0][TMR_IDX_CHECK_TASK]) < 0))
  5016. {
  5017. //==============================================
  5018. // Check task processing
  5019. //==============================================
  5020. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[0].SystemStatus != SYS_MODE_BOOTING)
  5021. checkTask();
  5022. //==============================================
  5023. // Check connection timeout specification
  5024. //==============================================
  5025. checkConnectionTimeout();
  5026. refreshStartTimer(&startTime[0][TMR_IDX_CHECK_TASK]);
  5027. }
  5028. //==============================================
  5029. // Something need run in Idle mode
  5030. //==============================================
  5031. 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)) &&
  5032. (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))
  5033. {
  5034. // Check restore factory setting request
  5035. if(ShmSysConfigAndInfo->SysInfo.FactoryConfiguration)
  5036. {
  5037. // Set led to initial
  5038. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  5039. {
  5040. setLedMotion(gun_index,LED_ACTION_INIT);
  5041. }
  5042. sleep(5);
  5043. system("cd /root;./Module_FactoryConfig -m");
  5044. system("rm -f /Storage/OCPP/OCPPConfiguration");
  5045. system("sync");
  5046. sleep(5);
  5047. system("reboot -f");
  5048. sleep(5);
  5049. system("reboot -f");
  5050. }
  5051. // Check upgrade firmware request
  5052. if(ShmSysConfigAndInfo->SysInfo.FirmwareUpdate ||
  5053. ocpp_get_update_firmware_req())
  5054. {
  5055. // If available memory too small, free memory cache first
  5056. if(getAvailableMemory() < (200*1024*1024))
  5057. {
  5058. DEBUG_INFO("Available memory (%.2f Bytes) less than 200 MBytes, free cache first.\n", getAvailableMemory()/(1024*1024.0));
  5059. system("echo 3 > /proc/sys/vm/drop_caches");
  5060. }
  5061. ShmCharger->isUpdateSuccess = NO;
  5062. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  5063. {
  5064. setLedMotion(gun_index,LED_ACTION_MAINTAIN);
  5065. setChargerMode(gun_index, SYS_MODE_UPDATE);
  5066. }
  5067. }
  5068. }
  5069. //==============================================
  5070. // Check remote reset request
  5071. //==============================================
  5072. checkReset();
  5073. //==============================================
  5074. // Check RFID authorization
  5075. //==============================================
  5076. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  5077. {
  5078. // The user is not allowed to use RFID when the system change to under those modes.
  5079. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_ALARM) ||
  5080. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_FAULT) ||
  5081. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_DEBUG) ||
  5082. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_UPDATE) ||
  5083. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_BOOTING) ||
  5084. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_COMPLETE) ||
  5085. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_MAINTAIN) ||
  5086. (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE))
  5087. {
  5088. }
  5089. else
  5090. {
  5091. checkRfidAuthrize();
  5092. }
  5093. }
  5094. //==============================================
  5095. // Check Local Power Sharing Communication
  5096. //==============================================
  5097. if(ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharing > 0)
  5098. {
  5099. if(ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer)
  5100. {
  5101. if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LocalPowerSharingCommunicationError == ON)
  5102. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LocalPowerSharingCommunicationError = OFF;
  5103. }
  5104. else
  5105. {
  5106. if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LocalPowerSharingCommunicationError == OFF)
  5107. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LocalPowerSharingCommunicationError = ON;
  5108. }
  5109. }
  5110. //==============================================
  5111. // Connector loop
  5112. //==============================================
  5113. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  5114. {
  5115. //==========================================
  5116. // Power saving logic
  5117. //==========================================
  5118. /*
  5119. * TODO:
  5120. * 1. Power saving logic
  5121. */
  5122. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A) && (ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn == OFF))
  5123. {
  5124. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_STATE_B]);
  5125. }
  5126. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_ALARM) ||
  5127. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_FAULT) ||
  5128. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_UPDATE) ||
  5129. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_MAINTAIN) ||
  5130. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_CHARGING) ||
  5131. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_TERMINATING) ||
  5132. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_COMPLETE) ||
  5133. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_RESERVATION))
  5134. {
  5135. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
  5136. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_RFID]);
  5137. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_METER]);
  5138. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]);
  5139. }
  5140. else
  5141. {
  5142. if((ShmCharger->gun_info[ShmCharger->gun_selectd].isHandshakeTimerRefresh == YES) ||
  5143. (gpio_get_value(GPIO_IN_WAKEUP) == OFF) ||
  5144. (ShmCharger->gun_info[gun_index].GPIO_Input.Button_Mode_Switch == ON) ||
  5145. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus != ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus) ||
  5146. (((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)) &&
  5147. ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B) || (ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn == ON)) &&
  5148. (getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_STATE_B]) < 10)))
  5149. {
  5150. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
  5151. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_RFID]);
  5152. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_METER]);
  5153. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]);
  5154. if(((gpio_get_value(GPIO_IN_WAKEUP) == OFF) || (ShmCharger->gun_info[gun_index].GPIO_Input.Button_Mode_Switch == ON)) &&
  5155. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_IDLE) &&
  5156. (getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_CHECK_POWER_CONSUMPTION]) > TIMEOUT_SPEC_CEHCK_POWER_CONSUMPTION))
  5157. {
  5158. ShmCharger->gun_info[gun_index].isCheckPowerConsumption = YES;
  5159. refreshStartTimer(&startTime[gun_index][TMR_IDX_LCM_POWER_CONSUMPTION]);
  5160. }
  5161. }
  5162. else
  5163. {
  5164. refreshStartTimer(&startTime[gun_index][TMR_IDX_CHECK_POWER_CONSUMPTION]);
  5165. if((getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_LCM_POWER_CONSUMPTION]) > TIMEOUT_SPEC_CEHCK_POWER_CONSUMPTION))
  5166. {
  5167. ShmCharger->gun_info[gun_index].isCheckPowerConsumption = NO;
  5168. }
  5169. }
  5170. }
  5171. if(getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD]) > TIMEOUT_SPEC_POWERSAVING_LCD)
  5172. {
  5173. if(ShmCharger->isLcdOn == ON)
  5174. {
  5175. DEBUG_INFO("LCD into power saving...%d\n", getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD]));
  5176. ShmCharger->isLcdOn = OFF;
  5177. }
  5178. }
  5179. else
  5180. {
  5181. if(ShmCharger->isLcdOn == OFF)
  5182. {
  5183. DEBUG_INFO("LCD exit power saving...%d\n", getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD]));
  5184. ShmCharger->isLcdOn = ON;
  5185. }
  5186. }
  5187. if(getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_RFID]) > TIMEOUT_SPEC_POWERSAVING_RFID)
  5188. {
  5189. if(gpio_get_value(GPIO_OUT_RST_RFID) == ON)
  5190. {
  5191. DEBUG_INFO("RFID into power saving...%d\n", getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_RFID]));
  5192. gpio_set_value(GPIO_OUT_RST_RFID, OFF);
  5193. }
  5194. }
  5195. else
  5196. {
  5197. if(gpio_get_value(GPIO_OUT_RST_RFID) == OFF)
  5198. {
  5199. DEBUG_INFO("RFID exit power saving...%d\n", getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_RFID]));
  5200. gpio_set_value(GPIO_OUT_RST_RFID, ON);
  5201. }
  5202. }
  5203. if(getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_METER]) > TIMEOUT_SPEC_POWERSAVING_METER)
  5204. {
  5205. if(ShmCharger->gun_info[gun_index].isMeterOn)
  5206. {
  5207. DEBUG_INFO("Meter into power saving...%d\n", getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_METER]));
  5208. ShmCharger->gun_info[gun_index].isMeterOn = OFF;
  5209. }
  5210. }
  5211. else
  5212. {
  5213. if(!ShmCharger->gun_info[gun_index].isMeterOn)
  5214. {
  5215. DEBUG_INFO("Meter exit power saving...%d\n", getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_METER]));
  5216. ShmCharger->gun_info[gun_index].isMeterOn = ON;
  5217. }
  5218. }
  5219. if(getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]) > TIMEOUT_SPEC_POWERSAVING_LED_STATUS)
  5220. {
  5221. if(ShmCharger->gun_info[gun_index].isSleepOn == NO)
  5222. {
  5223. DEBUG_INFO("LED status into power saving...%d\n", getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]));
  5224. ShmCharger->gun_info[gun_index].isSleepOn = YES;
  5225. }
  5226. }
  5227. else
  5228. {
  5229. if(ShmCharger->gun_info[gun_index].isSleepOn == YES)
  5230. {
  5231. DEBUG_INFO("LED status exit power saving...%d\n", getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]));
  5232. ShmCharger->gun_info[gun_index].isSleepOn = NO;
  5233. }
  5234. }
  5235. //==========================================
  5236. // Synchronize current rating value from MCU
  5237. //==========================================
  5238. ShmSysConfigAndInfo->SysConfig.RatingCurrent = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
  5239. //==========================================
  5240. // Assign connector location index for OCPP
  5241. //==========================================
  5242. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].Index = gun_index;
  5243. //==========================================
  5244. // Synchronize present charging power
  5245. //==========================================
  5246. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount == 1)
  5247. {
  5248. if(ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON)
  5249. {
  5250. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingVoltage*ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrent)/1000;
  5251. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower <= 1.0)
  5252. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = 0;
  5253. }
  5254. else
  5255. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = 0;
  5256. }
  5257. else
  5258. {
  5259. if(ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON)
  5260. {
  5261. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = (((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingVoltage*ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrent)/1000) +
  5262. ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingVoltageL2*ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrentL2)/1000) +
  5263. ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingVoltageL3*ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrentL3)/1000));
  5264. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower <= 1.0)
  5265. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = 0;
  5266. }
  5267. else
  5268. {
  5269. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = 0;
  5270. }
  5271. }
  5272. //==========================================
  5273. // Check initialization "PASS" or "FAIL"
  5274. //==========================================
  5275. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[0].SystemStatus != SYS_MODE_BOOTING)
  5276. {
  5277. // Alarm event check
  5278. if((ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode>0) || (ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode>0) || ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CCSboardStestFail)
  5279. {
  5280. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_ALARM)
  5281. {
  5282. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_UPDATE)
  5283. {
  5284. setChargerMode(gun_index, SYS_MODE_ALARM);
  5285. }
  5286. }
  5287. }
  5288. }
  5289. //==========================================
  5290. // Reservation request check
  5291. //==========================================
  5292. checkReservation(gun_index);
  5293. //==========================================
  5294. // Change availability check
  5295. //==========================================
  5296. checkAvailability(gun_index);
  5297. if(ShmCharger->gun_info[gun_index].isOperactive)
  5298. {
  5299. if(isMode(gun_index, SYS_MODE_MAINTAIN))
  5300. {
  5301. setChargerMode(gun_index, SYS_MODE_IDLE);
  5302. }
  5303. }
  5304. else
  5305. {
  5306. if(isMode(gun_index, SYS_MODE_IDLE))
  5307. {
  5308. setChargerMode(gun_index, SYS_MODE_MAINTAIN);
  5309. }
  5310. }
  5311. //==========================================
  5312. // Unlock Connector signal check
  5313. //==========================================
  5314. checkUnlocker(gun_index);
  5315. //==========================================
  5316. // Clean EVCCID timeout flag
  5317. //==========================================
  5318. if((ShmSysConfigAndInfo->SysConfig.isAuthrizeByEVCCID && (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_ENABLE)) &&
  5319. (ShmCharger->isCcsEnable) &&
  5320. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A))
  5321. {
  5322. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  5323. {
  5324. ShmCharger->gun_info[gun_index].isGetEvCCIDTimeout = OFF;
  5325. ShmCharger->gun_info[gun_index].isEvCCIDAuthorizeFail = NO;
  5326. }
  5327. }
  5328. //==========================================
  5329. // Check EVCCID communcation error
  5330. //==========================================
  5331. if(ShmCharger->gun_info[gun_index].isGetEvCCIDTimeout == ON)
  5332. {
  5333. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEvCommFail == OFF)
  5334. ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEvCommFail = ON;
  5335. }
  5336. else
  5337. {
  5338. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEvCommFail == ON)
  5339. ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEvCommFail = OFF;
  5340. }
  5341. //==========================================
  5342. // Clean isRemoteStartWait flag
  5343. //==========================================
  5344. if(ocpp_get_isRemoteStartWait())
  5345. {
  5346. if(ShmCharger->gun_info[gun_index].isRemoteStartWait == OFF)
  5347. {
  5348. ShmCharger->gun_info[gun_index].isRemoteStartWait = ON;
  5349. DEBUG_INFO("Remote start without connector id... \n");
  5350. }
  5351. refreshStartTimer(&startTime[gun_index][TMR_IDX_CLEAN_REMOTE_START_WAIT]);
  5352. }
  5353. else
  5354. {
  5355. if((getDiffSecNow(startTime[gun_index][TMR_IDX_CLEAN_REMOTE_START_WAIT]) > 5))
  5356. {
  5357. if(ShmCharger->gun_info[gun_index].isRemoteStartWait == ON)
  5358. {
  5359. ShmCharger->gun_info[gun_index].isRemoteStartWait = OFF;
  5360. DEBUG_INFO("Clean isRemoteStartWait flag... \n");
  5361. }
  5362. }
  5363. if((getDiffSecNow(startTime[gun_index][TMR_IDX_CLEAN_REMOTE_START_WAIT]) > 10))
  5364. {
  5365. refreshStartTimer(&startTime[gun_index][TMR_IDX_CLEAN_REMOTE_START_WAIT]);
  5366. }
  5367. }
  5368. //==========================================
  5369. // Connector process
  5370. //==========================================
  5371. switch(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus)
  5372. {
  5373. case SYS_MODE_BOOTING:
  5374. if(isModeChange(gun_index))
  5375. {
  5376. setLedMotion(gun_index,LED_ACTION_INIT);
  5377. //CSU Initialization & task spawn
  5378. if((Initialization(gun_index) != PASS) ||
  5379. (SpawnTask(gun_index) != PASS))
  5380. {
  5381. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = ON;
  5382. }
  5383. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
  5384. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_RFID]);
  5385. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_METER]);
  5386. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_STATE_B]);
  5387. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]);
  5388. refreshStartTimer(&startTime[gun_index][TMR_IDX_LCM_POWER_CONSUMPTION]);
  5389. }
  5390. if(ShmCharger->gun_info[gun_index].mcuFlag.isReadFwVerPass &&
  5391. ShmCharger->gun_info[gun_index].mcuFlag.isSetModelNamePass &&
  5392. ShmCharger->gun_info[gun_index].mcuFlag.isSetSerialNumberPass)
  5393. {
  5394. ShmCharger->gun_selectd = 0;
  5395. // Firmware version
  5396. get_firmware_version(gun_index);
  5397. // OCPP BootNotification info set
  5398. DEBUG_INFO("==========================================\n");
  5399. DEBUG_INFO("System ID: %s\n",ShmSysConfigAndInfo->SysConfig.SystemId);
  5400. DEBUG_INFO("==========================================\n");
  5401. DEBUG_INFO("=== OCPP BootNotification information ====\n");
  5402. ocpp_boot_info_sync();
  5403. DEBUG_INFO("OcppServerURL: %s\n",ShmSysConfigAndInfo->SysConfig.OcppServerURL);
  5404. DEBUG_INFO("ChargeBoxId: %s\n",ShmSysConfigAndInfo->SysConfig.ChargeBoxId);
  5405. DEBUG_INFO("ChargePointVendor: %s\n",ShmSysConfigAndInfo->SysConfig.chargePointVendor);
  5406. DEBUG_INFO("==========================================\n");
  5407. DEBUG_INFO("========== Set Wifi information ==========\n");
  5408. DEBUG_INFO("Wifi mode: %d\n", ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode);
  5409. DEBUG_INFO("Wifi SSID: %s\n", ShmSysConfigAndInfo->SysConfig.AthInterface.WifiSsid);
  5410. DEBUG_INFO("Wifi password: %s\n", ShmSysConfigAndInfo->SysConfig.AthInterface.WifiPassword);
  5411. DEBUG_INFO("==========================================\n");
  5412. // Set max current to rating current
  5413. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
  5414. // Default Ethernet / Wifi / 4G to 1:disconnected
  5415. switch(ShmSysConfigAndInfo->SysConfig.ModelName[10])
  5416. {
  5417. case 'E':
  5418. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
  5419. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = OFF;
  5420. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = OFF;
  5421. break;
  5422. case 'W':
  5423. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
  5424. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = ON;
  5425. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = OFF;
  5426. break;
  5427. case 'T':
  5428. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
  5429. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = OFF;
  5430. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = ON;
  5431. break;
  5432. case 'D':
  5433. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
  5434. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = ON;
  5435. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = ON;
  5436. break;
  5437. }
  5438. // Default LCM brightness to 100
  5439. ShmCharger->isLcdOn = ON;
  5440. // Defaule led status to not sleep mode
  5441. ShmCharger->gun_info[gun_index].isSleepOn = NO;
  5442. // If Web Server OPCC URL is empty kill Module_OcppBackend
  5443. if((strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0))
  5444. {
  5445. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0)
  5446. DEBUG_INFO("URL is empty kill Module_OcppBackend...\n");
  5447. system ("pkill OcppBackend");
  5448. }
  5449. // If rotate switch equal zero, the system needs to change Debug mode
  5450. if(ShmCharger->gun_info[gun_index].primaryMcuState.rotatory_switch == 0)
  5451. setChargerMode(gun_index, SYS_MODE_DEBUG);
  5452. else
  5453. setChargerMode(gun_index, SYS_MODE_IDLE);
  5454. // The system identifies 1 phase or 3 phases depending on the model name
  5455. ShmSysConfigAndInfo->SysConfig.AcPhaseCount = ((ShmSysConfigAndInfo->SysConfig.ModelName[2]=='Y') ||
  5456. (ShmSysConfigAndInfo->SysConfig.ModelName[2]=='D') ||
  5457. (ShmSysConfigAndInfo->SysConfig.ModelName[2]=='W')
  5458. ?3:1);
  5459. // Refresh PTB resend timer
  5460. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  5461. refreshStartTimer(&startTime[gun_index][TMR_IDX_PTB_METER_SEND]);
  5462. }
  5463. break;
  5464. case SYS_MODE_IDLE:
  5465. if(isModeChange(gun_index))
  5466. {
  5467. setLedMotion(gun_index,LED_ACTION_IDLE);
  5468. setRelay(gun_index, OFF);
  5469. setRequest(gun_index,OFF);
  5470. ShmCharger->gun_info[gun_index].isGunPlugged = NO;
  5471. ShmCharger->gun_info[gun_index].isGunUnpluggedBefore = NO;
  5472. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  5473. ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart = OFF;
  5474. ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop = OFF;
  5475. ShmCharger->gun_info[gun_index].isGetEvCCID = OFF;
  5476. ocpp_set_remotestart(gun_index, OFF);
  5477. ocpp_set_remotestop(gun_index, OFF);
  5478. ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode = 0x00;
  5479. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = 0;
  5480. presentChargedEnergyClear(gun_index);
  5481. ShmCharger->gun_info[gun_index].targetCurrent = 0xFF;
  5482. ocpp_set_unlocker_req(gun_index, OFF);
  5483. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId = -1;
  5484. // Response StopTransactionConf
  5485. ocpp_set_stoptransaction_conf(gun_index, OFF);
  5486. memset(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId));
  5487. memset(ShmSysConfigAndInfo->SysConfig.UserId, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  5488. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_IDLE;
  5489. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_BS;
  5490. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  5491. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  5492. ShmCharger->gun_info[gun_index].isDoEvReadyOnce = OFF;
  5493. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  5494. //if(ShmCharger->isCcsEnable)system("pkill Module_CCS");
  5495. DB_Check_Record_Buf(localDb, gun_index);
  5496. ShmCharger->gun_info[gun_index].isEmergencyStopReport = OFF;
  5497. // Default previousData every time
  5498. previousData[gun_index].primaryMcuCp_Pwn_Duty = 0;
  5499. previousData[gun_index].targetCurrent = 0;
  5500. previousData[gun_index].current_limit = 0;
  5501. // Refresh PTB resend timer
  5502. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  5503. refreshStartTimer(&startTime[gun_index][TMR_IDX_PTB_METER_SEND]);
  5504. }
  5505. // Check missing PTB meter messages
  5506. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  5507. checkMissingPtbMeterMessage(gun_index);
  5508. // Check handshake timeout
  5509. checkHandshakeCountdown(gun_index);
  5510. // LED status in Idle mode
  5511. if(!ShmCharger->isAuthrizing)
  5512. {
  5513. if(ocpp_get_isRemoteStartWait())
  5514. {
  5515. ShmCharger->gun_info[gun_index].isSleepOn = OFF;
  5516. setLedMotion(gun_index, LED_ACTION_AUTHED);
  5517. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
  5518. //DEBUG_INFO("Remote Start Transaction without connector Id.\n");
  5519. }
  5520. else
  5521. {
  5522. if(ShmSysConfigAndInfo->SysInfo.OcppConnStatus == ON)
  5523. {
  5524. if(ShmCharger->gun_info[gun_index].rfidReq == OFF)
  5525. {
  5526. if(ShmCharger->gun_info[gun_index].isSleepOn == NO)
  5527. setLedMotion(gun_index,LED_ACTION_IDLE_BACKEND_CONNECTED);
  5528. else
  5529. setLedMotion(gun_index,LED_ACTION_IDLE_BACKEND_CONNECTED_SLEEP);
  5530. }
  5531. }
  5532. else
  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_DISCONNECTED);
  5538. else
  5539. setLedMotion(gun_index,LED_ACTION_IDLE_BACKEND_DISCONNECTED_SLEEP);
  5540. }
  5541. }
  5542. }
  5543. }
  5544. /*
  5545. * TODO:
  5546. * 1. Try to get EVCCID if plug first
  5547. */
  5548. if((ShmSysConfigAndInfo->SysConfig.isAuthrizeByEVCCID && (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_ENABLE)) &&
  5549. (ShmCharger->isCcsEnable) &&
  5550. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B) &&
  5551. (ShmCharger->gun_info[gun_index].isGetEvCCIDTimeout == OFF) &&
  5552. (ShmCharger->gun_info[gun_index].isRemoteStartWait != ON) &&
  5553. (ShmCharger->gun_info[gun_index].isEvCCIDAuthorizeFail != YES))
  5554. {
  5555. switch(ShmCharger->gun_info[gun_index].ccsHandshakeState)
  5556. {
  5557. case HANDSHAKE_DUTY_5:
  5558. if(!getRequest(gun_index))
  5559. {
  5560. setRequest(gun_index, ON);
  5561. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  5562. DEBUG_INFO("Try to get EVCCID, Set Request On.\n");
  5563. //Let CCS task start to negotiate
  5564. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = ON;
  5565. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_NONE;
  5566. }
  5567. // Set CCS 5% PWM duty
  5568. if(ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty == CCS_PWM_DUTY_5) //set 5% by SeccComm.c
  5569. {
  5570. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_5;
  5571. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_DUTY_5_CHECK;
  5572. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  5573. DEBUG_INFO("ccsHandshakeState = HANDSHAKE_DUTY_5_CHECK\n");
  5574. }
  5575. break;
  5576. case HANDSHAKE_DUTY_5_CHECK:
  5577. if((ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF))
  5578. {
  5579. //2 secs timeout
  5580. refreshStartTimer(&startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]);
  5581. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_CCS;
  5582. DEBUG_INFO("ccsHandshakeState = HANDSHAKE_CCS\n");
  5583. }
  5584. break;
  5585. case HANDSHAKE_CCS:
  5586. if(getDiffSecNow(startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]) > TIMEOUT_SPEC_BS_HLC_HANDSHAKE)
  5587. {
  5588. ShmCharger->gun_info[gun_index].isGetEvCCIDTimeout = ON;
  5589. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  5590. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  5591. setLedMotion(gun_index, LED_ACTION_HANDSHAKE_FAIL);
  5592. setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
  5593. DEBUG_INFO("Get EVCCID timeout.\n");
  5594. sleep(3);
  5595. }
  5596. if((19 <= ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus) && (ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus < 253))
  5597. {
  5598. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  5599. {
  5600. sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%s%02X%02X%02X%02X%02X%02X", ShmOCPP16Data->ConfigurationTable.CoreProfile[EVCCID_PREFIX].ItemData,
  5601. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[0],
  5602. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[1],
  5603. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[2],
  5604. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[3],
  5605. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[4],
  5606. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[5]);
  5607. }
  5608. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  5609. {
  5610. sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X", ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[0],
  5611. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[1],
  5612. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[2],
  5613. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[3],
  5614. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[4],
  5615. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[5]);
  5616. }
  5617. //sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "F5902677");
  5618. ShmCharger->gun_info[gun_index].isGetEvCCID = ON;
  5619. DEBUG_INFO("Got EVCCID: %s\n", ShmSysConfigAndInfo->SysConfig.UserId);
  5620. }
  5621. break;
  5622. default:
  5623. break;
  5624. }
  5625. }
  5626. else
  5627. {
  5628. if(getRequest(gun_index))
  5629. {
  5630. setRequest(gun_index, OFF);
  5631. }
  5632. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_DUTY_5;
  5633. }
  5634. if(((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B)) ||
  5635. ((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)) ||
  5636. ((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) && (ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn == ON)) ||
  5637. (ShmCharger->gun_info[gun_index].rfidReq == ON) ||
  5638. (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart == ON) ||
  5639. (ocpp_get_remotestart(gun_index) == ON) ||
  5640. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStart == ON) ||
  5641. (ShmCharger->gun_info[gun_index].isGetEvCCID == ON))
  5642. {
  5643. if((ShmCharger->gun_info[gun_index].rfidReq == ON))
  5644. {
  5645. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_RFID;
  5646. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_ISO14443;
  5647. DEBUG_INFO("Start Method : RFID...\n");
  5648. }
  5649. else if(ocpp_get_remotestart(gun_index))
  5650. {
  5651. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_BACKEND;
  5652. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_Central;
  5653. ocpp_copy_userid_from_remotestart(gun_index);
  5654. setSpeaker(ON, SPEAKER_SHORT);
  5655. DEBUG_INFO("Start Method : BACKEND...\n");
  5656. }
  5657. else if(ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart == ON)
  5658. {
  5659. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_BLE;
  5660. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_Local;
  5661. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmCharger->gun_info[gun_index].bleLoginCentralId.id, ARRAY_SIZE(ShmCharger->gun_info[gun_index].bleLoginCentralId.id));
  5662. setSpeaker(ON, SPEAKER_SHORT);
  5663. DEBUG_INFO("Start Method : BLE...\n");
  5664. }
  5665. else if(ShmCharger->gun_info[gun_index].isGetEvCCID == ON)
  5666. {
  5667. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_EVCCID;
  5668. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_MacAddress;
  5669. setSpeaker(ON, SPEAKER_SHORT);
  5670. DEBUG_INFO("Start Method : EVCCID...\n");
  5671. }
  5672. else
  5673. {
  5674. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_FREE;
  5675. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_NoAuthorization;
  5676. //memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmSysConfigAndInfo->SysConfig.SerialNumber, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SerialNumber));
  5677. ocpp_get_freevend_idtag(ShmSysConfigAndInfo->SysConfig.UserId);
  5678. setSpeaker(ON, SPEAKER_SHORT);
  5679. DEBUG_INFO("Start Method : FREE...\n");
  5680. }
  5681. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  5682. ocpp_set_remotestart(gun_index, OFF);
  5683. ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart = OFF;
  5684. ShmCharger->gun_info[gun_index].isGunPlugged = NO;
  5685. ShmCharger->gun_info[gun_index].isGunUnpluggedBefore = NO;
  5686. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStart = OFF;
  5687. ShmCharger->gun_info[gun_index].isGetEvCCID = OFF;
  5688. // Get target current
  5689. ocpp_set_profile_req(gun_index, ON);
  5690. sleep(1);
  5691. checkChargingProfileLimit(gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus);
  5692. setChargerMode(gun_index, SYS_MODE_AUTHORIZING);
  5693. }
  5694. else
  5695. {}
  5696. break;
  5697. case SYS_MODE_AUTHORIZING:
  5698. if(isModeChange(gun_index))
  5699. {
  5700. refreshStartTimer(&startTime[gun_index][TMR_IDX_AUTH]);
  5701. if(ocpp_isAuthorizeRemoteStart() && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod == START_METHOD_BACKEND))
  5702. {
  5703. DEBUG_INFO("Remote start request authorize.\n");
  5704. ocpp_set_auth_req(ON, "ISO14443");
  5705. }
  5706. else if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod == START_METHOD_EVCCID))
  5707. {
  5708. DEBUG_INFO("EVCCID request authorize.\n");
  5709. ocpp_set_auth_req(ON, "MacAddress");
  5710. }
  5711. }
  5712. if(getDiffSecNow(startTime[gun_index][TMR_IDX_AUTH]) > TIMEOUT_SPEC_AUTH)
  5713. {
  5714. // Authorization timeout process.
  5715. setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
  5716. setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
  5717. sleep(3);
  5718. setChargerMode(gun_index, SYS_MODE_IDLE);
  5719. DEBUG_WARN("Authorize timeout !!!\n");
  5720. }
  5721. else
  5722. {
  5723. switch(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod)
  5724. {
  5725. case START_METHOD_BACKEND:
  5726. if(ocpp_isAuthorizeRemoteStart())
  5727. {
  5728. if(ocpp_get_auth_conf())
  5729. {
  5730. if(ocpp_get_auth_result(YES, gun_index))
  5731. {
  5732. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  5733. DEBUG_INFO("[START_METHOD_BACKEND] StartUserId : %s \n",ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId);
  5734. DEBUG_INFO("Authorize pass.\n");
  5735. setSpeaker(ON,SPEAKER_SHORT);
  5736. setLedMotion(gun_index,LED_ACTION_RFID_PASS);
  5737. #if 0
  5738. if(ShmCharger->isCcsEnable)
  5739. {
  5740. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_CP_STATE_F;
  5741. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  5742. sleep(4);
  5743. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  5744. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  5745. //system("/root/Module_CCS &");
  5746. }
  5747. else
  5748. #endif
  5749. sleep(4);
  5750. setChargerMode(gun_index, SYS_MODE_PREPARING);
  5751. }
  5752. else
  5753. {
  5754. DEBUG_INFO("Authorize fail.\n");
  5755. setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
  5756. setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
  5757. sleep(3);
  5758. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId == -1)
  5759. setChargerMode(gun_index, SYS_MODE_IDLE);
  5760. else
  5761. setChargerMode(gun_index, SYS_MODE_RESERVATION);
  5762. }
  5763. ocpp_set_auth_conf(OFF);
  5764. }
  5765. }
  5766. else
  5767. {
  5768. if(ShmCharger->isCcsEnable)
  5769. {
  5770. //ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_CP_STATE_F;
  5771. //ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  5772. //sleep(4);
  5773. //ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  5774. //ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  5775. //system("/root/Module_CCS &");
  5776. }
  5777. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  5778. DEBUG_INFO("[START_METHOD_BACKEND] StartUserId : %s \n",ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId);
  5779. setChargerMode(gun_index, SYS_MODE_PREPARING);
  5780. }
  5781. break;
  5782. case START_METHOD_EVCCID:
  5783. ShmCharger->gun_info[gun_index].resultAuthorization = UNKNOW_RFID;
  5784. if(ocpp_get_auth_conf() ||
  5785. (!ocpp_get_connection_status() && ((ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE) || (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_NOCHARGE))) ||
  5786. (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST) && (getDiffSecNow(startTime[0][TMR_IDX_AUTH]) > 2)))
  5787. {
  5788. if(ocpp_get_auth_result(YES, gun_index) ||
  5789. (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE)) ||
  5790. (!ocpp_get_connection_status() && (isValidLocalWhiteCard() == PASS) && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST)))
  5791. {
  5792. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  5793. DEBUG_INFO("[START_METHOD_EVCCID] StartUserId : %s \n",ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId);
  5794. ShmCharger->gun_info[gun_index].resultAuthorization = VALIDATED_RFID;
  5795. DEBUG_INFO("Authorize pass [EVCCID].\n");
  5796. setSpeaker(ON, SPEAKER_SHORT);
  5797. setLedMotion(gun_index, LED_ACTION_RFID_PASS);
  5798. sleep(1);
  5799. setChargerMode(gun_index, SYS_MODE_PREPARING);
  5800. ShmCharger->gun_info[gun_index].isEvCCIDAuthorizeFail = NO;
  5801. }
  5802. else
  5803. {
  5804. ShmCharger->gun_info[gun_index].resultAuthorization = UNVALIDATED_RFID;
  5805. DEBUG_INFO("Authorize fail [EVCCID].\n");
  5806. setSpeaker(ON, SPEAKER_INTERVAL_3COUNT);
  5807. setLedMotion(gun_index, LED_ACTION_RFID_FAIL);
  5808. sleep(3);
  5809. setChargerMode(gun_index, SYS_MODE_IDLE);
  5810. ShmCharger->gun_info[gun_index].isEvCCIDAuthorizeFail = YES;
  5811. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  5812. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  5813. }
  5814. ocpp_set_auth_conf(OFF);
  5815. }
  5816. break;
  5817. case START_METHOD_RFID:
  5818. case START_METHOD_BLE:
  5819. case START_METHOD_FREE:
  5820. default:
  5821. if(ShmCharger->isCcsEnable)
  5822. {
  5823. //ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_CP_STATE_F;
  5824. //ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  5825. //sleep(4);
  5826. //ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  5827. //ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  5828. //system("/root/Module_CCS &");
  5829. }
  5830. setChargerMode(gun_index, SYS_MODE_PREPARING);
  5831. break;
  5832. }
  5833. }
  5834. break;
  5835. case SYS_MODE_PREPARING:
  5836. if(isModeChange(gun_index))
  5837. {
  5838. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  5839. setLedMotion(gun_index,LED_ACTION_AUTHED);
  5840. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  5841. if(ShmCharger->isCcsEnable)
  5842. {
  5843. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod != START_METHOD_EVCCID)
  5844. {
  5845. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_DUTY_5;
  5846. DEBUG_INFO("ccsHandshakeState = HANDSHAKE_DUTY_5\n");
  5847. }
  5848. }
  5849. else
  5850. {
  5851. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_CP_STATE_E;
  5852. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_BS;
  5853. setRequest(gun_index, ON);
  5854. }
  5855. }
  5856. // If control pilot detect Bx, skip watch dog time out.
  5857. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B) ||
  5858. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C))
  5859. {
  5860. ShmCharger->gun_info[gun_index].isGunPlugged = YES;
  5861. ShmCharger->gun_info[gun_index].isGunUnpluggedBefore = NO;
  5862. switch(ShmCharger->gun_info[gun_index].ccsHandshakeState)
  5863. {
  5864. case HANDSHAKE_DUTY_5:
  5865. if(!getRequest(gun_index))
  5866. {
  5867. setRequest(gun_index, ON);
  5868. setLedMotion(gun_index,LED_ACTION_CONNECTED);
  5869. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  5870. DEBUG_INFO("Set Request On.\n");
  5871. //Let CCS task start to negotiate
  5872. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = ON;
  5873. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_NONE;
  5874. }
  5875. // Set CCS 5% PWM duty
  5876. if(ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty == CCS_PWM_DUTY_5)//set 5% by SeccComm.c
  5877. {
  5878. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_5;
  5879. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_DUTY_5_CHECK;
  5880. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  5881. DEBUG_INFO("ccsHandshakeState = HANDSHAKE_DUTY_5_CHECK\n");
  5882. }
  5883. break;
  5884. case HANDSHAKE_DUTY_5_CHECK:
  5885. if((ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF))
  5886. {
  5887. //2 secs timeout
  5888. refreshStartTimer(&startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]);
  5889. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_CCS;
  5890. DEBUG_INFO("ccsHandshakeState = HANDSHAKE_CCS\n");
  5891. }
  5892. break;
  5893. case HANDSHAKE_CCS:
  5894. //CCS handshake timeout
  5895. if(getDiffSecNow(startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]) > TIMEOUT_SPEC_BS_HLC_HANDSHAKE)
  5896. {
  5897. if(ShmCharger->isCcsEnable)
  5898. {
  5899. DEBUG_INFO("TIMEOUT_SPEC_BS_HLC_HANDSHAKE.\n");
  5900. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  5901. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_CP_STATE_F;
  5902. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  5903. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_CP_STATE_E;
  5904. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_BS;
  5905. break;
  5906. }
  5907. else
  5908. {
  5909. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  5910. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  5911. DEBUG_INFO("BS/HLC %d secs handshake timeout.\n", TIMEOUT_SPEC_BS_HLC_HANDSHAKE);
  5912. }
  5913. }
  5914. if((ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission == OFF) && (ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty != CCS_PWM_DUTY_5))
  5915. {
  5916. DEBUG_INFO("Wait CCS give up negotiagting.\n");
  5917. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_CP_STATE_F;
  5918. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  5919. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_CP_STATE_E;
  5920. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_BS;
  5921. }
  5922. //CCS status check
  5923. #if 0
  5924. if((16 < ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus) && (ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus < 254))
  5925. {
  5926. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_HLC;
  5927. DEBUG_INFO("Enter HLC Mode charging.\n");
  5928. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_HLC_MODE;
  5929. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  5930. }
  5931. #else
  5932. if((16 <= ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus) && (ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus < 253))
  5933. {
  5934. //chang PWM duty to BS
  5935. if((ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)&&(ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current!=CCS_PWM_DUTY_5))
  5936. {
  5937. 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);
  5938. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  5939. DEBUG_INFO("ccsHandshakeState = HANDSHAKE_CCS (set 5% duty)\n");
  5940. }
  5941. //ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_HLC;
  5942. //ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_HLC_MODE;
  5943. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  5944. }
  5945. if((37 <= ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus) && (ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus < 49))
  5946. {
  5947. //chang PWM duty to BS
  5948. if((ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)&&(ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current!=CCS_PWM_DUTY_5))
  5949. {
  5950. 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);
  5951. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  5952. }
  5953. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_HLC;
  5954. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_HLC_MODE;
  5955. //refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  5956. DEBUG_INFO("ccsHandshakeState = HANDSHAKE_HLC_MODE\n");
  5957. }
  5958. else if((54 < ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus) && (ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus <= 255))
  5959. {
  5960. DEBUG_INFO("ccsHandshakeState = CHARGING_MODE_BS, CCS terminated\n");
  5961. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  5962. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_CP_STATE_F;
  5963. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  5964. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_CP_STATE_E;
  5965. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_BS;
  5966. }
  5967. #endif
  5968. break;
  5969. case HANDSHAKE_CP_STATE_E:
  5970. if(ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)
  5971. {
  5972. if(ShmCharger->isCcsEnable)
  5973. {
  5974. DEBUG_INFO("Change to CP STATE E for 4 secs.\n");
  5975. //CP STATE E for 4 secs
  5976. sleep(4);
  5977. }
  5978. //restore normal CP PWM duty
  5979. // Determine max charging current to MCU
  5980. DEBUG_INFO("Determine max charging current to MCU.\n");
  5981. ocpp_set_profile_req(gun_index, ON);
  5982. sleep(1);
  5983. checkChargingProfileLimit(gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus);
  5984. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_SET_MAX_CURRENT;
  5985. refreshStartTimer(&startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]);
  5986. }
  5987. break;
  5988. case HANDSHAKE_SET_MAX_CURRENT:
  5989. if(ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)
  5990. {
  5991. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_BS_MODE;
  5992. DEBUG_INFO("Enter BS Mode charging.\n");
  5993. //for EV READY 30 secs didn't start charging to STATE E
  5994. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  5995. }
  5996. break;
  5997. case HANDSHAKE_BS_MODE:
  5998. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  5999. checkChargingProfileLimit(gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus);
  6000. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C) && ((ShmCharger->gun_info[gun_index].targetCurrent != 0)))
  6001. {
  6002. setRelay(gun_index,ON);
  6003. }
  6004. if((ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON) || (ShmCharger->gun_info[gun_index].targetCurrent == 0))
  6005. {
  6006. ocpp_set_unlocker_req(gun_index, OFF);
  6007. presentChargedEnergyClear(gun_index);
  6008. getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime);
  6009. ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption;
  6010. ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption;
  6011. ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption;
  6012. ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption;
  6013. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==1)
  6014. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  6015. else
  6016. {
  6017. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  6018. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[0] = (ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption/10000.0);
  6019. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[1] = (ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption/10000.0);
  6020. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[2] = (ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption/10000.0);
  6021. }
  6022. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  6023. ocpp_copy_userid_to_starttransaction(gun_index);
  6024. ocpp_set_starttransaction_req(gun_index, ON);
  6025. refreshStartTimer(&startChargingTime[gun_index]);
  6026. // PTB Permission
  6027. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  6028. setPtbMeterPermission(gun_index, PERMISSION_START_CHARGING);
  6029. setChargerMode(gun_index, SYS_MODE_CHARGING);
  6030. }
  6031. //EV READY CHECK
  6032. /*
  6033. if((DiffTimebWithNow(startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]) > TIMEOUT_SPEC_EV_READY) && (ShmCharger->gun_info[gun_index].isEvReady2StateE == OFF))
  6034. {
  6035. if(ShmCharger->gun_info[gun_index].isDoEvReadyOnce == OFF)
  6036. {
  6037. DEBUG_INFO("EV READY STATE E 4sec.\n");
  6038. ShmCharger->gun_info[gun_index].isEvReady2StateE = ON;
  6039. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_CP_STATE_E;
  6040. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6041. ShmCharger->gun_info[gun_index].evReadyState = EV_READY_STAT_E;
  6042. }
  6043. }
  6044. if(ShmCharger->gun_info[gun_index].isEvReady2StateE == ON)
  6045. {
  6046. switch(ShmCharger->gun_info[gun_index].evReadyState)
  6047. {
  6048. case EV_READY_STAT_E:
  6049. if(ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)
  6050. {
  6051. sleep(4);
  6052. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  6053. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6054. ShmCharger->gun_info[gun_index].evReadyState = EV_READY_STAT_C;
  6055. }
  6056. break;
  6057. case EV_READY_STAT_C:
  6058. if(ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)
  6059. {
  6060. usleep(500000);
  6061. DEBUG_INFO("EV READY Determine max charging current to MCU.\n");
  6062. if(ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent == 0)
  6063. {
  6064. 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);
  6065. if(ShmCharger->gun_info[gun_index].targetCurrent != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current)
  6066. {
  6067. 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);
  6068. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6069. }
  6070. }
  6071. else
  6072. {
  6073. ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent)?ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent:ShmCharger->gun_info[gun_index].targetCurrent);
  6074. if(ShmCharger->gun_info[gun_index].targetCurrent != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current)
  6075. {
  6076. 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);
  6077. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6078. }
  6079. }
  6080. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6081. ShmCharger->gun_info[gun_index].evReadyState = EV_READY_SET_MAX_CURRENT;
  6082. }
  6083. break;
  6084. case EV_READY_SET_MAX_CURRENT:
  6085. if(ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)
  6086. {
  6087. ShmCharger->gun_info[gun_index].isEvReady2StateE = OFF;
  6088. ShmCharger->gun_info[gun_index].isDoEvReadyOnce = ON;
  6089. }
  6090. break;
  6091. default:
  6092. break;
  6093. }
  6094. }*/
  6095. break;
  6096. case HANDSHAKE_HLC_MODE:
  6097. if(ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_START_MODE)//powerDelivery
  6098. {
  6099. if(ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn == OFF)
  6100. {
  6101. setRelay(gun_index,ON);
  6102. ShmCharger->gun_info[gun_index].isCCSStartTransation = ON;
  6103. DEBUG_INFO("HANDSHAKE_HLC_MODE:setRelay ON\n");
  6104. }
  6105. }
  6106. if((ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON) &&
  6107. (ShmCharger->gun_info[gun_index].isCCSStartTransation == ON))
  6108. {
  6109. DEBUG_INFO("HANDSHAKE_HLC_MODE:Relay ON done\n");
  6110. ocpp_set_unlocker_req(gun_index, OFF);
  6111. presentChargedEnergyClear(gun_index);
  6112. getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime);
  6113. ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption;
  6114. ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption;
  6115. ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption;
  6116. ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption;
  6117. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==1)
  6118. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  6119. else
  6120. {
  6121. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  6122. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[0] = (ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption/10000.0);
  6123. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[1] = (ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption/10000.0);
  6124. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[2] = (ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption/10000.0);
  6125. }
  6126. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  6127. ocpp_copy_userid_to_starttransaction(gun_index);
  6128. ocpp_set_starttransaction_req(gun_index, ON);
  6129. ShmCharger->gun_info[gun_index].isCCSStartTransation = OFF;
  6130. // PTB Permission
  6131. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  6132. setPtbMeterPermission(gun_index, PERMISSION_START_CHARGING);
  6133. setChargerMode(gun_index, SYS_MODE_CHARGING);
  6134. DEBUG_INFO("set SYS_MODE_CHARGING\n");
  6135. refreshStartTimer(&startChargingTime[gun_index]);
  6136. refreshStartTimer(&startTime[gun_index][TMR_IDX_CCS_HEARTBEAT_COUNT_RESET]);
  6137. }
  6138. //120 sec timeout
  6139. if(getDiffSecNow(startTime[gun_index][TMR_IDX_HANDSHAKING]) > TIMEOUT_SPEC_CCS_HANDSHAKE)
  6140. {
  6141. setLedMotion(gun_index, LED_ACTION_HANDSHAKE_FAIL);
  6142. if(getDiffSecNow(startTime[gun_index][TMR_IDX_HANDSHAKING]) > TIMEOUT_SPEC_CCS_HANDSHAKE+5)
  6143. {
  6144. DEBUG_INFO("CCS 120 secs handshake timeout, change to BS Mode...\n");
  6145. //Cancel CCS task negotiating
  6146. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  6147. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  6148. //ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = ON;
  6149. if((ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission == OFF) && (ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty != CCS_PWM_DUTY_5))
  6150. {
  6151. DEBUG_INFO("Wait CCS give up negotiagting.\n");
  6152. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_CP_STATE_F;
  6153. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6154. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_CP_STATE_E;
  6155. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_BS;
  6156. }
  6157. }
  6158. }
  6159. break;
  6160. default:
  6161. break;
  6162. }
  6163. }
  6164. else if(ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEMode)
  6165. {
  6166. DEBUG_INFO("Enter Socket-E Mode charging.\n");
  6167. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_SOCKETE;
  6168. if(ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn == ON)
  6169. setRelay(gun_index,ON);
  6170. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  6171. ocpp_copy_userid_to_starttransaction(gun_index);
  6172. ocpp_set_starttransaction_req(gun_index, ON);
  6173. refreshStartTimer(&startChargingTime[gun_index]);
  6174. // PTB Permission
  6175. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  6176. setPtbMeterPermission(gun_index, PERMISSION_START_CHARGING);
  6177. setChargerMode(gun_index, SYS_MODE_CHARGING);
  6178. }
  6179. else if(ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn == ON)
  6180. {
  6181. setRequest(gun_index, ON);
  6182. ShmCharger->gun_info[gun_index].isGunUnpluggedBefore = NO;
  6183. }
  6184. // Unplug charging gun to Idle mode
  6185. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A) && (ShmCharger->gun_info[gun_index].isGunPlugged == YES))
  6186. {
  6187. DEBUG_INFO("Unplug the connector.\n");
  6188. //Cancel CCS task negotiating
  6189. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  6190. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  6191. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = ON;
  6192. }
  6193. // Use RFID card to stop handshaking
  6194. if((ShmCharger->gun_info[gun_index].rfidReq == ON))
  6195. {
  6196. DEBUG_INFO("Use RFID card to stop handshaking.\n");
  6197. //Cancel CCS task negotiating
  6198. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  6199. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  6200. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = ON;
  6201. }
  6202. else
  6203. {
  6204. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  6205. }
  6206. // Check handshake timeout
  6207. checkHandshakeCountdown(gun_index);
  6208. if(getDiffSecNow(startTime[gun_index][TMR_IDX_HANDSHAKING]) > ShmCharger->timeoutSpec.Present_Timeout_Spec)
  6209. {
  6210. setLedMotion(gun_index, LED_ACTION_HANDSHAKE_FAIL);
  6211. if(getDiffSecNow(startTime[gun_index][TMR_IDX_HANDSHAKING]) > (ShmCharger->timeoutSpec.Present_Timeout_Spec+5))
  6212. {
  6213. DEBUG_INFO("Handshaking timeout...\n");
  6214. //Cancel CCS task negotiating
  6215. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  6216. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  6217. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = ON;
  6218. }
  6219. }
  6220. if((ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty == ON) && ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty != CCS_PWM_DUTY_5)
  6221. {
  6222. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  6223. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6224. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = OFF;
  6225. setChargerMode(gun_index, SYS_MODE_IDLE);
  6226. }
  6227. break;
  6228. case SYS_MODE_CHARGING:
  6229. if(isModeChange(gun_index))
  6230. {
  6231. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  6232. //ftime(&startChargingTime[gun_index]);
  6233. refreshStartTimer(&startTime[gun_index][TMR_IDX_REFRESH_CHARGING_INFO]);
  6234. refreshStartTimer(&startTime[gun_index][TMR_IDX_PROFILE_PREPARE]);
  6235. refreshStartTimer(&startTime[gun_index][TMR_IDX_PWN_CHANGE]);
  6236. ocpp_reset_smartcharging_profileId(gun_index);
  6237. ocpp_set_profile_req(gun_index, ON);
  6238. ShmCharger->gun_info[gun_index].isChargerStopByCondition = NO;
  6239. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  6240. // Refresh timer for getting PTB meter message
  6241. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  6242. refreshStartTimer(&startTime[gun_index][TMR_IDX_PTB_METER_MESSAGE]);
  6243. }
  6244. //if time up, clear CCS MSG count
  6245. if((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) &&
  6246. (getDiffSecNow(startTime[gun_index][TMR_IDX_CCS_HEARTBEAT_COUNT_RESET]) > TIMEOUT_SPEC_CCS_HEARTBEAT_COUNT_RESET))
  6247. {
  6248. refreshStartTimer(&startTime[gun_index][TMR_IDX_CCS_HEARTBEAT_COUNT_RESET]);
  6249. /*if(ShmCharger->gun_info[gun_index].acCcsInfo.CcsHeartBeat > 0)
  6250. {
  6251. ShmCharger->gun_info[gun_index].acCcsInfo.CcsHeartBeat = 0;
  6252. }
  6253. else
  6254. {
  6255. DEBUG_INFO("CCS could not get MSG from car.\n");
  6256. //setChargerMode(gun_index, SYS_MODE_TERMINATING);
  6257. //setRelay(gun_index, OFF);
  6258. }*/
  6259. }
  6260. // If unplug the connector during a session, the system must stop charging and stop session.
  6261. if((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS) || (ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC))
  6262. {
  6263. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A))
  6264. {
  6265. if(ShmCharger->gun_info[gun_index].isGunUnpluggedBefore != YES)
  6266. {
  6267. ShmCharger->gun_info[gun_index].isGunUnpluggedBefore = YES;
  6268. DEBUG_INFO("The connector was unplugged under CHARGING. [CHARGING_MODE_BS / CHARGING_MODE_HLC]. \n");
  6269. }
  6270. }
  6271. }
  6272. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE)
  6273. {
  6274. if(ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn != ON)
  6275. {
  6276. if(ShmCharger->gun_info[gun_index].isGunUnpluggedBefore != YES)
  6277. {
  6278. ShmCharger->gun_info[gun_index].isGunUnpluggedBefore = YES;
  6279. DEBUG_INFO("The socket e was unplugged under CHARGING. [CHARGING_MODE_SOCKETE]. \n");
  6280. }
  6281. }
  6282. }
  6283. else
  6284. {}
  6285. if((ShmCharger->gun_info[gun_index].isGunUnpluggedBefore == YES) ||
  6286. (ShmCharger->gun_info[gun_index].rfidReq == ON) ||
  6287. (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop == ON) ||
  6288. ocpp_get_remotestop(gun_index) ||
  6289. (ocpp_get_connection_status() && !ocpp_get_starttransaction_result(gun_index)) ||
  6290. ((ShmCharger->gun_info[gun_index].chargingMode != CHARGING_MODE_SOCKETE) && ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState != CP_STATE_C) ||
  6291. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE) && !ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn) ||
  6292. ocpp_get_reset_req() ||
  6293. ocpp_get_unlocker_req(gun_index) ||
  6294. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop == ON) ||
  6295. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && (ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_STOP_MODE)) ||
  6296. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && (ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_RENEGOTIATE_MODE)) ||
  6297. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && (ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_STANDBY_MODE)) ||
  6298. ((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)))
  6299. )
  6300. {
  6301. //printf("EVChargeProgress=0x%x, PresentMsgFlowStatus=0x%x\n",ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress,ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus);
  6302. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  6303. }
  6304. else
  6305. {
  6306. // Charging session info calculation
  6307. setLedMotion(gun_index,LED_ACTION_CHARGING);
  6308. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==1)
  6309. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  6310. else
  6311. {
  6312. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  6313. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[0] = (ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption/10000.0);
  6314. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[1] = (ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption/10000.0);
  6315. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[2] = (ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption/10000.0);
  6316. }
  6317. refreshStartTimer(&endChargingTime[gun_index]);
  6318. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = getDiffSecBetween(startChargingTime[gun_index], endChargingTime[gun_index]);
  6319. presentChargedEnergyUpdate(gun_index);
  6320. // Response StartTransactionConf
  6321. ocpp_set_starttransaction_conf(gun_index, OFF);
  6322. // Charging profile preparation
  6323. if((getDiffSecNow(startTime[gun_index][TMR_IDX_PROFILE_PREPARE]) > TIMEOUT_SPEC_PROFILE_PREPARE) || (getDiffSecNow(startTime[gun_index][TMR_IDX_PROFILE_PREPARE]) < 0))
  6324. {
  6325. if(!ocpp_get_profile_conf(gun_index))
  6326. {
  6327. ocpp_set_profile_req(gun_index, ON);
  6328. refreshStartTimer(&startTime[gun_index][TMR_IDX_PROFILE_PREPARE]);
  6329. }
  6330. else
  6331. {
  6332. ocpp_set_profile_conf(gun_index, OFF);
  6333. }
  6334. }
  6335. // Checking profile id > 0 and current time is between charging profile validFrom & validTo
  6336. checkChargingProfileLimit(gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus);
  6337. // Charging session local limit condition check
  6338. if(ocpp_get_connection_status())
  6339. {
  6340. // On-line max condition check
  6341. if((ShmSysConfigAndInfo->SysConfig.MaxChargingDuration > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60)))
  6342. {
  6343. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  6344. {
  6345. setRelay(gun_index, OFF);
  6346. ShmCharger->gun_info[gun_index].isChargerStopByCondition = YES;
  6347. }
  6348. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  6349. {
  6350. setRelay(gun_index, OFF);
  6351. }
  6352. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE)
  6353. {
  6354. setRelay(gun_index, OFF);
  6355. }
  6356. else
  6357. {}
  6358. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  6359. 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));
  6360. }
  6361. else if((ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy)))
  6362. {
  6363. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  6364. {
  6365. setRelay(gun_index, OFF);
  6366. ShmCharger->gun_info[gun_index].isChargerStopByCondition = YES;
  6367. }
  6368. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  6369. {
  6370. setRelay(gun_index, OFF);
  6371. }
  6372. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE)
  6373. {
  6374. setRelay(gun_index, OFF);
  6375. }
  6376. else
  6377. {}
  6378. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  6379. 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));
  6380. }
  6381. else
  6382. {
  6383. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  6384. {
  6385. ShmCharger->gun_info[gun_index].isChargerStopByCondition = NO;
  6386. if(ShmCharger->gun_info[gun_index].targetCurrent>0)
  6387. setRelay(gun_index, ON);
  6388. else
  6389. setRelay(gun_index, OFF);
  6390. }
  6391. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  6392. {
  6393. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)
  6394. setRelay(gun_index, ON);
  6395. }
  6396. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE)
  6397. {
  6398. if(ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn == ON)
  6399. setRelay(gun_index, ON);
  6400. else
  6401. setRelay(gun_index, OFF);
  6402. }
  6403. else
  6404. {}
  6405. }
  6406. }
  6407. else
  6408. {
  6409. // Off-line max condition check
  6410. if((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) ||
  6411. ((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_ENABLE) && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy != OFF_POLICY_NOCHARGE)))
  6412. {
  6413. 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))))
  6414. {
  6415. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  6416. {
  6417. setRelay(gun_index, OFF);
  6418. ShmCharger->gun_info[gun_index].isChargerStopByCondition = YES;
  6419. }
  6420. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  6421. {
  6422. setRelay(gun_index, OFF);
  6423. }
  6424. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE)
  6425. {
  6426. setRelay(gun_index, OFF);
  6427. }
  6428. else
  6429. {}
  6430. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  6431. 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));
  6432. }
  6433. 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))))
  6434. {
  6435. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  6436. {
  6437. setRelay(gun_index, OFF);
  6438. ShmCharger->gun_info[gun_index].isChargerStopByCondition = YES;
  6439. }
  6440. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  6441. {
  6442. setRelay(gun_index, OFF);
  6443. }
  6444. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE)
  6445. {
  6446. setRelay(gun_index, OFF);
  6447. }
  6448. else
  6449. {}
  6450. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  6451. 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));
  6452. }
  6453. else
  6454. {
  6455. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  6456. {
  6457. ShmCharger->gun_info[gun_index].isChargerStopByCondition = NO;
  6458. if(ShmCharger->gun_info[gun_index].targetCurrent>0)
  6459. setRelay(gun_index, ON);
  6460. else
  6461. setRelay(gun_index, OFF);
  6462. }
  6463. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  6464. {
  6465. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)
  6466. setRelay(gun_index, ON);
  6467. }
  6468. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE)
  6469. {
  6470. if(ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn == ON)
  6471. setRelay(gun_index, ON);
  6472. else
  6473. setRelay(gun_index, OFF);
  6474. }
  6475. else
  6476. {}
  6477. }
  6478. }
  6479. else
  6480. {
  6481. if(ShmCharger->gun_info[gun_index].primaryMcuState.relay_state > 0)
  6482. DEBUG_INFO("Connector-%d can not charging in off line\n", gun_index);
  6483. setRelay(gun_index, OFF);
  6484. }
  6485. }
  6486. // Debug information
  6487. if((getDiffSecNow(startTime[gun_index][TMR_IDX_REFRESH_CHARGING_INFO]) > TIMEOUT_SPEC_LOGPPRINTOUT) || (getDiffSecNow(startTime[gun_index][TMR_IDX_REFRESH_CHARGING_INFO]) < 0))
  6488. {
  6489. refreshStartTimer(&startTime[gun_index][TMR_IDX_REFRESH_CHARGING_INFO]);
  6490. getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime);
  6491. DB_Update_Record_Buf(localDb, gun_index);
  6492. }
  6493. }
  6494. break;
  6495. case SYS_MODE_TERMINATING:
  6496. if(isModeChange(gun_index))
  6497. {
  6498. if(!ShmCharger->gun_info[gun_index].primaryMcuState.relay_state)
  6499. {
  6500. setLedMotion(gun_index, LED_ACTION_STOP);
  6501. }
  6502. else
  6503. {}
  6504. getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime);
  6505. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  6506. if(ShmCharger->gun_info[gun_index].isGunUnpluggedBefore == YES)
  6507. setRelay(gun_index, OFF);
  6508. // Refresh timer for getting PTB meter message
  6509. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  6510. refreshStartTimer(&startTime[gun_index][TMR_IDX_PTB_METER_MESSAGE]);
  6511. }
  6512. refreshStartTimer(&endChargingTime[gun_index]);
  6513. //if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration != 0)
  6514. //{
  6515. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = getDiffSecBetween(startChargingTime[gun_index], endChargingTime[gun_index]);
  6516. //}
  6517. // If unplug the connector during a session, the system must stop charging and stop session.
  6518. if((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS) || (ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC))
  6519. {
  6520. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A))
  6521. {
  6522. if(ShmCharger->gun_info[gun_index].isGunUnpluggedBefore != YES)
  6523. {
  6524. ShmCharger->gun_info[gun_index].isGunUnpluggedBefore = YES;
  6525. DEBUG_INFO("The connector was unplugged under TERMINATING. [CHARGING_MODE_BS / CHARGING_MODE_HLC]. \n");
  6526. }
  6527. }
  6528. }
  6529. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE)
  6530. {
  6531. if(ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn != ON)
  6532. {
  6533. if(ShmCharger->gun_info[gun_index].isGunUnpluggedBefore != YES)
  6534. {
  6535. ShmCharger->gun_info[gun_index].isGunUnpluggedBefore = YES;
  6536. DEBUG_INFO("The socket e was unplugged under TERMINATING. [CHARGING_MODE_SOCKETE]. \n");
  6537. }
  6538. }
  6539. }
  6540. else
  6541. {}
  6542. // End authorize pass
  6543. if(((ShmCharger->gun_info[gun_index].rfidReq == ON) && isMatchStartUser(gun_index)) ||
  6544. ((ShmCharger->gun_info[gun_index].rfidReq == ON) && ocpp_get_auth_result(YES, gun_index)) ||
  6545. (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE) && (ShmCharger->gun_info[gun_index].rfidReq == ON)) ||
  6546. (!ocpp_get_connection_status() && (isValidLocalWhiteCard() == PASS) && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST) && (ShmCharger->gun_info[gun_index].rfidReq == ON)) ||
  6547. (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop == ON) ||
  6548. ocpp_get_remotestop(gun_index) ||
  6549. (ocpp_get_connection_status() && !ocpp_get_starttransaction_result(gun_index)) ||
  6550. ((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()) ||
  6551. ((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))) ||
  6552. ocpp_get_reset_req() ||
  6553. ocpp_get_unlocker_req(gun_index) ||
  6554. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop == ON) ||
  6555. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && (ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_STOP_MODE)))
  6556. {
  6557. setLedMotion(gun_index, LED_ACTION_STOP);
  6558. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  6559. {
  6560. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  6561. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6562. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  6563. {
  6564. proccessEndOfChargingForPtbMeter(gun_index);
  6565. }
  6566. else
  6567. {
  6568. sleep(1);
  6569. checkStopReason(gun_index);
  6570. setChargerMode(gun_index, SYS_MODE_COMPLETE);
  6571. }
  6572. }
  6573. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  6574. {
  6575. //setChargerMode(gun_index, SYS_MODE_COMPLETE);
  6576. //Cancel CCS task negotiating
  6577. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  6578. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  6579. setRelay(gun_index,OFF);
  6580. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = ON;
  6581. }
  6582. else
  6583. {
  6584. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  6585. {
  6586. proccessEndOfChargingForPtbMeter(gun_index);
  6587. }
  6588. else
  6589. {
  6590. checkStopReason(gun_index);
  6591. setChargerMode(gun_index, SYS_MODE_COMPLETE);
  6592. }
  6593. }
  6594. }
  6595. else
  6596. {
  6597. // Refresh timer for getting PTB meter message
  6598. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  6599. refreshStartTimer(&startTime[gun_index][TMR_IDX_PTB_METER_MESSAGE]);
  6600. // If the charger stops charging, the led should be stoped blink
  6601. if(!ShmCharger->gun_info[gun_index].primaryMcuState.relay_state)
  6602. {
  6603. setLedMotion(gun_index, LED_ACTION_STOP);
  6604. }
  6605. // Charging profile preparation
  6606. if((getDiffSecNow(startTime[gun_index][TMR_IDX_PROFILE_PREPARE]) > TIMEOUT_SPEC_PROFILE_PREPARE) || (getDiffSecNow(startTime[gun_index][TMR_IDX_PROFILE_PREPARE]) < 0))
  6607. {
  6608. if(!ocpp_get_profile_conf(gun_index))
  6609. {
  6610. ocpp_set_profile_req(gun_index, ON);
  6611. refreshStartTimer(&startTime[gun_index][TMR_IDX_PROFILE_PREPARE]);
  6612. }
  6613. else
  6614. {
  6615. ocpp_set_profile_conf(gun_index, OFF);
  6616. }
  6617. }
  6618. // Checking profile id > 0 and current time is between charging profile validFrom & validTo
  6619. checkChargingProfileLimit(gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus);
  6620. setRelay(gun_index, OFF);
  6621. // Debug information
  6622. if((getDiffSecNow(startTime[gun_index][TMR_IDX_REFRESH_CHARGING_INFO]) > TIMEOUT_SPEC_LOGPPRINTOUT) || (getDiffSecNow(startTime[gun_index][TMR_IDX_REFRESH_CHARGING_INFO]) < 0))
  6623. {
  6624. refreshStartTimer(&startTime[gun_index][TMR_IDX_REFRESH_CHARGING_INFO]);
  6625. }
  6626. if(!ocpp_get_auth_result(YES, gun_index))
  6627. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  6628. if((ShmCharger->gun_info[gun_index].isGunUnpluggedBefore != YES) &&
  6629. (((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)) &&
  6630. (ShmCharger->gun_info[gun_index].rfidReq != ON) &&
  6631. (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop != ON) &&
  6632. !ocpp_get_remotestop(gun_index) &&
  6633. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop != ON) &&
  6634. !ocpp_get_reset_req() &&
  6635. ocpp_get_starttransaction_result(gun_index) &&
  6636. !(ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60))) &&
  6637. !(ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy))) &&
  6638. !(!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)))) &&
  6639. !(!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)))) &&
  6640. (((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))
  6641. )
  6642. {
  6643. sleep(1);
  6644. setChargerMode(gun_index, SYS_MODE_CHARGING);
  6645. }
  6646. }
  6647. if((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) &&
  6648. (ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty == ON) &&
  6649. (ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty == CCS_PWM_DUTY_100))
  6650. {
  6651. DEBUG_INFO("Set PWM duty 100%% go to SYS_MODE_TERMINATING.\n");
  6652. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  6653. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6654. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = OFF;
  6655. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  6656. {
  6657. proccessEndOfChargingForPtbMeter(gun_index);
  6658. }
  6659. else
  6660. {
  6661. sleep(1);
  6662. checkStopReason(gun_index);
  6663. setChargerMode(gun_index, SYS_MODE_COMPLETE);
  6664. }
  6665. }
  6666. break;
  6667. case SYS_MODE_COMPLETE:
  6668. if(isModeChange(gun_index))
  6669. {
  6670. setLedMotion(gun_index, LED_ACTION_STOP);
  6671. sleep(6);
  6672. setRelay(gun_index, OFF);
  6673. setRequest(gun_index, OFF);
  6674. sleep(13);
  6675. }
  6676. if(((ShmCharger->gun_info[gun_index].chargingMode != CHARGING_MODE_SOCKETE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)) ||
  6677. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE) && (!ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn)) ||
  6678. ocpp_get_reset_req())
  6679. {
  6680. sleep(2);
  6681. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  6682. ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop = OFF;
  6683. ocpp_set_remotestop(gun_index, OFF);
  6684. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop = OFF;
  6685. ShmCharger->gun_info[gun_index].isGunUnpluggedBefore = NO;
  6686. DB_Insert_Record(localDb, gun_index);
  6687. setChargerMode(gun_index, SYS_MODE_IDLE);
  6688. }
  6689. break;
  6690. case SYS_MODE_ALARM:
  6691. setLedMotion(gun_index,LED_ACTION_ALARM);
  6692. setRelay(gun_index, OFF);
  6693. if((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS) || (ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC))
  6694. {
  6695. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A))
  6696. {
  6697. setRequest(gun_index,OFF);
  6698. if(ShmCharger->gun_info[gun_index].isGunUnpluggedBefore != YES)
  6699. {
  6700. ShmCharger->gun_info[gun_index].isGunUnpluggedBefore = YES;
  6701. DEBUG_INFO("The connector was unplugged under ALARM. [CHARGING_MODE_BS / CHARGING_MODE_HLC]. \n");
  6702. }
  6703. }
  6704. }
  6705. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE)
  6706. {
  6707. if(ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn != ON)
  6708. {
  6709. setRequest(gun_index,OFF);
  6710. if(ShmCharger->gun_info[gun_index].isGunUnpluggedBefore != YES)
  6711. {
  6712. ShmCharger->gun_info[gun_index].isGunUnpluggedBefore = YES;
  6713. DEBUG_INFO("The socket e was unplugged under ALARM. [CHARGING_MODE_SOCKETE]. \n");
  6714. }
  6715. }
  6716. }
  6717. else
  6718. {}
  6719. /*
  6720. * TODO:
  6721. * 1. Customize emergency stop and report stop transaction then return to idle mode if error recover.
  6722. * 2. Customer: Bambang
  6723. */
  6724. if(((ShmSysConfigAndInfo->SysConfig.ModelName[12] == 'B') && (ShmSysConfigAndInfo->SysConfig.ModelName[13] == 'B')) &&
  6725. (ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode == ALARM_EMERGENCY_STOP))
  6726. {
  6727. if(((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus == SYS_MODE_CHARGING) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus == SYS_MODE_TERMINATING)) &&
  6728. !ShmCharger->gun_info[gun_index].isEmergencyStopReport)
  6729. {
  6730. checkStopReason(gun_index);
  6731. ShmCharger->gun_info[gun_index].isEmergencyStopReport = ON;
  6732. }
  6733. }
  6734. if((ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode == 0) && !ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CCSboardStestFail)
  6735. {
  6736. if(((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus == SYS_MODE_CHARGING) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus == SYS_MODE_TERMINATING)) &&
  6737. (!ShmCharger->gun_info[gun_index].isEmergencyStopReport))
  6738. {
  6739. setChargerMode(gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus);
  6740. }
  6741. else
  6742. {
  6743. setChargerMode(gun_index, SYS_MODE_IDLE);
  6744. }
  6745. }
  6746. break;
  6747. case SYS_MODE_FAULT:
  6748. if(isModeChange(gun_index))
  6749. {}
  6750. break;
  6751. case SYS_MODE_MAINTAIN:
  6752. if(isModeChange(gun_index))
  6753. {
  6754. setLedMotion(gun_index,LED_ACTION_MAINTAIN);
  6755. }
  6756. break;
  6757. case SYS_MODE_UPDATE:
  6758. if(isModeChange(gun_index))
  6759. {
  6760. setLedMotion(gun_index,LED_ACTION_MAINTAIN);
  6761. }
  6762. //======================================
  6763. // Check local upgrade firmware request
  6764. //======================================
  6765. if(ShmSysConfigAndInfo->SysInfo.FirmwareUpdate)
  6766. {
  6767. DEBUG_INFO("Firmware local upgrading...\n");
  6768. ShmSysConfigAndInfo->SysInfo.FirmwareUpdate = OFF;
  6769. int value = upgrade_check();
  6770. DEBUG_INFO("Local update Value: %s... \n",((value == PASS)?"Pass": "Fail"));
  6771. if(value == PASS)
  6772. {
  6773. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == ON)
  6774. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = OFF;
  6775. ShmCharger->isUpdateSuccess = YES;
  6776. DEBUG_INFO("Local update success...\n");
  6777. }
  6778. else
  6779. {
  6780. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == OFF)
  6781. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = ON;
  6782. ShmCharger->isUpdateSuccess = NO;
  6783. DEBUG_INFO("Local update unsuccess...\n");
  6784. }
  6785. }
  6786. else if(ocpp_get_update_firmware_req())
  6787. {
  6788. //======================================
  6789. // Check remote upgrade firmware request
  6790. //======================================
  6791. checkRemoteUpgradeStatus();
  6792. }
  6793. else
  6794. {
  6795. //======================================
  6796. // Upgrade complete reboot system
  6797. //======================================
  6798. if(!ShmCharger->gun_info[gun_index].mcuFlag.isMcuUpgradeReq && ((AC_QUANTITY>1)?!ShmCharger->gun_info[gun_index^1].mcuFlag.isMcuUpgradeReq:YES) && !ShmCharger->isUpgradeLcmReq)
  6799. {
  6800. if(ShmCharger->isUpdateSuccess == YES)
  6801. {
  6802. if((strcmp((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installing")==0))
  6803. {
  6804. sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installed");
  6805. ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  6806. }
  6807. else if((strcmp((char*)ShmOCPP16Data->SignedFirmwareStatusNotification.status, "Installing")==0))
  6808. {
  6809. ShmOCPP16Data->SignedFirmwareStatusNotification.requestId = ShmOCPP16Data->SignedUpdateFirmware.requestId;
  6810. sprintf((char*)ShmOCPP16Data->SignedFirmwareStatusNotification.status, "Installed");
  6811. ShmOCPP16Data->SpMsg.bits.SignedFirmwareStatusNotificationReq = ON;
  6812. }
  6813. sprintf((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "Installed");
  6814. ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  6815. DEBUG_WARN("Firmware upgrade success.\n");
  6816. sleep(5);
  6817. DEBUG_INFO("Firmware upgraded, reboot...\n");
  6818. system("reboot -f");
  6819. sleep(5);
  6820. system("reboot -f");
  6821. }
  6822. else
  6823. {
  6824. sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "InstallationFailed");
  6825. ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  6826. sprintf((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "InstallationFailed");
  6827. ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  6828. DEBUG_WARN("Firmware upgrade fail.\n");
  6829. sleep(5);
  6830. system("rm -rvf /mnt/* ");
  6831. close(wtdFd);
  6832. system("/usr/bin/run_evse_restart.sh");
  6833. }
  6834. }
  6835. }
  6836. break;
  6837. case SYS_MODE_RESERVATION:
  6838. if(isModeChange(gun_index))
  6839. {}
  6840. setLedMotion(gun_index,LED_ACTION_RESERVATION_MODE);
  6841. if(isReservationExpired(gun_index))
  6842. {
  6843. DEBUG_INFO("Reservation: Time's up...\n");
  6844. setChargerMode(gun_index, SYS_MODE_IDLE);
  6845. }
  6846. else if(ocpp_get_cancelreservation_req(gun_index))
  6847. {
  6848. DEBUG_INFO("Reservation: Cancel reservation...\n");
  6849. setChargerMode(gun_index, SYS_MODE_IDLE);
  6850. ocpp_set_cancelreservation_req(gun_index, OFF);
  6851. }
  6852. else
  6853. {
  6854. // Check is there RFID or back end request start
  6855. if((ShmCharger->gun_info[gun_index].rfidReq == ON) ||
  6856. ocpp_get_remotestart(gun_index))
  6857. {
  6858. if((ShmCharger->gun_info[gun_index].rfidReq == ON))
  6859. {
  6860. if(ocpp_compare_reserve_id_with_user(gun_index) ||
  6861. ocpp_get_auth_result(YES, gun_index))
  6862. {
  6863. DEBUG_INFO("Start Method in reservation : RFID...\n");
  6864. DEBUG_INFO("Start request User Id : %s\n", ShmSysConfigAndInfo->SysConfig.UserId);
  6865. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_RFID;
  6866. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_ISO14443;
  6867. setChargerMode(gun_index, SYS_MODE_AUTHORIZING);
  6868. }
  6869. else
  6870. {
  6871. setLedMotion(gun_index,LED_ACTION_RESERVATION_MODE);
  6872. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  6873. DEBUG_INFO("It's not reserve user id.\n");
  6874. }
  6875. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  6876. }
  6877. else if(ocpp_get_remotestart(gun_index))
  6878. {
  6879. if(ocpp_compare_reserve_id_with_remote_user(gun_index) ||
  6880. ocpp_isAuthorizeRemoteStart())
  6881. {
  6882. DEBUG_INFO("Start Method in reservation: BACKEND...\n");
  6883. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_BACKEND;
  6884. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_Central;
  6885. if(ocpp_isAuthorizeRemoteStart())
  6886. ocpp_copy_userid_from_remotestart(gun_index);
  6887. setChargerMode(gun_index, SYS_MODE_AUTHORIZING);
  6888. }
  6889. ocpp_set_remotestart(gun_index, OFF);
  6890. }
  6891. }
  6892. }
  6893. break;
  6894. case SYS_MODE_BOOKING:
  6895. if(isModeChange(gun_index))
  6896. {}
  6897. break;
  6898. case SYS_MODE_DEBUG:
  6899. if(isModeChange(gun_index))
  6900. {
  6901. setLedMotion(gun_index,LED_ACTION_DEBUG);
  6902. }
  6903. break;
  6904. }
  6905. }
  6906. // System watch dog reset
  6907. write(wtdFd, "a", 1);
  6908. usleep(50000);
  6909. }
  6910. return FAIL;
  6911. }