main.c 315 KB

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