main.c 302 KB

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