main.c 307 KB

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