main.c 279 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944
  1. /*
  2. * main.c
  3. *
  4. * Created on: 2020年9月10日
  5. * Author: Wendell
  6. */
  7. #include <sys/types.h>
  8. #include <sys/stat.h>
  9. #include <sys/time.h>
  10. #include <sys/timeb.h>
  11. #include <sys/types.h>
  12. #include <sys/ioctl.h>
  13. #include <sys/socket.h>
  14. #include <sys/ipc.h>
  15. #include <sys/shm.h>
  16. #include <sys/mman.h>
  17. #include <linux/wireless.h>
  18. #include <arpa/inet.h>
  19. #include <netinet/in.h>
  20. #include <unistd.h>
  21. #include <stdarg.h>
  22. #include <stdio.h> /*標準輸入輸出定義*/
  23. #include <stdlib.h> /*標準函數庫定義*/
  24. #include <unistd.h> /*Unix 標準函數定義*/
  25. #include <fcntl.h> /*檔控制定義*/
  26. #include <termios.h> /*PPSIX 終端控制定義*/
  27. #include <errno.h> /*錯誤號定義*/
  28. #include <errno.h>
  29. #include <string.h>
  30. #include <stdint.h>
  31. #include <time.h>
  32. #include <ctype.h>
  33. #include <ifaddrs.h>
  34. #include <math.h>
  35. #include "../../define.h"
  36. #include "Config.h"
  37. #include <stdbool.h>
  38. #include <dirent.h>
  39. #include "timeout.h"
  40. #include "Module_EvComm.h"
  41. #include "Module_CabinetParallel.h"
  42. #include "Common.h"
  43. #define BTN_RELEASE 0
  44. #define BTN_PRESS 1
  45. #define MAX_BUF 64
  46. #define MtdBlockSize 0x300000
  47. #define SYSFS_GPIO_DIR "/sys/class/gpio"
  48. #define UPGRADE_FAN 0x02
  49. #define UPGRADE_RB 0x03
  50. #define UPGRADE_PRI 0x04
  51. #define UPGRADE_AC 0x05
  52. #define UPGRADE_LED 0x06
  53. #define UPGRADE_DORC1 0x07
  54. #define UPGRADE_DORC2 0x08
  55. #define UPGRADE_DDRB 0x09
  56. #define SYSTEM_MIN_VOL 150
  57. #define MIN_OUTPUT_CUR 0
  58. #define AC_OUTPUT_VOL 220
  59. #define NO_DEFINE 255
  60. #define DEFAULT_AC_INDEX 2
  61. #define PSU_MIN_CUR 100
  62. #define DB_FILE "/Storage/ChargeLog/localCgargingRecord.db"
  63. #define MAIN_PRIORITY_INTERVAL 5
  64. #define CABINET_ROLE_TIMEOUT 3 // unit: 1s
  65. #define AUTHORIZE_TIMEOUT 30
  66. #define AUTHORIZE_COMP_TIMEOUT 1
  67. #define AUTHORIZE_FAIL_TIMEOUT 3
  68. #define AUTHORIZE_STOP_TIMEOUT 30
  69. #define RETURN_TO_CHARGING_PAGE 30
  70. #define GUN_PREPARE_TIMEOUT 30
  71. #define GUN_EV_WAIT_TIMEOUT (120 + 10)
  72. #define GUN_EVSE_WAIT_TIMEOUT (60 + 10)
  73. #define GUN_COMP_WAIT_TIMEOUT 10
  74. #define GUN_PRECHARGING_TIMEOUT 60
  75. #define REBOOT_TIMEOUT 10
  76. #define RESET_TIMEOUT 10
  77. #define OCPP_COST_REQ_INTERVAL 5
  78. #define DISPENSER_RECONNECTE_TIME 30
  79. #define DISPENSER_AUTH_COMP_TIME 3
  80. #define FORCE_BALANCE_TIME 5
  81. #define DISPENSER_UPGRADE_TIME 600
  82. #define AC_CONTACTOR_REOPEN_TIME 40
  83. #define PSU_FAILURE_RESUME_TIME 180
  84. #define MAX_AC_CONTACTOR_COUNT 3
  85. #define STANDBY_TIME 600
  86. #define FAST_STANDBY_TIME 30
  87. #define WIRING_INFO_DELAY 30
  88. #define WAIT_REASSIGN_TIME 30 // unit: second
  89. #define MAX_REQUEST_CHARGING_TIME 15 // unit: second
  90. #define MIN_WAIT_PREPARNING_TIME 5 // unit: second
  91. #define FORCE_CHARGING_WAIT_EVSE 10 // unit: second
  92. #define TRY_RESET_4G_WIFI_TIME 300 // unit: second
  93. #define FAST_RESET_4G_WIFI_TIME 60 // unit: second
  94. #define ENERAGY_INTERVAL 1 // unit: second
  95. #define FAULT_RELEASE_TIME 1 // unit: second
  96. #define MAINTAIN_RECOVERY_TIME 1 // unit: second
  97. #define PARALLEL_WAIT_TIME 3 // unit: second
  98. #define START_UPGRADE_TIME 60 // unit: second
  99. #define PCABINET_UPGRADE_TIME 300 // unit: second
  100. #define MCABINET_UPGRADE_TIME 60 // unit: second
  101. #define AUTO_START_CHARGING "AutoStartCharging"
  102. char *valid_Internet[2] = {"8.8.8.8", "180.76.76.76"};
  103. unsigned char mask_table[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
  104. int whileLoopTime = 10000; // 10 ms
  105. int wtdFd = -1;
  106. byte _authorizeIndex = NO_DEFINE;
  107. BOOL _UpgradeNeedReboot = FALSE;
  108. const byte Group_to_Location_2_Gun[GENERAL_GUN_QUANTITY] = {0, 1, 0, 0};
  109. const byte Location_to_Group_2_Gun[GENERAL_GUN_QUANTITY] = {0, 1, 0, 0};
  110. const byte GroupParallelRelay_2_Gun[GENERAL_GUN_QUANTITY][GENERAL_GUN_QUANTITY] =
  111. {
  112. {0, 1, 0, 0},
  113. {1, 0, 0, 0},
  114. {0, 0, 0, 0},
  115. {0, 0, 0, 0}
  116. };
  117. //Location: 1 2 3 4
  118. // Gun: 1 3 4 2
  119. //Parallel: 1 2 3
  120. //const byte Group_to_Location_4_Gun[GENERAL_GUN_QUANTITY] = {0, 3, 1, 2};
  121. //const byte Location_to_Group_4_Gun[GENERAL_GUN_QUANTITY] = {0, 2, 3, 1};
  122. //const byte GroupParallelRelay_4_Gun[GENERAL_GUN_QUANTITY][GENERAL_GUN_QUANTITY] =
  123. //{
  124. // {0, 3, 1, 2}, // group 0
  125. // {1, 0, 2, 3}, // group 1
  126. // {1, 3, 0, 2}, // group 2
  127. // {1, 3, 2, 0} // group 3
  128. //};
  129. //Location: 1 2 3 4
  130. // Gun: 1 4 3 2
  131. //Parallel: 1 2 3
  132. const byte Group_to_Location_4_Gun[GENERAL_GUN_QUANTITY] = {0, 3, 2, 1};
  133. const byte Location_to_Group_4_Gun[GENERAL_GUN_QUANTITY] = {0, 3, 2, 1};
  134. const byte GroupParallelRelay_4_Gun[GENERAL_GUN_QUANTITY][GENERAL_GUN_QUANTITY] =
  135. {
  136. {0, 3, 2, 1}, // group 0
  137. {1, 0, 3, 2}, // group 1
  138. {1, 3, 0, 2}, // group 2
  139. {1, 3, 2, 0} // group 3
  140. };
  141. bool IsAuthorizingMode();
  142. void ClearAuthorizedFlag();
  143. bool isDetectPlugin();
  144. void ClearDetectPluginFlag();
  145. int mystrcmp(unsigned char *p1, unsigned char *p2);
  146. long long DiffTimebWithNow(struct timeb ST);
  147. unsigned char DetectBitValue(unsigned char _byte, unsigned char _bit);
  148. void SetBitValue(unsigned char *_byte, unsigned char _bit, unsigned char value);
  149. void ChargingTerminalProcess(byte gunIndex);
  150. void ChkPrimaryStatus();
  151. //void StartSystemTimeoutDet(unsigned char flag);
  152. //void StopSystemTimeoutDet();
  153. //void StartGunInfoTimeoutDet(unsigned char gunIndex, unsigned char flag);
  154. //void StopGunInfoTimeoutDet(unsigned char gunIndex);
  155. int StoreLogMsg_1(const char *fmt, ...);
  156. void gpio_set_value(unsigned int gpio, unsigned int value);
  157. void ChangeGunSelectByIndex(byte sel);
  158. void ChargingAlarmProcess(byte gunIndex);
  159. void InformOcppErrOccur(byte codeType);
  160. void SetOcppErrorCode(unsigned char _index, char *errCode);
  161. void SetOcppVendorErrorCode(unsigned char _index, char *vendorCode);
  162. void ReleaseAlarmCode(byte gunIndex);
  163. int DB_Open(sqlite3 *db);
  164. int DB_Insert_Record(sqlite3 *db, int gun_index);
  165. int DB_Update_Operactive(sqlite3 *db, uint8_t gun_index, uint8_t IsAvailable);
  166. int DB_Get_Operactive(sqlite3 *db, uint8_t gun_index);
  167. void InitialDHCP();
  168. void InitialDispenserDhcpServerConfig(void);
  169. void StartDispenserDhcpServer(void);
  170. void _SelfTestTimeout(void);
  171. void CheckConnectionTimeout(void);
  172. bool IsParallelCabinetIdle(void);
  173. bool IsConnectorWholeIdle(void);
  174. void SetAcContactor(unsigned char OnOff);
  175. void UpdateErrorCodeToOcpp(byte index);
  176. bool CheckConnectorTypeStatus(void);
  177. void CreateWatchdog(void);
  178. void TryCloseWatchdog(void);
  179. void TryFeedWatchdog(void);
  180. bool IsReadyParalleling(void);
  181. void SetParallelingStart(void);
  182. void SetParallelingDone(void);
  183. void SetPCabinetOutputRelay(unsigned char index, unsigned char OnOff);
  184. void SetParallelCabinetAcContactor(unsigned char OnOff);
  185. unsigned short GetTotalParallelCabinetPower(void);
  186. void MCabinetParallelingProcess(void);
  187. void SCabinetControllProcess(void);
  188. struct SysConfigAndInfo *ShmSysConfigAndInfo;
  189. struct StatusCodeData *ShmStatusCodeData;
  190. struct PsuData *ShmPsuData;
  191. struct CHAdeMOData *ShmCHAdeMOData;
  192. struct GBTData *ShmGBTData;
  193. struct CcsData *ShmCcsData;
  194. struct PrimaryMcuData *ShmPrimaryMcuData;
  195. struct FanModuleData *ShmFanModuleData;
  196. struct RelayModuleData *ShmRelayModuleData[2];
  197. struct LedModuleData *ShmLedModuleData;
  198. struct OCPP16Data *ShmOCPP16Data;
  199. struct OCPP20Data *ShmOCPP20Data;
  200. struct MeterInformation *ShmCsuMeterData;
  201. ChargerInfoData *ShmChargerInfo;
  202. PsuPositionInfoData *ShmPsuPosition;
  203. PsuGroupingInfoData *ShmPsuGrouping;
  204. struct ChargingInfoData *chargingInfo[CONNECTOR_QUANTITY];
  205. struct ChargingInfoData *ac_chargingInfo[AC_QUANTITY];
  206. struct timespec _cmdMainPriority_time;
  207. struct timespec _cmdSubPriority_time;
  208. struct timespec _ConnectorAuthorizing_Time[CONNECTOR_QUANTITY];
  209. struct timespec _ConnectorAuthorizeFail_Time[CONNECTOR_QUANTITY];
  210. struct timespec _DispenserAuthorizing_Time[CONNECTOR_QUANTITY];
  211. struct timespec _DispenserUpgrade_time;
  212. struct timespec _Standby_time;
  213. struct timespec _SystemStatus_Time[CONNECTOR_QUANTITY];
  214. struct timespec _Parallel_Time;
  215. float gunOutputVol[CONNECTOR_QUANTITY];
  216. unsigned char _ocppProfileChkFlag[CONNECTOR_QUANTITY];
  217. float _lastProfilePower[CONNECTOR_QUANTITY];
  218. float _lastProfileCurrent[CONNECTOR_QUANTITY];
  219. float _lastMaxProfilePower;
  220. struct StructStatusNotification _BackupStatusNotification[CONNECTOR_QUANTITY];
  221. bool _NeedReset4gWifi;
  222. struct timespec _4gWifiReset_time;
  223. // for initial index to check EV board type is correct
  224. byte _gunIndex = 0;
  225. byte _acgunIndex = 0;
  226. byte _chademoIndex = 0;
  227. byte _ccsIndex = 0;
  228. byte _gb_Index = 0;
  229. byte _ac_Index = 0;
  230. //byte bd0_1_status = 0;
  231. //byte bd0_2_status = 0;
  232. //byte bd1_1_status = 0;
  233. //byte bd1_2_status = 0;
  234. bool isCardScan = false;
  235. bool isModelNameMatch = true;
  236. //int rfidFd = -1;
  237. //char* rfidPortName = "/dev/ttyS2";
  238. char* fwVersion = "V1.05.00.0000.00";
  239. sqlite3 *localDb;
  240. bool isDb_ready;
  241. //================================================
  242. // initial can-bus
  243. //================================================
  244. int InitCanBus()
  245. {
  246. int s0,nbytes;
  247. struct timeval tv;
  248. struct ifreq ifr0;
  249. struct sockaddr_can addr0;
  250. system("/sbin/ip link set can0 down");
  251. system("/sbin/ip link set can0 type can bitrate 500000 restart-ms 100");
  252. system("/sbin/ip link set can0 up");
  253. s0 = socket(PF_CAN, SOCK_RAW, CAN_RAW);
  254. tv.tv_sec = 0;
  255. tv.tv_usec = 10000;
  256. if (setsockopt(s0, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval)) < 0)
  257. {
  258. #ifdef SystemLogMessage
  259. LOG_ERROR("Set SO_RCVTIMEO NG");
  260. #endif
  261. }
  262. nbytes=40960;
  263. if (setsockopt(s0, SOL_SOCKET, SO_RCVBUF, &nbytes, sizeof(int)) < 0)
  264. {
  265. #ifdef SystemLogMessage
  266. LOG_ERROR("Set SO_RCVBUF NG");
  267. #endif
  268. }
  269. nbytes=40960;
  270. if (setsockopt(s0, SOL_SOCKET, SO_SNDBUF, &nbytes, sizeof(int)) < 0)
  271. {
  272. #ifdef SystemLogMessage
  273. LOG_ERROR("Set SO_SNDBUF NG");
  274. #endif
  275. }
  276. strcpy(ifr0.ifr_name, "can0" );
  277. ioctl(s0, SIOCGIFINDEX, &ifr0); /* ifr.ifr_ifindex gets filled with that device's index */
  278. addr0.can_family = AF_CAN;
  279. addr0.can_ifindex = ifr0.ifr_ifindex;
  280. bind(s0, (struct sockaddr *)&addr0, sizeof(addr0));
  281. return s0;
  282. }
  283. //================================================
  284. // initial uart port
  285. //================================================
  286. char *_priPortName = "/dev/ttyS1";
  287. char *_485PortName = "/dev/ttyS5";
  288. int InitComPort(byte target)
  289. {
  290. int fd;
  291. struct termios tios;
  292. if(target == UPGRADE_PRI)
  293. fd = open(_priPortName, O_RDWR);
  294. else if (target == UPGRADE_FAN || target == UPGRADE_RB || target == UPGRADE_AC || target == UPGRADE_LED)
  295. fd = open(_485PortName, O_RDWR);
  296. if(fd<=0)
  297. {
  298. #ifdef SystemLogMessage
  299. LOG_ERROR("open 407 Communication port NG");
  300. #endif
  301. return -1;
  302. }
  303. ioctl (fd, TCGETS, &tios);
  304. tios.c_cflag = B115200| CS8 | CLOCAL | CREAD;
  305. tios.c_lflag = 0;
  306. tios.c_iflag = 0;
  307. tios.c_oflag = 0;
  308. tios.c_cc[VMIN]=0;
  309. tios.c_cc[VTIME]=(unsigned char)1;
  310. tios.c_lflag=0;
  311. tcflush(fd, TCIFLUSH);
  312. ioctl (fd, TCSETS, &tios);
  313. return fd;
  314. }
  315. //=================================
  316. // Common routine
  317. //=================================
  318. void substr(char *dest, const char* src, unsigned int start, unsigned int cnt)
  319. {
  320. strncpy(dest, src + start, cnt);
  321. dest[cnt] = 0;
  322. }
  323. int InitWatchDog()
  324. {
  325. int fd;
  326. int timeout = 180;
  327. system("/usr/bin/fuser -k /dev/watchdog");
  328. sleep(1);
  329. system("echo V > /dev/watchdog");
  330. sleep(1);
  331. fd=open("/dev/watchdog", O_RDWR);
  332. if(fd<=0)
  333. {
  334. LOG_ERROR("System watch dog initial fail.\r\n");
  335. }
  336. ioctl(fd, _IOWR('W', 6, int), &timeout);
  337. return fd;
  338. }
  339. int StoreLogMsg_1(const char *fmt, ...)
  340. {
  341. char Buf[4096+256];
  342. char buffer[4096];
  343. va_list args;
  344. struct timeb SeqEndTime;
  345. struct tm *tm;
  346. va_start(args, fmt);
  347. int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
  348. va_end(args);
  349. memset(Buf,0,sizeof(Buf));
  350. ftime(&SeqEndTime);
  351. SeqEndTime.time = time(NULL);
  352. tm=localtime(&SeqEndTime.time);
  353. if (ShmSysConfigAndInfo->SysConfig.SwitchDebugFlag == YES)
  354. {
  355. sprintf(Buf,"%02d:%02d:%02d:%03d - %s",
  356. tm->tm_hour,tm->tm_min,tm->tm_sec,SeqEndTime.millitm, buffer);
  357. printf("%s \n", Buf);
  358. }
  359. else
  360. {
  361. sprintf(Buf,"echo \'%04d-%02d-%02d %02d:%02d:%02d:%03d - %s\' >> /Storage/SystemLog/[%04d.%02d]SystemLog",
  362. tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,SeqEndTime.millitm,
  363. buffer,
  364. tm->tm_year+1900,tm->tm_mon+1);
  365. system(Buf);
  366. }
  367. return rc;
  368. }
  369. int mystrcmp(unsigned char *p1, unsigned char *p2)
  370. {
  371. while(*p1==*p2)
  372. {
  373. if(*p1=='\0' || *p2=='\0')
  374. break;
  375. p1++;
  376. p2++;
  377. }
  378. if(*p1=='\0' && *p2=='\0')
  379. return(PASS);
  380. else
  381. return(FAIL);
  382. }
  383. int DiffTimeb(struct timeb ST, struct timeb ET)
  384. {
  385. //return milli-second
  386. unsigned int StartTime,StopTime;
  387. StartTime=(unsigned int)ST.time;
  388. StopTime=(unsigned int)ET.time;
  389. //return (StopTime-StartTime)*1000+ET.millitm-ST.millitm;
  390. return (StopTime-StartTime);
  391. }
  392. bool CheckTimeOut(struct timeb ST)
  393. {
  394. struct timeb ET;
  395. unsigned int StartTime, StopTime;
  396. ftime(&ET);
  397. StartTime = (unsigned int) ST.time;
  398. StopTime = (unsigned int) ET.time;
  399. return (StopTime > StartTime)? YES : NO;
  400. }
  401. void setChargerMode(byte gun_index, byte mode)
  402. {
  403. chargingInfo[gun_index]->SystemStatus = mode;
  404. }
  405. long long DiffTimebWithNow(struct timeb ST)
  406. {
  407. //return milli-second
  408. struct timeb ET;
  409. long long StartTime,StopTime;
  410. ftime(&ET);
  411. StartTime=(long long)ST.time;
  412. StopTime=(long long)ET.time;
  413. return ((StopTime-StartTime)*1000) + (ET.millitm-ST.millitm);
  414. }
  415. /*
  416. //==========================================
  417. // Check interface status
  418. //==========================================
  419. int isInterfaceUp(const char *interface)
  420. {
  421. int result = FAIL;
  422. FILE *fp;
  423. char cmd[256];
  424. char buf[512];
  425. strcpy(cmd, "ifconfig");
  426. fp = popen(cmd, "r");
  427. if(fp != NULL)
  428. {
  429. while(fgets(buf, sizeof(buf), fp) != NULL)
  430. {
  431. if(strstr(buf, interface) > 0)
  432. {
  433. result = PASS;
  434. }
  435. }
  436. }
  437. pclose(fp);
  438. return result;
  439. }
  440. */
  441. //=================================
  442. // Create all share memory
  443. //=================================
  444. int CreateShareMemory()
  445. {
  446. int MeterSMId;
  447. if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo), IPC_CREAT | 0777)) < 0)
  448. {
  449. #ifdef SystemLogMessage
  450. LOG_ERROR("[main]CreatShareMemory:shmget ShmSysConfigAndInfo NG");
  451. #endif
  452. return 0;
  453. }
  454. else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  455. {
  456. #ifdef SystemLogMessage
  457. LOG_ERROR("[main]CreatShareMemory:shmat ShmSysConfigAndInfo NG");
  458. #endif
  459. return 0;
  460. }
  461. memset(ShmSysConfigAndInfo, 0, sizeof(struct SysConfigAndInfo));
  462. if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData), IPC_CREAT | 0777)) < 0)
  463. {
  464. #ifdef SystemLogMessage
  465. LOG_ERROR("[main]CreatShareMemory:shmget ShmStatusCodeData NG");
  466. #endif
  467. return 0;
  468. }
  469. else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  470. {
  471. #ifdef SystemLogMessage
  472. LOG_ERROR("[main]CreatShareMemory:shmat ShmStatusCodeData NG");
  473. #endif
  474. return 0;
  475. }
  476. memset(ShmStatusCodeData, 0, sizeof(struct StatusCodeData));
  477. //creat ShmPsuData
  478. if ((MeterSMId = shmget(ShmPsuKey, sizeof(struct PsuData), IPC_CREAT | 0777)) < 0)
  479. {
  480. #ifdef SystemLogMessage
  481. LOG_ERROR("[main]CreatShareMemory:shmget ShmPsuData NG");
  482. #endif
  483. return 0;
  484. }
  485. else if ((ShmPsuData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  486. {
  487. #ifdef SystemLogMessage
  488. LOG_ERROR("[main]CreatShareMemory:shmat ShmPsuData NG");
  489. #endif
  490. return 0;
  491. }
  492. memset(ShmPsuData, 0, sizeof(struct PsuData));
  493. /*
  494. if(CHAdeMO_QUANTITY > 0)
  495. {
  496. if ((MeterSMId = shmget(ShmCHAdeMOCommKey, sizeof(struct CHAdeMOData), IPC_CREAT | 0777)) < 0)
  497. {
  498. #ifdef SystemLogMessage
  499. LOG_ERROR("[main]CreatShareMemory:shmget ShmCHAdeMOData NG");
  500. #endif
  501. return 0;
  502. }
  503. else if ((ShmCHAdeMOData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  504. {
  505. #ifdef SystemLogMessage
  506. LOG_ERROR("[main]CreatShareMemory:shmat ShmCHAdeMOData NG");
  507. #endif
  508. return 0;
  509. }
  510. memset(ShmCHAdeMOData, 0, sizeof(struct CHAdeMOData));
  511. }
  512. if(GB_QUANTITY > 0)
  513. {
  514. if ((MeterSMId = shmget(ShmGBTCommKey, sizeof(struct GBTData), IPC_CREAT | 0777)) < 0)
  515. {
  516. #ifdef SystemLogMessage
  517. LOG_ERROR("[main]CreatShareMemory:shmget ShmGBTData NG");
  518. #endif
  519. return 0;
  520. }
  521. else if ((ShmGBTData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  522. {
  523. #ifdef SystemLogMessage
  524. LOG_ERROR("[main]CreatShareMemory:shmat ShmGBTData NG");
  525. #endif
  526. return 0;
  527. }
  528. memset(ShmGBTData, 0, sizeof(struct GBTData));
  529. }
  530. //creat ShmCcsData
  531. if(CCS_QUANTITY > 0)
  532. {
  533. if ((MeterSMId = shmget(ShmCcsCommKey, sizeof(struct CcsData), IPC_CREAT | 0777)) < 0)
  534. {
  535. #ifdef SystemLogMessage
  536. LOG_ERROR("[main]CreatShareMemory:shmget ShmCcsData NG");
  537. #endif
  538. return 0;
  539. }
  540. else if ((ShmCcsData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  541. {
  542. #ifdef SystemLogMessage
  543. LOG_ERROR("[main]CreatShareMemory:shmat ShmCcsData NG");
  544. #endif
  545. return 0;
  546. }
  547. memset(ShmCcsData, 0, sizeof(struct CcsData));
  548. }
  549. */
  550. //creat ShmPrimaryMcuData
  551. if ((MeterSMId = shmget(ShmPrimaryMcuKey, sizeof(struct PrimaryMcuData), IPC_CREAT | 0777)) < 0)
  552. {
  553. #ifdef SystemLogMessage
  554. LOG_ERROR("[main]CreatShareMemory:shmget ShmPrimaryMcuData NGn");
  555. #endif
  556. return 0;
  557. }
  558. else if ((ShmPrimaryMcuData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  559. {
  560. #ifdef SystemLogMessage
  561. LOG_ERROR("[main]CreatShareMemory:shmat ShmPrimaryMcuData NG");
  562. #endif
  563. return 0;
  564. }
  565. memset(ShmPrimaryMcuData, 0, sizeof(struct PrimaryMcuData));
  566. //creat ShmFanModuleData
  567. if ((MeterSMId = shmget(ShmFanBdKey, sizeof(struct FanModuleData), IPC_CREAT | 0777)) < 0)
  568. {
  569. #ifdef SystemLogMessage
  570. LOG_ERROR("[main]CreatShareMemory:shmget ShmFanModuleData NG");
  571. #endif
  572. return 0;
  573. }
  574. else if ((ShmFanModuleData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  575. {
  576. #ifdef SystemLogMessage
  577. LOG_ERROR("[main]CreatShareMemory:shmat ShmFanModuleData NG");
  578. #endif
  579. return 0;
  580. }
  581. memset(ShmFanModuleData, 0, sizeof(struct FanModuleData));
  582. //creat ShmRelayModuleData
  583. if ((MeterSMId = shmget(ShmRelayBdKey, sizeof(struct RelayModuleData), IPC_CREAT | 0777)) < 0)
  584. {
  585. #ifdef SystemLogMessage
  586. LOG_ERROR("[main]CreatShareMemory:shmget ShmRelayModuleData[0] NG");
  587. #endif
  588. return 0;
  589. }
  590. else if ((ShmRelayModuleData[0] = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  591. {
  592. #ifdef SystemLogMessage
  593. LOG_ERROR("[main]CreatShareMemory:shmat ShmRelayModuleData[0] NG");
  594. #endif
  595. return 0;
  596. }
  597. memset(ShmRelayModuleData[0], 0, sizeof(struct RelayModuleData));
  598. // DO360 RC2
  599. if ((MeterSMId = shmget(ShmRelay2BdKey, sizeof(struct RelayModuleData), IPC_CREAT | 0777)) < 0)
  600. {
  601. #ifdef SystemLogMessage
  602. LOG_ERROR("[main]CreatShareMemory:shmget ShmRelayModuleData[1] NG");
  603. #endif
  604. return 0;
  605. }
  606. else if ((ShmRelayModuleData[1] = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  607. {
  608. #ifdef SystemLogMessage
  609. LOG_ERROR("[main]CreatShareMemory:shmat ShmRelayModuleData[1] NG");
  610. #endif
  611. return 0;
  612. }
  613. memset(ShmRelayModuleData[1], 0, sizeof(struct RelayModuleData));
  614. if ((MeterSMId = shmget(ShmLedBdKey, sizeof(struct LedModuleData), IPC_CREAT | 0777)) < 0)
  615. {
  616. #ifdef SystemLogMessage
  617. LOG_ERROR("[main]CreatShareMemory:shmget ShmLedModuleData NG");
  618. #endif
  619. return 0;
  620. }
  621. else if ((ShmLedModuleData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  622. {
  623. #ifdef SystemLogMessage
  624. LOG_ERROR("[main]CreatShareMemory:shmat ShmLedModuleData NG");
  625. #endif
  626. return 0;
  627. }
  628. memset(ShmLedModuleData, 0, sizeof(struct LedModuleData));
  629. //creat ShmOCPP16Data
  630. if ((MeterSMId = shmget(ShmOcppModuleKey, sizeof(struct OCPP16Data), IPC_CREAT | 0777)) < 0)
  631. {
  632. #ifdef SystemLogMessage
  633. LOG_ERROR("[main]CreatShareMemory:shmget ShmOCPP16Data NG");
  634. #endif
  635. return 0;
  636. }
  637. else if ((ShmOCPP16Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  638. {
  639. #ifdef SystemLogMessage
  640. LOG_ERROR("[main]CreatShareMemory:shmat ShmOCPP16Data NG");
  641. #endif
  642. return 0;
  643. }
  644. memset(ShmOCPP16Data,0,sizeof(struct OCPP16Data));
  645. if ((MeterSMId = shmget(ShmOcpp20ModuleKey, sizeof(struct OCPP20Data), IPC_CREAT | 0777)) < 0)
  646. {
  647. LOG_ERROR("[main]CreatShareMemory:shmget OCPP20Data NG\n");
  648. return 0;
  649. }
  650. else if ((ShmOCPP20Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  651. {
  652. LOG_ERROR("[main]CreatShareMemory:shmat OCPP20Data NG\n");
  653. return 0;
  654. }
  655. memset(ShmOCPP20Data,0,sizeof(struct OCPP20Data));
  656. if ((MeterSMId = shmget(SM_ChargerInfoKey, sizeof(ChargerInfoData), IPC_CREAT | 0777)) < 0)
  657. {
  658. #ifdef SystemLogMessage
  659. LOG_ERROR("[main]CreatShareMemory:shmget ChargerInfoData NG");
  660. #endif
  661. return 0;
  662. }
  663. else if ((ShmChargerInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  664. {
  665. #ifdef SystemLogMessage
  666. LOG_ERROR("[main]CreatShareMemory:shmat ChargerInfoData NG");
  667. #endif
  668. return 0;
  669. }
  670. memset(ShmChargerInfo, 0, sizeof(ChargerInfoData));
  671. ShmPsuPosition = &ShmChargerInfo->PsuPosition;
  672. ShmPsuGrouping = &ShmChargerInfo->PsuGrouping;
  673. return 1;
  674. }
  675. //=================================
  676. // LCM Page
  677. //=================================
  678. void ChangeLcmByIndex(byte page_index)
  679. {
  680. if (ShmSysConfigAndInfo->SysWarningInfo.Level != 2 ||
  681. page_index == _LCM_COMPLETE || page_index == _LCM_FIX)
  682. {
  683. ShmSysConfigAndInfo->SysInfo.PageIndex = page_index;
  684. }
  685. }
  686. //======================================================
  687. // Peripheral initial
  688. //======================================================
  689. void InitGPIO()
  690. {
  691. /*****************0~3, 4 bank, bank x 32+ num*********************/
  692. /***************************************************************/
  693. /*************** GPIO 0 ***************************************/
  694. /***************************************************************/
  695. /* GPMC_AD8 => GPIO0_22 *//*ID BD1_1*/ // no use
  696. system("echo 22 > /sys/class/gpio/export");
  697. system("echo \"in\" > /sys/class/gpio/gpio22/direction");
  698. /* GPMC_AD9 => GPIO0_23 *//*ID BD1_2*/ // no use
  699. system("echo 23 > /sys/class/gpio/export");
  700. system("echo \"in\" > /sys/class/gpio/gpio23/direction");
  701. /* GPMC_AD10 => GPIO0_26 *//*IO BD1_1*/ // no use
  702. system("echo 26 > /sys/class/gpio/export");
  703. system("echo \"out\" > /sys/class/gpio/gpio26/direction");
  704. system("echo 1 > /sys/class/gpio/gpio26/value");
  705. /* GPMC_AD11 => GPIO0_27 *//*IO BD1_2*/ // no use
  706. system("echo 27 > /sys/class/gpio/export");
  707. system("echo \"in\" > /sys/class/gpio/gpio27/direction");
  708. /* RMII1_REF_CLK => GPIO0_29 *//*USB 0 OCP detection*/
  709. system("echo 29 > /sys/class/gpio/export");
  710. system("echo \"in\" > /sys/class/gpio/gpio29/direction");
  711. /*XDMA_EVENT_INTR0 => GPIO0_19 *//*AM_RFID_RST*/ // no use
  712. system("echo 19 > /sys/class/gpio/export");
  713. system("echo \"out\" > /sys/class/gpio/gpio19/direction");
  714. system("echo 1 > /sys/class/gpio/gpio19/value");
  715. /*XDMA_EVENT_INTR1 => GPIO0_20 *//*AM_RFID_ICC*/ // no use
  716. system("echo 20 > /sys/class/gpio/export");
  717. system("echo \"in\" > /sys/class/gpio/gpio20/direction");
  718. /***************************************************************/
  719. /*************** GPIO 1 ***************************************/
  720. /***************************************************************/
  721. /* GPMC_AD12 => GPIO1_12 *//*ID BD2_1*/ // no use
  722. system("echo 44 > /sys/class/gpio/export");
  723. system("echo \"in\" > /sys/class/gpio/gpio44/direction");
  724. /* GPMC_AD13 => GPIO1_13 *//*ID BD2_2*/ // no use
  725. system("echo 45 > /sys/class/gpio/export");
  726. system("echo \"in\" > /sys/class/gpio/gpio45/direction");
  727. /* GPMC_AD14 => GPIO1_14 *//*IO BD2_1*/ // no use
  728. system("echo 46 > /sys/class/gpio/export");
  729. system("echo \"out\" > /sys/class/gpio/gpio46/direction");
  730. system("echo 0 > /sys/class/gpio/gpio46/value");
  731. /* GPMC_AD15 => GPIO1_15 *//*IO BD2_2*/ // no use
  732. system("echo 47 > /sys/class/gpio/export");
  733. system("echo \"in\" > /sys/class/gpio/gpio47/direction");
  734. /***************************************************************/
  735. /*************** GPIO 2 ***************************************/
  736. /***************************************************************/
  737. /*LCD_AC_BIAS_EN => GPIO2_25*//*RS-485 for module DE control*/
  738. system("echo 89 > /sys/class/gpio/export");
  739. system("echo \"out\" > /sys/class/gpio/gpio89/direction");
  740. system("echo 1 > /sys/class/gpio/gpio89/value");
  741. /*LCD_HSYNC => GPIO2_23*//*RS-485 for module RE control*/
  742. system("echo 87 > /sys/class/gpio/export");
  743. system("echo \"out\" > /sys/class/gpio/gpio87/direction");
  744. system("echo 0 > /sys/class/gpio/gpio87/value");
  745. /*LCD_PCLK => GPIO2_24*//*CCS communication board 1 proximity*/ // no use
  746. system("echo 88 > /sys/class/gpio/export");
  747. system("echo \"in\" > /sys/class/gpio/gpio88/direction");
  748. /*LCD_VSYNC => GPIO2_22*//*CCS communication board 2 proximity*/ // no use
  749. system("echo 86 > /sys/class/gpio/export");
  750. system("echo \"in\" > /sys/class/gpio/gpio86/direction");
  751. /***************************************************************/
  752. /*************** GPIO 3 ***************************************/
  753. /***************************************************************/
  754. /*MCASP0_FSX => GPIO3_15*//*Emergency Stop button detect*/
  755. system("echo 111 > /sys/class/gpio/export");
  756. system("echo \"in\" > /sys/class/gpio/gpio111/direction");
  757. /*MCASP0_ACLKR => GPIO3_18*//*USB1 OCP detect*/
  758. system("echo 114 > /sys/class/gpio/export");
  759. system("echo \"in\" > /sys/class/gpio/gpio114/direction");
  760. /*MCASP0_AHCLKR => GPIO3_17*//*Emergency IO for AM3352 and STM32F407*/
  761. system("echo 113 > /sys/class/gpio/export");
  762. system("echo \"in\" > /sys/class/gpio/gpio113/direction");
  763. /*MCASP0_ACLKX => GPIO3_14*//*Ethernet PHY reset*/
  764. system("echo 110 > /sys/class/gpio/export");
  765. system("echo \"out\" > /sys/class/gpio/gpio110/direction");
  766. system("echo 0 > /sys/class/gpio/gpio110/value");
  767. /* MCASP0_FSR => GPIO3_19 *//*SMR Enable control_1 for Pskill_1*/ // no use
  768. system("echo 115 > /sys/class/gpio/export");
  769. system("echo \"out\" > /sys/class/gpio/gpio115/direction");
  770. system("echo 0 > /sys/class/gpio/gpio115/value");
  771. /* MCASP0_AXR0 => GPIO3_16 *//*CSU board function OK indicator.*/
  772. system("echo 112 > /sys/class/gpio/export");
  773. system("echo \"out\" > /sys/class/gpio/gpio112/direction");
  774. system("echo 1 > /sys/class/gpio/gpio112/value");
  775. /* MCASP0_AXR1 => GPIO3_20 *//*SMR Enable control_2 for Pskill_2*/ // no use
  776. system("echo 116 > /sys/class/gpio/export");
  777. system("echo \"out\" > /sys/class/gpio/gpio116/direction");
  778. system("echo 0 > /sys/class/gpio/gpio116/value");
  779. /* (C14) EMU0.gpio3[7] */ /*CP open/short feature enable/disable, pull low for default enable*/
  780. system("echo 103 > /sys/class/gpio/export");
  781. system("echo \"out\" > /sys/class/gpio/gpio103/direction");
  782. system("echo 0 > /sys/class/gpio/gpio103/value");
  783. /* (B14) EMU1.gpio3[8] */ /*4G module reset, pull high to reset when entry kernel, after Application start, it should be pull low.*/
  784. system("echo 104 > /sys/class/gpio/export");
  785. system("echo \"out\" > /sys/class/gpio/gpio104/direction");
  786. system("echo 0 > /sys/class/gpio/gpio104/value");
  787. LOG_INFO("[main]InitGPIO: Initial GPIO OK");
  788. }
  789. int LoadSysConfigAndInfo(struct SysConfigData *ptr)
  790. {
  791. int fd, wrd;
  792. unsigned char *buf;
  793. unsigned int ChkSum, ChkSumOrg;
  794. if((buf = malloc(MtdBlockSize)) == NULL)
  795. {
  796. LOG_ERROR("malloc buffer NG, rebooting..\n");
  797. if(ShmStatusCodeData!=NULL)
  798. {
  799. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
  800. }
  801. sleep(5);
  802. system("reboot -f");
  803. sleep(5);
  804. system("reboot -f");
  805. }
  806. memset(buf, 0, MtdBlockSize);
  807. //================================================
  808. // Load configuration from mtdblock10
  809. //================================================
  810. system("nanddump /dev/mtd10 -f /mnt/EvseConfig.bin");
  811. fd = open("/mnt/EvseConfig.bin", O_RDWR);
  812. if(fd < 0)
  813. {
  814. free(buf);
  815. LOG_ERROR("open mtdblock10 NG, rebooting..\n");
  816. if(ShmStatusCodeData != NULL)
  817. {
  818. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
  819. }
  820. sleep(5);
  821. system("reboot -f");
  822. sleep(5);
  823. system("reboot -f");
  824. }
  825. wrd = read(fd, buf, MtdBlockSize);
  826. close(fd);
  827. if(wrd < MtdBlockSize)
  828. {
  829. free(buf);
  830. LOG_ERROR("read SysConfigData data NG, rebooting..\n");
  831. if(ShmStatusCodeData != NULL)
  832. {
  833. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
  834. }
  835. sleep(5);
  836. system("reboot -f");
  837. sleep(5);
  838. system("reboot -f");
  839. }
  840. ChkSum = 0;
  841. for(wrd = ARRAY_SIZE(ptr->CsuBootLoadFwRev); wrd < MtdBlockSize - 4; wrd++)
  842. {
  843. ChkSum += buf[wrd];
  844. }
  845. memcpy(&ChkSumOrg, buf + (MtdBlockSize - 4), sizeof(ChkSumOrg));
  846. memcpy(&ptr->ModelName, buf + (ARRAY_SIZE(ptr->CsuBootLoadFwRev)), ARRAY_SIZE(ptr->ModelName));
  847. memcpy(&ptr->SerialNumber, buf + (ARRAY_SIZE(ptr->CsuBootLoadFwRev) + ARRAY_SIZE(ptr->ModelName) + ARRAY_SIZE(ptr->AcModelName)), ARRAY_SIZE(ptr->SerialNumber));
  848. //================================================
  849. // Load configuration from mtdblock11
  850. //================================================
  851. if(ChkSum != ChkSumOrg)
  852. {
  853. LOG_ERROR("Primary SysConfigData checksum NG, read backup\n");
  854. system("nanddump /dev/mtd11 -f /mnt/EvseConfig.bin");
  855. fd = open("/mnt/EvseConfig.bin", O_RDWR);
  856. if(fd < 0)
  857. {
  858. free(buf);
  859. LOG_ERROR("open mtdblock11 (backup) NG, rebooting..\n");
  860. if(ShmStatusCodeData != NULL)
  861. {
  862. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
  863. }
  864. sleep(5);
  865. system("reboot -f");
  866. sleep(5);
  867. system("reboot -f");
  868. }
  869. memset(buf, 0, MtdBlockSize);
  870. wrd = read(fd, buf, MtdBlockSize);
  871. close(fd);
  872. if(wrd < MtdBlockSize)
  873. {
  874. free(buf);
  875. LOG_ERROR("read backup SysConfigData data NG, rebooting..\n");
  876. if(ShmStatusCodeData != NULL)
  877. {
  878. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
  879. }
  880. sleep(5);
  881. system("reboot -f");
  882. sleep(5);
  883. system("reboot -f");
  884. }
  885. ChkSum = 0;
  886. for(wrd = ARRAY_SIZE(ptr->CsuBootLoadFwRev); wrd < MtdBlockSize - 4; wrd++)
  887. {
  888. ChkSum += buf[wrd];
  889. }
  890. memcpy(&ChkSumOrg, buf + (MtdBlockSize - 4), sizeof(ChkSumOrg));
  891. //================================================
  892. // Load configuration from mtdblock12 (Factory default)
  893. //================================================
  894. if(ChkSum != ChkSumOrg)
  895. {
  896. LOG_ERROR("backup SysConfigData checksum NG, read Factory default\n");
  897. system("nanddump /dev/mtd12 -f /mnt/EvseConfig.bin");
  898. fd = open("/mnt/EvseConfig.bin", O_RDWR);
  899. if(fd < 0)
  900. {
  901. free(buf);
  902. LOG_ERROR("open mtdblock12 (Factory default) NG, rebooting..\n");
  903. if(ShmStatusCodeData != NULL)
  904. {
  905. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
  906. }
  907. sleep(5);
  908. system("reboot -f");
  909. sleep(5);
  910. system("reboot -f");
  911. }
  912. memset(buf, 0, MtdBlockSize);
  913. wrd = read(fd, buf, MtdBlockSize);
  914. close(fd);
  915. if(wrd < MtdBlockSize)
  916. {
  917. free(buf);
  918. LOG_ERROR("read factory default SysConfigData data NG, rebooting..\n");
  919. if(ShmStatusCodeData != NULL)
  920. {
  921. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
  922. }
  923. sleep(5);
  924. system("reboot -f");
  925. sleep(5);
  926. system("reboot -f");
  927. }
  928. ChkSum = 0;
  929. for(wrd = ARRAY_SIZE(ptr->CsuBootLoadFwRev); wrd < MtdBlockSize - 4; wrd++)
  930. {
  931. ChkSum += buf[wrd];
  932. }
  933. memcpy(&ChkSumOrg, buf + (MtdBlockSize - 4), sizeof(ChkSumOrg));
  934. memcpy(buf + (ARRAY_SIZE(ptr->CsuBootLoadFwRev)), &ptr->ModelName, ARRAY_SIZE(ptr->ModelName));
  935. memcpy(buf + (ARRAY_SIZE(ptr->CsuBootLoadFwRev) + ARRAY_SIZE(ptr->ModelName) + ARRAY_SIZE(ptr->AcModelName)), &ptr->SerialNumber, ARRAY_SIZE(ptr->SerialNumber));
  936. if(ChkSum != ChkSumOrg)
  937. {
  938. LOG_ERROR("factory default SysConfigData checksum NG, restore factory default\n");
  939. free(buf);
  940. system("cd /root;./FactoryConfig -m");
  941. system("rm -f /Storage/OCPP/OCPPConfiguration");
  942. system("sync");
  943. sleep(5);
  944. system("reboot -f");
  945. sleep(5);
  946. system("reboot -f");
  947. return FAIL;
  948. }
  949. }
  950. }
  951. //load OK
  952. memcpy((struct SysConfigData *)ptr, buf, sizeof(struct SysConfigData));
  953. free(buf);
  954. system("rm -f /mnt/EvseConfig.bin");
  955. // SysConfig in flash is empty (0xffffffff)
  956. if((strlen((char*)ShmSysConfigAndInfo->SysConfig.ModelName) > ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.ModelName)) ||
  957. (strlen((char*)ShmSysConfigAndInfo->SysConfig.SerialNumber) > ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SerialNumber)) ||
  958. (strlen((char*)ShmSysConfigAndInfo->SysConfig.SystemId) > ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SystemId)) ||
  959. (ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient == 0xff))
  960. {
  961. if(strlen((char*)ShmSysConfigAndInfo->SysConfig.ModelName) > ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.ModelName))
  962. {
  963. LOG_INFO("Model name over length.");
  964. memset(ShmSysConfigAndInfo->SysConfig.ModelName, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.ModelName));
  965. }
  966. if(strlen((char*)ShmSysConfigAndInfo->SysConfig.SerialNumber) > ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SerialNumber))
  967. {
  968. LOG_INFO("Model serial number over length.");
  969. memset(ShmSysConfigAndInfo->SysConfig.SerialNumber, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SerialNumber));
  970. }
  971. if(strlen((char*)ShmSysConfigAndInfo->SysConfig.SystemId) > ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SystemId))
  972. {
  973. LOG_INFO("System id over length.");
  974. memset(ShmSysConfigAndInfo->SysConfig.SystemId, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SystemId));
  975. }
  976. if(ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient == 0xff)
  977. {
  978. LOG_INFO("Ethernet dhcp config is null.");
  979. }
  980. system("cd /root;./Module_FactoryConfig -m");
  981. sleep(3);
  982. system("/usr/bin/run_evse_restart.sh");
  983. }
  984. LOG_INFO("Load SysConfigData OK");
  985. return PASS;
  986. }
  987. /*
  988. byte GetCurEthUsage()
  989. {
  990. byte result = _ETHERNET_USAGE_NONE;
  991. FILE *fp;
  992. char cmd[256];
  993. char buf[512];
  994. byte targetC = 2;
  995. strcpy(cmd, "route -n");
  996. fp = popen(cmd, "r");
  997. if (fp != NULL)
  998. {
  999. while(fgets(buf, sizeof(buf), fp) != NULL)
  1000. {
  1001. if (targetC-- == 0)
  1002. {
  1003. if (strstr(buf, "eth0") > 0)
  1004. result = _ETHERNET_USAGE_LAN;
  1005. else if (strstr(buf, "mlan0") > 0)
  1006. result = _ETHERNET_USAGE_WIFI;
  1007. else if (strstr(buf, "ppp0") > 0)
  1008. result = _ETHERNET_USAGE_3G_4g;
  1009. break;
  1010. }
  1011. // if (strstr(buf, "inet addr:") > 0)
  1012. // {
  1013. // }
  1014. }
  1015. }
  1016. pclose(fp);
  1017. memset(buf, 0x00, sizeof(buf));
  1018. return result;
  1019. }
  1020. */
  1021. int isEthernetCablePlugIn(int ethernet)
  1022. {
  1023. int fd, PlugInStatus = 0;
  1024. char ch[2];
  1025. char buffer[64];
  1026. snprintf(buffer, sizeof(buffer), "/sys/class/net/eth%d/carrier", ethernet);
  1027. fd = open(buffer, O_RDONLY);
  1028. if(fd < 0)
  1029. {
  1030. return -1;
  1031. }
  1032. if(read(fd, ch, 1) < 0)
  1033. {
  1034. return -1;
  1035. }
  1036. PlugInStatus = atoi(ch);
  1037. close(fd);
  1038. return PlugInStatus;
  1039. }
  1040. int isRouteFail()
  1041. {
  1042. int result = YES;
  1043. FILE *fp;
  1044. char buf[512];
  1045. fp = popen("route -n", "r");
  1046. if(fp != NULL)
  1047. {
  1048. while(fgets(buf, sizeof(buf), fp) != NULL)
  1049. {
  1050. if(strstr(buf, "eth0") != NULL)
  1051. result = NO;
  1052. }
  1053. }
  1054. pclose(fp);
  1055. return result;
  1056. }
  1057. int isReachableInternet()
  1058. {
  1059. int result = FAIL;
  1060. FILE *fp;
  1061. char cmd[256];
  1062. char buf[512];
  1063. char tmp[512];
  1064. // if (ShmOCPP16Data->OcppConnStatus == PASS)
  1065. // {
  1066. // result = PASS;
  1067. // }
  1068. // else
  1069. {
  1070. strcpy(cmd, "ifconfig eth0");
  1071. fp = popen(cmd, "r");
  1072. if (fp != NULL)
  1073. {
  1074. while(fgets(buf, sizeof(buf), fp) != NULL)
  1075. {
  1076. if (strstr(buf, "inet addr:") > 0)
  1077. {
  1078. sscanf(buf, "%*s%s", tmp);
  1079. substr(tmp, tmp, strspn(tmp, "addr:"), strlen(buf)-strspn(tmp, "addr:"));
  1080. if (strcmp(tmp, (char *)ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress) != EQUAL)
  1081. {
  1082. strcpy((char *) ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress, tmp);
  1083. }
  1084. }
  1085. }
  1086. }
  1087. pclose(fp);
  1088. memset(buf, 0x00, sizeof(buf));
  1089. for(int idx=0;idx<ARRAY_SIZE(valid_Internet);idx++)
  1090. {
  1091. sprintf(cmd, "ping -c 1 -w 3 -I eth0 %s", valid_Internet[idx]);
  1092. fp = popen(cmd, "r");
  1093. if(fp != NULL)
  1094. {
  1095. while(fgets(buf, sizeof(buf), fp) != NULL)
  1096. {
  1097. if(strstr(buf, "transmitted") > 0)
  1098. {
  1099. //sscanf(buf, "%*s%*s%*s%*s%*s%*s%s", tmp);
  1100. if(strstr(buf,"100%") != NULL)
  1101. {
  1102. }
  1103. else
  1104. {
  1105. result = PASS;
  1106. }
  1107. //DEBUG_INFO("%s",buf);
  1108. //DEBUG_INFO("%s\n",tmp);
  1109. }
  1110. }
  1111. }
  1112. pclose(fp);
  1113. }
  1114. }
  1115. return result;
  1116. }
  1117. void AnnounceEthernetStatus(void)
  1118. {
  1119. for(int index = 0; index < GENERAL_GUN_QUANTITY; index++)
  1120. {
  1121. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].LocalStatus != _DS_None &&
  1122. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].LocalStatus != _DS_Timeout)
  1123. {
  1124. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].Setting.bits.EthernetStatusRequest = true;
  1125. }
  1126. }
  1127. }
  1128. void AnnounceWiFiStatus(void)
  1129. {
  1130. for(int index = 0; index < GENERAL_GUN_QUANTITY; index++)
  1131. {
  1132. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].LocalStatus != _DS_None &&
  1133. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].LocalStatus != _DS_Timeout)
  1134. {
  1135. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].Setting.bits.WiFiStatusRequest = true;
  1136. }
  1137. }
  1138. }
  1139. void AnnounceTelcomModemStatus(void)
  1140. {
  1141. for(int index = 0; index < GENERAL_GUN_QUANTITY; index++)
  1142. {
  1143. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].LocalStatus != _DS_None &&
  1144. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].LocalStatus != _DS_Timeout)
  1145. {
  1146. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].Setting.bits.TelcomModemStatusRequest = true;
  1147. }
  1148. }
  1149. }
  1150. void AnnounceBackendStatus(void)
  1151. {
  1152. for(int index = 0; index < GENERAL_GUN_QUANTITY; index++)
  1153. {
  1154. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].LocalStatus != _DS_None &&
  1155. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].LocalStatus != _DS_Timeout)
  1156. {
  1157. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].Setting.bits.BackendStatusRequest = true;
  1158. }
  1159. }
  1160. }
  1161. void AnnounceBillingStatus(void)
  1162. {
  1163. for(int index = 0; index < GENERAL_GUN_QUANTITY; index++)
  1164. {
  1165. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].LocalStatus != _DS_None &&
  1166. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].LocalStatus != _DS_Timeout)
  1167. {
  1168. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].Setting.bits.BillingStatusRequest = true;
  1169. }
  1170. }
  1171. }
  1172. void AnnounceStopChargingButtonStatus(void)
  1173. {
  1174. for(int index = 0; index < GENERAL_GUN_QUANTITY; index++)
  1175. {
  1176. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].LocalStatus != _DS_None &&
  1177. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].LocalStatus != _DS_Timeout)
  1178. {
  1179. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].Setting.bits.StopButtonStatusRequest = true;
  1180. }
  1181. }
  1182. }
  1183. void AnnounceAuthModeConfig(void)
  1184. {
  1185. for(int index = 0; index < GENERAL_GUN_QUANTITY; index++)
  1186. {
  1187. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].LocalStatus != _DS_None &&
  1188. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].LocalStatus != _DS_Timeout)
  1189. {
  1190. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].Setting.bits.AuthModeConfigRequest = true;
  1191. }
  1192. }
  1193. }
  1194. void AnnounceEVCCIDConfig(void)
  1195. {
  1196. for(int index = 0; index < GENERAL_GUN_QUANTITY; index++)
  1197. {
  1198. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].LocalStatus != _DS_None &&
  1199. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].LocalStatus != _DS_Timeout)
  1200. {
  1201. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].Setting.bits.EVCCIDConfigRequest = true;
  1202. }
  1203. }
  1204. }
  1205. void UpdateConfigAndIcon(void)
  1206. {
  1207. unsigned char status = _Connnection_Disable;
  1208. // update ethernet connection status
  1209. status = ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet == YES ? _Connnection_Disconnected : _Connnection_Connected;
  1210. if(ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.EthernetStatus != status)
  1211. {
  1212. ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.EthernetStatus = status;
  1213. AnnounceEthernetStatus();
  1214. }
  1215. // update wifi connection status
  1216. if(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode != _SYS_WIFI_MODE_DISABLE)
  1217. {
  1218. status = ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi == YES ? _Connnection_Disconnected : _Connnection_Connected;
  1219. }
  1220. else
  1221. {
  1222. status = _Connnection_Disable;
  1223. }
  1224. if(ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.WiFiStatus != status)
  1225. {
  1226. ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.WiFiStatus = status;
  1227. AnnounceWiFiStatus();
  1228. }
  1229. // update 4g connection status
  1230. if(ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomEnabled == YES)
  1231. {
  1232. status = (ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi == NO &&
  1233. ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomNetworkConn == YES) ? _Connnection_Connected : _Connnection_Disconnected;
  1234. }
  1235. else
  1236. {
  1237. status = _Connnection_Disable;
  1238. }
  1239. if(ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.TelcomModemStatus != status)
  1240. {
  1241. ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.TelcomModemStatus = status;
  1242. AnnounceTelcomModemStatus();
  1243. }
  1244. // update backend connection status
  1245. status = ShmStatusCodeData->InfoCode.InfoEvents.bits.BackendDisconnectedViaEthernet == YES ? _Connnection_Disconnected : _Connnection_Connected;
  1246. if(ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.BackendStatus != status)
  1247. {
  1248. ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.BackendStatus = status;
  1249. AnnounceBackendStatus();
  1250. }
  1251. // update billing status
  1252. status = ShmSysConfigAndInfo->SysConfig.BillingData.isBilling;
  1253. if(ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.BillingStatus != status)
  1254. {
  1255. ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.BillingStatus = status;
  1256. AnnounceBillingStatus();
  1257. }
  1258. // update stop charging button
  1259. status = ShmSysConfigAndInfo->SysConfig.StopChargingByButton;
  1260. if(ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.StopChargingButton != status)
  1261. {
  1262. ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.StopChargingButton = status;
  1263. AnnounceStopChargingButtonStatus();
  1264. }
  1265. // update AuthMode config
  1266. status = ShmSysConfigAndInfo->SysConfig.AuthorisationMode;
  1267. if(ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.AuthModeConfig != status)
  1268. {
  1269. ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.AuthModeConfig = status;
  1270. AnnounceAuthModeConfig();
  1271. AnnounceEVCCIDConfig();
  1272. }
  1273. // update EVCCID config
  1274. status = ShmSysConfigAndInfo->SysConfig.isAuthrizeByEVCCID;
  1275. if(ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.EVCCIDConfig != status)
  1276. {
  1277. ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.EVCCIDConfig = status;
  1278. AnnounceEVCCIDConfig();
  1279. }
  1280. }
  1281. void Check4gWifiReset(void)
  1282. {
  1283. int timeDelay = 0;
  1284. if(ShmChargerInfo->Control.SysCtrl.bits.BackendEnable)
  1285. {
  1286. if((!ShmSysConfigAndInfo->SysInfo.InternetConn && !ShmSysConfigAndInfo->SysInfo.OcppConnStatus &&
  1287. (ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode != _SYS_WIFI_MODE_DISABLE ||
  1288. ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomEnabled == YES)) ||
  1289. ShmStatusCodeData->FaultCode.FaultEvents.bits.Telecom4GModuleBroken == YES)
  1290. {
  1291. if(!_NeedReset4gWifi)
  1292. {
  1293. GetClockTime(&_4gWifiReset_time);
  1294. LOG_INFO("Backend Enable But Internet Not Available!");
  1295. }
  1296. _NeedReset4gWifi = true;
  1297. }
  1298. else
  1299. {
  1300. _NeedReset4gWifi = false;
  1301. }
  1302. if(_NeedReset4gWifi)
  1303. {
  1304. timeDelay = ShmStatusCodeData->FaultCode.FaultEvents.bits.Telecom4GModuleBroken == YES ?
  1305. FAST_RESET_4G_WIFI_TIME : TRY_RESET_4G_WIFI_TIME;
  1306. if(GetTimeoutValue(_4gWifiReset_time) / uSEC_VAL >= timeDelay)
  1307. {
  1308. ShmChargerInfo->Control.SysCtrl.bits.Wifi4gResetEnable = true;
  1309. usleep(100000);
  1310. // before reset 4g io, kill Module_4g & Module_Wifi task
  1311. if(ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomEnabled == YES)
  1312. {
  1313. system("killall Module_4g &");
  1314. }
  1315. usleep(100000);
  1316. if(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode != _SYS_WIFI_MODE_DISABLE)
  1317. {
  1318. system("killall Module_Wifi &");
  1319. }
  1320. LOG_INFO("Reset 4g_Wifi Module");
  1321. system("echo 1 > /sys/class/gpio/gpio104/value");
  1322. sleep(1);
  1323. system("echo 0 > /sys/class/gpio/gpio104/value");
  1324. _NeedReset4gWifi = false;
  1325. ShmChargerInfo->Control.SysCtrl.bits.Wifi4gResetEnable = false;
  1326. }
  1327. }
  1328. }
  1329. else
  1330. {
  1331. _NeedReset4gWifi = false;
  1332. }
  1333. }
  1334. void MasterCabinetDhcpClientConfig(void)
  1335. {
  1336. char tmpbuf[256];
  1337. //Run DHCP client if enabled
  1338. system("killall udhcpc");
  1339. system("rm -rf /etc/resolv.conf");
  1340. system("echo nameserver 8.8.8.8 > /etc/resolv.conf"); //Google DNS server
  1341. system("echo nameserver 180.76.76.76 > /etc/resolv.conf"); //Baidu DNS server
  1342. //system("/sbin/ifconfig eth0 down;/sbin/ifconfig eth0 up");
  1343. if(ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient == 0)
  1344. {
  1345. sprintf(tmpbuf, "/sbin/udhcpc -i eth0 -x hostname:CSU3_%s -s /root/dhcp_script/eth0.script > /dev/null &", ShmSysConfigAndInfo->SysConfig.SystemId);
  1346. system(tmpbuf);
  1347. }
  1348. //Upgrade system id to /etc/hostname
  1349. sprintf(tmpbuf, "echo %s > /etc/hostname", ShmSysConfigAndInfo->SysConfig.SystemId);
  1350. system(tmpbuf);
  1351. }
  1352. void InitMasterCabinetEthernet(void)
  1353. {
  1354. char tmpbuf[256];
  1355. //Init Eth0 for internet
  1356. memset(tmpbuf,0,256);
  1357. sprintf(tmpbuf,"/sbin/ifconfig eth0 %s netmask %s up",
  1358. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress,
  1359. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress);
  1360. system(tmpbuf);
  1361. memset(tmpbuf,0,256);
  1362. sprintf(tmpbuf,"route add default gw %s eth0 ",
  1363. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthGatewayAddress);
  1364. system(tmpbuf);
  1365. //system("ifconfig lo up");
  1366. // /sbin/ifconfig eth0 192.168.1.10 netmask 255.255.255.0 up
  1367. //Init Eth1 for administrator tool
  1368. memset(tmpbuf,0,256);
  1369. sprintf(tmpbuf,"/sbin/ifconfig eth1 %s netmask %s up", "192.168.100.1", "255.255.255.0");
  1370. system(tmpbuf);
  1371. }
  1372. void InitSlaveCabinetEthernet(void)
  1373. {
  1374. char tmpbuf[256];
  1375. system("/sbin/ifconfig eth0 down");
  1376. system("/sbin/ifconfig eth1 down");
  1377. system("killall udhcpc");
  1378. system("rm -rf /etc/resolv.conf");
  1379. system("pgrep -f \"udhcpd /etc/udhcpd_eth1.conf\" | xargs kill");
  1380. //Init Eth0 for internet
  1381. memset(tmpbuf,0,256);
  1382. sprintf(tmpbuf,"/sbin/ifconfig eth0 192.168.100.3%d netmask %s up",
  1383. (ShmChargerInfo->Control.CabinetSwitch - 1),
  1384. "255.255.255.0");
  1385. system(tmpbuf);
  1386. system("/sbin/route add default gw 192.168.100.1 eth0");
  1387. //Init Eth1 for internet
  1388. memset(tmpbuf,0,256);
  1389. sprintf(tmpbuf,"/sbin/ifconfig eth1 %s netmask %s up", SLAVE_ETH1_IP, SLAVE_ETH1_SUBMASK);
  1390. system(tmpbuf);
  1391. }
  1392. void InitEthernet(void)
  1393. {
  1394. system("ifconfig eth0 down");
  1395. system("ifconfig eth1 down");
  1396. sleep(2);
  1397. char tmpbuf[256];
  1398. // /sbin/ifconfig eth0 192.168.1.10 netmask 255.255.255.0 down
  1399. system("echo 1 > /sys/class/gpio/gpio110/value");//reset PHY
  1400. sleep(2);
  1401. InitMasterCabinetEthernet();
  1402. MasterCabinetDhcpClientConfig();
  1403. // DO360 DHCP Server
  1404. InitialDispenserDhcpServerConfig();
  1405. StartDispenserDhcpServer();
  1406. pid_t pid = fork();
  1407. uint8_t cnt_pingDNS_Fail;
  1408. if(pid == 0)
  1409. {
  1410. ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.BackendStatus = _Connnection_Disconnected;
  1411. ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.EthernetStatus = _Connnection_Disconnected;
  1412. ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.WiFiStatus = _Connnection_Disable;
  1413. ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.TelcomModemStatus = _Connnection_Disable;
  1414. LOG_INFO("Internet Fork PID = %d", getpid());
  1415. for(;;)
  1416. {
  1417. if(isEthernetCablePlugIn(0) == YES)
  1418. {
  1419. if(isRouteFail())
  1420. {
  1421. LOG_INFO("eth0 not in route, restart eht0.");
  1422. system("/sbin/ifconfig eth0 down;/sbin/ifconfig eth0 up");
  1423. if (ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient == 0)
  1424. {
  1425. InitialDHCP();
  1426. }
  1427. else
  1428. {
  1429. system("pgrep -f \"udhcpc -i eth0\" | xargs kill");
  1430. memset(tmpbuf,0,256);
  1431. sprintf(tmpbuf,"/sbin/ifconfig eth0 %s netmask %s up &",
  1432. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress,
  1433. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress);
  1434. system(tmpbuf);
  1435. memset(tmpbuf,0,256);
  1436. sprintf(tmpbuf,"route add default gw %s eth0 &",
  1437. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthGatewayAddress);
  1438. system(tmpbuf);
  1439. }
  1440. }
  1441. }
  1442. if(isReachableInternet() == PASS)
  1443. {
  1444. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet != NO)
  1445. {
  1446. LOG_INFO("Internet is Reachable");
  1447. }
  1448. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = NO;
  1449. ShmSysConfigAndInfo->SysInfo.ethInternetConn = YES;
  1450. cnt_pingDNS_Fail = 0;
  1451. }
  1452. else
  1453. {
  1454. if(++cnt_pingDNS_Fail > 3)
  1455. {
  1456. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet != YES)
  1457. {
  1458. LOG_INFO("Internet is Disconnect Via Ethernet");
  1459. }
  1460. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = YES;
  1461. ShmSysConfigAndInfo->SysInfo.ethInternetConn = NO;
  1462. }
  1463. }
  1464. bool ethResult = ShmSysConfigAndInfo->SysInfo.ethInternetConn;
  1465. if(ethResult == YES)
  1466. {
  1467. system("/sbin/ifmetric eth0 0");
  1468. if(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode != _SYS_WIFI_MODE_DISABLE &&
  1469. ((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D')))
  1470. {
  1471. system("/sbin/ifmetric mlan0 1");
  1472. }
  1473. if(ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomEnabled == YES &&
  1474. ((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D')))
  1475. {
  1476. system("/sbin/ifmetric ppp0 2");
  1477. }
  1478. }
  1479. if (!ethResult &&
  1480. ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode != _SYS_WIFI_MODE_DISABLE &&
  1481. (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W' || ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  1482. {
  1483. ethResult = ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi == YES ? NO : YES;
  1484. if (ethResult)
  1485. {
  1486. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  1487. {
  1488. system("/sbin/ifmetric eth0 1");
  1489. system("/sbin/ifmetric mlan0 0");
  1490. }
  1491. if(ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomEnabled == YES &&
  1492. ((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D')))
  1493. {
  1494. system("/sbin/ifmetric ppp0 2");
  1495. }
  1496. }
  1497. }
  1498. if (!ethResult &&
  1499. ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomEnabled == YES &&
  1500. (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T' || ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  1501. {
  1502. ethResult = (ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi == NO &&
  1503. ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomNetworkConn == YES) ? YES : NO;
  1504. if (ethResult)
  1505. {
  1506. if(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode != _SYS_WIFI_MODE_DISABLE &&
  1507. ((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D')))
  1508. {
  1509. system("/sbin/ifmetric mlan0 2");
  1510. }
  1511. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  1512. {
  1513. system("/sbin/ifmetric eth0 1");
  1514. system("/sbin/ifmetric ppp0 0");
  1515. }
  1516. }
  1517. }
  1518. if(system("pidof -s OcppBackend > /dev/null") != 0)
  1519. {
  1520. ShmOCPP16Data->OcppConnStatus = false;
  1521. ShmSysConfigAndInfo->SysInfo.OcppConnStatus = false;
  1522. }
  1523. ShmSysConfigAndInfo->SysInfo.InternetConn = ethResult;
  1524. ShmStatusCodeData->InfoCode.InfoEvents.bits.WiFiDisable = ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode == false ? true : false;
  1525. ShmStatusCodeData->InfoCode.InfoEvents.bits.Telocom4GModuleDisable = ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomEnabled == false ? true : false;
  1526. ShmStatusCodeData->InfoCode.InfoEvents.bits.BackendDisconnectedViaEthernet = ShmSysConfigAndInfo->SysInfo.OcppConnStatus == false ? true : false;
  1527. UpdateConfigAndIcon();
  1528. Check4gWifiReset();
  1529. sleep(5);
  1530. }
  1531. }
  1532. #ifdef SystemLogMessage
  1533. LOG_INFO("[main]InitEthernet: Initial Ethernet OK.");
  1534. #endif
  1535. }
  1536. /*
  1537. int InitialRfidPort()
  1538. {
  1539. int uartO2 = open(rfidPortName, O_RDWR);
  1540. struct termios tios;
  1541. if (uartO2 != FAIL)
  1542. {
  1543. ioctl (uartO2, TCGETS, &tios);
  1544. tios.c_cflag = B19200 | CS8 | CLOCAL | CREAD;
  1545. tios.c_lflag = 0;
  1546. tios.c_iflag = 0;
  1547. tios.c_oflag = 0;
  1548. tios.c_cc[VMIN] = 0;
  1549. tios.c_cc[VTIME] = (unsigned char) 1;
  1550. tios.c_lflag = 0;
  1551. tcflush(uartO2, TCIFLUSH);
  1552. ioctl(uartO2, TCSETS, &tios);
  1553. }
  1554. if (uartO2 < 0)
  1555. {
  1556. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RfidModuleCommFail = 1;
  1557. }
  1558. return uartO2;
  1559. }
  1560. */
  1561. void GetMacAddress()
  1562. {
  1563. for (byte index = 0; index < 2; index++)
  1564. {
  1565. int fd;
  1566. struct ifreq ifr;
  1567. char tarEth[5];
  1568. char Mac[18];
  1569. sprintf(tarEth,"eth%d",index);
  1570. fd = socket(AF_INET, SOCK_DGRAM, 0);
  1571. ifr.ifr_addr.sa_family = AF_INET;
  1572. strncpy(ifr.ifr_name, tarEth, IFNAMSIZ - 1);
  1573. ioctl(fd, SIOCGIFHWADDR, &ifr);
  1574. close(fd);
  1575. sprintf(Mac, "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
  1576. ifr.ifr_hwaddr.sa_data[0], ifr.ifr_hwaddr.sa_data[1], ifr.ifr_hwaddr.sa_data[2],
  1577. ifr.ifr_hwaddr.sa_data[3], ifr.ifr_hwaddr.sa_data[4], ifr.ifr_hwaddr.sa_data[5]);
  1578. if (index == 0)
  1579. strcpy((char *) ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthMacAddress, Mac);
  1580. else
  1581. strcpy((char *) ShmSysConfigAndInfo->SysConfig.Eth1Interface.EthMacAddress, Mac);
  1582. }
  1583. }
  1584. void GetFirmwareVersion()
  1585. {
  1586. // Get CSU root file system version
  1587. sprintf((char*)ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev, fwVersion);
  1588. byte count = 0, chademo = 0, ccs = 0, gb = 0;
  1589. for(uint8_t idx=0;idx<3;idx++)
  1590. {
  1591. if (ShmSysConfigAndInfo->SysConfig.ModelName[7+idx] == 'J')
  1592. {
  1593. chademo++;
  1594. count++;
  1595. }
  1596. else if (ShmSysConfigAndInfo->SysConfig.ModelName[7+idx] == 'G')
  1597. {
  1598. gb++;
  1599. count++;
  1600. }
  1601. else if (ShmSysConfigAndInfo->SysConfig.ModelName[7+idx] == 'U' ||
  1602. ShmSysConfigAndInfo->SysConfig.ModelName[7+idx] == 'E')
  1603. {
  1604. ccs++;
  1605. count++;
  1606. }
  1607. }
  1608. if (count == 1)
  1609. {
  1610. if (chademo > 0)
  1611. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[7] = '1';
  1612. else if (ccs > 0)
  1613. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[7] = '2';
  1614. else if (gb > 0)
  1615. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[7] = '3';
  1616. }
  1617. else
  1618. {
  1619. if (chademo > 0 && ccs > 0)
  1620. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[7] = '4';
  1621. else if (chademo > 0 && gb > 0)
  1622. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[7] = '5';
  1623. else if (ccs > 0 && gb > 0)
  1624. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[7] = '6';
  1625. }
  1626. // Get network option from model name
  1627. switch(ShmSysConfigAndInfo->SysConfig.ModelName[10])
  1628. {
  1629. case 'B':
  1630. case 'U':
  1631. //Blue tooth
  1632. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '3';
  1633. break;
  1634. case 'W':
  1635. // WIFI
  1636. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '1';
  1637. break;
  1638. case 'T':
  1639. // 3G/4G
  1640. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '2';
  1641. break;
  1642. case 'D':
  1643. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '5';
  1644. break;
  1645. default:
  1646. // LAN
  1647. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '0';
  1648. break;
  1649. }
  1650. // Get rating power from model name
  1651. memcpy(&ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[10], &ShmSysConfigAndInfo->SysConfig.ModelName[4], 0x03);
  1652. // Get IEC or UL
  1653. char _buf[3] = {0};
  1654. memcpy(_buf, &ShmSysConfigAndInfo->SysConfig.ModelName[2], 2);
  1655. if (strcmp(_buf, "YE") == EQUAL || strcmp(_buf, "YC") == EQUAL)
  1656. ShmSysConfigAndInfo->SysInfo.ChargerType = _CHARGER_TYPE_IEC;
  1657. else if (strcmp(_buf, "WU") == EQUAL)
  1658. ShmSysConfigAndInfo->SysInfo.ChargerType = _CHARGER_TYPE_UL;
  1659. }
  1660. void InitialShareMemoryInfo()
  1661. {
  1662. FILE *fp;
  1663. char cmd[512];
  1664. char buf[512];
  1665. _UpgradeNeedReboot = FALSE;
  1666. //sprintf((char *)ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomApn, "Internet");
  1667. //sprintf((char *)ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomChapPapId, " ");
  1668. //sprintf((char *)ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomChapPapPwd, " ");
  1669. ShmSysConfigAndInfo->SysConfig.TotalConnectorCount = 0;
  1670. ShmSysConfigAndInfo->SysConfig.AcConnectorCount = 0;
  1671. ShmSysConfigAndInfo->SysInfo.FactoryConfiguration = 0;
  1672. ShmSysConfigAndInfo->SysInfo.InputVoltageR = 0;
  1673. ShmSysConfigAndInfo->SysInfo.InputVoltageS = 0;
  1674. ShmSysConfigAndInfo->SysInfo.InputVoltageT = 0;
  1675. ShmSysConfigAndInfo->SysInfo.SystemFanRotaSpeed = 0;
  1676. ShmSysConfigAndInfo->SysInfo.PsuFanRotaSpeed = 0;
  1677. ShmSysConfigAndInfo->SysInfo.AuxPower5V = 0;
  1678. ShmSysConfigAndInfo->SysInfo.AuxPower12V = 0;
  1679. ShmSysConfigAndInfo->SysInfo.AuxPower24V = 0;
  1680. ShmSysConfigAndInfo->SysInfo.AuxPower48V = 0;
  1681. sprintf((char *)ShmSysConfigAndInfo->SysInfo.CsuHwRev, "REV:5.0");
  1682. memcpy(ShmSysConfigAndInfo->SysInfo.CsuBootLoadFwRev, ShmSysConfigAndInfo->SysConfig.CsuBootLoadFwRev, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.CsuBootLoadFwRev));
  1683. sprintf(cmd, "/bin/uname -r");
  1684. fp = popen(cmd, "r");
  1685. if(fp == NULL)
  1686. sprintf((char*)ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev, "Unknown version");
  1687. else
  1688. {
  1689. while(fgets(buf, sizeof(buf), fp) != NULL)
  1690. {
  1691. strcpy((char*)ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev, buf);
  1692. }
  1693. }
  1694. // 雙槍 CCS + Chademo
  1695. GetFirmwareVersion();
  1696. //sprintf((char *) ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev, fwVersion);
  1697. sprintf((char *) ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev, " ");
  1698. sprintf((char *) ShmSysConfigAndInfo->SysInfo.LcmHwRev, " ");
  1699. sprintf((char *) ShmSysConfigAndInfo->SysInfo.LcmFwRev, " ");
  1700. sprintf((char *) ShmSysConfigAndInfo->SysInfo.PsuHwRev, " ");
  1701. sprintf((char *) ShmSysConfigAndInfo->SysInfo.PsuPrimFwRev, " ");
  1702. sprintf((char *) ShmSysConfigAndInfo->SysInfo.PsuSecFwRev, " ");
  1703. sprintf((char *) ShmSysConfigAndInfo->SysInfo.AuxPwrHwRev, " ");
  1704. sprintf((char *) ShmSysConfigAndInfo->SysInfo.AuxPwrFwRev, " ");
  1705. sprintf((char *) ShmSysConfigAndInfo->SysInfo.FanModuleHwRev, " ");
  1706. sprintf((char *) ShmSysConfigAndInfo->SysInfo.FanModuleFwRev, " ");
  1707. sprintf((char *) ShmSysConfigAndInfo->SysInfo.RelayModuleHwRev, " ");
  1708. sprintf((char *) ShmSysConfigAndInfo->SysInfo.RelayModuleFwRev, " ");
  1709. sprintf((char *) ShmSysConfigAndInfo->SysInfo.Relay2ModuleHwRev, " "); //DO360 RC2
  1710. sprintf((char *) ShmSysConfigAndInfo->SysInfo.Relay2ModuleFwRev, " "); //DO360 RC2
  1711. sprintf((char *) ShmSysConfigAndInfo->SysInfo.TelcomModemFwRev, " ");
  1712. sprintf((char *) ShmSysConfigAndInfo->SysInfo.LedModuleFwRev, " ");
  1713. sprintf((char *) ShmSysConfigAndInfo->SysInfo.Connector1FwRev, " ");
  1714. sprintf((char *) ShmSysConfigAndInfo->SysInfo.Connector2FwRev, " ");
  1715. ShmSysConfigAndInfo->SysInfo.SystemAmbientTemp = 0;
  1716. ShmSysConfigAndInfo->SysInfo.SystemCriticalTemp = 0;
  1717. ShmSysConfigAndInfo->SysInfo.PsuAmbientTemp = 0;
  1718. ShmSysConfigAndInfo->SysInfo.CcsConnectorTemp = 0;
  1719. ShmSysConfigAndInfo->SysInfo.InternetConn = 0;
  1720. ShmSysConfigAndInfo->SysInfo.OcppConnStatus = 0;
  1721. ShmSysConfigAndInfo->SysInfo.OrderCharging = NO_DEFINE;
  1722. ShmSysConfigAndInfo->SysInfo.MaxChargingProfilePower = -1;
  1723. strcpy((char *) ShmSysConfigAndInfo->SysConfig.UserId, "");
  1724. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RelayboardStestFail = NO;
  1725. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FanboardStestFail = NO;
  1726. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PrimaryStestFail = NO;
  1727. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ChademoboardStestFail = NO;
  1728. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CCSboardStestFail = NO;
  1729. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcContactStestFail = NO;
  1730. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuModuleStestFail = NO;
  1731. memset(ShmSysConfigAndInfo->SysInfo.FanModuleFwRev, 0, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.FanModuleFwRev));
  1732. memset(ShmSysConfigAndInfo->SysInfo.RelayModuleFwRev, 0, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.RelayModuleFwRev));
  1733. memset(ShmSysConfigAndInfo->SysInfo.Relay2ModuleFwRev, 0, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.Relay2ModuleFwRev)); //DO360 RC2
  1734. ShmPrimaryMcuData->SelfTest_Comp = NO;
  1735. ShmRelayModuleData[0]->SelfTest_Comp = NO;
  1736. ShmRelayModuleData[1]->SelfTest_Comp = NO;
  1737. ShmFanModuleData->SelfTest_Comp = NO;
  1738. ShmLedModuleData->SelfTest_Comp = NO;
  1739. ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
  1740. ShmSysConfigAndInfo->SysInfo.MainChargingMode = _MAIN_CHARGING_MODE_MAX;
  1741. ShmSysConfigAndInfo->SysInfo.ReAssignedFlag = _REASSIGNED_NONE;
  1742. ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc = NO_DEFINE;
  1743. ShmFanModuleData->TestFanSpeed = 0;
  1744. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ModelNameNoneMatchStestFail = NO;
  1745. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuNoResource = NO;
  1746. ShmSysConfigAndInfo->SysConfig.SwitchDebugFlag = NO;
  1747. ShmSysConfigAndInfo->SysConfig.AlwaysGfdFlag = NO;
  1748. LOG_INFO("DispenserSequence = %d, MaxConnectorQuantity = %d",
  1749. ShmSysConfigAndInfo->SysConfig.WiringInfo.DispenserSequence,
  1750. ShmSysConfigAndInfo->SysConfig.WiringInfo.MaxConnectorQuantity);
  1751. for(int i = 0; i < ShmSysConfigAndInfo->SysConfig.WiringInfo.DispenserSequence; i++)
  1752. {
  1753. LOG_INFO("Dispenser[%d] <=> %d", i, ShmSysConfigAndInfo->SysConfig.WiringInfo.WiringSetting[i]);
  1754. }
  1755. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  1756. {
  1757. memset((char *)&_BackupStatusNotification[i], 0, sizeof(struct StructStatusNotification));
  1758. }
  1759. }
  1760. int Initialization(void)
  1761. {
  1762. // 初始化卡號驗證的 Flag
  1763. ClearAuthorizedFlag();
  1764. // 初始化插槍驗證的 Flag
  1765. ClearDetectPluginFlag();
  1766. // int pinOut[2] = { 116, 115 };
  1767. for (byte count = 0; count < CONNECTOR_QUANTITY; count++)
  1768. {
  1769. chargingInfo[count]->RemoteStartFlag = NO;
  1770. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[count].Parameter.bits.RemoteStartRequest = false;
  1771. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[count].Parameter.bits.RemoteStartConfirm = false;
  1772. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[count].Parameter.bits.RemoteStopRequest = false;
  1773. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[count].Parameter.bits.RemoteStopConfirm = false;
  1774. SetOcppErrorCode(count, "NoError");
  1775. }
  1776. LOG_INFO("Initialization OK");
  1777. return PASS;
  1778. }
  1779. void InitialPsuGroupingAndLocation(void)
  1780. {
  1781. if(ShmChargerInfo->Control.SysCtrl.bits.SecondRelayBoardEnable)
  1782. {
  1783. memcpy(ShmPsuGrouping->Location, Group_to_Location_4_Gun, sizeof(ShmPsuGrouping->Location));
  1784. memcpy(ShmPsuGrouping->Layout, Location_to_Group_4_Gun, sizeof(ShmPsuGrouping->Layout));
  1785. }
  1786. else
  1787. {
  1788. memcpy(ShmPsuGrouping->Location, Group_to_Location_2_Gun, sizeof(ShmPsuGrouping->Location));
  1789. memcpy(ShmPsuGrouping->Layout, Location_to_Group_2_Gun, sizeof(ShmPsuGrouping->Layout));
  1790. }
  1791. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  1792. {
  1793. ShmPsuGrouping->GroupCollection[i].Index = i;
  1794. ShmPsuGrouping->GroupCollection[i].Location = ShmPsuGrouping->Location[i];
  1795. if(ShmChargerInfo->Control.SysCtrl.bits.SecondRelayBoardEnable)
  1796. {
  1797. memcpy(&ShmPsuGrouping->GroupCollection[i].ParallelConfig[0], &GroupParallelRelay_4_Gun[i][0], GENERAL_GUN_QUANTITY);
  1798. }
  1799. else
  1800. {
  1801. memcpy(&ShmPsuGrouping->GroupCollection[i].ParallelConfig[0], &GroupParallelRelay_2_Gun[i][0], GENERAL_GUN_QUANTITY);
  1802. }
  1803. ShmChargerInfo->Control.GunAvailable[i] = NO;
  1804. }
  1805. }
  1806. void InitialMaxDispenserConnectorQuantity(void)
  1807. {
  1808. if(ShmChargerInfo->Control.SysCtrl.bits.SecondRelayBoardEnable == false)
  1809. {
  1810. ShmChargerInfo->Control.MaxDispenser = 2;
  1811. ShmChargerInfo->Control.MaxConnector = 2;
  1812. }
  1813. else
  1814. {
  1815. ShmChargerInfo->Control.MaxDispenser = GENERAL_GUN_QUANTITY;
  1816. ShmChargerInfo->Control.MaxConnector = GENERAL_GUN_QUANTITY;
  1817. }
  1818. }
  1819. void InitialAuthMode(void)
  1820. {
  1821. if(ShmSysConfigAndInfo->SysConfig.ModelName[0] == 'D' && ShmSysConfigAndInfo->SysConfig.ModelName[1] == 'K')
  1822. {
  1823. ShmChargerInfo->AuthInfo.AuthMode.bits.AutoStartEnable = true;
  1824. }
  1825. }
  1826. void InitialQRCodeMode(void)
  1827. {
  1828. if(ShmSysConfigAndInfo->SysConfig.ModelName[12] == 'A' && ShmSysConfigAndInfo->SysConfig.ModelName[13] == 'D')
  1829. {
  1830. ShmChargerInfo->AuthInfo.QRCodeMode = _QR_MODE_ChargeBoxId;
  1831. }
  1832. else
  1833. {
  1834. // customized
  1835. if(ShmSysConfigAndInfo->SysConfig.QRCodeMadeMode)
  1836. {
  1837. ShmChargerInfo->AuthInfo.QRCodeMode = _QR_MODE_Customized;
  1838. }
  1839. else
  1840. {
  1841. ShmChargerInfo->AuthInfo.QRCodeMode = _QR_MODE_Default;
  1842. }
  1843. }
  1844. }
  1845. void InitialPowerCabinetSetting(void)
  1846. {
  1847. if(ShmSysConfigAndInfo->SysConfig.ModelName[12] == 'A' && ShmSysConfigAndInfo->SysConfig.ModelName[13] == 'D')
  1848. {
  1849. ShmSysConfigAndInfo->SysConfig.BillingData.isBilling = true;
  1850. }
  1851. ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.BillingStatus = ShmSysConfigAndInfo->SysConfig.BillingData.isBilling;
  1852. ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.StopChargingButton = ShmSysConfigAndInfo->SysConfig.StopChargingByButton;
  1853. ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.AuthModeConfig = ShmSysConfigAndInfo->SysConfig.AuthorisationMode;
  1854. ShmSysConfigAndInfo->SysInfo.CabinetMicsStatus.EVCCIDConfig = ShmSysConfigAndInfo->SysConfig.isAuthrizeByEVCCID;
  1855. }
  1856. bool InitialChargerSetting(void)
  1857. {
  1858. bool result = true;
  1859. if(ShmSysConfigAndInfo->SysConfig.ModelName[0] == 'D' && ShmSysConfigAndInfo->SysConfig.ModelName[1] == 'O')
  1860. {
  1861. ShmChargerInfo->Control.PrimaryCtrl.bits.AcContactorReverse = true;
  1862. ShmChargerInfo->Control.PrimaryCtrl.bits.DoorSensorReverse = true;
  1863. ShmChargerInfo->Control.SysCtrl.bits.LedBoardDisable = true;
  1864. ShmChargerInfo->Control.SysCtrl.bits.SecondRelayBoardEnable = true;
  1865. ShmChargerInfo->Control.SysCtrl.bits.DOLedIndication = true;
  1866. }
  1867. else if(ShmSysConfigAndInfo->SysConfig.ModelName[0] == 'D' && ShmSysConfigAndInfo->SysConfig.ModelName[1] == 'K')
  1868. {
  1869. ShmChargerInfo->Control.SysCtrl.bits.FanBoardDisable = true;
  1870. ShmChargerInfo->Control.SysCtrl.bits.LedBoardDisable = true;
  1871. ShmChargerInfo->Control.SysCtrl.bits.DKLedIndication = true;
  1872. }
  1873. else if(ShmSysConfigAndInfo->SysConfig.ModelName[0] == 'D' && ShmSysConfigAndInfo->SysConfig.ModelName[1] == 'B')
  1874. {
  1875. //ShmChargerInfo->Control.SysCtrl.bits.FanBoardDisable = true;
  1876. ShmChargerInfo->Control.SysCtrl.bits.LedBoardDisable = true;
  1877. ShmChargerInfo->Control.SysCtrl.bits.DOLedIndication = true;
  1878. //ShmChargerInfo->Control.SysCtrl.bits.DKLedIndication = true;
  1879. ShmChargerInfo->Control.RelayCtrl.bits.AcInputDisable = true;
  1880. ShmChargerInfo->Control.RelayCtrl.bits.DcInputEnable = true;
  1881. }
  1882. else
  1883. {
  1884. result = false;
  1885. }
  1886. InitialMaxDispenserConnectorQuantity();
  1887. InitialAuthMode();
  1888. InitialQRCodeMode();
  1889. InitialPsuGroupingAndLocation();
  1890. InitialPowerCabinetSetting();
  1891. if(!CheckConnectorTypeStatus())
  1892. {
  1893. result = false;
  1894. }
  1895. return result;
  1896. }
  1897. bool InitialSystemDefaultConfig()
  1898. {
  1899. bool result = true;
  1900. LoadSysConfigAndInfo(&ShmSysConfigAndInfo->SysConfig);
  1901. InitGPIO();
  1902. InitEthernet();
  1903. GetMacAddress();
  1904. // system("echo 1 > /sys/class/gpio/gpio110/value"); //reset PHY
  1905. // sleep(3);
  1906. // system("/sbin/ifconfig eth0 192.168.1.10 netmask 255.255.255.0 down");
  1907. // sleep(1);
  1908. // system("/sbin/ifconfig eth1 192.168.0.10 netmask 255.255.255.0 up");
  1909. return result;
  1910. }
  1911. /*
  1912. bool DisplaySelfTestFailReason()
  1913. {
  1914. bool result = false;
  1915. // RB、FB、407、EV 小板中有些板子無回應
  1916. if (ShmRelayModuleData->SelfTest_Comp == NO)
  1917. { ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RelayboardStestFail = YES; result = true; }
  1918. if (ShmFanModuleData->SelfTest_Comp == NO)
  1919. { ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FanboardStestFail = YES; result = true; }
  1920. if (ShmPrimaryMcuData->SelfTest_Comp == NO)
  1921. { ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PrimaryStestFail = YES; result = true; }
  1922. // if (ShmLedModuleData->SelfTest_Comp == NO)
  1923. // { ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LedboardStestFail = YES; }
  1924. for (byte index = 0; index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; index++)
  1925. {
  1926. if (chargingInfo[index]->Type == _Type_Chademo)
  1927. {
  1928. if (ShmCHAdeMOData->evse[chargingInfo[index]->type_index].SelfTest_Comp == NO)
  1929. { ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ChademoboardStestFail = YES; result = true; }
  1930. }
  1931. else if (chargingInfo[index]->Type == _Type_GB)
  1932. {
  1933. if (ShmGBTData->evse[chargingInfo[index]->type_index].SelfTest_Comp == NO)
  1934. { ShmStatusCodeData->AlarmCode.AlarmEvents.bits.GbtboardStestFail = YES; result = true; }
  1935. }
  1936. else if (chargingInfo[index]->Type == _Type_CCS_2)
  1937. {
  1938. if (ShmCcsData->CommProtocol == _CCS_COMM_V2GMessage_DIN70121)
  1939. {
  1940. if (ShmCcsData->V2GMessage_DIN70121[chargingInfo[index]->type_index].SelfTest_Comp == NO)
  1941. { ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CCSboardStestFail = YES; result = true; }
  1942. }
  1943. }
  1944. }
  1945. for (byte index = 0; index < ShmSysConfigAndInfo->SysConfig.AcConnectorCount; index++)
  1946. {
  1947. // 先借 GBT 顯示
  1948. if (ac_chargingInfo[index]->SelfTest_Comp == NO)
  1949. { ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcConnectorStestFail = YES; result = true; }
  1950. }
  1951. if (ShmSysConfigAndInfo->SysInfo.AcContactorStatus == NO)
  1952. {
  1953. // AC Contact 未搭上
  1954. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcContactStestFail = YES;
  1955. result = true;
  1956. }
  1957. else if (ShmPsuData->SystemAvailablePower <= 0 && ShmPsuData->SystemAvailableCurrent <= 0)
  1958. {
  1959. // PSU 通訊問題
  1960. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuModuleStestFail = YES;
  1961. result = true;
  1962. }
  1963. return result;
  1964. }
  1965. */
  1966. void SelfTestRun(void)
  1967. {
  1968. LOG_INFO("Self test.");
  1969. system("/root/Module_ChargerSelfTest &");
  1970. }
  1971. void SpawnNormalService(void)
  1972. {
  1973. system("/root/Module_EventLogging &");
  1974. system("/root/Module_PrimaryComm &");
  1975. system("/root/Module_EvComm &");
  1976. //system("/root/Module_LcmControl &");
  1977. system("/root/Module_InternalComm &");
  1978. system("/root/Module_PsuComm &");
  1979. system("/root/Module_ProduceUtils &");
  1980. system("/root/Module_CabinetParallel &");
  1981. system("/root/Module_LedIndication &");
  1982. }
  1983. void SpawnOcppService(void)
  1984. {
  1985. if(strcmp((char *)ShmSysConfigAndInfo->SysConfig.OcppServerURL, "") != EQUAL &&
  1986. strcmp((char *)ShmSysConfigAndInfo->SysConfig.ChargeBoxId, "") != EQUAL)
  1987. {
  1988. system("/root/OcppBackend &");
  1989. }
  1990. }
  1991. void SpawnInternetService(void)
  1992. {
  1993. if(ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T')
  1994. {
  1995. if(ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomEnabled == YES)
  1996. {
  1997. system("/root/Module_4g &");
  1998. }
  1999. }
  2000. if(ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W')
  2001. {
  2002. if(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode != _SYS_WIFI_MODE_DISABLE)
  2003. {
  2004. system("/root/Module_Wifi &");
  2005. }
  2006. }
  2007. if(ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D')
  2008. {
  2009. if(ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomEnabled == YES)
  2010. {
  2011. system("/root/Module_4g &");
  2012. }
  2013. if(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode != _SYS_WIFI_MODE_DISABLE)
  2014. {
  2015. system("/root/Module_Wifi &");
  2016. }
  2017. }
  2018. }
  2019. int SpawnTask(void)
  2020. {
  2021. sleep(2);
  2022. SpawnNormalService();
  2023. SpawnInternetService();
  2024. return PASS;
  2025. }
  2026. int runFlashShellCmd(const char *cmd)
  2027. {
  2028. int result = FAIL;
  2029. char buf[256];
  2030. FILE *fp;
  2031. fp = popen(cmd, "r");
  2032. if(fp != NULL)
  2033. {
  2034. while(fgets(buf, sizeof(buf), fp) != NULL)
  2035. {
  2036. LOG_INFO("%s\n", buf);
  2037. }
  2038. result = PASS;
  2039. }
  2040. pclose(fp);
  2041. return result;
  2042. }
  2043. int StoreUsrConfigData(struct SysConfigData *UsrData)
  2044. {
  2045. int result = PASS;
  2046. int fd, wrd;
  2047. unsigned int i, Chk;
  2048. unsigned char *ptr, *BufTmp;
  2049. Chk = 0;
  2050. ptr = (unsigned char *)UsrData;
  2051. if((BufTmp = malloc(MtdBlockSize)) != NULL)
  2052. {
  2053. memset(BufTmp, 0, MtdBlockSize);
  2054. memcpy(BufTmp, ptr, sizeof(struct SysConfigData));
  2055. for(i = ARRAY_SIZE(UsrData->CsuBootLoadFwRev); i < MtdBlockSize - 4; i++)
  2056. {
  2057. Chk += *(BufTmp+i);
  2058. }
  2059. memcpy(BufTmp + MtdBlockSize - 4, &Chk, 4);
  2060. // Output configuration to file.
  2061. fd = open("/mnt/EvseTempConfig.bin", O_RDWR | O_CREAT | O_TRUNC);
  2062. if(fd < 0)
  2063. {
  2064. LOG_ERROR("open /mnt/EvseTempConfig.bin NG");
  2065. free(BufTmp);
  2066. return 0;
  2067. }
  2068. wrd = write(fd, BufTmp, MtdBlockSize);
  2069. close(fd);
  2070. if(wrd < MtdBlockSize)
  2071. {
  2072. LOG_ERROR("write /mnt/EvseTempConfig.bin NG");
  2073. free(BufTmp);
  2074. return 0;
  2075. }
  2076. LOG_INFO("EvseTempConfig write to file in /mnt OK.");
  2077. LOG_INFO("Erase /dev/mtd10.");
  2078. runFlashShellCmd("flash_erase /dev/mtd10 0 0");
  2079. LOG_INFO("Write /dev/mtd10.");
  2080. runFlashShellCmd("nandwrite -p /dev/mtd10 /mnt/EvseTempConfig.bin");
  2081. LOG_INFO("Erase /dev/mtd11.");
  2082. runFlashShellCmd("flash_erase /dev/mtd11 0 0");
  2083. LOG_INFO("Write /dev/mtd11.");
  2084. runFlashShellCmd("nandwrite -p /dev/mtd11 /mnt/EvseTempConfig.bin");
  2085. system("rm -f /mnt/EvseTempConfig.bin");
  2086. LOG_INFO("EvseTempConfig write to flash OK");
  2087. }
  2088. else
  2089. {
  2090. LOG_ERROR("alloc BlockSize NG");
  2091. result = FAIL;
  2092. }
  2093. if(BufTmp != NULL)
  2094. {
  2095. free(BufTmp);
  2096. }
  2097. return result;
  2098. }
  2099. //===============================================
  2100. // Common Detect Chk - Stop Charging ?
  2101. //===============================================
  2102. bool isEvBoardStopChargeFlag(byte gunIndex)
  2103. {
  2104. return chargingInfo[gunIndex]->ChargingStopFlag.bits.AlarmStop;
  2105. }
  2106. bool isNormalStopChargeFlag(byte gunIndex)
  2107. {
  2108. return (chargingInfo[gunIndex]->ChargingStopFlag.bits.NormalStop || chargingInfo[gunIndex]->ChargingStopFlag.bits.ManualStop);
  2109. }
  2110. //===============================================
  2111. // 掃描插槍狀況
  2112. //===============================================
  2113. void ClearDetectPluginFlag()
  2114. {
  2115. ShmSysConfigAndInfo->SysInfo.WaitForPlugit = NO;
  2116. for (byte gun_index = 0; gun_index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun_index++)
  2117. {
  2118. if (chargingInfo[gun_index]->RemoteStartFlag == YES)
  2119. chargingInfo[gun_index]->RemoteStartFlag = NO;
  2120. }
  2121. if (ShmSysConfigAndInfo->SysInfo.OrderCharging != NO_DEFINE)
  2122. ShmSysConfigAndInfo->SysInfo.OrderCharging = NO_DEFINE;
  2123. }
  2124. void DetectPluginStart()
  2125. {
  2126. ShmSysConfigAndInfo->SysInfo.WaitForPlugit = YES;
  2127. }
  2128. bool isDetectPlugin()
  2129. {
  2130. if(ShmSysConfigAndInfo->SysInfo.WaitForPlugit == YES)
  2131. return YES;
  2132. return NO;
  2133. }
  2134. //===============================================
  2135. // Common Detect Chk - Chademo
  2136. //===============================================
  2137. bool isEvGunLocked_chademo(byte gunIndex)
  2138. {
  2139. return (DetectBitValue(chargingInfo[gunIndex]->GunLocked , 0) == 0)? NO : YES;
  2140. }
  2141. bool isEvContactorWelding_chademo(byte gunIndex)
  2142. {
  2143. return DetectBitValue(ShmCHAdeMOData->ev[chargingInfo[gunIndex]->type_index].EvDetection, 3);
  2144. }
  2145. bool isEvStopReq_chademo(byte gunIndex)
  2146. {
  2147. return DetectBitValue(ShmCHAdeMOData->ev[chargingInfo[gunIndex]->type_index].EvDetection, 4);
  2148. }
  2149. bool isEvStopCharging_chademo(byte gunIndex)
  2150. {
  2151. if (isEvGunLocked_chademo(gunIndex) == NO)
  2152. {
  2153. // 無鎖槍 = 停止
  2154. LOG_INFO("gun locked none (%d)", gunIndex);
  2155. return YES;
  2156. }
  2157. return NO;
  2158. }
  2159. byte isPrechargeStatus_chademo(byte gunIndex)
  2160. {
  2161. byte result = 0x00;
  2162. result = ShmCHAdeMOData->ev[chargingInfo[gunIndex]->type_index].PresentMsgFlowStatus;
  2163. return result;
  2164. }
  2165. //===============================================
  2166. // Common Detect Chk - GB
  2167. //===============================================
  2168. bool isEvGunLocked_gb(byte gunIndex)
  2169. {
  2170. return (DetectBitValue(chargingInfo[gunIndex]->GunLocked , 0) == 0)? NO : YES;
  2171. }
  2172. bool isEvStopCharging_gb(byte gunIndex)
  2173. {
  2174. if (isEvGunLocked_gb(gunIndex) == NO)
  2175. {
  2176. // 無鎖槍 = 停止
  2177. LOG_INFO("gun locked none.");
  2178. return YES;
  2179. }
  2180. return NO;
  2181. }
  2182. byte isPrechargeStatus_gb(byte gunIndex)
  2183. {
  2184. byte result = 0x00;
  2185. result = ShmGBTData->ev[chargingInfo[gunIndex]->type_index].PresentMsgFlowStatus;
  2186. return result;
  2187. }
  2188. //===============================================
  2189. // Common Detect Chk - CCS
  2190. //===============================================
  2191. bool isEvGunLocked_ccs(byte gunIndex)
  2192. {
  2193. return (DetectBitValue(chargingInfo[gunIndex]->GunLocked , 0) == 0)? NO : YES;
  2194. }
  2195. byte isPrechargeStatus_ccs(byte gunIndex)
  2196. {
  2197. byte result = 0x00;
  2198. if (ShmCcsData->CommProtocol == _CCS_COMM_V2GMessage_DIN70121)
  2199. {
  2200. result = ShmCcsData->V2GMessage_DIN70121[chargingInfo[gunIndex]->type_index].PresentMsgFlowStatus;
  2201. }
  2202. return result;
  2203. }
  2204. bool isEvStopCharging_ccs(byte gunIndex)
  2205. {
  2206. if (isEvGunLocked_ccs(gunIndex) == NO)
  2207. {
  2208. // 無鎖槍 = 停止
  2209. LOG_INFO("gun locked none.");
  2210. return YES;
  2211. }
  2212. return NO;
  2213. }
  2214. //===============================================
  2215. // Callback
  2216. //===============================================
  2217. void DisplayChargingInfo()
  2218. {
  2219. LOG_INFO("*********** DisplayChargingInfo ***********");
  2220. for (byte i = 0; i < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; i++)
  2221. {
  2222. if (chargingInfo[i]->SystemStatus != S_IDLE &&
  2223. chargingInfo[i]->SystemStatus != S_RESERVATION)
  2224. {
  2225. ChangeGunSelectByIndex(i);
  2226. return;
  2227. }
  2228. }
  2229. if (ShmSysConfigAndInfo->SysConfig.AcConnectorCount > 0 &&
  2230. ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc == NO_DEFINE &&
  2231. ac_chargingInfo[0]->SystemStatus >= S_PREPARNING && ac_chargingInfo[0]->SystemStatus <= S_COMPLETE)
  2232. {
  2233. ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc = DEFAULT_AC_INDEX;
  2234. }
  2235. usleep(50000);
  2236. ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
  2237. }
  2238. void _AutoReturnTimeout()
  2239. {
  2240. LOG_INFO("*********** _AutoReturnTimeout %d*********** ", ShmSysConfigAndInfo->SysInfo.PageIndex);
  2241. if (ShmSysConfigAndInfo->SysInfo.PageIndex == _LCM_WAIT_FOR_PLUG)
  2242. {
  2243. ClearDetectPluginFlag();
  2244. }
  2245. // else if (ShmSysConfigAndInfo->SysInfo.PageIndex == _LCM_AUTHORIZ_COMP)
  2246. // {
  2247. // DetectPluginStart();
  2248. // }
  2249. usleep(50000);
  2250. ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
  2251. }
  2252. void _SelfTestTimeout(void)
  2253. {
  2254. if (ShmSysConfigAndInfo->SysInfo.BootingStatus != BOOT_COMPLETE)
  2255. {
  2256. for (byte gun_index = 0; gun_index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun_index++)
  2257. {
  2258. setChargerMode(gun_index, MODE_FAULT);
  2259. }
  2260. }
  2261. ShmPsuData->Work_Step = _NO_WORKING;
  2262. ShmSysConfigAndInfo->SysInfo.SelfTestSeq = _STEST_FAIL;
  2263. LOG_INFO("Self test timeout.");
  2264. }
  2265. void _AuthorizedTimeout()
  2266. {
  2267. if(IsAuthorizingMode())
  2268. {
  2269. LOG_INFO("*********** _AuthorizedTimeout ***********");
  2270. isCardScan = false;
  2271. ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_AUTHORIZ_FAIL;
  2272. ChangeLcmByIndex(_LCM_AUTHORIZ_FAIL);
  2273. strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
  2274. ClearAuthorizedFlag();
  2275. }
  2276. }
  2277. void _DetectPlugInTimeout()
  2278. {
  2279. LOG_INFO("*********** _DetectPlugInTimeout ***********");
  2280. strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
  2281. ClearDetectPluginFlag();
  2282. usleep(50000);
  2283. ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
  2284. }
  2285. void _DetectEvChargingEnableTimeout(byte gunIndex)
  2286. {
  2287. if (chargingInfo[gunIndex]->Type == _Type_Chademo)
  2288. {
  2289. if(!isEvGunLocked_chademo(gunIndex))
  2290. {
  2291. LOG_INFO("*********** _DetectEvChargingEnableTimeout (chademo) ***********");
  2292. }
  2293. }
  2294. else if (chargingInfo[gunIndex]->Type == _Type_GB)
  2295. {
  2296. if(!isEvGunLocked_ccs(gunIndex))
  2297. {
  2298. LOG_INFO("*********** _DetectEvChargingEnableTimeout (gb) ***********");
  2299. }
  2300. }
  2301. else if (chargingInfo[gunIndex]->Type == _Type_CCS_2)
  2302. {
  2303. if(!isEvGunLocked_ccs(gunIndex))
  2304. {
  2305. LOG_INFO("*********** _DetectEvChargingEnableTimeout (ccs) ***********");
  2306. }
  2307. }
  2308. ChargingTerminalProcess(gunIndex);
  2309. _AutoReturnTimeout();
  2310. }
  2311. void _DetectEvseChargingEnableTimeout(byte gunIndex)
  2312. {
  2313. LOG_INFO("*********** _DetectEvseChargingEnableTimeout (GFD timeout) ***********");
  2314. //if (chargingInfo[gunIndex]->GroundFaultStatus != GFD_PASS)
  2315. {
  2316. setChargerMode(gunIndex, MODE_TERMINATING);
  2317. _AutoReturnTimeout();
  2318. }
  2319. }
  2320. void _PrepareTimeout(byte gunIndex)
  2321. {
  2322. LOG_INFO("*********** _PrepareTimeout ***********");
  2323. setChargerMode(gunIndex, MODE_TERMINATING);
  2324. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuNoResource = YES;
  2325. _AutoReturnTimeout();
  2326. }
  2327. void _CcsPrechargeTimeout(byte gunIndex)
  2328. {
  2329. LOG_INFO("*********** _CcsPrechargeTimeout ***********");
  2330. setChargerMode(gunIndex, MODE_IDLE);
  2331. }
  2332. //===============================================
  2333. // 取得卡號與卡號驗證
  2334. //===============================================
  2335. bool canStartCharging()
  2336. {
  2337. char buf2[16] = "";
  2338. memset(buf2, 0, ARRAY_SIZE(buf2));
  2339. for (byte index = 0; index < strlen((char *)ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status); index++)
  2340. {
  2341. sprintf(buf2 + (index - 1) * 2, "%02X", ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status[index]);
  2342. }
  2343. sprintf(buf2, "%s", ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status);
  2344. // 因為無法得知實際的長度,所以只能用搜尋的方式
  2345. if(strcmp(buf2, "Accepted") == EQUAL)
  2346. return true;
  2347. else
  2348. {
  2349. }
  2350. return false;
  2351. }
  2352. void AuthorizingStart()
  2353. {
  2354. ShmOCPP16Data->SpMsg.bits.AuthorizeReq = YES;
  2355. ShmSysConfigAndInfo->SysInfo.AuthorizeFlag = YES;
  2356. }
  2357. void ClearAuthorizedFlag()
  2358. {
  2359. ShmOCPP16Data->SpMsg.bits.AuthorizeConf = NO;
  2360. ShmSysConfigAndInfo->SysInfo.AuthorizeFlag = NO;
  2361. }
  2362. bool isAuthorizedComplete()
  2363. {
  2364. if (ShmOCPP16Data->SpMsg.bits.AuthorizeConf == NO)
  2365. return false;
  2366. return true;
  2367. }
  2368. bool IsAuthorizingMode()
  2369. {
  2370. if(ShmSysConfigAndInfo->SysInfo.AuthorizeFlag == NO)
  2371. return false;
  2372. return true;
  2373. }
  2374. void ReleaseAlarmCode(byte gunIndex)
  2375. {
  2376. if (strcmp((char *)ShmOCPP16Data->StatusNotification[gunIndex].ErrorCode, "NoError") != EQUAL)
  2377. {
  2378. SetOcppErrorCode(gunIndex, "NoError");
  2379. }
  2380. if (strcmp((char *)ShmOCPP16Data->StatusNotification[gunIndex].VendorErrorCode, "") != EQUAL)
  2381. {
  2382. SetOcppVendorErrorCode(gunIndex, "");
  2383. }
  2384. if (strcmp((char *)chargingInfo[gunIndex]->ConnectorAlarmCode, "") != EQUAL)
  2385. {
  2386. strcpy((char *)chargingInfo[gunIndex]->ConnectorAlarmCode, "");
  2387. }
  2388. if (strcmp((char *)chargingInfo[gunIndex]->EvConnAlarmCode, "") != EQUAL)
  2389. {
  2390. strcpy((char *)chargingInfo[gunIndex]->EvConnAlarmCode, "");
  2391. }
  2392. if (strcmp((char *)ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gunIndex].RemotenAlarmCode, "") != EQUAL)
  2393. {
  2394. strcpy((char *)ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gunIndex].RemotenAlarmCode, "");
  2395. }
  2396. }
  2397. //===============================================
  2398. // EmergencyStop and Charging Stop
  2399. //===============================================
  2400. void ChargingTerminalProcess(byte gunIndex)
  2401. {
  2402. setChargerMode(gunIndex, MODE_TERMINATING);
  2403. }
  2404. void ChargingAlarmProcess(byte gunIndex)
  2405. {
  2406. UpdateErrorCodeToOcpp(gunIndex);
  2407. setChargerMode(gunIndex, MODE_ALARM);
  2408. }
  2409. void AcChargingTerminalProcess()
  2410. {
  2411. ac_chargingInfo[0]->SystemStatus = MODE_TERMINATING;
  2412. }
  2413. void StopChargingProcessByString(byte level)
  2414. {
  2415. if (level > ShmSysConfigAndInfo->SysWarningInfo.Level)
  2416. {
  2417. ShmSysConfigAndInfo->SysWarningInfo.Level = level;
  2418. }
  2419. }
  2420. void ReleaseChargingProcessByString(byte level)
  2421. {
  2422. if (level >= ShmSysConfigAndInfo->SysWarningInfo.Level)
  2423. ShmSysConfigAndInfo->SysWarningInfo.Level = 0;
  2424. }
  2425. // 一般錯誤停止充電處理函式
  2426. void BoardErrOccurByString(byte index, char *code)
  2427. {
  2428. byte level = 1;
  2429. if ((chargingInfo[index]->SystemStatus > S_IDLE && chargingInfo[index]->SystemStatus < S_TERMINATING) ||
  2430. (chargingInfo[index]->SystemStatus >= S_CCS_PRECHARGE_ST0 && chargingInfo[index]->SystemStatus <= S_CCS_PRECHARGE_ST1))
  2431. {
  2432. if (strncmp(code, "023730", 6) == EQUAL && ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargerGetEmergencyStop == NO)
  2433. {
  2434. ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargerGetEmergencyStop = YES;
  2435. }
  2436. ChargingTerminalProcess(index);
  2437. }
  2438. StopChargingProcessByString(level);
  2439. }
  2440. // 急停狀況的停止充電處理函式
  2441. void EmcOccureByString(char *code)
  2442. {
  2443. byte level = 2;
  2444. if(ShmSysConfigAndInfo->SysInfo.SelfTestSeq != _STEST_COMPLETE)
  2445. {
  2446. return;
  2447. }
  2448. // 嚴重的急停有以下幾種 : EMC 按鈕、Mainbreak、Dooropen
  2449. // 其錯誤等級為 2
  2450. if (strncmp(code, "042251", 6) == EQUAL || strncmp(code, "042252", 6) == EQUAL ||
  2451. strncmp(code, "042238", 6) == EQUAL || strncmp(code, "042267", 6) == EQUAL)
  2452. {
  2453. for (byte gun = 0; gun < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun++)
  2454. {
  2455. if ((chargingInfo[gun]->SystemStatus > S_IDLE && chargingInfo[gun]->SystemStatus < S_TERMINATING) ||
  2456. (chargingInfo[gun]->SystemStatus >= S_CCS_PRECHARGE_ST0 && chargingInfo[gun]->SystemStatus <= S_CCS_PRECHARGE_ST1))
  2457. {
  2458. if (strncmp((char *)chargingInfo[gun]->ConnectorAlarmCode, "", 6) == EQUAL)
  2459. {
  2460. memcpy(chargingInfo[gun]->ConnectorAlarmCode, code, 6);
  2461. }
  2462. ChargingAlarmProcess(gun);
  2463. }
  2464. }
  2465. StopChargingProcessByString(level);
  2466. InformOcppErrOccur(4);
  2467. }
  2468. }
  2469. void ReleaseBoardErrOccurByString(byte index, char *code)
  2470. {
  2471. bool isTrigger = false;
  2472. byte level = 1;
  2473. if (strncmp(code, "023730", 6) == 0 && ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargerGetEmergencyStop == YES)
  2474. {
  2475. isTrigger = true;
  2476. ShmStatusCodeData->InfoCode.InfoEvents.bits.ChademoChargerGetEmergencyStop = NO;
  2477. }
  2478. if (isTrigger)
  2479. {
  2480. ReleaseChargingProcessByString(level);
  2481. }
  2482. }
  2483. void ReleaseEmsOccureByString(byte index, char *code)
  2484. {
  2485. bool isTrigger = false;
  2486. byte level = 2;
  2487. if (strncmp(code, "042251", 6) == 0 && ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip == YES)
  2488. {
  2489. isTrigger = true;
  2490. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip = NO;
  2491. }
  2492. else if (strncmp(code, "042252", 6) == 0 && ShmStatusCodeData->AlarmCode.AlarmEvents.bits.DoorOpen == YES)
  2493. {
  2494. isTrigger = true;
  2495. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.DoorOpen = NO;
  2496. }
  2497. else if (strncmp(code, "042237", 6) == 0 && ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SpdTrip == YES)
  2498. {
  2499. isTrigger = true;
  2500. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SpdTrip = NO;
  2501. }
  2502. else if (strncmp(code, "042238", 6) == 0 && ShmStatusCodeData->AlarmCode.AlarmEvents.bits.MainPowerBreakerTrip == YES)
  2503. {
  2504. isTrigger = true;
  2505. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.MainPowerBreakerTrip = NO;
  2506. }
  2507. else if (strncmp(code, "042267", 6) == 0 && ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuFailureAlarm == YES)
  2508. {
  2509. isTrigger = true;
  2510. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuFailureAlarm = NO;
  2511. }
  2512. if (isTrigger)
  2513. {
  2514. ReleaseChargingProcessByString(level);
  2515. }
  2516. }
  2517. //===============================================
  2518. // 確認硬體 (按鈕) 狀態
  2519. //===============================================
  2520. void ChkPrimaryStatus()
  2521. {
  2522. if(ShmChargerInfo->Control.TestCtrl.bits.ChargingSimulation)
  2523. {
  2524. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip = NO;
  2525. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.DoorOpen = NO;
  2526. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.MainPowerBreakerTrip = NO;
  2527. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SpdTrip = NO;
  2528. ShmChargerInfo->Control.RelayCtrl.bits.AcContactorOffByEmergency = NO;
  2529. return;
  2530. }
  2531. if (ShmPrimaryMcuData->InputDet.bits.EmergencyButton == ABNORMAL)
  2532. {
  2533. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip = YES;
  2534. ShmChargerInfo->Control.RelayCtrl.bits.AcContactorOffByEmergency = YES;
  2535. EmcOccureByString("042251");
  2536. }
  2537. else
  2538. {
  2539. ReleaseEmsOccureByString(0, "042251");
  2540. ShmChargerInfo->Control.RelayCtrl.bits.AcContactorOffByEmergency = NO;
  2541. }
  2542. if (ShmPrimaryMcuData->InputDet.bits.AcMainBreakerDetec == ABNORMAL)
  2543. {
  2544. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.MainPowerBreakerTrip = YES;
  2545. //EmcOccureByString("042238");
  2546. }
  2547. else
  2548. {
  2549. //ReleaseEmsOccureByString(0, "042238");
  2550. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.MainPowerBreakerTrip = NO;
  2551. }
  2552. if (ShmPrimaryMcuData->InputDet.bits.SpdDetec == ABNORMAL)
  2553. {
  2554. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SpdTrip = YES;
  2555. }
  2556. else
  2557. {
  2558. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SpdTrip = NO;
  2559. }
  2560. if (ShmPrimaryMcuData->InputDet.bits.DoorOpen == ABNORMAL)
  2561. {
  2562. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.DoorOpen = YES;
  2563. EmcOccureByString("042252");
  2564. }
  2565. else
  2566. {
  2567. ReleaseEmsOccureByString(0, "042252");
  2568. }
  2569. }
  2570. struct timespec _AcContactReOpen_Time;
  2571. void ChkPsuStatus(void)
  2572. {
  2573. if(!ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuFailureAlarm)
  2574. {
  2575. for(int psuGroup = 0; psuGroup < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; psuGroup++)
  2576. {
  2577. if(ShmPsuData->PsuGroup[psuGroup].GroupErrorFlag.PsuGroupErrorValue != 0)
  2578. {
  2579. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuFailureAlarm = YES;
  2580. }
  2581. }
  2582. if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuFailureAlarm)
  2583. {
  2584. EmcOccureByString("042267");
  2585. }
  2586. }
  2587. else
  2588. {
  2589. if(ShmChargerInfo->Control.RelayCtrl.bits.AcContactor &&
  2590. ShmChargerInfo->Control.PsuCtrl.bits.FailureResume == NO)
  2591. {
  2592. bool allFaultStatus = true;
  2593. for(int gunIndex = 0; gunIndex < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gunIndex++)
  2594. {
  2595. if(chargingInfo[gunIndex]->SystemStatus != S_FAULT && chargingInfo[gunIndex]->SystemStatus != S_MAINTAIN)
  2596. {
  2597. allFaultStatus = false;
  2598. }
  2599. }
  2600. if(allFaultStatus)
  2601. {
  2602. LOG_INFO("PSU Failure, Need Resume");
  2603. ShmChargerInfo->Control.PsuCtrl.bits.FailureResume = YES;
  2604. }
  2605. }
  2606. }
  2607. }
  2608. int AcContactorReOpenCount = 0;
  2609. void PsuFailureResume(void)
  2610. {
  2611. if(ShmChargerInfo->Control.PsuCtrl.bits.FailureResume)
  2612. {
  2613. if(ShmChargerInfo->Control.RelayCtrl.bits.AcContactorOffByPsu == NO)
  2614. {
  2615. LOG_INFO("Ac Contactor Off By Psu Failure");
  2616. // update _AcContactReOpen_Time
  2617. GetClockTime(&_AcContactReOpen_Time);
  2618. ShmChargerInfo->Control.RelayCtrl.bits.AcContactorOffByPsu = YES;
  2619. AcContactorReOpenCount++;
  2620. }
  2621. else
  2622. {
  2623. if(AcContactorReOpenCount < MAX_AC_CONTACTOR_COUNT)
  2624. {
  2625. if(GetTimeoutValue(_AcContactReOpen_Time) / uSEC_VAL >= AC_CONTACTOR_REOPEN_TIME)
  2626. {
  2627. ReleaseEmsOccureByString(0, "042267");
  2628. // update _AcContactReOpen_Time
  2629. GetClockTime(&_AcContactReOpen_Time);
  2630. ShmChargerInfo->Control.RelayCtrl.bits.AcContactorOffByPsu = NO;
  2631. ShmChargerInfo->Control.PsuCtrl.bits.FailureResume = NO;
  2632. LOG_INFO("Psu Failure Resume");
  2633. }
  2634. }
  2635. }
  2636. }
  2637. else
  2638. {
  2639. if(AcContactorReOpenCount > 0)
  2640. {
  2641. if(GetTimeoutValue(_AcContactReOpen_Time) / uSEC_VAL >= PSU_FAILURE_RESUME_TIME)
  2642. {
  2643. AcContactorReOpenCount = 0;
  2644. }
  2645. }
  2646. }
  2647. }
  2648. void SetAcContactor(unsigned char OnOff)
  2649. {
  2650. OnOff = OnOff ? ON : OFF;
  2651. if(ShmChargerInfo->Control.RelayCtrl.bits.AcContactor != OnOff)
  2652. {
  2653. if(OnOff)
  2654. {
  2655. ShmChargerInfo->Control.RelayCtrl.bits.StandbyCountdown = NO;
  2656. }
  2657. LOG_INFO("Set Ac Contactor %s", OnOff == ON ? "On" : "Off");
  2658. }
  2659. ShmChargerInfo->Control.RelayCtrl.bits.AcContactor = OnOff == ON ? ON : OFF;
  2660. if(ShmChargerInfo->Control.CabinetRole == _CROLE_MASTER && ShmChargerInfo->ParallelCabinet.ParallelStatus == _Parallel_None)
  2661. {
  2662. SetParallelCabinetAcContactor(OnOff);
  2663. }
  2664. }
  2665. void StandbyCheck(void)
  2666. {
  2667. if(IsConnectorWholeIdle() && IsParallelCabinetIdle())
  2668. {
  2669. if(ShmChargerInfo->Control.RelayCtrl.bits.StandbyCountdown)
  2670. {
  2671. int time = STANDBY_TIME;
  2672. if(ShmChargerInfo->Control.RelayCtrl.bits.AcContactor)
  2673. {
  2674. if(ShmChargerInfo->Control.TestCtrl.bits.FastStandbyTime)
  2675. {
  2676. time = FAST_STANDBY_TIME;
  2677. }
  2678. if((GetTimeoutValue(_Standby_time) / uSEC_VAL) >= time)
  2679. {
  2680. SetAcContactor(OFF);
  2681. }
  2682. }
  2683. }
  2684. else
  2685. {
  2686. ShmChargerInfo->Control.RelayCtrl.bits.StandbyCountdown = YES;
  2687. GetClockTime(&_Standby_time);
  2688. }
  2689. }
  2690. else
  2691. {
  2692. if(ShmChargerInfo->Control.RelayCtrl.bits.StandbyCountdown)
  2693. {
  2694. ShmChargerInfo->Control.RelayCtrl.bits.StandbyCountdown = NO;
  2695. }
  2696. }
  2697. }
  2698. void CheckDisconnectionStatusRecovery(void)
  2699. {
  2700. bool recovery = true;
  2701. // check all connector
  2702. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  2703. {
  2704. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].Parameter.bits.Disconnection)
  2705. {
  2706. recovery = false;
  2707. }
  2708. }
  2709. if(recovery)
  2710. {
  2711. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.DisconnectedFromDo = false;
  2712. }
  2713. }
  2714. //===============================================
  2715. // 確認各小板偵測的錯誤狀況
  2716. //===============================================
  2717. void CheckErrorOccurStatus(byte index)
  2718. {
  2719. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].Parameter.bits.NormalStopRequest)
  2720. {
  2721. chargingInfo[index]->ChargingStopFlag.bits.NormalStop = true;
  2722. }
  2723. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].Parameter.bits.AlarmStopRequest)
  2724. {
  2725. if(strncmp((char *)chargingInfo[index]->ConnectorAlarmCode, "", 6) == EQUAL)
  2726. {
  2727. memcpy(chargingInfo[index]->ConnectorAlarmCode, ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].RemotenAlarmCode, 6);
  2728. }
  2729. if(!chargingInfo[index]->ChargingStopFlag.bits.AlarmStop)
  2730. {
  2731. LOG_INFO("Connector %d Error Occur %s", index + 1, chargingInfo[index]->ConnectorAlarmCode);
  2732. }
  2733. chargingInfo[index]->ChargingStopFlag.bits.AlarmStop = true;
  2734. }
  2735. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].Parameter.bits.TimeoutStopRequest)
  2736. {
  2737. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].Parameter.bits.TimeoutStopRequest = false;
  2738. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].Parameter.bits.Disconnection = true;
  2739. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.DisconnectedFromDo = true;
  2740. if(chargingInfo[index]->SystemStatus == S_AUTHORIZING ||
  2741. chargingInfo[index]->SystemStatus == S_PREPARNING ||
  2742. chargingInfo[index]->SystemStatus == S_PREPARING_FOR_EV ||
  2743. chargingInfo[index]->SystemStatus == S_PREPARING_FOR_EVSE ||
  2744. chargingInfo[index]->SystemStatus == S_CHARGING)
  2745. {
  2746. if(strncmp((char *)chargingInfo[index]->ConnectorAlarmCode, "", 6) == EQUAL)
  2747. {
  2748. memcpy(chargingInfo[index]->ConnectorAlarmCode, "042304", 6);
  2749. }
  2750. if(!chargingInfo[index]->ChargingStopFlag.bits.AlarmStop)
  2751. {
  2752. LOG_INFO("Connector %d Disconnect Alarm Occur %s", index + 1, chargingInfo[index]->ConnectorAlarmCode);
  2753. }
  2754. chargingInfo[index]->ChargingStopFlag.bits.AlarmStop = true;
  2755. }
  2756. else if(chargingInfo[index]->SystemStatus == S_REASSIGN_CHECK ||
  2757. chargingInfo[index]->SystemStatus == S_REASSIGN)
  2758. {
  2759. setChargerMode(index, MODE_IDLE);
  2760. }
  2761. }
  2762. if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.DisconnectedFromDo)
  2763. {
  2764. CheckDisconnectionStatusRecovery();
  2765. }
  2766. if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip == YES ||
  2767. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.DoorOpen)
  2768. {
  2769. if (ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess == _EXTRA_ERR_PROCESS_NONE)
  2770. {
  2771. ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess = _EXTRA_ERR_PROCESS_PRIMARY;
  2772. StopChargingProcessByString(2);
  2773. }
  2774. if (strncmp((char *)chargingInfo[index]->ConnectorAlarmCode, "", 6) == EQUAL)
  2775. {
  2776. if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip == YES)
  2777. memcpy(chargingInfo[index]->ConnectorAlarmCode, "042251", 6);
  2778. else if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.DoorOpen == YES)
  2779. memcpy(chargingInfo[index]->ConnectorAlarmCode, "042252", 6);
  2780. }
  2781. }
  2782. else
  2783. {
  2784. if (ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess == _EXTRA_ERR_PROCESS_PRIMARY)
  2785. {
  2786. ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess = _EXTRA_ERR_PROCESS_NONE;
  2787. ReleaseChargingProcessByString(2);
  2788. }
  2789. }
  2790. // RB
  2791. if (ShmSysConfigAndInfo->SysConfig.PhaseLossPolicy == YES)
  2792. {
  2793. if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP == YES ||
  2794. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP == YES ||
  2795. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP == YES)
  2796. {
  2797. if (ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess == _EXTRA_ERR_PROCESS_NONE)
  2798. {
  2799. ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess = _EXTRA_ERR_PROCESS_INUVP;
  2800. StopChargingProcessByString(2);
  2801. }
  2802. if (strncmp((char *)chargingInfo[index]->ConnectorAlarmCode, "", 6) == EQUAL)
  2803. {
  2804. if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputUVP == YES)
  2805. memcpy(chargingInfo[index]->ConnectorAlarmCode, "042203", 6);
  2806. else if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputUVP == YES)
  2807. memcpy(chargingInfo[index]->ConnectorAlarmCode, "042204", 6);
  2808. else if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputUVP == YES)
  2809. memcpy(chargingInfo[index]->ConnectorAlarmCode, "042205", 6);
  2810. }
  2811. if(!chargingInfo[index]->ChargingStopFlag.bits.AlarmStop)
  2812. {
  2813. LOG_INFO("Connector %d RC Board Input UVP Occur %s", index + 1, chargingInfo[index]->ConnectorAlarmCode);
  2814. }
  2815. chargingInfo[index]->ChargingStopFlag.bits.AlarmStop = true;
  2816. }
  2817. else
  2818. {
  2819. if (ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess == _EXTRA_ERR_PROCESS_INUVP)
  2820. {
  2821. ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess = _EXTRA_ERR_PROCESS_NONE;
  2822. ReleaseChargingProcessByString(2);
  2823. }
  2824. }
  2825. }
  2826. else
  2827. {
  2828. if (ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess == _EXTRA_ERR_PROCESS_INUVP)
  2829. {
  2830. ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess = _EXTRA_ERR_PROCESS_NONE;
  2831. ReleaseChargingProcessByString(2);
  2832. }
  2833. }
  2834. if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP == YES ||
  2835. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP == YES ||
  2836. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP == YES)
  2837. {
  2838. if (ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess == _EXTRA_ERR_PROCESS_NONE)
  2839. {
  2840. ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess = _EXTRA_ERR_PROCESS_INOVP;
  2841. StopChargingProcessByString(2);
  2842. }
  2843. if (strncmp((char *)chargingInfo[index]->ConnectorAlarmCode, "", 6) == EQUAL)
  2844. {
  2845. if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP == YES)
  2846. memcpy(chargingInfo[index]->ConnectorAlarmCode, "042200", 6);
  2847. else if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP == YES)
  2848. memcpy(chargingInfo[index]->ConnectorAlarmCode, "042201", 6);
  2849. else if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP == YES)
  2850. memcpy(chargingInfo[index]->ConnectorAlarmCode, "042202", 6);
  2851. }
  2852. if(!chargingInfo[index]->ChargingStopFlag.bits.AlarmStop)
  2853. {
  2854. LOG_INFO("Connector %d RC Board Input OVP Occur %s", index + 1, chargingInfo[index]->ConnectorAlarmCode);
  2855. }
  2856. chargingInfo[index]->ChargingStopFlag.bits.AlarmStop = true;
  2857. }
  2858. else
  2859. {
  2860. if (ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess == _EXTRA_ERR_PROCESS_INOVP)
  2861. {
  2862. ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess = _EXTRA_ERR_PROCESS_NONE;
  2863. ReleaseChargingProcessByString(2);
  2864. }
  2865. }
  2866. }
  2867. /*
  2868. //===============================================
  2869. // 確認 GPIO 狀態
  2870. //===============================================
  2871. void gpio_set_value(unsigned int gpio, unsigned int value)
  2872. {
  2873. int fd;
  2874. char buf[MAX_BUF];
  2875. snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%d/value", gpio);
  2876. fd = open(buf, O_WRONLY);
  2877. if (fd < 0)
  2878. {
  2879. perror("gpio/set-value");
  2880. return;
  2881. }
  2882. if (value)
  2883. write(fd, "1", 2);
  2884. else
  2885. write(fd, "0", 2);
  2886. close(fd);
  2887. }
  2888. int gpio_get_value(unsigned int gpio, unsigned int *value)
  2889. {
  2890. int fd;
  2891. char buf[MAX_BUF];
  2892. char ch;
  2893. snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%d/value", gpio);
  2894. fd = open(buf, O_RDONLY);
  2895. if (fd < 0) {
  2896. perror("gpio/get-value");
  2897. return fd;
  2898. }
  2899. read(fd, &ch, 1);
  2900. if (ch != '0') {
  2901. *value = 1;
  2902. } else {
  2903. *value = 0;
  2904. }
  2905. close(fd);
  2906. return 0;
  2907. }
  2908. void CheckGpioInStatus()
  2909. {
  2910. int pinIn[2] = { 27, 47 };
  2911. unsigned int gpioValue = 0;
  2912. for (int i = 0; i < ARRAY_SIZE(pinIn); i++)
  2913. {
  2914. gpio_get_value(pinIn[i], &gpioValue);
  2915. if (gpioValue == 0x01)
  2916. {
  2917. switch(pinIn[i])
  2918. {
  2919. // 小板緊急停止
  2920. case 47:
  2921. {
  2922. for(int i = 0; i < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; i++)
  2923. {
  2924. if (chargingInfo[i]->slotsIndex == 1)
  2925. {
  2926. if (chargingInfo[i]->Type == _Type_Chademo)
  2927. BoardErrOccurByString(i, "023730");
  2928. else if (chargingInfo[i]->Type == _Type_CCS_2)
  2929. BoardErrOccurByString(i, "013627");
  2930. break;
  2931. }
  2932. }
  2933. }
  2934. break;
  2935. case 27:
  2936. {
  2937. for(int i = 0; i < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; i++)
  2938. {
  2939. if (chargingInfo[i]->slotsIndex == 3)
  2940. {
  2941. if (chargingInfo[i]->Type == _Type_Chademo)
  2942. BoardErrOccurByString(i, "023730");
  2943. else if (chargingInfo[i]->Type == _Type_CCS_2)
  2944. BoardErrOccurByString(i, "013627");
  2945. break;
  2946. }
  2947. }
  2948. }
  2949. break;
  2950. }
  2951. }
  2952. else
  2953. {
  2954. switch (pinIn[i])
  2955. {
  2956. // 小板解除緊急停止
  2957. case 47:
  2958. {
  2959. for(int i = 0; i < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; i++)
  2960. {
  2961. if (chargingInfo[i]->slotsIndex == 1)
  2962. {
  2963. if (chargingInfo[i]->Type == _Type_Chademo)
  2964. ReleaseBoardErrOccurByString(i, "023730");
  2965. else if (chargingInfo[i]->Type == _Type_CCS_2)
  2966. ReleaseBoardErrOccurByString(i, "013627");
  2967. break;
  2968. }
  2969. }
  2970. }
  2971. break;
  2972. case 27:
  2973. {
  2974. for (int i = 0; i < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; i++)
  2975. {
  2976. if (chargingInfo[i]->slotsIndex == 3)
  2977. {
  2978. if (chargingInfo[i]->Type == _Type_Chademo)
  2979. ReleaseBoardErrOccurByString(i, "023730");
  2980. else if (chargingInfo[i]->Type == _Type_CCS_2)
  2981. ReleaseBoardErrOccurByString(i, "013627");
  2982. break;
  2983. }
  2984. }
  2985. }
  2986. break;
  2987. }
  2988. }
  2989. }
  2990. }
  2991. */
  2992. //===============================================
  2993. // Main process
  2994. //===============================================
  2995. // 檢查 Byte 中某個 Bit 的值
  2996. // _byte : 欲改變的 byte
  2997. // _bit : 該 byte 的第幾個 bit
  2998. unsigned char DetectBitValue(unsigned char _byte, unsigned char _bit)
  2999. {
  3000. return ( _byte & mask_table[_bit] ) != 0x00;
  3001. }
  3002. // 設定 Byte 中某個 Bit的值
  3003. // _byte : 欲改變的 byte
  3004. // _bit : 該 byte 的第幾個 bit
  3005. // value : 修改的值為 0 or 1
  3006. void SetBitValue(unsigned char *_byte, unsigned char _bit, unsigned char value)
  3007. {
  3008. if(value == 1)
  3009. *_byte |= (1 << _bit);
  3010. else if (value == 0)
  3011. *_byte ^= (1 << _bit);
  3012. }
  3013. void UserScanFunction()
  3014. {
  3015. }
  3016. unsigned char isModeChange(unsigned char gun_index)
  3017. {
  3018. unsigned char result = NO;
  3019. if(chargingInfo[gun_index]->SystemStatus != chargingInfo[gun_index]->PreviousSystemStatus)
  3020. {
  3021. result = YES;
  3022. chargingInfo[gun_index]->PreviousSystemStatus = chargingInfo[gun_index]->SystemStatus;
  3023. }
  3024. return result;
  3025. }
  3026. void ScannerCardProcess()
  3027. {
  3028. }
  3029. struct timespec _StartAuthorizing_Time;
  3030. void PowerCabinetAuthorizingSettingInitial(void)
  3031. {
  3032. ShmSysConfigAndInfo->SysInfo.AuthorizedDispenser = 0;
  3033. ShmSysConfigAndInfo->SysInfo.AuthorizedTarget = 0;
  3034. ShmSysConfigAndInfo->SysInfo.AuthorizedType = _AuthResult_None;
  3035. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_Idle;
  3036. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.StartAuthorize = false;
  3037. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.AuthorizingCompleted = false;
  3038. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.BackendAuthorized = false;
  3039. }
  3040. void AnnounceAccountBalance(unsigned char index, int balance)
  3041. {
  3042. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].Parameter.bits.AnnounceBalance = true;
  3043. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].AccountBalance = balance;
  3044. if(!ShmChargerInfo->Control.TestCtrl.bits.DisableBalance)
  3045. {
  3046. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].Parameter.bits.AccountBalanceRequest = true;
  3047. }
  3048. LOG_INFO("%sAnnounce Account Balance %d To Connector %d",
  3049. ShmChargerInfo->Control.TestCtrl.bits.DisableBalance ? "Do Not " : "", balance, index + 1);
  3050. }
  3051. void FouceAnnounceAccountBalance(unsigned char index)
  3052. {
  3053. if(!ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].Parameter.bits.AnnounceBalance)
  3054. {
  3055. AnnounceAccountBalance(index, 0);
  3056. }
  3057. }
  3058. void CleanConnectorUserIdAndPrice(unsigned char index)
  3059. {
  3060. if(chargingInfo[index]->SystemStatus == S_IDLE)
  3061. {
  3062. LOG_INFO("*********** Connector %d Clean UserId & UserPrice ***********", index + 1);
  3063. memset(chargingInfo[index]->StartUserId, 0x00, 32);
  3064. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].UserPrice = 0;
  3065. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].AccountBalance = -6553500;
  3066. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].Parameter.bits.AnnounceBalance = false;
  3067. }
  3068. }
  3069. void DispenserAuthorizationInitial(unsigned char dispenser)
  3070. {
  3071. LOG_INFO("*********** Dispenser %d Authorizing Initial ***********", dispenser + 1);
  3072. memset(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].UserId, 0x00, 32);
  3073. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_Idle;
  3074. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthTarget = 0;
  3075. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthType = _AuthType_None;
  3076. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult = _AuthResult_None;
  3077. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].Setting.bits.EnableAutoGunSelection = false;
  3078. }
  3079. void ConnectorAuthorizationInitial(unsigned char connector)
  3080. {
  3081. LOG_INFO("*********** Connector %d Authorizing Initial ***********", connector + 1);
  3082. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].AuthorizingType = _AuthType_None;
  3083. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].AuthorizingResult = _AuthResult_None;
  3084. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].Parameter.bits.SwipeRfidConfirm = false;
  3085. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].Parameter.bits.RemoteStartRequest = false;
  3086. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].Parameter.bits.RemoteStartConfirm = false;
  3087. chargingInfo[connector]->RemoteStartFlag = false;
  3088. CleanConnectorUserIdAndPrice(connector);
  3089. }
  3090. void SetAuthorizingTarget(unsigned char dispenser, unsigned char target, unsigned char type)
  3091. {
  3092. memset(ShmSysConfigAndInfo->SysConfig.UserId, 0x00, 32);
  3093. switch(type)
  3094. {
  3095. case _AuthType_RFID:
  3096. LOG_INFO("*********** Dispenser %d Target %02X RFID Authorize ***********", dispenser + 1, target);
  3097. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].UserId, 32);
  3098. break;
  3099. case _AuthType_RemoteStart:
  3100. LOG_INFO("*********** Connector %d Remote Start Authorize ***********", target);
  3101. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmOCPP16Data->RemoteStartTransaction[target - 1].IdTag, 20);
  3102. break;
  3103. }
  3104. if(target == AUTO_GUN_SELECTION)
  3105. {
  3106. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].Setting.bits.EnableAutoGunSelection = true;
  3107. }
  3108. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_Busy;
  3109. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthType = type;
  3110. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.StartAuthorize = true;
  3111. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.AuthorizingCompleted = false;
  3112. ShmSysConfigAndInfo->SysInfo.AuthorizedDispenser = dispenser;
  3113. ShmSysConfigAndInfo->SysInfo.AuthorizedTarget = target;
  3114. ShmSysConfigAndInfo->SysInfo.AuthorizedType = type;
  3115. }
  3116. void OCPPAuthorizingStart(void)
  3117. {
  3118. ShmOCPP16Data->SpMsg.bits.AuthorizeConf = false;
  3119. ShmOCPP16Data->SpMsg.bits.AuthorizeReq = true;
  3120. }
  3121. void AuthorizeTimeoutProcess(void)
  3122. {
  3123. for(int index = 0; index < GENERAL_GUN_QUANTITY; index++)
  3124. {
  3125. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].AuthorizingResult == _AuthResult_Invalid)
  3126. {
  3127. FouceAnnounceAccountBalance(index);
  3128. if(GetTimeoutValue(_ConnectorAuthorizeFail_Time[index]) / uSEC_VAL >= AUTHORIZE_FAIL_TIMEOUT)
  3129. {
  3130. LOG_INFO("*********** Connector id %d Authorized Fail Return ***********", index + 1);
  3131. ConnectorAuthorizationInitial(index);
  3132. }
  3133. }
  3134. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].AuthStatus == _AuthorizeStatus_End)
  3135. {
  3136. int CompletedTime = 0;
  3137. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].AuthTarget != AUTO_GUN_SELECTION)
  3138. {
  3139. CompletedTime = DISPENSER_AUTH_COMP_TIME;
  3140. }
  3141. else
  3142. {
  3143. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].AuthResult == _AuthResult_Valid)
  3144. {
  3145. CompletedTime = ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectorTimeout;
  3146. }
  3147. else
  3148. {
  3149. CompletedTime = AUTHORIZE_FAIL_TIMEOUT;
  3150. }
  3151. }
  3152. if(GetTimeoutValue(_DispenserAuthorizing_Time[index]) / uSEC_VAL >= CompletedTime)
  3153. {
  3154. LOG_INFO("*********** Dispenser id %d Authorized Return ***********", index + 1);
  3155. DispenserAuthorizationInitial(index);
  3156. }
  3157. }
  3158. }
  3159. }
  3160. bool IsNewAuthorizingRequest(void)
  3161. {
  3162. bool NewRequest = false;
  3163. bool FindRemoteStartRequest = false;
  3164. // remote start check
  3165. for(int index = 0; index < GENERAL_GUN_QUANTITY; index++)
  3166. {
  3167. if(ShmOCPP16Data->CsMsg.bits[index].RemoteStartTransactionReq == true)
  3168. {
  3169. unsigned char dispenser = ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].ParentDispensetIndex;
  3170. SetAuthorizingTarget(dispenser, index + 1, _AuthType_RemoteStart);
  3171. ShmOCPP16Data->CsMsg.bits[index].RemoteStartTransactionReq = false;
  3172. chargingInfo[index]->RemoteStartFlag = true;
  3173. FindRemoteStartRequest = true;
  3174. NewRequest = true;
  3175. break;
  3176. }
  3177. }
  3178. if(!FindRemoteStartRequest)
  3179. {
  3180. // local rfid authorize check
  3181. for(int index = 0; index < GENERAL_GUN_QUANTITY; index++)
  3182. {
  3183. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].AuthStatus == _AuthorizeStatus_Idle &&
  3184. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].Setting.bits.AuthorizeRequest == true)
  3185. {
  3186. if(strlen((char *)ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].UserId) > 0)
  3187. {
  3188. SetAuthorizingTarget(index, ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].AuthTarget, _AuthType_RFID);
  3189. NewRequest = true;
  3190. }
  3191. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].Setting.bits.AuthorizeRequest = false;
  3192. }
  3193. }
  3194. }
  3195. return NewRequest;
  3196. }
  3197. void PowerCabinetAuthorizeProcess(void)
  3198. {
  3199. unsigned char dispenser = 0, connector = 0;
  3200. dispenser = ShmSysConfigAndInfo->SysInfo.AuthorizedDispenser;
  3201. AuthorizeTimeoutProcess();
  3202. switch(ShmSysConfigAndInfo->SysInfo.AuthorizedStatus)
  3203. {
  3204. case _AuthorizeStatus_Idle:
  3205. if(IsNewAuthorizingRequest())
  3206. {
  3207. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_Wait;
  3208. }
  3209. break;
  3210. case _AuthorizeStatus_Wait:
  3211. if(ShmSysConfigAndInfo->SysInfo.AuthorizedType == _AuthType_RemoteStart)
  3212. {
  3213. LOG_INFO("*********** Connector %d Remote Start Authorizing Bypass ***********",
  3214. ShmSysConfigAndInfo->SysInfo.AuthorizedTarget);
  3215. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.BackendAuthorized = true;
  3216. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult = _AuthResult_Valid;
  3217. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_Done;
  3218. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_Done;
  3219. }
  3220. else
  3221. {
  3222. if(ShmOCPP16Data->OcppConnStatus)
  3223. {
  3224. LOG_INFO("*********** Dispenser %d OPCC AuthorizeReq ***********", dispenser + 1);
  3225. OCPPAuthorizingStart();
  3226. }
  3227. else
  3228. {
  3229. LOG_INFO("*********** Dispenser %d Start Local Authorizing ***********", dispenser + 1);
  3230. }
  3231. // update start authorizing timeout
  3232. GetClockTime(&_StartAuthorizing_Time);
  3233. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_Busy;
  3234. }
  3235. break;
  3236. case _AuthorizeStatus_Busy:
  3237. if(GetTimeoutValue(_StartAuthorizing_Time) / uSEC_VAL >= AUTHORIZE_TIMEOUT)
  3238. {
  3239. LOG_INFO("*********** Dispenser %d Authorizing Timeout ***********", dispenser + 1);
  3240. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult = _AuthResult_Invalid;
  3241. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_Done;
  3242. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_Done;
  3243. }
  3244. else
  3245. {
  3246. if(ShmOCPP16Data->OcppConnStatus)
  3247. {
  3248. if(ShmOCPP16Data->SpMsg.bits.AuthorizeConf)
  3249. {
  3250. BOOL accept = false;
  3251. if(strcmp((char *)ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status, "Accepted") == EQUAL)
  3252. {
  3253. accept = true;
  3254. }
  3255. LOG_INFO("*********** Dispenser %d OCPP Authorize %s ***********", dispenser + 1, accept ? "OK" : "NG");
  3256. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.BackendAuthorized = true;
  3257. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult = accept ? _AuthResult_Valid : _AuthResult_Invalid;
  3258. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_Done;
  3259. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_Done;
  3260. }
  3261. }
  3262. else
  3263. {
  3264. if(ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_NO_CHARGING)
  3265. {
  3266. LOG_INFO("*********** Dispenser %d No Charging ***********", dispenser + 1);
  3267. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult = _AuthResult_Invalid;
  3268. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_Done;
  3269. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_Done;
  3270. }
  3271. else if(ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_FREE_CHARGING)
  3272. {
  3273. // set authorize pass when offline policy is free charge
  3274. LOG_INFO("*********** Dispenser %d Free Charging ***********", dispenser + 1);
  3275. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult = _AuthResult_Valid;
  3276. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_Done;
  3277. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_Done;
  3278. }
  3279. else if(ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_LOCAL_LIST)
  3280. {
  3281. BOOL find = false;
  3282. // check white list
  3283. for(int i = 0; i < 10; i++)
  3284. {
  3285. if (strcmp((char *)ShmSysConfigAndInfo->SysConfig.LocalWhiteCard[i], "") != EQUAL)
  3286. {
  3287. if (strcmp((char *)ShmSysConfigAndInfo->SysConfig.LocalWhiteCard[i], (char *)ShmSysConfigAndInfo->SysConfig.UserId) == EQUAL)
  3288. {
  3289. find = true;
  3290. LOG_INFO("*********** Dispenser %d White Card OK ***********", dispenser + 1);
  3291. break;
  3292. }
  3293. }
  3294. }
  3295. if(find == false)
  3296. {
  3297. if(ShmChargerInfo->AuthInfo.AuthMode.bits.AutoStartEnable &&
  3298. strcmp((char *)ShmSysConfigAndInfo->SysConfig.UserId, AUTO_START_CHARGING) == EQUAL)
  3299. {
  3300. find = true;
  3301. LOG_INFO("******** Dispenser %d Auto Start Charging ********", dispenser + 1);
  3302. }
  3303. }
  3304. LOG_INFO("*********** Dispenser %d Local Authorization %s ***********", dispenser + 1, find ? "OK" : "NG");
  3305. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult = find ? _AuthResult_Valid : _AuthResult_Invalid;
  3306. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_Done;
  3307. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_Done;
  3308. }
  3309. else
  3310. {
  3311. LOG_INFO("*********** Dispenser %d Invalid Policy ***********", dispenser + 1);
  3312. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult = _AuthResult_Invalid;
  3313. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_Done;
  3314. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_Done;
  3315. }
  3316. }
  3317. }
  3318. break;
  3319. case _AuthorizeStatus_Done:
  3320. if(ShmSysConfigAndInfo->SysInfo.AuthorizedTarget == AUTO_GUN_SELECTION)
  3321. {
  3322. // auto gun selection
  3323. }
  3324. else
  3325. {
  3326. connector = ShmSysConfigAndInfo->SysInfo.AuthorizedTarget - 1;
  3327. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].AuthorizingType = ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthType;
  3328. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].AuthorizingResult = ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult;
  3329. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].GeneralChargingData.SystemStatus == S_IDLE &&
  3330. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult == _AuthResult_Valid)
  3331. {
  3332. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthType == _AuthType_RFID)
  3333. {
  3334. LOG_INFO("*********** Connector %d RFID Authorize OK ***********", connector + 1);
  3335. memcpy(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].GeneralChargingData.StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, 32);
  3336. }
  3337. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthType == _AuthType_RemoteStart)
  3338. {
  3339. LOG_INFO("*********** Connector id %d RemoteAuthorize OK ***********", connector + 1);
  3340. memcpy(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].GeneralChargingData.StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, 32);
  3341. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].Parameter.bits.RemoteStartRequest = true;
  3342. }
  3343. }
  3344. else if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult == _AuthResult_Invalid)
  3345. {
  3346. // update connector authorizing timeout
  3347. GetClockTime(&_ConnectorAuthorizeFail_Time[connector]);
  3348. }
  3349. }
  3350. // authorize completed
  3351. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.AuthorizingCompleted = true;
  3352. // update dispenser authorizing timeout
  3353. GetClockTime(&_DispenserAuthorizing_Time[dispenser]);
  3354. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_End;
  3355. // update authorizing completed timeout
  3356. GetClockTime(&_StartAuthorizing_Time);
  3357. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_End;
  3358. break;
  3359. case _AuthorizeStatus_End:
  3360. if(GetTimeoutValue(_StartAuthorizing_Time) / uSEC_VAL >= AUTHORIZE_COMP_TIMEOUT)
  3361. {
  3362. LOG_INFO("*********** PowerCabinet Authorize Completed ***********");
  3363. PowerCabinetAuthorizingSettingInitial();
  3364. }
  3365. break;
  3366. default:
  3367. // update authorizing completed timeout
  3368. GetClockTime(&_StartAuthorizing_Time);
  3369. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_End;
  3370. break;
  3371. }
  3372. }
  3373. BOOL IsConnectorAuthorizeSuccess(unsigned char connector)
  3374. {
  3375. BOOL success = false;
  3376. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].AuthorizingResult == _AuthResult_Valid)
  3377. {
  3378. success = true;
  3379. }
  3380. return success;
  3381. }
  3382. BOOL IsAutoGunSelectionAuthorizeSuccess(unsigned char connector)
  3383. {
  3384. BOOL success = false;
  3385. unsigned char dispenser = 0;
  3386. dispenser = ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].ParentDispensetIndex;
  3387. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].Setting.bits.EnableAutoGunSelection &&
  3388. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult == _AuthResult_Valid)
  3389. {
  3390. success = true;
  3391. }
  3392. return success;
  3393. }
  3394. /*
  3395. bool AddGunInfoByConnector(byte typeValue, byte slots)
  3396. {
  3397. bool result = true;
  3398. switch (typeValue)
  3399. {
  3400. case '0': // none
  3401. break;
  3402. case '1': // IEC 62196-2 Type 1/SAE J1772 Plug
  3403. break;
  3404. case '2': // IEC 62196-2 Type 1/SAE J1772 Socket
  3405. break;
  3406. case '3': // IEC 62196-2 Type 2 Plug
  3407. case '4': // IEC 62196-2 Type 2 Socket
  3408. if (AC_QUANTITY > _ac_Index)
  3409. {
  3410. ac_chargingInfo[_acgunIndex] = &ShmSysConfigAndInfo->SysInfo.AcChargingData[_ac_Index];
  3411. // AC 固定 index
  3412. ac_chargingInfo[_acgunIndex]->Index = 0;
  3413. ac_chargingInfo[_acgunIndex]->ReservationId = -1;
  3414. ac_chargingInfo[_acgunIndex]->SystemStatus = S_IDLE;
  3415. ac_chargingInfo[_acgunIndex]->Type = _Type_AC;
  3416. ac_chargingInfo[_acgunIndex]->IsAvailable = YES;
  3417. _ac_Index++;
  3418. _acgunIndex++;
  3419. }
  3420. else
  3421. result = false;
  3422. break;
  3423. case '5': // GB/T AC Plug
  3424. break;
  3425. case '6': // GB/T AC Socket
  3426. break;
  3427. case 'J': // CHAdeMO
  3428. {
  3429. if (CHAdeMO_QUANTITY > _chademoIndex)
  3430. {
  3431. chargingInfo[_gunIndex] = &ShmSysConfigAndInfo->SysInfo.ChademoChargingData[_chademoIndex];
  3432. chargingInfo[_gunIndex]->Index = _gunIndex;
  3433. chargingInfo[_gunIndex]->ReservationId = -1;
  3434. chargingInfo[_gunIndex]->slotsIndex = slots;
  3435. chargingInfo[_gunIndex]->SystemStatus = S_BOOTING;
  3436. chargingInfo[_gunIndex]->Type = _Type_Chademo;
  3437. chargingInfo[_gunIndex]->type_index = _chademoIndex;
  3438. chargingInfo[_gunIndex]->IsAvailable = YES;
  3439. _chademoIndex++;
  3440. _gunIndex++;
  3441. }
  3442. else
  3443. result = false;
  3444. }
  3445. break;
  3446. case 'U': // CCS1 combo
  3447. case 'E': // CCS2 combo
  3448. {
  3449. if (CCS_QUANTITY > _ccsIndex)
  3450. {
  3451. chargingInfo[_gunIndex] = &ShmSysConfigAndInfo->SysInfo.CcsChargingData[_ccsIndex];
  3452. chargingInfo[_gunIndex]->Index = _gunIndex;
  3453. chargingInfo[_gunIndex]->ReservationId = -1;
  3454. chargingInfo[_gunIndex]->slotsIndex = slots;
  3455. chargingInfo[_gunIndex]->SystemStatus = S_BOOTING;
  3456. chargingInfo[_gunIndex]->Type = _Type_CCS_2;
  3457. chargingInfo[_gunIndex]->type_index = _ccsIndex;
  3458. chargingInfo[_gunIndex]->IsAvailable = YES;
  3459. // 現階段預設為走 DIN70121
  3460. ShmCcsData->CommProtocol = _CCS_COMM_V2GMessage_DIN70121;
  3461. _ccsIndex++;
  3462. _gunIndex++;
  3463. }
  3464. else
  3465. result = false;
  3466. }
  3467. break;
  3468. case 'G': // GBT DC
  3469. {
  3470. if (GB_QUANTITY > _gb_Index)
  3471. {
  3472. chargingInfo[_gunIndex] = &ShmSysConfigAndInfo->SysInfo.GbChargingData[_gb_Index];
  3473. chargingInfo[_gunIndex]->Index = _gunIndex;
  3474. chargingInfo[_gunIndex]->ReservationId = -1;
  3475. chargingInfo[_gunIndex]->slotsIndex = slots;
  3476. chargingInfo[_gunIndex]->SystemStatus = S_BOOTING;
  3477. chargingInfo[_gunIndex]->Type = _Type_GB;
  3478. chargingInfo[_gunIndex]->type_index = _gb_Index;
  3479. chargingInfo[_gunIndex]->IsAvailable = YES;
  3480. _gb_Index++;
  3481. _gunIndex++;
  3482. }
  3483. else
  3484. result = false;
  3485. }
  3486. break;
  3487. case 'D': // GBT DC x 2
  3488. break;
  3489. }
  3490. return result;
  3491. }
  3492. */
  3493. unsigned short ParsingRatingPower(char *modelname)
  3494. {
  3495. char strVal[3], strExp[2];
  3496. unsigned short value = 0, exponent = 0;
  3497. memset(strVal, 0x00, sizeof(strVal));
  3498. memset(strExp, 0x00, sizeof(strExp));
  3499. memcpy(strVal, &modelname[4], 2);
  3500. memcpy(strExp, &modelname[6], 1);
  3501. value = atoi(strVal);
  3502. exponent = atoi(strExp);
  3503. if(value < 0 || exponent < 0)
  3504. {
  3505. return 0;
  3506. }
  3507. for(int i = 0; i < exponent; i++)
  3508. {
  3509. value *= 10;
  3510. }
  3511. return value;
  3512. }
  3513. bool CheckConnectorTypeStatus(void)
  3514. {
  3515. bool result = true;
  3516. if (strlen((char *) ShmSysConfigAndInfo->SysConfig.ModelName) >= 14)
  3517. {
  3518. // DO360 for Audi, two gun only
  3519. _gunIndex = ShmChargerInfo->Control.MaxConnector;
  3520. ShmSysConfigAndInfo->SysConfig.TotalConnectorCount = _gunIndex;
  3521. ShmChargerInfo->Control.ChargerRatingPower = ParsingRatingPower((char *)ShmSysConfigAndInfo->SysConfig.ModelName);
  3522. LOG_INFO("DC Gun Count = %d, RatingPower = %d.%d kW",
  3523. ShmSysConfigAndInfo->SysConfig.TotalConnectorCount,
  3524. (ShmChargerInfo->Control.ChargerRatingPower / 10),
  3525. (ShmChargerInfo->Control.ChargerRatingPower % 10));
  3526. if(ShmSysConfigAndInfo->SysConfig.TotalConnectorCount == 0)
  3527. {
  3528. result = false;
  3529. }
  3530. //DO360 charging info default setting
  3531. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  3532. {
  3533. chargingInfo[i] = &ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].GeneralChargingData;
  3534. chargingInfo[i]->Index = (i < ShmSysConfigAndInfo->SysConfig.WiringInfo.MaxConnectorQuantity || i == 0) ? i : 0xFF;
  3535. chargingInfo[i]->Evboard_id = 0x00;
  3536. chargingInfo[i]->ReservationId = -1;
  3537. chargingInfo[i]->slotsIndex = 0;
  3538. chargingInfo[i]->SystemStatus = S_BOOTING;
  3539. chargingInfo[i]->Type = _Type_Unknown;
  3540. chargingInfo[i]->type_index = 0;
  3541. chargingInfo[i]->IsAvailable = YES;
  3542. }
  3543. }
  3544. else
  3545. {
  3546. // Module Name 不正確 - 告警
  3547. result = false;
  3548. }
  3549. return result;
  3550. }
  3551. void KillTaskExceptPrimary()
  3552. {
  3553. ChangeLcmByIndex(_LCM_FIX);
  3554. system("killall Module_CabinetParallel");
  3555. system("killall Module_ChargerSelfTest");
  3556. system("killall Module_LedIndication");
  3557. system("killall Module_EvComm");
  3558. system("killall Module_InternalComm");
  3559. system("killall Module_PsuComm");
  3560. system("killall Module_4g &");
  3561. system("killall Module_Wifi &");
  3562. }
  3563. void KillAllTask()
  3564. {
  3565. ChangeLcmByIndex(_LCM_FIX);
  3566. system("killall Module_CabinetParallel");
  3567. system("killall Module_ChargerSelfTest");
  3568. system("killall Module_LedIndication");
  3569. system("killall Module_EventLogging");
  3570. system("killall Module_PrimaryComm");
  3571. system("killall Module_EvComm");
  3572. system("killall Module_LcmControl");
  3573. system("killall Module_InternalComm");
  3574. system("killall Module_PsuComm");
  3575. system("killall OcppBackend &");
  3576. system("killall Module_4g &");
  3577. system("killall Module_Wifi &");
  3578. }
  3579. int TransferImageViaFTP(char *IpAddress, char *SourcePath)
  3580. {
  3581. int isPass = PASS;
  3582. unsigned char ftpcmdbuf[256];
  3583. LOG_INFO("Transfer image(%s) to ip: %s ", SourcePath, IpAddress);
  3584. //Using ftpput command to transfer upgrade image,
  3585. //User name : root
  3586. //User password : y42j/4cj84
  3587. //Destination : as same as source path
  3588. sprintf((char*)ftpcmdbuf,"ftpput -u root -p y42j/4cj84 %s %s %s", IpAddress, SourcePath, SourcePath);
  3589. if(system((char*)ftpcmdbuf) != 0)
  3590. {
  3591. isPass = FAIL;
  3592. LOG_INFO("Transfer Image NG - FTP put upgrade image to fail");
  3593. }
  3594. else
  3595. {
  3596. LOG_INFO("FTP put Image OK");
  3597. }
  3598. return isPass;
  3599. }
  3600. void TriggerDispenserUpgrade(unsigned char index, char *FileName)
  3601. {
  3602. memset(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].FwFileName, 0x00, 128);
  3603. memcpy(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].FwFileName, FileName, strlen(FileName));
  3604. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].Setting.bits.FirmwareUpdateRequest = true;
  3605. LOG_INFO("Trigger dispenser %d to update image [%s]", index + 1, FileName);
  3606. }
  3607. BOOL PutImageToAllDispenser(char *SourcePath, char *FileName)
  3608. {
  3609. int isPass = FAIL;
  3610. BOOL transferred = FALSE;
  3611. for(int i = 0; i < GENERAL_GUN_QUANTITY; i++)
  3612. {
  3613. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[i].Status == _CNS_DispenserMatched)
  3614. {
  3615. char DispenserIpAddress[16];
  3616. memset((char*)DispenserIpAddress, 0x00, 16);
  3617. sprintf((char*)DispenserIpAddress, "%d.%d.%d.%d",
  3618. ((ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[i].IpAddress >> 0) & 0xFF),
  3619. ((ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[i].IpAddress >> 8) & 0xFF),
  3620. ((ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[i].IpAddress >> 16) & 0xFF),
  3621. ((ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[i].IpAddress >> 24) & 0xFF));
  3622. isPass = TransferImageViaFTP(DispenserIpAddress, SourcePath);
  3623. if(isPass == PASS)
  3624. {
  3625. TriggerDispenserUpgrade(ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[i].DispenserIndex, FileName);
  3626. }
  3627. transferred = true;
  3628. }
  3629. }
  3630. return transferred;
  3631. }
  3632. BOOL WaitAllDispenserUpgradeCompleted(void)
  3633. {
  3634. BOOL completed = TRUE;
  3635. GetClockTime(&_DispenserUpgrade_time);
  3636. do
  3637. {
  3638. completed = TRUE;
  3639. for(int i = 0; i < GENERAL_GUN_QUANTITY; i++)
  3640. {
  3641. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.FirmwareUpdateRequest ||
  3642. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.FirmwareUpdateConfirm)
  3643. {
  3644. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.FirmwareUpdateCompleted)
  3645. {
  3646. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.FirmwareUpdateRequest = false;
  3647. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.FirmwareUpdateConfirm = false;
  3648. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.FirmwareUpdateCompleted = false;
  3649. LOG_INFO("Dispenser %d Upgrade Success", i + 1);
  3650. }
  3651. else
  3652. {
  3653. completed = FALSE;
  3654. }
  3655. }
  3656. }
  3657. if(GetTimeoutValue(_DispenserUpgrade_time) / uSEC_VAL >= DISPENSER_UPGRADE_TIME)
  3658. {
  3659. LOG_INFO("Wait Upgrade Timeout");
  3660. completed = FALSE;
  3661. break;
  3662. }
  3663. if(completed == FALSE)
  3664. {
  3665. sleep(1);
  3666. }
  3667. }while(!completed);
  3668. return completed;
  3669. }
  3670. void UpgradePrepare(void)
  3671. {
  3672. int count = 0;
  3673. SetAcContactor(OFF);
  3674. if(ShmChargerInfo->Control.CabinetRole == _CROLE_MASTER)
  3675. {
  3676. for(int i = 0; i < MAX_SLAVE_CABINET_QUANTITY; i++)
  3677. {
  3678. if(ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Idle ||
  3679. ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Alarm ||
  3680. ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Charging)
  3681. {
  3682. count++;
  3683. }
  3684. }
  3685. }
  3686. if(count > 0)
  3687. {
  3688. sleep(3);
  3689. }
  3690. else
  3691. {
  3692. sleep(1);
  3693. }
  3694. }
  3695. void TriggerPCabinetUpgrade(unsigned char index, char *FileName)
  3696. {
  3697. memset(ShmChargerInfo->ParallelCabinet.PCabinet[index].FwFileName, 0x00, 128);
  3698. memcpy(ShmChargerInfo->ParallelCabinet.PCabinet[index].FwFileName, FileName, strlen(FileName));
  3699. ShmChargerInfo->ParallelCabinet.PCabinet[index].UpdateRequest = YES;
  3700. LOG_INFO("Trigger PCabinet %d to update image [%s]", index + 1, FileName);
  3701. }
  3702. BOOL PutImageToAllParallelCabinet(char *SourcePath, char *FileName)
  3703. {
  3704. int isPass = FAIL;
  3705. BOOL transferred = FALSE;
  3706. for(int i = 0; i < MAX_SLAVE_CABINET_QUANTITY; i++)
  3707. {
  3708. if(ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Idle ||
  3709. ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Alarm ||
  3710. ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Charging)
  3711. {
  3712. int channel = ShmChargerInfo->ParallelCabinet.PCabinet[i].SocketChannel;
  3713. if(ShmChargerInfo->CabinetConnInfo[channel].Status == _SCONN_MATCHED &&
  3714. ShmChargerInfo->ParallelCabinet.PCUpdateState[i] == Not_Update)
  3715. {
  3716. char PCabinetIpAddress[16];
  3717. memset((char*)PCabinetIpAddress, 0x00, 16);
  3718. sprintf((char*)PCabinetIpAddress, "%d.%d.%d.%d",
  3719. ((ShmChargerInfo->CabinetConnInfo[channel].IpAddress >> 0) & 0xFF),
  3720. ((ShmChargerInfo->CabinetConnInfo[channel].IpAddress >> 8) & 0xFF),
  3721. ((ShmChargerInfo->CabinetConnInfo[channel].IpAddress >> 16) & 0xFF),
  3722. ((ShmChargerInfo->CabinetConnInfo[channel].IpAddress >> 24) & 0xFF));
  3723. isPass = TransferImageViaFTP(PCabinetIpAddress, SourcePath);
  3724. if(isPass == PASS)
  3725. {
  3726. TriggerPCabinetUpgrade(i, FileName);
  3727. }
  3728. transferred = true;
  3729. }
  3730. }
  3731. }
  3732. return transferred;
  3733. }
  3734. BOOL WaitAllPCabinetStartUpgrade(void)
  3735. {
  3736. BOOL isStart = true;
  3737. int count = 0;
  3738. struct timespec _waitStart;
  3739. GetClockTime(&_waitStart);
  3740. do
  3741. {
  3742. isStart = true;
  3743. count = 0;
  3744. for(int i = 0; i < MAX_SLAVE_CABINET_QUANTITY; i++)
  3745. {
  3746. if(ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Idle ||
  3747. ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Alarm ||
  3748. ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Charging)
  3749. {
  3750. count++;
  3751. if(ShmChargerInfo->ParallelCabinet.PCUpdateState[i] != Updating)
  3752. {
  3753. isStart = false;
  3754. }
  3755. }
  3756. }
  3757. if((GetTimeoutValue(_waitStart) / uSEC_VAL) >= START_UPGRADE_TIME)
  3758. {
  3759. isStart = false;
  3760. break;
  3761. }
  3762. usleep(10000);
  3763. }while(!isStart);
  3764. if(isStart && count > 0)
  3765. {
  3766. LOG_INFO("Total %d PCabinet upgrade start...", count);
  3767. }
  3768. else
  3769. {
  3770. if(count > 0)
  3771. {
  3772. LOG_INFO("Wait PCabinet upgrade timeout");
  3773. }
  3774. else
  3775. {
  3776. LOG_INFO("No PCabinet need to upgrade");
  3777. }
  3778. }
  3779. return isStart;
  3780. }
  3781. BOOL WaitAllPCabinetUpgradeCompleted(void)
  3782. {
  3783. BOOL completed = true;
  3784. int count = 0;
  3785. struct timespec _waitCompleted;
  3786. GetClockTime(&_waitCompleted);
  3787. do
  3788. {
  3789. completed = true;
  3790. count = 0;
  3791. for(int i = 0; i < MAX_SLAVE_CABINET_QUANTITY; i++)
  3792. {
  3793. if(ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Idle ||
  3794. ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Alarm ||
  3795. ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Charging)
  3796. {
  3797. count++;
  3798. if(ShmChargerInfo->ParallelCabinet.PCUpdateState[i] != Updated)
  3799. {
  3800. completed = false;
  3801. }
  3802. }
  3803. }
  3804. if((GetTimeoutValue(_waitCompleted) / uSEC_VAL) >= PCABINET_UPGRADE_TIME)
  3805. {
  3806. completed = false;
  3807. break;
  3808. }
  3809. usleep(10000);
  3810. }while(!completed);
  3811. if(completed && count > 0)
  3812. {
  3813. LOG_INFO("Total %d PCabinet upgrade completed!", count);
  3814. }
  3815. else
  3816. {
  3817. if(count > 0)
  3818. {
  3819. LOG_INFO("Wait PCabinet upgrade completed timeout");
  3820. }
  3821. else
  3822. {
  3823. LOG_INFO("Need not to wait PCabinet completed");
  3824. }
  3825. }
  3826. return completed;
  3827. }
  3828. BOOL WaitMCabinetUpgradeCompleted(void)
  3829. {
  3830. BOOL completed = true;
  3831. struct timespec _waitCompleted;
  3832. GetClockTime(&_waitCompleted);
  3833. do
  3834. {
  3835. completed = false;
  3836. if(ShmChargerInfo->SCabinetControl.NeedUpgrade == _R_NoUpgrade)
  3837. {
  3838. completed = true;
  3839. }
  3840. if(ShmChargerInfo->SCabinetControl.SCabinetStatus != _DeviceStatus_Idle &&
  3841. ShmChargerInfo->SCabinetControl.SCabinetStatus != _DeviceStatus_Alarm &&
  3842. ShmChargerInfo->SCabinetControl.SCabinetStatus != _DeviceStatus_Charging)
  3843. {
  3844. completed = false;
  3845. break;
  3846. }
  3847. if((GetTimeoutValue(_waitCompleted) / uSEC_VAL) >= MCABINET_UPGRADE_TIME)
  3848. {
  3849. completed = false;
  3850. break;
  3851. }
  3852. usleep(10000);
  3853. }while(!completed);
  3854. if(completed)
  3855. {
  3856. LOG_INFO("MCabinet upgrade completed!");
  3857. }
  3858. else
  3859. {
  3860. LOG_INFO("Wait MCabinet upgrade timeout or disconnected...");
  3861. }
  3862. return completed;
  3863. }
  3864. bool IsModelNameMatch(char *model)
  3865. {
  3866. if(ShmSysConfigAndInfo->SysConfig.ModelName[0] == model[0] &&
  3867. ShmSysConfigAndInfo->SysConfig.ModelName[1] == model[1] &&
  3868. ShmSysConfigAndInfo->SysConfig.ModelName[7] == model[7] &&
  3869. ShmSysConfigAndInfo->SysConfig.ModelName[8] == model[8] &&
  3870. ShmSysConfigAndInfo->SysConfig.ModelName[9] == model[9] &&
  3871. ShmSysConfigAndInfo->SysConfig.ModelName[11] == model[11] &&
  3872. ShmSysConfigAndInfo->SysConfig.ModelName[12] == model[12] &&
  3873. ShmSysConfigAndInfo->SysConfig.ModelName[13] == model[13])
  3874. {
  3875. return true;
  3876. }
  3877. return false;
  3878. }
  3879. char CheckUpdateProcess()
  3880. {
  3881. char model[32];
  3882. bool support = false;
  3883. bool OneImageOnly = false;
  3884. int isPass = true;
  3885. uint8_t retSucc = 0;
  3886. uint8_t retFail = 0;
  3887. byte target = 0;
  3888. char *new_str = NULL;
  3889. unsigned char *ptr = NULL;
  3890. int fd = 0;
  3891. int uartFd = 0;
  3892. unsigned int Type = 0;
  3893. long int MaxLen = 48 * 1024 * 1024, ImageLen = 0;
  3894. DIR *d;
  3895. struct dirent *dir;
  3896. char cmdBuf[128];
  3897. d = opendir("/mnt/");
  3898. if(d)
  3899. {
  3900. while((dir = readdir(d)) != NULL && !OneImageOnly)
  3901. {
  3902. if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0) {
  3903. continue;
  3904. }
  3905. new_str = calloc(strlen("/mnt/") + strlen(dir->d_name) + 1, sizeof(char));
  3906. strcat(new_str, "/mnt/");
  3907. strcat(new_str, dir->d_name);
  3908. fd = open(new_str, O_RDONLY);
  3909. if(fd < 0)
  3910. {
  3911. close(fd);
  3912. free(new_str);
  3913. continue;
  3914. }
  3915. LOG_INFO("%s\n", new_str);
  3916. ptr = calloc(MaxLen, sizeof(char)); //-48 is take out the header
  3917. memset(ptr, 0xFF, MaxLen); //-48 is take out the header
  3918. //get the image length
  3919. ImageLen = read(fd, ptr, MaxLen);
  3920. if (ImageLen > 20)
  3921. {
  3922. support = false;
  3923. memcpy(model, ptr, 16);
  3924. LOG_INFO("Model: %s", model);
  3925. Type = (((unsigned int)ptr[16]) << 24 | ((unsigned int)ptr[17]) << 16 | ((unsigned int)ptr[18]) << 8 | ((unsigned int)ptr[19]));
  3926. LOG_INFO("Typed...%x", Type);
  3927. //if(strcmp(model, (char *)ShmSysConfigAndInfo->SysConfig.ModelName) == EQUAL)
  3928. if(IsModelNameMatch(model))
  3929. {
  3930. if(ShmChargerInfo->Control.CabinetRole == _CROLE_MASTER)
  3931. {
  3932. PutImageToAllParallelCabinet(new_str, dir->d_name);
  3933. WaitAllPCabinetStartUpgrade();
  3934. }
  3935. if(ShmChargerInfo->Control.CabinetRole == _CROLE_SLAVE && ShmChargerInfo->SCabinetControl.NeedUpgrade)
  3936. {
  3937. ShmChargerInfo->SCabinetControl.UpgradeState = Updating;
  3938. sleep(1);
  3939. }
  3940. switch (Type)
  3941. {
  3942. case 0x10000001:
  3943. case 0x10000002:
  3944. case 0x10000003:
  3945. case 0x10000004:
  3946. case 0x10000005:
  3947. support = true;
  3948. _UpgradeNeedReboot = TRUE;
  3949. isPass = Upgrade_Flash(Type, new_str, (char *)ShmSysConfigAndInfo->SysConfig.ModelName);
  3950. break;
  3951. case 0x10000006: // primary mcu
  3952. case 0x1000000D: // relay board
  3953. case 0x1000000E: // fan board
  3954. case 0x10000014: // led board
  3955. support = true;
  3956. target = 0x00;
  3957. if (Type == 0x10000006)
  3958. {
  3959. target = UPGRADE_PRI;
  3960. }
  3961. else if (Type == 0x1000000D)
  3962. {
  3963. target = UPGRADE_RB;
  3964. }
  3965. else if (Type == 0x1000000E)
  3966. {
  3967. target = UPGRADE_FAN;
  3968. }
  3969. else if (Type == 0x10000014)
  3970. {
  3971. target = UPGRADE_LED;
  3972. }
  3973. uartFd = InitComPort(target);
  3974. if(target == UPGRADE_RB)
  3975. {
  3976. isPass = Upgrade_UART(uartFd, Type, UPGRADE_DORC1, new_str, (char *)ShmSysConfigAndInfo->SysConfig.ModelName);
  3977. if(isPass == PASS)
  3978. {
  3979. retSucc++;
  3980. }
  3981. else
  3982. {
  3983. retFail++;
  3984. }
  3985. LOG_INFO("Upgrade %s", isPass == PASS ? "Success" : "Fail");
  3986. sleep(3);
  3987. isPass = Upgrade_UART(uartFd, Type, UPGRADE_DORC2, new_str, (char *)ShmSysConfigAndInfo->SysConfig.ModelName);
  3988. }
  3989. else
  3990. {
  3991. isPass = Upgrade_UART(uartFd, Type, target, new_str, (char *)ShmSysConfigAndInfo->SysConfig.ModelName);
  3992. }
  3993. close(uartFd);
  3994. break;
  3995. }
  3996. if(support)
  3997. {
  3998. if(isPass == PASS)
  3999. {
  4000. retSucc++;
  4001. }
  4002. else
  4003. {
  4004. retFail++;
  4005. }
  4006. LOG_INFO("Upgrade %s", isPass == PASS ? "Success" : "Fail");
  4007. }
  4008. if(ShmChargerInfo->Control.CabinetRole == _CROLE_MASTER)
  4009. {
  4010. LOG_INFO("MCabinet upgrade completed");
  4011. WaitAllPCabinetUpgradeCompleted();
  4012. }
  4013. if(ShmChargerInfo->Control.CabinetRole == _CROLE_SLAVE && ShmChargerInfo->SCabinetControl.UpgradeState == Updating)
  4014. {
  4015. ShmChargerInfo->SCabinetControl.UpgradeState = Updated;
  4016. LOG_INFO("SCabinet upgrade completed");
  4017. WaitMCabinetUpgradeCompleted();
  4018. }
  4019. }
  4020. else
  4021. {
  4022. if(model[0] == 'D' && (model[1] == 'D' || model[1] == 'X'))
  4023. {
  4024. OneImageOnly = true;
  4025. _UpgradeNeedReboot = TRUE;
  4026. LOG_INFO("Start Put Image To All Dispenser");
  4027. PutImageToAllDispenser(new_str, dir->d_name);
  4028. WaitAllDispenserUpgradeCompleted();
  4029. LOG_INFO("All Dispenser Upgrade Completed");
  4030. }
  4031. }
  4032. }
  4033. sprintf(cmdBuf, "rm -f %s", new_str);
  4034. system(cmdBuf);
  4035. close(fd);
  4036. free(new_str);
  4037. free(ptr);
  4038. }
  4039. }
  4040. free(dir);
  4041. closedir(d);
  4042. if(retFail != 0)
  4043. {
  4044. return FAIL;
  4045. }
  4046. return PASS;
  4047. }
  4048. /*
  4049. void CreateRfidFork()
  4050. {
  4051. pid_t rfidRecPid;
  4052. rfidRecPid = fork();
  4053. if (rfidRecPid == 0)
  4054. {
  4055. while(true)
  4056. {
  4057. // 刷卡判斷
  4058. RFID rfid;
  4059. if (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_NO_CHARGING ||
  4060. !ShmSysConfigAndInfo->SysConfig.isRFID)
  4061. {}
  4062. else if(getRequestCardSN(rfidFd, 0, &rfid))
  4063. {
  4064. PRINTF_FUNC("Get Card..-%s- \n", ShmSysConfigAndInfo->SysConfig.UserId);
  4065. if (strlen((char *)ShmSysConfigAndInfo->SysConfig.UserId) == 0)
  4066. {
  4067. if (ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian == RFID_ENDIAN_LITTLE)
  4068. {
  4069. switch (rfid.snType)
  4070. {
  4071. case RFID_SN_TYPE_6BYTE:
  4072. sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
  4073. "%02X%02X%02X%02X%02X%02X",
  4074. rfid.currentCard[0], rfid.currentCard[1],
  4075. rfid.currentCard[2], rfid.currentCard[3],
  4076. rfid.currentCard[4], rfid.currentCard[5]);
  4077. break;
  4078. case RFID_SN_TYPE_7BYTE:
  4079. sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
  4080. "%02X%02X%02X%02X%02X%02X%02X",
  4081. rfid.currentCard[0], rfid.currentCard[1],
  4082. rfid.currentCard[2], rfid.currentCard[3],
  4083. rfid.currentCard[4], rfid.currentCard[5],
  4084. rfid.currentCard[6]);
  4085. break;
  4086. case RFID_SN_TYPE_10BYTE:
  4087. sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
  4088. "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
  4089. rfid.currentCard[0], rfid.currentCard[1],
  4090. rfid.currentCard[2], rfid.currentCard[3],
  4091. rfid.currentCard[4], rfid.currentCard[5],
  4092. rfid.currentCard[6], rfid.currentCard[7],
  4093. rfid.currentCard[8], rfid.currentCard[9]);
  4094. break;
  4095. case RFID_SN_TYPE_4BYTE:
  4096. sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
  4097. "%02X%02X%02X%02X",
  4098. rfid.currentCard[0], rfid.currentCard[1],
  4099. rfid.currentCard[2], rfid.currentCard[3]);
  4100. break;
  4101. }
  4102. }
  4103. else if (ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian == RFID_ENDIAN_BIG)
  4104. {
  4105. switch (rfid.snType)
  4106. {
  4107. case RFID_SN_TYPE_6BYTE:
  4108. sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
  4109. "%02X%02X%02X%02X%02X%02X",
  4110. rfid.currentCard[5], rfid.currentCard[4],
  4111. rfid.currentCard[3], rfid.currentCard[2],
  4112. rfid.currentCard[1], rfid.currentCard[0]);
  4113. break;
  4114. case RFID_SN_TYPE_7BYTE:
  4115. sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
  4116. "%02X%02X%02X%02X%02X%02X%02X",
  4117. rfid.currentCard[6], rfid.currentCard[5],
  4118. rfid.currentCard[4], rfid.currentCard[3],
  4119. rfid.currentCard[2], rfid.currentCard[1],
  4120. rfid.currentCard[0]);
  4121. break;
  4122. case RFID_SN_TYPE_10BYTE:
  4123. sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
  4124. "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
  4125. rfid.currentCard[9], rfid.currentCard[8],
  4126. rfid.currentCard[7], rfid.currentCard[6],
  4127. rfid.currentCard[5], rfid.currentCard[4],
  4128. rfid.currentCard[3], rfid.currentCard[2],
  4129. rfid.currentCard[1], rfid.currentCard[0]);
  4130. break;
  4131. case RFID_SN_TYPE_4BYTE:
  4132. sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
  4133. "%02X%02X%02X%02X",
  4134. rfid.currentCard[3], rfid.currentCard[2],
  4135. rfid.currentCard[1], rfid.currentCard[0]);
  4136. break;
  4137. }
  4138. }
  4139. LOG_INFOUNC("card number = %s\n", ShmSysConfigAndInfo->SysConfig.UserId);
  4140. }
  4141. }
  4142. sleep(1);
  4143. }
  4144. }
  4145. }
  4146. */
  4147. #if 0
  4148. void StartSystemTimeoutDet(unsigned char flag)
  4149. {
  4150. if (ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag != flag)
  4151. {
  4152. gettimeofday(&ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer, NULL);
  4153. }
  4154. ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag = flag;
  4155. }
  4156. void StopSystemTimeoutDet()
  4157. {
  4158. gettimeofday(&ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer, NULL);
  4159. ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag = Timeout_None;
  4160. }
  4161. void StartGunInfoTimeoutDet(unsigned char gunIndex, unsigned char flag)
  4162. {
  4163. if (gunIndex < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount)
  4164. {
  4165. if (chargingInfo[gunIndex]->TimeoutFlag != flag)
  4166. {
  4167. gettimeofday(&chargingInfo[gunIndex]->TimeoutTimer, NULL);
  4168. }
  4169. chargingInfo[gunIndex]->TimeoutFlag = flag;
  4170. }
  4171. }
  4172. void StopGunInfoTimeoutDet(unsigned char gunIndex)
  4173. {
  4174. if (gunIndex < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount)
  4175. {
  4176. chargingInfo[gunIndex]->TimeoutFlag = Timeout_None;
  4177. }
  4178. }
  4179. #endif
  4180. void TriggerDispenserConnectionTimeoutSetting(void)
  4181. {
  4182. BOOL trigger = FALSE;
  4183. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  4184. {
  4185. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ConnectorQuantity > 0)
  4186. {
  4187. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.ConnectorTimeoutConfigRequest = 1;
  4188. trigger = TRUE;
  4189. }
  4190. }
  4191. if(trigger)
  4192. {
  4193. LOG_INFO("********** Trigger Dispenser Connector Timeout Value: %d **********", ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectorTimeout);
  4194. }
  4195. }
  4196. void CheckConnectionTimeout(void)
  4197. {
  4198. if(system("pidof -s OcppBackend > /dev/null") != 0)
  4199. {
  4200. _connectionTimeout = CONN_PLUG_TIME_OUT;
  4201. }
  4202. else
  4203. {
  4204. if(ShmOCPP16Data->OcppConnStatus &&
  4205. strcmp((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData,"") != 0)
  4206. {
  4207. _connectionTimeout = atoi((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData);
  4208. if(_connectionTimeout <= 0)
  4209. {
  4210. _connectionTimeout = CONN_PLUG_TIME_OUT;
  4211. }
  4212. }
  4213. else
  4214. {
  4215. _connectionTimeout = CONN_PLUG_TIME_OUT;
  4216. }
  4217. }
  4218. if(_connectionTimeout != ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectorTimeout)
  4219. {
  4220. ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectorTimeout = _connectionTimeout;
  4221. TriggerDispenserConnectionTimeoutSetting();
  4222. }
  4223. }
  4224. void CreateTimeoutFork()
  4225. {
  4226. pid_t timeoutPid;
  4227. timeoutPid = fork();
  4228. if (timeoutPid == 0)
  4229. {
  4230. GetClockTime(&_cmdSubPriority_time);
  4231. CheckConnectionTimeout();
  4232. LOG_INFO("Timeout Fork PID = %d", getpid());
  4233. while(true)
  4234. {
  4235. if ((GetTimeoutValue(_cmdSubPriority_time) / 1000) > 5000)
  4236. {
  4237. CheckConnectionTimeout();
  4238. GetClockTime(&_cmdSubPriority_time);
  4239. }
  4240. //printf("Timeout ***********SystemTimeoutFlag = %d, ********\n", ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag);
  4241. // 系統
  4242. // switch(ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag)
  4243. // {
  4244. // case Timeout_SelftestChk:
  4245. // if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) / uSEC_VAL >= SELFTEST_TIMEOUT)
  4246. // {
  4247. // _SelfTestTimeout();
  4248. // StopSystemTimeoutDet();
  4249. // }
  4250. // break;
  4251. // case Timeout_Authorizing:
  4252. // if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) / uSEC_VAL >= AUTHORIZE_TIMEOUT)
  4253. // {
  4254. // _AuthorizedTimeout();
  4255. // StopSystemTimeoutDet();
  4256. // }
  4257. // break;
  4258. // case Timeout_VerifyFail:
  4259. // if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) / uSEC_VAL >= AUTHORIZE_FAIL_TIMEOUT)
  4260. // {
  4261. // _AutoReturnTimeout();
  4262. // StopSystemTimeoutDet();
  4263. // }
  4264. // break;
  4265. // case Timeout_VerifyComp:
  4266. // if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) / uSEC_VAL >= AUTHORIZE_COMP_TIMEOUT)
  4267. // {
  4268. // _AutoReturnTimeout();
  4269. // StopSystemTimeoutDet();
  4270. // }
  4271. // break;
  4272. // case Timeout_WaitPlug:
  4273. // if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) / uSEC_VAL >= _connectionTimeout)
  4274. // {
  4275. // _DetectPlugInTimeout();
  4276. // StopSystemTimeoutDet();
  4277. // }
  4278. // break;
  4279. // case Timeout_ReturnToChargingGunDet:
  4280. // {
  4281. // if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) / uSEC_VAL >= RETURN_TO_CHARGING_PAGE)
  4282. // {
  4283. // DisplayChargingInfo();
  4284. // StopSystemTimeoutDet();
  4285. // }
  4286. // }
  4287. // break;
  4288. // case Timeout_AuthorizingForStop:
  4289. // {
  4290. // if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) / uSEC_VAL >= AUTHORIZE_STOP_TIMEOUT)
  4291. // {
  4292. // strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
  4293. // ClearAuthorizedFlag();
  4294. // StopSystemTimeoutDet();
  4295. // }
  4296. // }
  4297. // break;
  4298. // }
  4299. // 各槍
  4300. // for (byte gun_index = 0; gun_index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun_index++)
  4301. // {
  4302. //printf("Timeout ***********TimeoutFlag = %d, ********\n", chargingInfo[gun_index]->TimeoutFlag);
  4303. // switch(chargingInfo[gun_index]->TimeoutFlag)
  4304. // {
  4305. // case Timeout_Preparing:
  4306. // {
  4307. // if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) / uSEC_VAL >= GUN_PREPARE_TIMEOUT)
  4308. // {
  4309. // _PrepareTimeout(gun_index);
  4310. // StopGunInfoTimeoutDet(gun_index);
  4311. // }
  4312. // }
  4313. // break;
  4314. // case Timeout_EvChargingDet:
  4315. // {
  4316. // if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) / uSEC_VAL >= GUN_EV_WAIT_TIMEOUT)
  4317. // {
  4318. // _DetectEvChargingEnableTimeout(gun_index);
  4319. // StopGunInfoTimeoutDet(gun_index);
  4320. // }
  4321. // }
  4322. // break;
  4323. // case Timeout_EvseChargingDet:
  4324. // {
  4325. // if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) / uSEC_VAL >= GUN_EVSE_WAIT_TIMEOUT)
  4326. // {
  4327. // _DetectEvseChargingEnableTimeout(gun_index);
  4328. // StopGunInfoTimeoutDet(gun_index);
  4329. // }
  4330. // }
  4331. // break;
  4332. // case Timeout_EvseCompleteDet:
  4333. // {
  4334. // if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) / uSEC_VAL >= GUN_COMP_WAIT_TIMEOUT)
  4335. // {
  4336. // StopGunInfoTimeoutDet(gun_index);
  4337. // }
  4338. // }
  4339. // break;
  4340. // case Timeout_ForCcsPrechargeDet:
  4341. // {
  4342. // if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) / uSEC_VAL >= GUN_PRECHARGING_TIMEOUT)
  4343. // {
  4344. // _CcsPrechargeTimeout(gun_index);
  4345. // StopGunInfoTimeoutDet(gun_index);
  4346. // }
  4347. // }
  4348. // break;
  4349. // }
  4350. // }
  4351. sleep(1);
  4352. }
  4353. }
  4354. }
  4355. void CheckFactoryConfigFunction(void)
  4356. {
  4357. if(ShmSysConfigAndInfo->SysInfo.FactoryConfiguration)
  4358. {
  4359. char Buf[256];
  4360. sprintf(Buf, "cd /root;./FactoryConfig -m");
  4361. system(Buf);
  4362. system("rm -f /Storage/OCPP/OCPPConfiguration");
  4363. system("sync");
  4364. sleep(5);
  4365. system("reboot -f");
  4366. sleep(5);
  4367. system("reboot -f");
  4368. }
  4369. }
  4370. void CheckFwUpdateFunction(void)
  4371. {
  4372. char UpdateResult = PASS;
  4373. if (ShmSysConfigAndInfo->SysInfo.FirmwareUpdate == YES)
  4374. {
  4375. ShmChargerInfo->Control.SysCtrl.bits.NeedSelfTest = false;
  4376. UpgradePrepare();
  4377. ShmChargerInfo->Control.PrimaryCtrl.bits.Paused = true;
  4378. ShmChargerInfo->Control.RelayCtrl.bits.Paused = true;
  4379. ShmChargerInfo->Control.FanCtrl.bits.Paused = true;
  4380. LOG_INFO("ftp : update start.");
  4381. TryCloseWatchdog();
  4382. //KillTask();
  4383. ChangeLcmByIndex(_LCM_FIX);
  4384. system("killall Module_PrimaryComm");
  4385. system("killall Module_InternalComm");
  4386. UpdateResult = CheckUpdateProcess();
  4387. if (UpdateResult == PASS)
  4388. {
  4389. LOG_INFO("ftp : update complete.");
  4390. }
  4391. else
  4392. {
  4393. LOG_INFO("ftp : update fail.");
  4394. }
  4395. ShmSysConfigAndInfo->SysInfo.FirmwareUpdate = NO;
  4396. sleep(5);
  4397. if(_UpgradeNeedReboot)
  4398. {
  4399. system("reboot -f");
  4400. }
  4401. else
  4402. {
  4403. KillAllTask();
  4404. system("/usr/bin/run_evse_restart.sh");
  4405. }
  4406. }
  4407. else if(ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq == YES)
  4408. {
  4409. ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq = NO;
  4410. ShmChargerInfo->Control.SysCtrl.bits.NeedSelfTest = false;
  4411. UpgradePrepare();
  4412. ShmChargerInfo->Control.PrimaryCtrl.bits.Paused = true;
  4413. ShmChargerInfo->Control.RelayCtrl.bits.Paused = true;
  4414. ShmChargerInfo->Control.FanCtrl.bits.Paused = true;
  4415. if (strcmp((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Downloaded") == EQUAL)
  4416. {
  4417. LOG_INFO("Backend : update start.");
  4418. TryCloseWatchdog();
  4419. strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "");
  4420. strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installing");
  4421. ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
  4422. //KillTask();
  4423. system("killall Module_PrimaryComm");
  4424. system("killall Module_InternalComm");
  4425. for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++)
  4426. {
  4427. setChargerMode(_index, MODE_UPDATE);
  4428. }
  4429. UpdateResult = CheckUpdateProcess();
  4430. if (UpdateResult == PASS)
  4431. {
  4432. LOG_INFO("Backend : update complete.");
  4433. strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installed");
  4434. }
  4435. else
  4436. {
  4437. LOG_INFO("Backend : update fail.");
  4438. strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "InstallationFailed");
  4439. }
  4440. //strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installed");
  4441. sleep(1);
  4442. ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
  4443. sleep(5);
  4444. if(_UpgradeNeedReboot)
  4445. {
  4446. system("reboot -f");
  4447. }
  4448. else
  4449. {
  4450. KillAllTask();
  4451. system("/usr/bin/run_evse_restart.sh");
  4452. }
  4453. }
  4454. }
  4455. }
  4456. void ExecuteWriteWiringInfo(void)
  4457. {
  4458. struct SysConfigData config;
  4459. memcpy(&config, &ShmSysConfigAndInfo->SysConfig, sizeof(struct SysConfigData));
  4460. config.SwitchDebugFlag = NO;
  4461. strcpy((char *) config.UserId, "");
  4462. int result = StoreUsrConfigData(&config);
  4463. if(result != 1)
  4464. {
  4465. LOG_INFO("Store User Config NG");
  4466. }
  4467. else
  4468. {
  4469. LOG_INFO("Store User Config OK");
  4470. }
  4471. }
  4472. struct timespec _WiringInfo_time;
  4473. int CheckWiringInfoUpdate(void)
  4474. {
  4475. if(ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.FlashConfigChanged)
  4476. {
  4477. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.FlashConfigChanged = false;
  4478. LOG_INFO("Flash Config Changed");
  4479. GetClockTime(&_WiringInfo_time);
  4480. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.EnableWriteFlash = true;
  4481. }
  4482. if(ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.EnableWriteFlash)
  4483. {
  4484. // 30s for reboot request timeout
  4485. if((GetTimeoutValue(_WiringInfo_time) / uSEC_VAL) >= WIRING_INFO_DELAY ||
  4486. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.CleanWiringInfo)
  4487. {
  4488. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.EnableWriteFlash = false;
  4489. LOG_INFO("Start Write To Flash");
  4490. pid_t writePid = fork();
  4491. if(writePid == 0)
  4492. {
  4493. ExecuteWriteWiringInfo();
  4494. if(ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.CleanWiringInfo)
  4495. {
  4496. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.CleanWiringInfo = false;
  4497. ShmChargerInfo->Control.SysCtrl.bits.NeedSoftReset = true;
  4498. LOG_INFO("Clean Wiring Info And Need Soft Reset");
  4499. }
  4500. return NO;
  4501. }
  4502. LOG_INFO("Clean Write Flahs Flag");
  4503. }
  4504. }
  4505. return YES;
  4506. }
  4507. void CheckSoftHardReset(void)
  4508. {
  4509. if(ShmChargerInfo->Control.SysCtrl.bits.NeedSoftReset)
  4510. {
  4511. ShmChargerInfo->Control.SysCtrl.bits.NeedSoftReset = false;
  4512. LOG_INFO("********** Need Soft Reset **********");
  4513. sleep(5);
  4514. system("killall OcppBackend &");
  4515. KillAllTask();
  4516. TryCloseWatchdog();
  4517. system("/usr/bin/run_evse_restart.sh");
  4518. }
  4519. if(ShmChargerInfo->Control.SysCtrl.bits.NeedHardReset)
  4520. {
  4521. ShmChargerInfo->Control.SysCtrl.bits.NeedHardReset = false;
  4522. LOG_INFO("********** Need Hard Reset **********");
  4523. sleep(5);
  4524. system("reboot -f");
  4525. }
  4526. }
  4527. //===============================================
  4528. // Check reservation date is expired
  4529. //===============================================
  4530. int isReservationExpired(unsigned char gun_index)
  4531. {
  4532. int result = NO;
  4533. struct tm expiredDate;
  4534. struct timeb expiredTime;
  4535. if (sscanf((char*) ShmOCPP16Data->ReserveNow[gun_index].ExpiryDate,
  4536. "%4d-%2d-%2dT%2d:%2d:%2d", &expiredDate.tm_year,
  4537. &expiredDate.tm_mon, &expiredDate.tm_mday, &expiredDate.tm_hour,
  4538. &expiredDate.tm_min, &expiredDate.tm_sec) == 6)
  4539. {
  4540. expiredDate.tm_year -= 1900;
  4541. expiredDate.tm_mon -= 1;
  4542. expiredTime.time = mktime(&expiredDate);
  4543. if (!CheckTimeOut(expiredTime))
  4544. {
  4545. result = YES;
  4546. }
  4547. }
  4548. return result;
  4549. }
  4550. struct timespec _Reboot_time;
  4551. void TriggerDispenserHardwareReboot(void)
  4552. {
  4553. BOOL trigger = FALSE;
  4554. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  4555. {
  4556. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ConnectorQuantity > 0)
  4557. {
  4558. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.HardwareRebootConfirm == 0 &&
  4559. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.HardwareRebootRequest == 0)
  4560. {
  4561. trigger = TRUE;
  4562. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.HardwareRebootRequest = 1;
  4563. }
  4564. }
  4565. }
  4566. if(trigger)
  4567. {
  4568. GetClockTime(&_Reboot_time);
  4569. LOG_INFO("********** Trigger Dispenser Hardware Reboot **********");
  4570. }
  4571. }
  4572. BOOL IsDispenserHardwareRebootResponsed(void)
  4573. {
  4574. BOOL response_ok = TRUE;
  4575. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  4576. {
  4577. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ConnectorQuantity > 0)
  4578. {
  4579. if(!ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.HardwareRebootConfirm)
  4580. {
  4581. response_ok = FALSE;
  4582. // 10s for reboot request timeout
  4583. if((GetTimeoutValue(_Reboot_time) / uSEC_VAL) >= REBOOT_TIMEOUT)
  4584. {
  4585. response_ok = TRUE;
  4586. LOG_INFO("Reboot request timeout");
  4587. }
  4588. }
  4589. }
  4590. }
  4591. return response_ok;
  4592. }
  4593. struct timespec _Reset_time;
  4594. void TriggerDispenserSoftwareReset(void)
  4595. {
  4596. BOOL trigger = FALSE;
  4597. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  4598. {
  4599. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ConnectorQuantity > 0)
  4600. {
  4601. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.SoftwareResetConfirm == 0 &&
  4602. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.SoftwareResetRequest == 0)
  4603. {
  4604. trigger = TRUE;
  4605. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.SoftwareResetRequest = 1;
  4606. }
  4607. }
  4608. }
  4609. if(trigger)
  4610. {
  4611. GetClockTime(&_Reset_time);
  4612. LOG_INFO("********** Trigger Dispenser Software Reset **********");
  4613. }
  4614. }
  4615. BOOL IsDispenserSoftwareResetResponsed(void)
  4616. {
  4617. BOOL response_ok = TRUE;
  4618. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  4619. {
  4620. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ConnectorQuantity > 0)
  4621. {
  4622. if(!ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.SoftwareResetConfirm)
  4623. {
  4624. response_ok = FALSE;
  4625. // 10s for reset request timeout
  4626. if((GetTimeoutValue(_Reset_time) / uSEC_VAL) >= RESET_TIMEOUT)
  4627. {
  4628. response_ok = TRUE;
  4629. LOG_INFO("Reset request timeout");
  4630. }
  4631. }
  4632. }
  4633. }
  4634. return response_ok;
  4635. }
  4636. // the unit of return value: 0.01 dollar
  4637. int TariffParsing(char *StringItem, char *TariffCode)
  4638. {
  4639. char *ptrSave, *ptrToken;
  4640. char strSource[128];
  4641. int fee = 0;
  4642. memcpy(strSource, StringItem, 128);
  4643. ptrToken = strtok_r(strSource, ";", &ptrSave);
  4644. while(ptrToken != NULL)
  4645. {
  4646. char *strTariff = strstr(ptrToken, TariffCode);
  4647. if(strTariff != NULL)
  4648. {
  4649. char *strFee = strstr(strTariff, "$");
  4650. if(strFee != NULL)
  4651. {
  4652. strFee++;
  4653. float fFee = atof(strFee);
  4654. fee = (int)(fFee * 100);
  4655. break;
  4656. }
  4657. }
  4658. ptrToken = strtok_r(NULL, ";", &ptrSave);
  4659. }
  4660. return fee;
  4661. }
  4662. void DefaultPriceHandler(char *StrDefaultPrice)
  4663. {
  4664. BOOL trigger = FALSE;
  4665. unsigned int ConnectionFee = 0, CurrentRate = 0, OccupancyFee = 0;
  4666. LOG_INFO("********** Default Price: %s", StrDefaultPrice);
  4667. ConnectionFee = TariffParsing(StrDefaultPrice, "Connection Fee");
  4668. LOG_INFO("********** Connection Fee: %d.%02d **********", (ConnectionFee / 100), (ConnectionFee % 100));
  4669. CurrentRate = TariffParsing(StrDefaultPrice, "Current Rate");
  4670. LOG_INFO("********** Current Rate: %d.%02d **********", (CurrentRate / 100), (CurrentRate % 100));
  4671. OccupancyFee = TariffParsing(StrDefaultPrice, "Occupancy Fee");
  4672. LOG_INFO("********** Occupancy Fee: %d.%02d **********", (OccupancyFee / 100), (OccupancyFee % 100));
  4673. ShmSysConfigAndInfo->SysInfo.DispenserInfo.DefaultPrice = CurrentRate;
  4674. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  4675. {
  4676. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ConnectorQuantity > 0)
  4677. {
  4678. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.DefaultPriceConfigRequest == 0)
  4679. {
  4680. trigger = TRUE;
  4681. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.DefaultPriceConfigRequest = 1;
  4682. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.CurrencyConfigRequest = 1;
  4683. }
  4684. }
  4685. }
  4686. if(trigger)
  4687. {
  4688. LOG_INFO("********** Trigger Dispenser Default Price **********");
  4689. }
  4690. }
  4691. void UserPriceHandler(char *UserId, char *UserPrice)
  4692. {
  4693. unsigned int ConnectionFee = 0, CurrentRate = 0, OccupancyFee = 0;
  4694. int AccountBalance = 0;
  4695. ConnectionFee = TariffParsing((char *)ShmOCPP16Data->Cost.SetUserPrice.price, "Connection Fee");
  4696. CurrentRate = TariffParsing((char *)ShmOCPP16Data->Cost.SetUserPrice.price, "Current Rate");
  4697. OccupancyFee = TariffParsing((char *)ShmOCPP16Data->Cost.SetUserPrice.price, "Occupancy Fee");
  4698. AccountBalance = TariffParsing((char *)ShmOCPP16Data->Cost.SetUserPrice.price, "Account Balance");
  4699. LOG_INFO("********** User Id: %s **********", ShmOCPP16Data->Cost.SetUserPrice.idToken);
  4700. LOG_INFO("********** User Price: %s", ShmOCPP16Data->Cost.SetUserPrice.price);
  4701. LOG_INFO("********** Connection Fee: %d.%02d **********", (ConnectionFee / 100), (ConnectionFee % 100));
  4702. LOG_INFO("********** Current Rate: %d.%02d **********", (CurrentRate / 100), (CurrentRate % 100));
  4703. LOG_INFO("********** Occupancy Fee: %d.%02d **********", (OccupancyFee / 100), (OccupancyFee % 100));
  4704. LOG_INFO("********** Account Balance: %d.%02d **********", (AccountBalance / 100), (AccountBalance % 100));
  4705. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  4706. {
  4707. if(strcmp((char *)ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].GeneralChargingData.StartUserId, UserId) == EQUAL)
  4708. {
  4709. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].UserPrice != CurrentRate ||
  4710. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].AccountBalance != AccountBalance)
  4711. {
  4712. LOG_INFO("********** Connector Id %d User Price %d.%02d, Account Balance %d.%02d **********",
  4713. (i + 1), (CurrentRate / 100), (CurrentRate % 100), (AccountBalance / 100), (AccountBalance % 100));
  4714. }
  4715. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].UserPrice = CurrentRate;
  4716. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].AccountBalance = AccountBalance;
  4717. if(chargingInfo[i]->SystemStatus == S_AUTHORIZING)
  4718. {
  4719. AnnounceAccountBalance(i, AccountBalance);
  4720. }
  4721. }
  4722. }
  4723. }
  4724. void RunningFinalCostHandler(void)
  4725. {
  4726. unsigned int ConnectionFee = 0, SessionFee = 0, OccupancyFee = 0, TotalCost = 0;
  4727. int AccountBalance = 0;
  4728. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  4729. {
  4730. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].GeneralChargingData.SystemStatus >= S_REASSIGN_CHECK &&
  4731. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].GeneralChargingData.SystemStatus <= S_ALARM)
  4732. {
  4733. if(strlen((char *)ShmOCPP16Data->Cost.RunningCost[i].description) > 0)
  4734. {
  4735. ConnectionFee = TariffParsing((char *)ShmOCPP16Data->Cost.RunningCost[i].description, "Connection Fee");
  4736. SessionFee = TariffParsing((char *)ShmOCPP16Data->Cost.RunningCost[i].description, "Session Fee");
  4737. OccupancyFee = TariffParsing((char *)ShmOCPP16Data->Cost.RunningCost[i].description, "Occupancy Fee");
  4738. TotalCost = TariffParsing((char *)ShmOCPP16Data->Cost.RunningCost[i].description, "Total Cost");
  4739. AccountBalance = TariffParsing((char *)ShmOCPP16Data->Cost.RunningCost[i].description, "Account Balance");
  4740. LOG_INFO("********** Connector Id: %d Running Cost **********", (i + 1));
  4741. LOG_INFO("********** Connection Fee: %d.%02d **********", (ConnectionFee / 100), (ConnectionFee % 100));
  4742. LOG_INFO("********** Session Fee: %d.%02d **********", (SessionFee / 100), (SessionFee % 100));
  4743. LOG_INFO("********** Occupancy Fee: %d.%02d **********", (OccupancyFee / 100), (OccupancyFee % 100));
  4744. LOG_INFO("********** Total Cost: %d.%02d **********", (TotalCost / 100), (TotalCost % 100));
  4745. LOG_INFO("********** Account Balance: %d.%02d **********", (AccountBalance / 100), (AccountBalance % 100));
  4746. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].TotalCost != TotalCost ||
  4747. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].AccountBalance != AccountBalance)
  4748. {
  4749. LOG_INFO("********** Connector Id %d Total Cost %d.%02d, Account Balance %d.%02d **********",
  4750. (i + 1), (TotalCost / 100), (TotalCost % 100), (AccountBalance / 100), (AccountBalance % 100));
  4751. }
  4752. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].TotalCost = TotalCost;
  4753. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].AccountBalance = AccountBalance;
  4754. memset(&ShmOCPP16Data->Cost.RunningCost[i], 0x00, sizeof(struct StrcutRunningCost));
  4755. }
  4756. if(strlen((char *)ShmOCPP16Data->Cost.FinalCost[i].description) > 0)
  4757. {
  4758. ConnectionFee = TariffParsing((char *)ShmOCPP16Data->Cost.FinalCost[i].description, "Connection Fee");
  4759. SessionFee = TariffParsing((char *)ShmOCPP16Data->Cost.FinalCost[i].description, "Session Fee");
  4760. OccupancyFee = TariffParsing((char *)ShmOCPP16Data->Cost.FinalCost[i].description, "Occupancy Fee");
  4761. TotalCost = TariffParsing((char *)ShmOCPP16Data->Cost.FinalCost[i].description, "Total Cost");
  4762. AccountBalance = TariffParsing((char *)ShmOCPP16Data->Cost.FinalCost[i].description, "Account Balance");
  4763. LOG_INFO("********** Connector Id: %d Final Cost **********", (i + 1));
  4764. LOG_INFO("********** Connection Fee: %d.%02d **********", (ConnectionFee / 100), (ConnectionFee % 100));
  4765. LOG_INFO("********** Session Fee: %d.%02d **********", (SessionFee / 100), (SessionFee % 100));
  4766. LOG_INFO("********** Occupancy Fee: %d.%02d **********", (OccupancyFee / 100), (OccupancyFee % 100));
  4767. LOG_INFO("********** Total Cost: %d.%02d **********", (TotalCost / 100), (TotalCost % 100));
  4768. LOG_INFO("********** Account Balance: %d.%02d **********", (AccountBalance / 100), (AccountBalance % 100));
  4769. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].TotalCost != TotalCost ||
  4770. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].AccountBalance != AccountBalance)
  4771. {
  4772. LOG_INFO("********** Connector Id %d Total Cost %d.%02d, Account Balance %d.%02d **********",
  4773. (i + 1), (TotalCost / 100), (TotalCost % 100), (AccountBalance / 100), (AccountBalance % 100));
  4774. }
  4775. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].TotalCost = TotalCost;
  4776. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].AccountBalance = AccountBalance;
  4777. memset(&ShmOCPP16Data->Cost.FinalCost[i], 0x00, sizeof(struct StrcutFinalCost));
  4778. }
  4779. }
  4780. }
  4781. }
  4782. struct timespec _Cost_Price_time;
  4783. char MyDefaultPriceString[128];
  4784. struct StrcutSetUserPrice MyUserPrice;
  4785. char MyConnectorRunningCostString[CONNECTOR_QUANTITY][128];
  4786. char MyConnectorFinalCostString[CONNECTOR_QUANTITY][128];
  4787. void CheckOcppCostAndPrice(void)
  4788. {
  4789. // 5s for reboot request timeout
  4790. if((GetTimeoutValue(_Cost_Price_time) / uSEC_VAL) >= OCPP_COST_REQ_INTERVAL)
  4791. {
  4792. GetClockTime(&_Cost_Price_time);
  4793. if(strcmp(MyDefaultPriceString, (char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[DefaultPrice].ItemData) != EQUAL)
  4794. {
  4795. DefaultPriceHandler((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[DefaultPrice].ItemData);
  4796. memcpy(MyDefaultPriceString, ShmOCPP16Data->ConfigurationTable.CoreProfile[DefaultPrice].ItemData, 128);
  4797. }
  4798. if(strlen((char *)ShmOCPP16Data->Cost.SetUserPrice.idToken) > 0 && strlen((char *)ShmOCPP16Data->Cost.SetUserPrice.price) > 0)
  4799. {
  4800. UserPriceHandler((char *)ShmOCPP16Data->Cost.SetUserPrice.idToken, (char *)ShmOCPP16Data->Cost.SetUserPrice.price);
  4801. memset(&ShmOCPP16Data->Cost.SetUserPrice, 0x00, sizeof(struct StrcutSetUserPrice));
  4802. }
  4803. RunningFinalCostHandler();
  4804. }
  4805. }
  4806. //===============================================
  4807. // OCPP
  4808. //===============================================
  4809. void CheckOcppStatus()
  4810. {
  4811. if (ShmOCPP16Data->SpMsg.bits.BootNotificationConf == YES)
  4812. {
  4813. ShmOCPP16Data->SpMsg.bits.BootNotificationConf = NO;
  4814. LOG_INFO("*********************OCPP Boot Notification****************************");
  4815. }
  4816. if (ShmOCPP16Data->MsMsg.bits.ResetReq == YES)
  4817. {
  4818. bool canReset = true;
  4819. if (ShmSysConfigAndInfo->SysWarningInfo.Level != 2)
  4820. {
  4821. for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++)
  4822. {
  4823. if (chargingInfo[_index]->SystemStatus != S_IDLE &&
  4824. chargingInfo[_index]->SystemStatus != S_RESERVATION &&
  4825. chargingInfo[_index]->SystemStatus != S_MAINTAIN)
  4826. {
  4827. canReset = false;
  4828. if (chargingInfo[_index]->SystemStatus >= S_REASSIGN && chargingInfo[_index]->SystemStatus < S_TERMINATING)
  4829. {
  4830. ChargingTerminalProcess(_index);
  4831. }
  4832. }
  4833. }
  4834. }
  4835. if(canReset)
  4836. {
  4837. if(strcmp((char *)ShmOCPP16Data->Reset.Type, "Hard") == EQUAL)
  4838. {
  4839. //trigger dispenser to hardware reboot
  4840. TriggerDispenserHardwareReboot();
  4841. if(IsDispenserHardwareRebootResponsed())
  4842. {
  4843. ShmOCPP16Data->MsMsg.bits.ResetReq = NO;
  4844. sprintf((char*)ShmOCPP16Data->Reset.ResponseStatus, "Accepted");
  4845. LOG_INFO("****** Hard Reboot ******");
  4846. ShmOCPP16Data->MsMsg.bits.ResetConf = YES;
  4847. for(int i = 0; i < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; i++)
  4848. {
  4849. setChargerMode(i, MODE_MAINTAIN);
  4850. }
  4851. sleep(3);
  4852. system("reboot -f");
  4853. }
  4854. }
  4855. if(strcmp((char *)ShmOCPP16Data->Reset.Type, "Soft") == EQUAL)
  4856. {
  4857. //trigger dispenser to software reset
  4858. TriggerDispenserSoftwareReset();
  4859. if(IsDispenserSoftwareResetResponsed())
  4860. {
  4861. ShmOCPP16Data->MsMsg.bits.ResetReq = NO;
  4862. sprintf((char*)ShmOCPP16Data->Reset.ResponseStatus, "Accepted");
  4863. LOG_INFO("****** Soft Reboot ******");
  4864. ShmOCPP16Data->MsMsg.bits.ResetConf = YES;
  4865. for(int i = 0; i < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; i++)
  4866. {
  4867. setChargerMode(i, MODE_MAINTAIN);
  4868. }
  4869. sleep(3);
  4870. system("killall OcppBackend &");
  4871. KillAllTask();
  4872. TryCloseWatchdog();
  4873. system("/usr/bin/run_evse_restart.sh");
  4874. }
  4875. }
  4876. }
  4877. }
  4878. CheckOcppCostAndPrice();
  4879. }
  4880. void OcppStartTransation(byte gunIndex)
  4881. {
  4882. byte _OcppGunIndex = gunIndex;
  4883. strcpy((char *)ShmOCPP16Data->StartTransaction[_OcppGunIndex].IdTag, (char *)chargingInfo[gunIndex]->StartUserId);
  4884. chargingInfo[gunIndex]->EvBatteryStartSoc = chargingInfo[gunIndex]->EvBatterySoc;
  4885. LOG_INFO("Gun index %d, OCPP Start Transation Index %d, IdTag = %s, StartSoc = %d",
  4886. chargingInfo[gunIndex]->Index, _OcppGunIndex, ShmOCPP16Data->StartTransaction[_OcppGunIndex].IdTag, chargingInfo[gunIndex]->EvBatteryStartSoc);
  4887. ShmOCPP16Data->CpMsg.bits[_OcppGunIndex].StartTransactionConf = NO;
  4888. ShmOCPP16Data->CpMsg.bits[_OcppGunIndex].StartTransactionReq = YES;
  4889. }
  4890. void OcppStopTransation(byte gunIndex)
  4891. {
  4892. byte _OcppGunIndex = gunIndex;
  4893. strcpy((char *)ShmOCPP16Data->StopTransaction[_OcppGunIndex].IdTag, (char *)chargingInfo[gunIndex]->StartUserId);
  4894. LOG_INFO("Gun index %d, OCPP Stop Transation Index %d, IdTag = %s, StopSoc = %d",
  4895. chargingInfo[gunIndex]->Index, _OcppGunIndex, ShmOCPP16Data->StopTransaction[_OcppGunIndex].IdTag, chargingInfo[gunIndex]->EvBatterySoc);
  4896. ShmOCPP16Data->CpMsg.bits[_OcppGunIndex].StopTransactionReq = YES;
  4897. }
  4898. // no use
  4899. bool OcppRemoteStop(byte gunIndex)
  4900. {
  4901. byte acDirIndex = ShmSysConfigAndInfo->SysConfig.AcConnectorCount;
  4902. // 有 AC 槍的話
  4903. if (acDirIndex > 0 && gunIndex > 0)
  4904. {
  4905. gunIndex += acDirIndex;
  4906. }
  4907. bool result = ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq;
  4908. if (ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq == YES)
  4909. {
  4910. strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "Remote");
  4911. ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq = NO;
  4912. }
  4913. return result;
  4914. }
  4915. void OcppRemoteStartChk()
  4916. {
  4917. if (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_NO_CHARGING)
  4918. {}
  4919. else if(!isDetectPlugin())
  4920. {
  4921. // 如果有 AC 槍,則固定是第 2 把槍,所以索引固定為 1
  4922. byte acDirIndex = ShmSysConfigAndInfo->SysConfig.AcConnectorCount;
  4923. for (byte ac_index = 0; ac_index < ShmSysConfigAndInfo->SysConfig.AcConnectorCount; ac_index++)
  4924. {
  4925. if (ShmOCPP16Data->CsMsg.bits[acDirIndex].RemoteStartTransactionReq == YES)
  4926. {
  4927. if (ac_chargingInfo[ac_index]->SystemStatus == S_IDLE ||
  4928. ac_chargingInfo[ac_index]->SystemStatus == S_RESERVATION)
  4929. {
  4930. ShmOCPP16Data->CsMsg.bits[acDirIndex].RemoteStartTransactionReq = NO;
  4931. ac_chargingInfo[ac_index]->RemoteStartFlag = YES;
  4932. ShmSysConfigAndInfo->SysInfo.OrderCharging = YES;
  4933. //ShmSysConfigAndInfo->SysInfo.OrderCharging = DEFAULT_AC_INDEX;
  4934. ShmOCPP16Data->CsMsg.bits[ShmSysConfigAndInfo->SysConfig.TotalConnectorCount + ac_index].RemoteStartTransactionReq = NO;
  4935. DetectPluginStart();
  4936. return;
  4937. }
  4938. ShmOCPP16Data->CsMsg.bits[acDirIndex].RemoteStartTransactionReq = NO;
  4939. }
  4940. }
  4941. byte threeGunIndex = 0;
  4942. byte dcIndex = 0;
  4943. bool isGunUsingStatus = false;
  4944. for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++)
  4945. {
  4946. // 如果有 AC 槍,且 DC 槍也有兩把
  4947. if (acDirIndex == 1 && _index == 1)
  4948. threeGunIndex = 1;
  4949. if (ShmOCPP16Data->CsMsg.bits[_index + threeGunIndex].RemoteStartTransactionReq == YES)
  4950. dcIndex = _index;
  4951. if (chargingInfo[_index]->SystemStatus != S_IDLE)
  4952. {
  4953. isGunUsingStatus = true;
  4954. }
  4955. }
  4956. // 如果是雙槍單模,只認閒置狀態的槍,如果有預約~ 則預約也算被使用
  4957. if (isGunUsingStatus && ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf)
  4958. {
  4959. if (dcIndex == 0)
  4960. threeGunIndex = 0;
  4961. ShmOCPP16Data->CsMsg.bits[dcIndex + threeGunIndex].RemoteStartTransactionReq = NO;
  4962. return;
  4963. }
  4964. if (dcIndex == 0)
  4965. threeGunIndex = 0;
  4966. if (ShmOCPP16Data->CsMsg.bits[dcIndex + threeGunIndex].RemoteStartTransactionReq == YES)
  4967. {
  4968. if (chargingInfo[dcIndex]->SystemStatus == S_IDLE ||
  4969. chargingInfo[dcIndex]->SystemStatus == S_RESERVATION)
  4970. {
  4971. chargingInfo[dcIndex]->RemoteStartFlag = YES;
  4972. ShmSysConfigAndInfo->SysInfo.OrderCharging = YES;
  4973. //ShmSysConfigAndInfo->SysInfo.OrderCharging = gun_index;
  4974. ShmOCPP16Data->CsMsg.bits[dcIndex + threeGunIndex].RemoteStartTransactionReq = NO;
  4975. DetectPluginStart();
  4976. }
  4977. ShmOCPP16Data->CsMsg.bits[dcIndex + threeGunIndex].RemoteStartTransactionReq = NO;
  4978. }
  4979. }
  4980. }
  4981. void ChkOcppStatus(byte gunIndex)
  4982. {
  4983. if(strcmp((char *)ShmOCPP16Data->StatusNotification[gunIndex].ErrorCode, "") == EQUAL)
  4984. {
  4985. if(strcmp((char *)_BackupStatusNotification[gunIndex].ErrorCode, "") != EQUAL)
  4986. {
  4987. strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].ErrorCode, (char *)_BackupStatusNotification[gunIndex].ErrorCode);
  4988. strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].VendorErrorCode, (char *)_BackupStatusNotification[gunIndex].VendorErrorCode);
  4989. //LOG_INFO("Gun %d Ocpp StatusNotification Recovery", gunIndex + 1);
  4990. }
  4991. }
  4992. if (chargingInfo[gunIndex]->SystemStatus == S_IDLE &&
  4993. ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowReq == YES)
  4994. {
  4995. ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowReq = NO;
  4996. if (isReservationExpired(gunIndex))
  4997. {
  4998. LOG_INFO("***************ChkOcppStatus: Gun %d OcppReservedStatus********************", gunIndex + 1);
  4999. chargingInfo[gunIndex]->ReservationId = ShmOCPP16Data->ReserveNow[gunIndex].ReservationId;
  5000. chargingInfo[gunIndex]->SystemStatus = S_RESERVATION;
  5001. }
  5002. ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowConf = YES;
  5003. }
  5004. if (chargingInfo[gunIndex]->SystemStatus == S_RESERVATION &&
  5005. ShmOCPP16Data->CsMsg.bits[gunIndex].CancelReservationReq == YES)
  5006. {
  5007. ShmOCPP16Data->CsMsg.bits[gunIndex].CancelReservationReq = NO;
  5008. if (isReservationExpired(gunIndex))
  5009. {
  5010. LOG_INFO("***************ChkOcppStatus: Gun %d Cancel OcppReservedStatus********************", gunIndex + 1);
  5011. chargingInfo[gunIndex]->ReservationId = 0;
  5012. chargingInfo[gunIndex]->SystemStatus = S_IDLE;
  5013. }
  5014. ShmOCPP16Data->CsMsg.bits[gunIndex].CancelReservationConf = YES;
  5015. }
  5016. if (ShmOCPP16Data->CsMsg.bits[gunIndex].ChangeAvailabilityReq == YES)
  5017. {
  5018. LOG_INFO("***************ChkOcppStatus: Gun %d OcppChangeAvailability********************", gunIndex + 1);
  5019. ShmOCPP16Data->CsMsg.bits[gunIndex].ChangeAvailabilityReq = NO;
  5020. if(strcmp((char *)ShmOCPP16Data->ChangeAvailability[gunIndex].Type, "Operative") == EQUAL)
  5021. {
  5022. if (isDb_ready)
  5023. DB_Update_Operactive(localDb, gunIndex, true);
  5024. chargingInfo[gunIndex]->IsAvailable = YES;
  5025. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gunIndex].Parameter.bits.AvailabilityRequest = 1;
  5026. if (chargingInfo[gunIndex]->SystemStatus == S_IDLE ||
  5027. chargingInfo[gunIndex]->SystemStatus == S_RESERVATION ||
  5028. chargingInfo[gunIndex]->SystemStatus == S_MAINTAIN)
  5029. {
  5030. setChargerMode(gunIndex, MODE_IDLE);
  5031. }
  5032. }
  5033. else if (strcmp((char *)ShmOCPP16Data->ChangeAvailability[gunIndex].Type, "Inoperative") == EQUAL)
  5034. {
  5035. if (isDb_ready)
  5036. DB_Update_Operactive(localDb, gunIndex, false);
  5037. chargingInfo[gunIndex]->IsAvailable = NO;
  5038. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gunIndex].Parameter.bits.AvailabilityRequest = 1;
  5039. if (chargingInfo[gunIndex]->SystemStatus == S_IDLE ||
  5040. chargingInfo[gunIndex]->SystemStatus == S_RESERVATION ||
  5041. chargingInfo[gunIndex]->SystemStatus == S_MAINTAIN)
  5042. {
  5043. setChargerMode(gunIndex, MODE_MAINTAIN);
  5044. }
  5045. }
  5046. }
  5047. if (ShmOCPP16Data->CsMsg.bits[gunIndex].UnlockConnectorReq == YES)
  5048. {
  5049. ShmOCPP16Data->CsMsg.bits[gunIndex].UnlockConnectorReq = NO;
  5050. if(chargingInfo[gunIndex]->SystemStatus == S_PREPARNING ||
  5051. chargingInfo[gunIndex]->SystemStatus == S_PREPARING_FOR_EV ||
  5052. chargingInfo[gunIndex]->SystemStatus == S_PREPARING_FOR_EVSE ||
  5053. chargingInfo[gunIndex]->SystemStatus == S_CHARGING)
  5054. {
  5055. // 充電中,需停止充電
  5056. strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "UnlockCommand");
  5057. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gunIndex].Parameter.bits.UnlockStopRequest = true;
  5058. LOG_INFO("********** OcppUnlockStop Gun %d **********", gunIndex + 1);
  5059. }
  5060. strcpy((char *)ShmOCPP16Data->UnlockConnector[gunIndex].ResponseStatus, "Unlocked");
  5061. ShmOCPP16Data->CsMsg.bits[gunIndex].UnlockConnectorConf = YES;
  5062. }
  5063. if (ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq == YES)
  5064. {
  5065. ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq = NO;
  5066. if(chargingInfo[gunIndex]->SystemStatus == S_PREPARNING ||
  5067. chargingInfo[gunIndex]->SystemStatus == S_PREPARING_FOR_EV ||
  5068. chargingInfo[gunIndex]->SystemStatus == S_PREPARING_FOR_EVSE ||
  5069. chargingInfo[gunIndex]->SystemStatus == S_CHARGING)
  5070. {
  5071. strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "Remote");
  5072. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gunIndex].Parameter.bits.RemoteStopRequest = true;
  5073. LOG_INFO("********** OcppRemoteStop Gun %d **********", gunIndex + 1);
  5074. }
  5075. }
  5076. }
  5077. bool CheckBackendChargingTimeout(byte gunIndex)
  5078. {
  5079. bool result = false;
  5080. if (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_ENABLE)
  5081. {
  5082. if (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration > 0)
  5083. {
  5084. if (chargingInfo[gunIndex]->PresentChargedDuration > (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration * 60))
  5085. result = true;
  5086. }
  5087. }
  5088. else if (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE)
  5089. {
  5090. // 隨插即充電的要看 offline
  5091. if (ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeDuration > 0)
  5092. {
  5093. if (chargingInfo[gunIndex]->PresentChargedDuration > (ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeDuration * 60))
  5094. result = true;
  5095. }
  5096. }
  5097. return result;
  5098. }
  5099. bool CheckBackendChargingEnergy(byte gunIndex)
  5100. {
  5101. bool result = false;
  5102. if (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_ENABLE)
  5103. {
  5104. if (ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy > 0)
  5105. {
  5106. if (chargingInfo[gunIndex]->PresentChargedEnergy > ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy)
  5107. result = true;
  5108. }
  5109. }
  5110. else if (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE)
  5111. {
  5112. // 隨插即充電的要看 offline
  5113. if (ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy > 0)
  5114. {
  5115. if (chargingInfo[gunIndex]->PresentChargedEnergy > (ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy))
  5116. result = true;
  5117. }
  5118. }
  5119. return result;
  5120. }
  5121. void InformOcppErrOccur(byte codeType)
  5122. {
  5123. char _error[25];
  5124. switch(codeType)
  5125. {
  5126. case 4: strcpy(_error, "InternalError"); break;
  5127. case 6: strcpy(_error, "NoError"); break;
  5128. case 7: strcpy(_error, "OtherError"); break;
  5129. case 13: strcpy(_error, "UnderVoltage"); break;
  5130. case 14: strcpy(_error, "OverVoltage"); break;
  5131. }
  5132. for (byte gun_index = 0; gun_index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun_index++)
  5133. {
  5134. SetOcppErrorCode(gun_index, _error);
  5135. }
  5136. }
  5137. void SetOcppErrorCode(unsigned char _index, char *errCode)
  5138. {
  5139. strcpy((char *)ShmOCPP16Data->StatusNotification[_index].ErrorCode, errCode);
  5140. strcpy((char *)_BackupStatusNotification[_index].ErrorCode, errCode);
  5141. }
  5142. void SetOcppVendorErrorCode(unsigned char _index, char *vendorCode)
  5143. {
  5144. strcpy((char *)ShmOCPP16Data->StatusNotification[_index].VendorErrorCode, vendorCode);
  5145. strcpy((char *)_BackupStatusNotification[_index].VendorErrorCode, vendorCode);
  5146. }
  5147. //===============================================
  5148. // SQLite3 related routine
  5149. //===============================================
  5150. int DB_Open(sqlite3 *db)
  5151. {
  5152. int result = PASS;
  5153. char* errMsg = NULL;
  5154. char* createRecordSql="CREATE TABLE IF NOT EXISTS charging_record("
  5155. "idx integer primary key AUTOINCREMENT, "
  5156. "reservationId text, "
  5157. "transactionId text, "
  5158. "startMethod text, "
  5159. "userId text, "
  5160. "dateTimeStart text, "
  5161. "dateTimeStop text,"
  5162. "socStart text, "
  5163. "socStop text, "
  5164. "chargeEnergy text, "
  5165. "stopReason text"
  5166. ");";
  5167. char* createCfgSql="CREATE TABLE IF NOT EXISTS `config` ( "
  5168. "`idx` INTEGER PRIMARY KEY AUTOINCREMENT, "
  5169. "`IsAvailable` TEXT NOT NULL, "
  5170. "`connector` INTEGER NOT NULL, "
  5171. "`val` TEXT NOT NULL, unique(IsAvailable,connector) on conflict replace);";
  5172. if(sqlite3_open(DB_FILE, &db))
  5173. {
  5174. result = FAIL;
  5175. LOG_ERROR( "Can't open database: %s", sqlite3_errmsg(db));
  5176. sqlite3_close(db);
  5177. }
  5178. else
  5179. {
  5180. LOG_INFO( "Local charging record database open successfully.");
  5181. if (sqlite3_exec(db, createRecordSql, 0, 0, &errMsg) != SQLITE_OK)
  5182. {
  5183. result = FAIL;
  5184. LOG_INFO( "Create local charging record table error message: %s", errMsg);
  5185. }
  5186. else
  5187. {
  5188. LOG_INFO( "Opened local charging record table successfully");
  5189. }
  5190. if (sqlite3_exec(db, createCfgSql, 0, 0, &errMsg) != SQLITE_OK)
  5191. {
  5192. result = FAIL;
  5193. LOG_INFO( "Create local config table error message: %s", errMsg);
  5194. }
  5195. else
  5196. {
  5197. LOG_INFO( "Opened local config table successfully");
  5198. }
  5199. sqlite3_close(db);
  5200. }
  5201. return result;
  5202. }
  5203. int DB_Insert_Record(sqlite3 *db, int gun_index)
  5204. {
  5205. int result = PASS;
  5206. char* errMsg = NULL;
  5207. char insertSql[1024];
  5208. sprintf(insertSql, "insert into charging_record(reservationId, transactionId, startMethod, userId, dateTimeStart, dateTimeStop, socStart, socStop, chargeEnergy, stopReason) "
  5209. "values('%d', '%d', '%d', '%s', '%s', '%s', '%d', '%d', '%f', '%s');",
  5210. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId,
  5211. ShmOCPP16Data->StartTransaction[gun_index].ResponseTransactionId,
  5212. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod,
  5213. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId,
  5214. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime,
  5215. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime,
  5216. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
  5217. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
  5218. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy,
  5219. ShmOCPP16Data->StopTransaction[gun_index].StopReason);
  5220. if(sqlite3_open("/Storage/ChargeLog/localCgargingRecord.db", &db))
  5221. {
  5222. result = FAIL;
  5223. LOG_ERROR( "Can't open database: %s", sqlite3_errmsg(db));
  5224. sqlite3_close(db);
  5225. }
  5226. else
  5227. {
  5228. LOG_INFO( "Local charging record database open successfully.");
  5229. if (sqlite3_exec(db, insertSql, 0, 0, &errMsg) != SQLITE_OK)
  5230. {
  5231. result = FAIL;
  5232. LOG_INFO( "Insert local charging record error message: %s", errMsg);
  5233. }
  5234. else
  5235. {
  5236. LOG_INFO( "Insert local charging record successfully");
  5237. }
  5238. sqlite3_close(db);
  5239. }
  5240. return result;
  5241. }
  5242. int DB_Update_Operactive(sqlite3 *db, uint8_t gun_index, uint8_t IsAvailable)
  5243. {
  5244. uint8_t result = false;
  5245. char* errMsg = NULL;
  5246. char sqlStr[1024];
  5247. srand(time(NULL));
  5248. if(sqlite3_open(DB_FILE, &db))
  5249. {
  5250. result = FAIL;
  5251. LOG_ERROR( "Can't open database: %s", sqlite3_errmsg(db));
  5252. sqlite3_close(db);
  5253. }
  5254. else
  5255. {
  5256. LOG_INFO( "Local charging record database open successfully (%d).", IsAvailable);
  5257. sprintf(sqlStr, "insert or replace into config (IsAvailable, connector, val) values('IsAvailable', %d, %d);", gun_index, IsAvailable);
  5258. LOG_INFO("sqlStr= %s", sqlStr);
  5259. if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
  5260. {
  5261. result = FAIL;
  5262. LOG_INFO( "update config error message: %s", errMsg);
  5263. }
  5264. else
  5265. {
  5266. LOG_INFO("update connector-%d config item isOperactive to %d", gun_index, IsAvailable);
  5267. }
  5268. sqlite3_close(db);
  5269. }
  5270. return result;
  5271. }
  5272. int DB_Get_Operactive(sqlite3 *db, uint8_t gun_index)
  5273. {
  5274. uint8_t result = true;
  5275. char* errMsg = NULL;
  5276. char sqlStr[1024];
  5277. char **rs;
  5278. int rows, cols;
  5279. sprintf(sqlStr, "select * from config where IsAvailable='IsAvailable' and connector=%d;", gun_index);
  5280. //DEBUG_INFO("sqlStr= %s\r\n", sqlStr);
  5281. if(sqlite3_open(DB_FILE, &db))
  5282. {
  5283. result = FAIL;
  5284. LOG_ERROR( "Can't open database: %s", sqlite3_errmsg(db));
  5285. sqlite3_close(db);
  5286. }
  5287. else
  5288. {
  5289. LOG_INFO( "Local config query database open successfully.");
  5290. sqlite3_get_table(db, sqlStr, &rs, &rows, &cols, &errMsg);
  5291. if(rows>0)
  5292. {
  5293. for(int idxRow=1;idxRow<=rows;idxRow++)
  5294. {
  5295. if(strcmp(rs[(idxRow*cols)+3], "0") == 0)
  5296. {
  5297. result = false;
  5298. }
  5299. LOG_INFO("Query connector-%d isOperactive: %s", gun_index, rs[(idxRow*cols)+3]);
  5300. }
  5301. }
  5302. else
  5303. {
  5304. LOG_INFO("Query connector-%d fail, set default value to operactive.", gun_index);
  5305. }
  5306. sqlite3_free_table(rs);
  5307. sqlite3_close(db);
  5308. }
  5309. return result;
  5310. }
  5311. //===============================================
  5312. // Config process
  5313. //===============================================
  5314. void AddPlugInTimes(byte gunIndex)
  5315. {
  5316. if (chargingInfo[gunIndex]->Type == _Type_Chademo)
  5317. ShmSysConfigAndInfo->SysConfig.ChademoPlugInTimes += 1;
  5318. else if(chargingInfo[gunIndex]->Type == _Type_CCS_2)
  5319. ShmSysConfigAndInfo->SysConfig.Ccs2PlugInTimes += 1;
  5320. else if(chargingInfo[gunIndex]->Type == _Type_GB)
  5321. ShmSysConfigAndInfo->SysConfig.GbPlugInTimes += 1;
  5322. }
  5323. void ChangeStartOrStopDateTime(byte isStart, byte gunIndex)
  5324. {
  5325. char cmdBuf[32];
  5326. struct timeb csuTime;
  5327. struct tm *tmCSU;
  5328. ftime(&csuTime);
  5329. tmCSU = localtime(&csuTime.time);
  5330. sprintf(cmdBuf, "%04d-%02d-%02d %02d:%02d:%02d", tmCSU->tm_year + 1900,
  5331. tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
  5332. tmCSU->tm_sec);
  5333. if (isStart)
  5334. strcpy((char *)chargingInfo[gunIndex]->StartDateTime, cmdBuf);
  5335. else
  5336. strcpy((char *)chargingInfo[gunIndex]->StopDateTime, cmdBuf);
  5337. }
  5338. void zipLogFiles()
  5339. {
  5340. const char* logPath = "/Storage/SystemLog";
  5341. // 獲取目錄
  5342. DIR* pDir = opendir(logPath);
  5343. if (pDir != NULL)
  5344. {
  5345. struct timeb csuTime;
  5346. struct tm *tmCSU;
  5347. ftime(&csuTime);
  5348. tmCSU = localtime(&csuTime.time);
  5349. // LOG_INFO("Time : %04d-%02d-%02d %02d:%02d:%02d \n", tmCSU->tm_year + 1900,
  5350. // tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
  5351. // tmCSU->tm_sec);
  5352. // Read items inside the folder
  5353. struct dirent* pEntry = NULL;
  5354. while ((pEntry = readdir(pDir)) != NULL)
  5355. {
  5356. if (strcmp(pEntry->d_name, ".") != 0 &&
  5357. strcmp(pEntry->d_name, "..") != 0 &&
  5358. strncmp(pEntry->d_name, "[", 1) == 0 &&
  5359. strstr(pEntry->d_name, "tar") < 0)
  5360. {
  5361. char yearC[5];
  5362. unsigned short year = 0;
  5363. char monthC[3];
  5364. unsigned short month = 0;
  5365. yearC[4] = '\0';
  5366. strncpy(yearC, pEntry->d_name + 1, 4);
  5367. monthC[2] = '\0';
  5368. strncpy(monthC, pEntry->d_name + 6, 2);
  5369. year = atoi(yearC);
  5370. month = atoi(monthC);
  5371. if (year != 0)
  5372. {
  5373. if (year < tmCSU->tm_year + 1900 ||
  5374. (year >= tmCSU->tm_year + 1900 && month < tmCSU->tm_mon + 1))
  5375. {
  5376. LOG_INFO("tar file name : %s", pEntry->d_name);
  5377. char file[256];
  5378. memset(file, 0x00, sizeof(file));
  5379. strcat(file, "tar zcvf ");
  5380. strcat(file, logPath);
  5381. strncat(file, "/", 1);
  5382. strcat(file, pEntry->d_name);
  5383. strcat(file, ".tar");
  5384. strncat(file, " ", 1);
  5385. strcat(file, logPath);
  5386. strncat(file, "/", 1);
  5387. strcat(file, pEntry->d_name);
  5388. LOG_INFO("zip = %s \n", file);
  5389. system(file);
  5390. }
  5391. }
  5392. }
  5393. }
  5394. }
  5395. // Close folder
  5396. closedir(pDir);
  5397. }
  5398. void ChangeGunSelectByIndex(byte sel)
  5399. {
  5400. ShmSysConfigAndInfo->SysInfo.CurGunSelected = sel;
  5401. ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc = NO_DEFINE;
  5402. }
  5403. void StopProcessingLoop()
  5404. {
  5405. for (;;)
  5406. {
  5407. CheckFactoryConfigFunction();
  5408. CheckFwUpdateFunction();
  5409. if (ShmSysConfigAndInfo->SysWarningInfo.Level == 2)
  5410. {
  5411. ChkPrimaryStatus();
  5412. if (ShmSysConfigAndInfo->SysWarningInfo.Level == 0)
  5413. {
  5414. LOG_INFO("Soft reboot for retry self-tets (Primary).");
  5415. KillAllTask();
  5416. sleep(3);
  5417. TryCloseWatchdog();
  5418. system("/usr/bin/run_evse_restart.sh");
  5419. return;
  5420. }
  5421. }
  5422. if(ShmOCPP16Data->MsMsg.bits.ResetReq == YES)
  5423. {
  5424. if(strcmp((char *)ShmOCPP16Data->Reset.Type, "Hard") == EQUAL)
  5425. {
  5426. ShmChargerInfo->Control.SysCtrl.bits.NeedHardReset = true;
  5427. }
  5428. if(strcmp((char *)ShmOCPP16Data->Reset.Type, "Soft") == EQUAL)
  5429. {
  5430. ShmChargerInfo->Control.SysCtrl.bits.NeedSoftReset = true;
  5431. }
  5432. }
  5433. CheckSoftHardReset();
  5434. sleep(1);
  5435. }
  5436. }
  5437. void CreateWatchdog(void)
  5438. {
  5439. wtdFd = InitWatchDog();
  5440. if(wtdFd < 0)
  5441. {
  5442. LOG_INFO("Watchdog Initial Fail");
  5443. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
  5444. }
  5445. else
  5446. {
  5447. LOG_INFO("Watchdog Initial Success");
  5448. }
  5449. }
  5450. void TryCloseWatchdog(void)
  5451. {
  5452. if(wtdFd > 0)
  5453. {
  5454. write(wtdFd, "V", 1);
  5455. close(wtdFd);
  5456. }
  5457. }
  5458. void TryFeedWatchdog(void)
  5459. {
  5460. if(wtdFd > 0)
  5461. {
  5462. write(wtdFd, "a", 1);
  5463. }
  5464. }
  5465. bool IsParallelCabinetIdle(void)
  5466. {
  5467. bool result = true;
  5468. if(ShmChargerInfo->Control.CabinetRole == _CROLE_SLAVE)
  5469. {
  5470. result = false;
  5471. }
  5472. return result;
  5473. }
  5474. bool IsConnectorWholeIdle(void)
  5475. {
  5476. bool result = true;
  5477. for (byte count = 0; count < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; count++)
  5478. {
  5479. if (chargingInfo[count]->SystemStatus != S_IDLE &&
  5480. chargingInfo[count]->SystemStatus != S_RESERVATION &&
  5481. chargingInfo[count]->SystemStatus != S_FAULT &&
  5482. chargingInfo[count]->SystemStatus != S_MAINTAIN)
  5483. {
  5484. result = false;
  5485. break;
  5486. }
  5487. }
  5488. return result;
  5489. }
  5490. void ClearAlarmCodeWhenAcOff()
  5491. {
  5492. if (!ShmSysConfigAndInfo->SysInfo.AcContactorStatus)
  5493. {
  5494. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuNoResource = NO;
  5495. }
  5496. }
  5497. //==========================================
  5498. // Check task processing
  5499. //==========================================
  5500. void CheckTask()
  5501. {
  5502. if(ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T' || ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D')
  5503. {
  5504. if(ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomEnabled == YES)
  5505. {
  5506. if(system("pidof -s Module_4g > /dev/null") != 0 && ShmChargerInfo->Control.SysCtrl.bits.Wifi4gResetEnable == false)
  5507. {
  5508. LOG_ERROR("Module_4g not running, restart it.");
  5509. system("/root/Module_4g &");
  5510. }
  5511. }
  5512. }
  5513. if(ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W' || ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D')
  5514. {
  5515. if(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode != _SYS_WIFI_MODE_DISABLE)
  5516. {
  5517. if(system("pidof -s Module_Wifi > /dev/null") != 0 && ShmChargerInfo->Control.SysCtrl.bits.Wifi4gResetEnable == false)
  5518. {
  5519. LOG_ERROR("Module_Wifi not running, restart it.");
  5520. system("/root/Module_Wifi &");
  5521. }
  5522. }
  5523. }
  5524. if(ShmChargerInfo->Control.CabinetRole != _CROLE_SLAVE &&
  5525. strcmp((char *)ShmSysConfigAndInfo->SysConfig.OcppServerURL, "") != EQUAL &&
  5526. strcmp((char *)ShmSysConfigAndInfo->SysConfig.ChargeBoxId, "") != EQUAL)
  5527. {
  5528. ShmChargerInfo->Control.SysCtrl.bits.BackendEnable = true;
  5529. if((time((time_t*)NULL) - ShmOCPP16Data->procDogTime) > 180)
  5530. {
  5531. LOG_ERROR("OcppBackend watch dog timeout task restart.");
  5532. ShmOCPP16Data->procDogTime = time((time_t*)NULL);
  5533. system("pkill OcppBackend");
  5534. }
  5535. if(system("pidof -s OcppBackend > /dev/null") != 0)
  5536. {
  5537. LOG_ERROR("OcppBackend not running, restart it.");
  5538. system("/root/OcppBackend &");
  5539. }
  5540. }
  5541. else
  5542. {
  5543. ShmChargerInfo->Control.SysCtrl.bits.BackendEnable = false;
  5544. }
  5545. if(system("pidof -s Module_ProduceUtils > /dev/null") != 0)
  5546. {
  5547. LOG_ERROR("Module_ProduceUtils not running, restart it.");
  5548. system ("/root/Module_ProduceUtils &");
  5549. }
  5550. if(system("pidof -s Module_EvComm > /dev/null") != 0)
  5551. {
  5552. LOG_ERROR("Module_EvComm not running, restart it.");
  5553. system ("/root/Module_EvComm &");
  5554. }
  5555. if(system("pidof -s Module_InternalComm > /dev/null") != 0)
  5556. {
  5557. LOG_ERROR("Module_InternalComm not running, restart it.");
  5558. system ("/root/Module_InternalComm &");
  5559. //ShmChargerInfo->Control.SysCtrl.bits.NeedSoftReset = true;
  5560. }
  5561. }
  5562. void InitialDHCP()
  5563. {
  5564. char tmpbuf[256];
  5565. memset(tmpbuf,0,256);
  5566. system("pgrep -f \"udhcpc -i eth0\" | xargs kill");
  5567. sprintf(tmpbuf, "/sbin/udhcpc -i eth0 -x hostname:CSU3_%s -s /root/dhcp_script/eth0.script > /dev/null &", ShmSysConfigAndInfo->SysConfig.SystemId);
  5568. system(tmpbuf);
  5569. }
  5570. void InitialDispenserDhcpServerConfig(void)
  5571. {
  5572. system("echo 'start 192.168.100.10' > /etc/udhcpd_eth1.conf");
  5573. system("echo 'end 192.168.100.20' >> /etc/udhcpd_eth1.conf");
  5574. system("echo 'interface eth1' >> /etc/udhcpd_eth1.conf");
  5575. system("echo 'opt dns 8.8.8.8' >> /etc/udhcpd_eth1.conf");
  5576. system("echo 'option subnet 255.255.255.0' >> /etc/udhcpd_eth1.conf");
  5577. system("echo 'opt router 192.168.100.1' >> /etc/udhcpd_eth1.conf");
  5578. system("echo 'option domain local' >> /etc/udhcpd_eth1.conf");
  5579. system("echo 'option lease 86400' >> /etc/udhcpd_eth1.conf");
  5580. usleep(1000);
  5581. }
  5582. void StartDispenserDhcpServer(void)
  5583. {
  5584. system("pgrep -f \"udhcpd /etc/udhcpd_eth1.conf\" | xargs kill");
  5585. system("/usr/sbin/udhcpd /etc/udhcpd_eth1.conf > /dev/null &");
  5586. }
  5587. //==========================================
  5588. // Check Smart Charging Profile
  5589. //==========================================
  5590. void Ocpp_ProfileReq_Cmd(byte gunIndex)
  5591. {
  5592. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  5593. {
  5594. if(ShmOCPP16Data->CSUMsg.bits[gunIndex].ChargingProfileConf == NO)
  5595. {
  5596. if(ShmOCPP16Data->CSUMsg.bits[gunIndex].ChargingProfileReq == NO)
  5597. {
  5598. ShmOCPP16Data->CSUMsg.bits[gunIndex].ChargingProfileReq = YES;
  5599. }
  5600. }
  5601. }
  5602. }
  5603. bool Ocpp_Chk_ProfileConf_Cmd(byte gunIndex)
  5604. {
  5605. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  5606. {
  5607. if (ShmOCPP16Data->CSUMsg.bits[gunIndex].ChargingProfileConf == YES)
  5608. {
  5609. ShmOCPP16Data->CSUMsg.bits[gunIndex].ChargingProfileConf = NO;
  5610. return true;
  5611. }
  5612. }
  5613. return false;
  5614. }
  5615. int GetStartScheduleTime(unsigned char *time)
  5616. {
  5617. int result = -1;
  5618. struct tm tmScheduleStart;
  5619. struct timeb tbScheduleStart;
  5620. if((sscanf((char *)time, "%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))
  5621. {
  5622. tmScheduleStart.tm_year -= 1900;
  5623. tmScheduleStart.tm_mon -= 1;
  5624. tbScheduleStart.time = mktime(&tmScheduleStart);
  5625. tbScheduleStart.millitm = 0;
  5626. result = DiffTimebWithNow(tbScheduleStart) / 1000;
  5627. }
  5628. return result;
  5629. }
  5630. void Ocpp_ChargingProfile_Process(byte _index)
  5631. {
  5632. int _time = 0;
  5633. int _startCount = NO_DEFINE;
  5634. int _maxCount = 0;
  5635. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  5636. {
  5637. if (strcmp((char *)ShmOCPP16Data->SmartChargingProfile[_index].ChargingProfileKind, "Absolute") == EQUAL &&
  5638. ShmOCPP16Data->SmartChargingProfile[_index].ChargingProfileId == YES)
  5639. {
  5640. _time = GetStartScheduleTime(ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.StartSchedule);
  5641. _maxCount = ARRAY_SIZE(ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod);
  5642. _startCount = NO_DEFINE;
  5643. for (byte _count = 0; _count < _maxCount; _count++)
  5644. {
  5645. // 預設最小輸出電流 (MIN_OUTPUT_CUR) A
  5646. if (_time >= ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_count].StartPeriod)
  5647. {
  5648. if ((_count == 0 && ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_count].Limit >= MIN_OUTPUT_CUR) ||
  5649. ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_count].Limit > MIN_OUTPUT_CUR)
  5650. {
  5651. _startCount = _count;
  5652. }
  5653. }
  5654. }
  5655. if (_startCount < _maxCount)
  5656. {
  5657. chargingInfo[_index]->ChargingProfilePower = ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_startCount].Limit * AC_OUTPUT_VOL * ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_startCount].NumberPhases;
  5658. if (chargingInfo[_index]->EvBatterytargetVoltage > 0 &&
  5659. (int)chargingInfo[_index]->PresentChargingVoltage > 0)
  5660. {
  5661. chargingInfo[_index]->ChargingProfileCurrent = (chargingInfo[_index]->ChargingProfilePower / chargingInfo[_index]->PresentChargingVoltage) * 10;
  5662. }
  5663. else
  5664. {
  5665. chargingInfo[_index]->ChargingProfileCurrent = -1;
  5666. }
  5667. }
  5668. else
  5669. {
  5670. chargingInfo[_index]->ChargingProfilePower = -1;
  5671. chargingInfo[_index]->ChargingProfileCurrent = -1;
  5672. }
  5673. }
  5674. else
  5675. {
  5676. chargingInfo[_index]->ChargingProfilePower = -1;
  5677. chargingInfo[_index]->ChargingProfileCurrent = -1;
  5678. }
  5679. }
  5680. else
  5681. {
  5682. chargingInfo[_index]->ChargingProfilePower = -1;
  5683. chargingInfo[_index]->ChargingProfileCurrent = -1;
  5684. }
  5685. if((int)_lastProfilePower[_index] != (int)chargingInfo[_index]->ChargingProfilePower ||
  5686. (int)_lastProfileCurrent[_index] != (int)chargingInfo[_index]->ChargingProfileCurrent)
  5687. {
  5688. LOG_INFO("Gun %d Get Profile - Index = %d, Limit = %f",
  5689. _index + 1, _startCount,
  5690. ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_startCount].Limit);
  5691. LOG_INFO("Max: %d kW, Gun %d ChargingProfile Power = %d, Current = %d",
  5692. ShmSysConfigAndInfo->SysInfo.MaxChargingProfilePower == -1 ? (int)ShmSysConfigAndInfo->SysInfo.MaxChargingProfilePower : ((int)ShmSysConfigAndInfo->SysInfo.MaxChargingProfilePower / 1000),
  5693. _index + 1, (int)chargingInfo[_index]->ChargingProfilePower, (int)chargingInfo[_index]->ChargingProfileCurrent);
  5694. }
  5695. _lastProfilePower[_index] = chargingInfo[_index]->ChargingProfilePower;
  5696. _lastProfileCurrent[_index] = chargingInfo[_index]->ChargingProfileCurrent;
  5697. }
  5698. void Ocpp_MaxChargingProfile_Process(void)
  5699. {
  5700. int _time = 0;
  5701. int _startCount = NO_DEFINE;
  5702. int _maxCount = 0;
  5703. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  5704. {
  5705. if (strcmp((char *)ShmOCPP16Data->MaxChargingProfile.ChargingProfileKind, "Absolute") == EQUAL &&
  5706. ShmOCPP16Data->MaxChargingProfile.ChargingProfileId == YES)
  5707. {
  5708. _time = GetStartScheduleTime(ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.StartSchedule);
  5709. _maxCount = ARRAY_SIZE(ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod);
  5710. _startCount = NO_DEFINE;
  5711. for (byte _count = 0; _count < _maxCount; _count++)
  5712. {
  5713. // 預設最小輸出電流 (MIN_OUTPUT_CUR) A
  5714. if (_time >= ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[_count].StartPeriod)
  5715. {
  5716. if ((_count == 0 && ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[_count].Limit >= MIN_OUTPUT_CUR) ||
  5717. ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[_count].Limit > MIN_OUTPUT_CUR)
  5718. {
  5719. _startCount = _count;
  5720. }
  5721. }
  5722. }
  5723. if(_startCount < _maxCount)
  5724. {
  5725. ShmSysConfigAndInfo->SysInfo.MaxChargingProfilePower = ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[_startCount].Limit * AC_OUTPUT_VOL * ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[_startCount].NumberPhases;
  5726. }
  5727. else
  5728. {
  5729. ShmSysConfigAndInfo->SysInfo.MaxChargingProfilePower = -1;
  5730. }
  5731. }
  5732. else
  5733. {
  5734. ShmSysConfigAndInfo->SysInfo.MaxChargingProfilePower = -1;
  5735. }
  5736. }
  5737. else
  5738. {
  5739. ShmSysConfigAndInfo->SysInfo.MaxChargingProfilePower = -1;
  5740. }
  5741. if((int)_lastMaxProfilePower != (int)ShmSysConfigAndInfo->SysInfo.MaxChargingProfilePower)
  5742. {
  5743. LOG_INFO("Charger Get Max Profile - Index = %d, Limit = %f",
  5744. _startCount, ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[_startCount].Limit);
  5745. LOG_INFO("Charger Max Profile Power = %d", (int)ShmSysConfigAndInfo->SysInfo.MaxChargingProfilePower);
  5746. }
  5747. _lastMaxProfilePower = ShmSysConfigAndInfo->SysInfo.MaxChargingProfilePower;
  5748. }
  5749. void CheckSmartChargeProfile(byte _index)
  5750. {
  5751. if(Ocpp_Chk_ProfileConf_Cmd(_index))
  5752. {
  5753. Ocpp_MaxChargingProfile_Process();
  5754. Ocpp_ChargingProfile_Process(_index);
  5755. }
  5756. }
  5757. bool Ocpp_CheckInvalidId(byte _index)
  5758. {
  5759. bool invalid = false;
  5760. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  5761. {
  5762. if(strstr((char *) ShmOCPP16Data->ConfigurationTable.CoreProfile[StopTransactionOnInvalidId].ItemData, "TRUE"))
  5763. {
  5764. if(strcmp((char *)ShmOCPP16Data->StartTransaction[_index].ResponseIdTagInfo.Status, "Blocked") == EQUAL ||
  5765. strcmp((char *)ShmOCPP16Data->StartTransaction[_index].ResponseIdTagInfo.Status, "Expired") == EQUAL ||
  5766. strcmp((char *)ShmOCPP16Data->StartTransaction[_index].ResponseIdTagInfo.Status, "Invalid") == EQUAL)
  5767. {
  5768. invalid = true;
  5769. LOG_INFO("Gun %d Stop Transaction On Invalid Id", _index + 1);
  5770. }
  5771. }
  5772. else
  5773. {
  5774. if(strcmp((char *)ShmOCPP16Data->StartTransaction[_index].ResponseIdTagInfo.Status, "Accepted") != EQUAL)
  5775. {
  5776. invalid = true;
  5777. LOG_INFO("Gun %d Start Transaction Not Accepted", _index + 1);
  5778. }
  5779. }
  5780. }
  5781. return invalid;
  5782. }
  5783. void TheEndCharging(byte gun_index)
  5784. {
  5785. chargingInfo[gun_index]->isRemoteStart = NO;
  5786. //StopGunInfoTimeoutDet(gun_index);
  5787. //StartGunInfoTimeoutDet(gun_index, Timeout_EvseCompleteDet);
  5788. ChangeStartOrStopDateTime(NO, gun_index);
  5789. //DB_Insert_Record(localDb, gun_index);
  5790. }
  5791. void UpdateErrorCodeToOcpp(byte index)
  5792. {
  5793. //printf("ConnectorAlarmCode = %s \n", chargingInfo[index]->ConnectorAlarmCode);
  5794. if (strcmp((char *)chargingInfo[index]->ConnectorAlarmCode, "") != EQUAL)
  5795. {
  5796. SetOcppErrorCode(index, "InternalError");
  5797. SetOcppVendorErrorCode(index, (char *)chargingInfo[index]->ConnectorAlarmCode);
  5798. }
  5799. else if (strcmp((char *)chargingInfo[index]->EvConnAlarmCode, "") != EQUAL)
  5800. {
  5801. SetOcppErrorCode(index, "OtherError");
  5802. SetOcppVendorErrorCode(index, (char *)chargingInfo[index]->EvConnAlarmCode);
  5803. }
  5804. }
  5805. void CheckMiscCommandRequirement(void)
  5806. {
  5807. BOOL NeedAnnouncement = FALSE;
  5808. unsigned char connector = 0;
  5809. if(ShmSysConfigAndInfo->SysInfo.FirmwareUpdate != YES)
  5810. {
  5811. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  5812. {
  5813. NeedAnnouncement = FALSE;
  5814. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].LocalStatus != _DS_None &&
  5815. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].LocalStatus != _DS_Timeout)
  5816. {
  5817. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.ConnectorTimeoutConfigRequest ||
  5818. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.DefaultPriceConfigRequest ||
  5819. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.CurrencyConfigRequest ||
  5820. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.HardwareRebootRequest ||
  5821. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.SoftwareResetRequest ||
  5822. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.BackendStatusRequest ||
  5823. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.EthernetStatusRequest ||
  5824. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.WiFiStatusRequest ||
  5825. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.TelcomModemStatusRequest ||
  5826. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.BillingStatusRequest ||
  5827. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.StopButtonStatusRequest ||
  5828. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.AuthModeConfigRequest ||
  5829. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.EVCCIDConfigRequest)
  5830. {
  5831. NeedAnnouncement = TRUE;
  5832. }
  5833. for(int j = 0; j < ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ConnectorQuantity; j++)
  5834. {
  5835. connector = ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ConnectorID[j] - 1;
  5836. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].Parameter.bits.AvailabilityRequest ||
  5837. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].Parameter.bits.RemoteStartRequest ||
  5838. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].Parameter.bits.AccountBalanceRequest)
  5839. {
  5840. NeedAnnouncement = TRUE;
  5841. }
  5842. }
  5843. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.MiscNeedAnnouncement != NeedAnnouncement)
  5844. {
  5845. if(NeedAnnouncement)
  5846. {
  5847. LOG_INFO("********** Dispenser %d Misc Command Need Announcement **********", i + 1);
  5848. }
  5849. else
  5850. {
  5851. LOG_INFO("********** Dispenser %d Misc Command Announced **********", i + 1);
  5852. }
  5853. }
  5854. }
  5855. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.MiscNeedAnnouncement = NeedAnnouncement;
  5856. }
  5857. }
  5858. }
  5859. void CheckDispenserVersionUpdateRequirement(void)
  5860. {
  5861. }
  5862. bool IsReadyParalleling(void)
  5863. {
  5864. bool ready = true;
  5865. for(int i = 0; i < ShmChargerInfo->Control.MaxConnector; i++)
  5866. {
  5867. if(chargingInfo[i]->SystemStatus != S_IDLE && chargingInfo[i]->SystemStatus != S_MAINTAIN)
  5868. {
  5869. ready = false;
  5870. break;
  5871. }
  5872. }
  5873. return ready;
  5874. }
  5875. void SetParallelingStart(void)
  5876. {
  5877. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  5878. {
  5879. if(chargingInfo[i]->SystemStatus == S_IDLE)
  5880. {
  5881. setChargerMode(i, MODE_MAINTAIN);
  5882. }
  5883. }
  5884. ShmChargerInfo->ParallelCabinet.ParallelStatus = _Parallel_Wait;
  5885. }
  5886. void SetParallelingDone(void)
  5887. {
  5888. unsigned short totalPow = 0;
  5889. totalPow = GetTotalParallelCabinetPower();
  5890. if(totalPow != ShmChargerInfo->ParallelCabinet.TotalParallelPower)
  5891. {
  5892. LOG_INFO("Total Parallel Cabinet Power: %d.%d kW", (totalPow / 10), (totalPow % 10));
  5893. }
  5894. ShmChargerInfo->ParallelCabinet.TotalParallelPower = totalPow;
  5895. ShmChargerInfo->ParallelCabinet.ParallelStatus = _Parallel_None;
  5896. }
  5897. void SetPCabinetOutputRelay(unsigned char index, unsigned char OnOff)
  5898. {
  5899. unsigned char relay = 0;
  5900. if(ShmChargerInfo->Control.CabinetRole == _CROLE_MASTER)
  5901. {
  5902. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  5903. {
  5904. if(ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Idle &&
  5905. ShmChargerInfo->ParallelCabinet.PCabinet[i].ParallelConfirm)
  5906. {
  5907. relay = OnOff == YES ? YES : NO;
  5908. if(ShmChargerInfo->ParallelCabinet.PCabinet[index].OutputRelaySetting[index] != relay)
  5909. {
  5910. LOG_INFO("Set Parallel Cabinet Gun %d Output Relay %s", index + 1, relay == YES ? "ON" : "OFF");
  5911. }
  5912. ShmChargerInfo->ParallelCabinet.PCabinet[i].OutputRelaySetting[index] = relay;
  5913. }
  5914. }
  5915. }
  5916. }
  5917. void SetParallelCabinetAcContactor(unsigned char OnOff)
  5918. {
  5919. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  5920. {
  5921. if(ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Idle &&
  5922. ShmChargerInfo->ParallelCabinet.PCabinet[i].ParallelConfirm)
  5923. {
  5924. ShmChargerInfo->ParallelCabinet.PCabinet[i].AcContactorSetting = OnOff == YES ? YES : NO;
  5925. }
  5926. }
  5927. }
  5928. unsigned short GetTotalParallelCabinetPower(void)
  5929. {
  5930. unsigned short power = 0, slavePow = 0;
  5931. if(ShmChargerInfo->Control.CabinetRole == _CROLE_MASTER)
  5932. {
  5933. for(int i = 0; i < MAX_SLAVE_CABINET_QUANTITY; i++)
  5934. {
  5935. if(ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Idle ||
  5936. ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Alarm ||
  5937. ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Charging)
  5938. {
  5939. slavePow = ParsingRatingPower((char *)ShmChargerInfo->ParallelCabinet.PCabinet[i].ModelName);
  5940. power += slavePow;
  5941. }
  5942. }
  5943. }
  5944. return power;
  5945. }
  5946. unsigned char preParallelStatus = 0;
  5947. void MCabinetParallelingProcess(void)
  5948. {
  5949. bool PsuReInitial = false;
  5950. unsigned char status = 0;
  5951. if(ShmChargerInfo->Control.CabinetRole == _CROLE_MASTER)
  5952. {
  5953. if(IsReadyParalleling())
  5954. {
  5955. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  5956. {
  5957. if(ShmChargerInfo->ParallelCabinet.PCabinet[i].ParallelRequest)
  5958. {
  5959. ShmChargerInfo->ParallelCabinet.PCabinet[i].ParallelRequest = false;
  5960. ShmChargerInfo->ParallelCabinet.PCabinet[i].ParallelConfirm = true;
  5961. PsuReInitial = true;
  5962. }
  5963. }
  5964. if(PsuReInitial)
  5965. {
  5966. SetParallelingStart();
  5967. }
  5968. }
  5969. status = ShmChargerInfo->ParallelCabinet.ParallelStatus;
  5970. switch(status)
  5971. {
  5972. case _Parallel_None:
  5973. if(preParallelStatus != status)
  5974. {
  5975. LOG_INFO("MCabinet Parallel Status [None]");
  5976. GetClockTime(&_Parallel_Time);
  5977. }
  5978. unsigned short totalPow = 0;
  5979. totalPow = GetTotalParallelCabinetPower();
  5980. if(totalPow != ShmChargerInfo->ParallelCabinet.TotalParallelPower)
  5981. {
  5982. LOG_INFO("Total Parallel Cabinet Power: %d.%d kW", (totalPow / 10), (totalPow % 10));
  5983. }
  5984. ShmChargerInfo->ParallelCabinet.TotalParallelPower = totalPow;
  5985. break;
  5986. case _Parallel_Wait:
  5987. if(preParallelStatus != status)
  5988. {
  5989. LOG_INFO("MCabinet Parallel Status [Wait]");
  5990. SetAcContactor(OFF);
  5991. SetParallelCabinetAcContactor(OFF);
  5992. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  5993. {
  5994. SetPCabinetOutputRelay(i, OFF);
  5995. }
  5996. GetClockTime(&_Parallel_Time);
  5997. }
  5998. if((GetTimeoutValue(_Parallel_Time) / uSEC_VAL) >= PARALLEL_WAIT_TIME)
  5999. {
  6000. ShmChargerInfo->ParallelCabinet.ParallelStatus = _Parallel_Working;
  6001. }
  6002. break;
  6003. case _Parallel_Working:
  6004. if(preParallelStatus != status)
  6005. {
  6006. LOG_INFO("MCabinet Parallel Status [Working]");
  6007. SetAcContactor(ON);
  6008. SetParallelCabinetAcContactor(ON);
  6009. GetClockTime(&_Parallel_Time);
  6010. }
  6011. if(ShmPsuData->Work_Step == _WORK_CHARGING)
  6012. {
  6013. ShmChargerInfo->ParallelCabinet.ParallelStatus = _Parallel_Done;
  6014. }
  6015. break;
  6016. case _Parallel_Done:
  6017. if(preParallelStatus != status)
  6018. {
  6019. LOG_INFO("MCabinet Parallel Status [Done]");
  6020. GetClockTime(&_Parallel_Time);
  6021. }
  6022. if((GetTimeoutValue(_Parallel_Time) / uSEC_VAL) >= PARALLEL_WAIT_TIME)
  6023. {
  6024. SetParallelingDone();
  6025. }
  6026. break;
  6027. }
  6028. preParallelStatus = status;
  6029. }
  6030. }
  6031. void SCabinetControllProcess(void)
  6032. {
  6033. if(ShmChargerInfo->Control.CabinetRole == _CROLE_SLAVE)
  6034. {
  6035. if(ShmChargerInfo->SCabinetControl.SAcContactor)
  6036. {
  6037. SetAcContactor(ON);
  6038. }
  6039. else
  6040. {
  6041. SetAcContactor(OFF);
  6042. }
  6043. unsigned short _parallelRelay = 0;
  6044. for(int i = 0; i < GENERAL_GUN_QUANTITY; i++)
  6045. {
  6046. _parallelRelay = ShmChargerInfo->SCabinetControl.SParallelRelay[i] > 0 ? (1 < i) : 0;
  6047. }
  6048. if(_parallelRelay != ShmChargerInfo->PsuGrouping.ParallelRelayConfig.CtrlValue)
  6049. {
  6050. LOG_INFO("SCabinet Set Parallel Relay %X -> %X", ShmChargerInfo->PsuGrouping.ParallelRelayConfig.CtrlValue, _parallelRelay);
  6051. }
  6052. ShmChargerInfo->PsuGrouping.ParallelRelayConfig.CtrlValue = _parallelRelay;
  6053. }
  6054. }
  6055. void CheckConnectorDisconnectionRecovery(unsigned char connector)
  6056. {
  6057. unsigned char dispenser = 0;
  6058. dispenser = ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].ParentDispensetIndex;
  6059. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].LocalStatus != _DS_Timeout)
  6060. {
  6061. LOG_INFO("Connector %d Disconnection Recovery", connector + 1);
  6062. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].Parameter.bits.Disconnection = false;
  6063. }
  6064. }
  6065. bool ConnectorRequestToCharging(unsigned char connector)
  6066. {
  6067. unsigned char role = 0;
  6068. bool done = false;
  6069. role = ShmPsuGrouping->GroupCollection[connector].Role;
  6070. switch(role)
  6071. {
  6072. case _GROLE_IDLE:
  6073. if(!ShmPsuGrouping->GroupCollection[connector].GroupCtrl.bits.ChargingRequest)
  6074. {
  6075. LOG_INFO("Request Gun %d To Start Charging", connector + 1);
  6076. }
  6077. ShmPsuGrouping->GroupCollection[connector].GroupCtrl.bits.ChargingRequest = true;
  6078. break;
  6079. case _GROLE_MASTER:
  6080. done = true;
  6081. break;
  6082. case _GROLE_SLAVE:
  6083. if(!ShmPsuGrouping->GroupCollection[connector].GroupCtrl.bits.SlaveChargingRequest)
  6084. {
  6085. LOG_INFO("Gun %d Wait For Re-Grouping", connector + 1);
  6086. }
  6087. ShmPsuGrouping->GroupCollection[connector].GroupCtrl.bits.SlaveChargingRequest = true;
  6088. break;
  6089. case _GROLE_REQUEST_TO_CHARGING:
  6090. done = true;
  6091. break;
  6092. default:
  6093. break;
  6094. }
  6095. return done;
  6096. }
  6097. bool IsConnectorGroupingCompleted(unsigned char connector)
  6098. {
  6099. unsigned char role = 0;
  6100. bool completed = false;
  6101. role = ShmPsuGrouping->GroupCollection[connector].Role;
  6102. switch(role)
  6103. {
  6104. case _GROLE_MASTER:
  6105. completed = true;
  6106. break;
  6107. default:
  6108. break;
  6109. }
  6110. return completed;
  6111. }
  6112. void SelfTestFailReason(void)
  6113. {
  6114. char reason[50];
  6115. memset(reason, 0x00, sizeof(reason));
  6116. if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip)
  6117. {
  6118. StatusCodeCompose(reason, "042251");
  6119. }
  6120. else if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PrimaryStestFail ||
  6121. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RelayboardStestFail ||
  6122. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FanboardStestFail)
  6123. {
  6124. if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RelayboardStestFail)
  6125. {
  6126. StatusCodeCompose(reason, "042280");
  6127. }
  6128. if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FanboardStestFail)
  6129. {
  6130. StatusCodeCompose(reason, "042281");
  6131. }
  6132. if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PrimaryStestFail)
  6133. {
  6134. StatusCodeCompose(reason, "042282");
  6135. }
  6136. }
  6137. else if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcContactStestFail ||
  6138. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuModuleStestFail)
  6139. {
  6140. if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcContactStestFail)
  6141. {
  6142. StatusCodeCompose(reason, "042285");
  6143. }
  6144. if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuModuleStestFail)
  6145. {
  6146. StatusCodeCompose(reason, "042286");
  6147. }
  6148. }
  6149. else
  6150. {
  6151. StatusCodeCompose(reason, "Self Test Fail");
  6152. }
  6153. for (byte gun_index = 0; gun_index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun_index++)
  6154. {
  6155. SetOcppErrorCode(gun_index, "InternalError");
  6156. SetOcppVendorErrorCode(gun_index, reason);
  6157. setChargerMode(gun_index, MODE_MAINTAIN);
  6158. }
  6159. }
  6160. int main(void)
  6161. {
  6162. unsigned long time = 0;
  6163. if(CreateShareMemory() == 0)
  6164. {
  6165. #ifdef SystemLogMessage
  6166. LOG_ERROR("CreatShareMemory NG");
  6167. #endif
  6168. if(ShmStatusCodeData!=NULL)
  6169. {
  6170. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory = 1;
  6171. }
  6172. sleep(5);
  6173. system("reboot -f");
  6174. sleep(5);
  6175. system("reboot -f");
  6176. }
  6177. LOG_INFO("\n");
  6178. LOG_INFO("===== Boot and Initialization start =====");
  6179. LOG_INFO("Main Fork PID = %d", getpid());
  6180. if (!InitialSystemDefaultConfig())
  6181. {
  6182. LOG_INFO("InitialSystemDefaultConfig NG");
  6183. StopProcessingLoop();
  6184. }
  6185. LOG_INFO("ModelName: [%s], SN: [%s], SW Version: [%s]",
  6186. ShmSysConfigAndInfo->SysConfig.ModelName, ShmSysConfigAndInfo->SysConfig.SerialNumber, fwVersion);
  6187. LOG_INFO("InitialShareMemoryInfo");
  6188. InitialShareMemoryInfo();
  6189. LOG_INFO("ChargerType (IEC or UL) = %d", ShmSysConfigAndInfo->SysInfo.ChargerType);
  6190. ChangeLcmByIndex(_LCM_INIT);
  6191. if(!InitialChargerSetting())
  6192. {
  6193. isModelNameMatch = false;
  6194. }
  6195. Initialization();
  6196. LOG_INFO("Spawn all Task.");
  6197. SpawnTask();
  6198. if (!isModelNameMatch)
  6199. {
  6200. LOG_INFO("Module Name & HW info none match.");
  6201. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ModelNameNoneMatchStestFail = YES;
  6202. ChangeLcmByIndex(_LCM_FIX);
  6203. // Module Name 與硬體對應不正確
  6204. LOG_ERROR("Module Name & HW info none match.");
  6205. sleep(3);
  6206. KillAllTask();
  6207. StopProcessingLoop();
  6208. }
  6209. LOG_INFO("Module Name & HW info correct. Initialize.......");
  6210. CreateTimeoutFork();
  6211. SelfTestRun();
  6212. while(ShmSysConfigAndInfo->SysInfo.BootingStatus != BOOT_COMPLETE)
  6213. {
  6214. sleep(1);
  6215. }
  6216. if(ShmSysConfigAndInfo->SysInfo.SelfTestSeq != _STEST_COMPLETE)
  6217. {
  6218. sleep(1);
  6219. SelfTestFailReason();
  6220. }
  6221. else
  6222. {
  6223. for (byte gun_index = 0; gun_index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun_index++)
  6224. {
  6225. setChargerMode(gun_index, MODE_IDLE);
  6226. if(ShmPsuData->PsuGroup[gun_index].GroupPresentPsuQuantity > 0)
  6227. {
  6228. ShmChargerInfo->Control.GunAvailable[gun_index] = YES;
  6229. }
  6230. }
  6231. }
  6232. if(ShmChargerInfo->Control.CabinetRole != _CROLE_SLAVE)
  6233. {
  6234. SetAcContactor(ON);
  6235. SpawnOcppService();
  6236. }
  6237. else
  6238. {
  6239. InitSlaveCabinetEthernet();
  6240. for (byte gun_index = 0; gun_index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun_index++)
  6241. {
  6242. setChargerMode(gun_index, MODE_MAINTAIN);
  6243. }
  6244. }
  6245. // Local DB
  6246. if(DB_Open(localDb) != PASS)
  6247. {
  6248. LOG_INFO("DB_Open fail.");
  6249. isDb_ready = false;
  6250. }
  6251. else
  6252. {
  6253. isDb_ready = true;
  6254. for(int _index=0; _index< ShmSysConfigAndInfo->SysConfig.TotalConnectorCount;_index++)
  6255. {
  6256. chargingInfo[_index]->IsAvailable = DB_Get_Operactive(localDb, _index);
  6257. }
  6258. }
  6259. ChangeLcmByIndex(_LCM_IDLE);
  6260. sleep(1);
  6261. CreateWatchdog();
  6262. // Main loop
  6263. LOG_INFO("%s \n", ShmSysConfigAndInfo->SysInfo.SelfTestSeq == _STEST_COMPLETE ?
  6264. "****************************Main Loop**********************************" :
  6265. "********************** SelfTest Fail **********************");
  6266. GetClockTime(&_cmdMainPriority_time);
  6267. for (;;)
  6268. {
  6269. CheckOcppStatus();
  6270. ChkPrimaryStatus();
  6271. ChkPsuStatus();
  6272. PsuFailureResume();
  6273. if ((IsConnectorWholeIdle() || ShmSysConfigAndInfo->SysInfo.PageIndex == _LCM_FIX) &&
  6274. ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag != Timeout_ReturnToChargingGunDet)
  6275. {
  6276. CheckFactoryConfigFunction();
  6277. CheckFwUpdateFunction();
  6278. }
  6279. if(CheckWiringInfoUpdate() != YES)
  6280. {
  6281. // return fork process
  6282. return 0;
  6283. }
  6284. CheckSoftHardReset();
  6285. StandbyCheck();
  6286. // OCPP 邏輯
  6287. //OcppRemoteStartChk();
  6288. // 讀卡邏輯
  6289. //ScannerCardProcess();
  6290. PowerCabinetAuthorizeProcess();
  6291. // 當 AC 沒有搭上時,清除一些錯誤碼
  6292. ClearAlarmCodeWhenAcOff();
  6293. if ((GetTimeoutValue(_cmdMainPriority_time) / uSEC_VAL) > MAIN_PRIORITY_INTERVAL)
  6294. {
  6295. CheckTask();
  6296. for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++)
  6297. {
  6298. if((chargingInfo[_index]->SystemStatus >= S_PREPARING_FOR_EVSE && chargingInfo[_index]->SystemStatus <= S_CHARGING) ||
  6299. (chargingInfo[_index]->SystemStatus >= S_CCS_PRECHARGE_ST0 && chargingInfo[_index]->SystemStatus <= S_CCS_PRECHARGE_ST1))
  6300. {
  6301. if (chargingInfo[_index]->SystemStatus == S_CHARGING && _ocppProfileChkFlag[_index] == 12)
  6302. {
  6303. Ocpp_ProfileReq_Cmd(_index);
  6304. gunOutputVol[_index] = chargingInfo[_index]->PresentChargingVoltage;
  6305. _ocppProfileChkFlag[_index] = 0;
  6306. }
  6307. else if (chargingInfo[_index]->SystemStatus != S_CHARGING)
  6308. {
  6309. Ocpp_ProfileReq_Cmd(_index);
  6310. _ocppProfileChkFlag[_index] = 0;
  6311. }
  6312. else
  6313. {
  6314. _ocppProfileChkFlag[_index]++;
  6315. }
  6316. }
  6317. }
  6318. GetClockTime(&_cmdMainPriority_time);
  6319. }
  6320. CheckMiscCommandRequirement();
  6321. CheckDispenserVersionUpdateRequirement();
  6322. MCabinetParallelingProcess();
  6323. SCabinetControllProcess();
  6324. for (byte gun_index = 0; gun_index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun_index++)
  6325. {
  6326. //CheckGpioInStatus();
  6327. CheckErrorOccurStatus(gun_index);
  6328. ChkOcppStatus(gun_index);
  6329. if((chargingInfo[gun_index]->SystemStatus >= S_PREPARING_FOR_EVSE && chargingInfo[gun_index]->SystemStatus <= S_CHARGING) ||
  6330. (chargingInfo[gun_index]->SystemStatus >= S_CCS_PRECHARGE_ST0 && chargingInfo[gun_index]->SystemStatus <= S_CCS_PRECHARGE_ST1))
  6331. {
  6332. if(chargingInfo[gun_index]->SystemStatus == S_CHARGING)
  6333. {
  6334. // 進充電後,如果輸出電壓落差大於 10V 則直接繼續看 ChargingProfile
  6335. if (chargingInfo[gun_index]->PresentChargingVoltage >= gunOutputVol[gun_index] + 10 ||
  6336. chargingInfo[gun_index]->PresentChargingVoltage <= gunOutputVol[gun_index] - 10)
  6337. {
  6338. _ocppProfileChkFlag[gun_index] = 12;
  6339. gunOutputVol[gun_index] = chargingInfo[gun_index]->PresentChargingVoltage;
  6340. }
  6341. }
  6342. }
  6343. CheckSmartChargeProfile(gun_index);
  6344. //LOG_INFO("index = %d, ErrorCode = %s \n", gun_index, ShmOCPP16Data->StatusNotification[gun_index].ErrorCode);
  6345. switch(chargingInfo[gun_index]->SystemStatus)
  6346. {
  6347. case S_MAINTAIN:
  6348. if(isModeChange(gun_index))
  6349. {
  6350. if(ShmChargerInfo->Control.CabinetRole == _CROLE_SLAVE)
  6351. {
  6352. LOG_INFO("================== Slave Cabinet %d ==================", ShmChargerInfo->Control.CabinetSwitch - 1);
  6353. }
  6354. LOG_INFO("================== S_MAINTAIN (%x) ================== \n", gun_index + 1);
  6355. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.AvailabilityRequest = true;
  6356. GetClockTime(&_SystemStatus_Time[gun_index]);
  6357. }
  6358. time = GetSecTimeoutValue(_SystemStatus_Time[gun_index]);
  6359. if(ShmSysConfigAndInfo->SysInfo.BootingStatus != BOOT_COMPLETE ||
  6360. ShmSysConfigAndInfo->SysInfo.SelfTestSeq != _STEST_COMPLETE ||
  6361. ShmChargerInfo->Control.CabinetRole == _CROLE_SLAVE)
  6362. {
  6363. break;
  6364. }
  6365. if(chargingInfo[gun_index]->IsAvailable == YES &&
  6366. (ShmChargerInfo->Control.GunAvailable[gun_index] == YES || ShmPsuData->PsuGroup[gun_index].GroupPresentPsuQuantity > 0) &&
  6367. ShmChargerInfo->ParallelCabinet.ParallelStatus == _Parallel_None)
  6368. {
  6369. if(time >= MAINTAIN_RECOVERY_TIME)
  6370. {
  6371. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.AvailabilityRequest = true;
  6372. setChargerMode(gun_index, MODE_IDLE);
  6373. }
  6374. }
  6375. break;
  6376. case S_IDLE:
  6377. case S_RESERVATION:
  6378. case S_FAULT:
  6379. {
  6380. // clean PermissionRequest flag
  6381. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PermissionRequest = false;
  6382. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable = true;
  6383. if(isModeChange(gun_index))
  6384. {
  6385. if (chargingInfo[gun_index]->SystemStatus == S_IDLE)
  6386. {
  6387. LOG_INFO("================== S_IDLE (%x) ================== \n", gun_index + 1);
  6388. chargingInfo[gun_index]->PresentChargedDuration = 0;
  6389. chargingInfo[gun_index]->RemainChargingDuration = 0;
  6390. strcpy((char *)chargingInfo[gun_index]->StartDateTime, "");
  6391. strcpy((char *)chargingInfo[gun_index]->StopDateTime, "");
  6392. strcpy((char *)chargingInfo[gun_index]->StartUserId, "");
  6393. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "");
  6394. ReleaseAlarmCode(gun_index);
  6395. // clean connector information
  6396. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].AuthorizingType = _AuthType_None;
  6397. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].AuthorizingResult = _AuthResult_None;
  6398. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteChargingVoltage = 0;
  6399. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteChargingCurrent = 0;
  6400. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteRemainChargingDuration = 0;
  6401. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteSoc = 0;
  6402. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].UserPrice = 0;
  6403. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].TotalCost = 0;
  6404. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].AccountBalance = -6553500;
  6405. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.AnnounceBalance = false;
  6406. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.StartWaitPlug = false;
  6407. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.NeedCleanAuthorizeInfo = false;
  6408. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.OutputLimitEnable = false;
  6409. chargingInfo[gun_index]->EvBatterytargetVoltage = 0;
  6410. chargingInfo[gun_index]->EvBatterytargetCurrent = 0;
  6411. chargingInfo[gun_index]->EvBatteryMaxVoltage = 0;
  6412. chargingInfo[gun_index]->EvBatterySoc = 0;
  6413. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteTargetVoltage = 0;
  6414. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteTargetCurrent = 0;
  6415. // clean RemoteStart & RemoteStop flag
  6416. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.RemoteStartRequest = false;
  6417. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.RemoteStartConfirm = false;
  6418. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.RemoteStopRequest = false;
  6419. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.RemoteStopConfirm = false;
  6420. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.UnlockStopRequest = false;
  6421. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.UnlockStopConfirm = false;
  6422. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.NormalStopRequest = false;
  6423. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.AlarmStopRequest = false;
  6424. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.FaultStatusRequest = false;
  6425. memset(chargingInfo[gun_index]->ConnectorAlarmCode, 0x00, sizeof(chargingInfo[gun_index]->ConnectorAlarmCode));
  6426. memset(&ShmOCPP16Data->Cost.RunningCost[gun_index], 0x00, sizeof(struct StrcutRunningCost));
  6427. memset(&ShmOCPP16Data->Cost.FinalCost[gun_index], 0x00, sizeof(struct StrcutFinalCost));
  6428. chargingInfo[gun_index]->PresentChargedEnergy = 0;
  6429. chargingInfo[gun_index]->PresentChargingPower = 0;
  6430. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].MaxTotalChargingPower = 0;
  6431. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].MaxTotalChargingCurrent = 0;
  6432. chargingInfo[gun_index]->ChargingProfilePower = -1;
  6433. chargingInfo[gun_index]->ChargingProfileCurrent = -1;
  6434. // clean force charging info
  6435. memset(&ShmChargerInfo->Control.FCharging[gun_index], 0x00, sizeof(ForceCharging));
  6436. }
  6437. else if (chargingInfo[gun_index]->SystemStatus == S_RESERVATION)
  6438. {
  6439. LOG_INFO("================== S_RESERVATION (%x) ================== \n", gun_index + 1);
  6440. ShmOCPP16Data->CsMsg.bits[gun_index].ReserveNowConf = YES;
  6441. }
  6442. else if (chargingInfo[gun_index]->SystemStatus == S_FAULT)
  6443. {
  6444. LOG_INFO("================== S_FAULT (%x) ================== \n", gun_index + 1);
  6445. }
  6446. GetClockTime(&_SystemStatus_Time[gun_index]);
  6447. }
  6448. if (chargingInfo[gun_index]->IsAvailable == NO ||
  6449. (ShmChargerInfo->Control.GunAvailable[gun_index] == NO && ShmPsuData->PsuGroup[gun_index].GroupPresentPsuQuantity == 0))
  6450. {
  6451. setChargerMode(gun_index, MODE_MAINTAIN);
  6452. continue;
  6453. }
  6454. if (ShmSysConfigAndInfo->SysWarningInfo.Level == 2 ||
  6455. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteStatus == _CRS_Alarm ||
  6456. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.FaultStatusRequest ||
  6457. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.Disconnection)
  6458. {
  6459. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.FaultStatusRequest)
  6460. {
  6461. if(strncmp((char *)chargingInfo[gun_index]->ConnectorAlarmCode, "", 6) == EQUAL)
  6462. {
  6463. memcpy(chargingInfo[gun_index]->ConnectorAlarmCode, ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemotenAlarmCode, 6);
  6464. }
  6465. }
  6466. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.FaultStatusRequest = false;
  6467. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.Disconnection)
  6468. {
  6469. if(strncmp((char *)chargingInfo[gun_index]->ConnectorAlarmCode, "", 6) == EQUAL)
  6470. {
  6471. memcpy(chargingInfo[gun_index]->ConnectorAlarmCode, "042304", 6);
  6472. LOG_INFO("Connector %d Disconnect Occur", gun_index + 1);
  6473. }
  6474. }
  6475. if(chargingInfo[gun_index]->SystemStatus != S_FAULT)
  6476. {
  6477. ClearDetectPluginFlag();
  6478. UpdateErrorCodeToOcpp(gun_index);
  6479. setChargerMode(gun_index, MODE_FAULT);
  6480. }
  6481. else
  6482. {
  6483. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.Disconnection)
  6484. {
  6485. CheckConnectorDisconnectionRecovery(gun_index);
  6486. }
  6487. }
  6488. }
  6489. else
  6490. {
  6491. if (chargingInfo[gun_index]->SystemStatus == S_FAULT)
  6492. {
  6493. time = GetSecTimeoutValue(_SystemStatus_Time[gun_index]);
  6494. if(time >= FAULT_RELEASE_TIME)
  6495. {
  6496. ReleaseAlarmCode(gun_index);
  6497. setChargerMode(gun_index, MODE_IDLE);
  6498. }
  6499. break;
  6500. }
  6501. // clean stop charge flag
  6502. chargingInfo[gun_index]->StopChargeFlag = false;
  6503. chargingInfo[gun_index]->ChargingStopFlag.ChargingStopValue = 0;
  6504. { // Idle 正常程序起點
  6505. // 判斷是否有啟用檢查插槍
  6506. if(IsConnectorAuthorizeSuccess(gun_index))
  6507. {
  6508. if(chargingInfo[gun_index]->IsAvailable &&
  6509. chargingInfo[gun_index]->SystemStatus == S_IDLE)
  6510. {
  6511. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].AuthorizingType == _AuthType_RemoteStart)
  6512. {
  6513. LOG_INFO("Connector %d remote start charging", gun_index + 1);
  6514. }
  6515. else if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].AuthorizingType == _AuthType_RFID)
  6516. {
  6517. LOG_INFO("Connector %d swipe rfid start charging", gun_index + 1);
  6518. }
  6519. setChargerMode(gun_index, MODE_AUTHORIZING);
  6520. continue;
  6521. }
  6522. }
  6523. else if(IsAutoGunSelectionAuthorizeSuccess(gun_index))
  6524. {
  6525. if(chargingInfo[gun_index]->IsAvailable &&
  6526. chargingInfo[gun_index]->SystemStatus == S_IDLE &&
  6527. chargingInfo[gun_index]->ConnectorPlugIn &&
  6528. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteStatus == _CRS_Preparing)
  6529. {
  6530. strcpy((char *)chargingInfo[gun_index]->StartUserId, (char *)ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].ParentDispensetIndex].UserId);
  6531. LOG_INFO("Auto Gun Selection %d, CardNumber = %s", gun_index, chargingInfo[gun_index]->StartUserId);
  6532. DispenserAuthorizationInitial(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].ParentDispensetIndex);
  6533. setChargerMode(gun_index, MODE_REASSIGN_CHECK);
  6534. continue;
  6535. }
  6536. }
  6537. else if (chargingInfo[gun_index]->SystemStatus == S_RESERVATION)
  6538. {
  6539. if (!isReservationExpired(gun_index))
  6540. {
  6541. chargingInfo[gun_index]->SystemStatus = S_IDLE;
  6542. }
  6543. }
  6544. // only for test & debug purpose
  6545. else if(ShmChargerInfo->Control.FCharging[gun_index].FCtrl.bits.EnableForceCharging &&
  6546. ShmChargerInfo->Control.FCharging[gun_index].FCtrl.bits.StartForceCharging)
  6547. {
  6548. ShmChargerInfo->Control.FCharging[gun_index].FCtrl.bits.StartForceCharging = false;
  6549. LOG_INFO("Gun %d Start Force Charging", gun_index + 1);
  6550. setChargerMode(gun_index, MODE_REASSIGN_CHECK);
  6551. continue;
  6552. }
  6553. else
  6554. {
  6555. }
  6556. } // Idle 正常程序終點
  6557. }
  6558. }
  6559. break;
  6560. case S_AUTHORIZING:
  6561. if(isModeChange(gun_index))
  6562. {
  6563. LOG_INFO("================== S_AUTHORIZING (%x) ================== \n", gun_index + 1);
  6564. ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
  6565. if (ShmSysConfigAndInfo->SysInfo.OrderCharging != NO_DEFINE)
  6566. ShmSysConfigAndInfo->SysInfo.OrderCharging = NO_DEFINE;
  6567. //StopSystemTimeoutDet();
  6568. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable = false;
  6569. SetAcContactor(ON);
  6570. GetClockTime(&_ConnectorAuthorizing_Time[gun_index]);
  6571. }
  6572. if(GetTimeoutValue(_ConnectorAuthorizing_Time[gun_index]) / uSEC_VAL >= FORCE_BALANCE_TIME)
  6573. {
  6574. FouceAnnounceAccountBalance(gun_index);
  6575. }
  6576. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].AuthorizingType == _AuthType_RemoteStart)
  6577. {
  6578. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.RemoteStartConfirm)
  6579. {
  6580. // sync with dispenser
  6581. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.RemoteStartConfirm = false;
  6582. GetClockTime(&_ConnectorAuthorizing_Time[gun_index]);
  6583. LOG_INFO("Sync with Gun %d through remote start", gun_index + 1);
  6584. FouceAnnounceAccountBalance(gun_index);
  6585. }
  6586. }
  6587. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].AuthorizingType == _AuthType_RFID)
  6588. {
  6589. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.SwipeRfidConfirm)
  6590. {
  6591. // sync with dispenser
  6592. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.SwipeRfidConfirm = false;
  6593. GetClockTime(&_ConnectorAuthorizing_Time[gun_index]);
  6594. LOG_INFO("Sync with Connector %d through swipe rfid", gun_index + 1);
  6595. }
  6596. }
  6597. if(GetTimeoutValue(_ConnectorAuthorizing_Time[gun_index]) / uSEC_VAL >= ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectorTimeout)
  6598. {
  6599. if(!chargingInfo[gun_index]->ConnectorPlugIn)
  6600. {
  6601. LOG_INFO("*********** Gun %d Plug In Timeout ***********", gun_index + 1);
  6602. }
  6603. else
  6604. {
  6605. LOG_INFO("*********** Gun %d Preparing State Timeout ***********", gun_index + 1);
  6606. }
  6607. setChargerMode(gun_index, MODE_IDLE);
  6608. ConnectorAuthorizationInitial(gun_index);
  6609. }
  6610. else
  6611. {
  6612. if(chargingInfo[gun_index]->ConnectorPlugIn &&
  6613. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteStatus == _CRS_Preparing)
  6614. {
  6615. AddPlugInTimes(gun_index);
  6616. LOG_INFO("index = %d, CardNumber = %s \n", gun_index, chargingInfo[gun_index]->StartUserId);
  6617. setChargerMode(gun_index, MODE_REASSIGN_CHECK);
  6618. ConnectorAuthorizationInitial(gun_index);
  6619. }
  6620. else if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.NeedCleanAuthorizeInfo)
  6621. {
  6622. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.StartWaitPlug = false;
  6623. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.NeedCleanAuthorizeInfo = false;
  6624. LOG_INFO("*********** Gun %d User Stop Plug In ***********", gun_index + 1);
  6625. setChargerMode(gun_index, MODE_IDLE);
  6626. ConnectorAuthorizationInitial(gun_index);
  6627. }
  6628. else if(isEvBoardStopChargeFlag(gun_index) == YES)
  6629. {
  6630. LOG_INFO("********** Gun %d Alarm Stop (S_AUTHORIZING) **********", gun_index + 1);
  6631. setChargerMode(gun_index, MODE_IDLE);
  6632. ConnectorAuthorizationInitial(gun_index);
  6633. }
  6634. }
  6635. break;
  6636. case S_REASSIGN_CHECK:
  6637. {
  6638. if (isModeChange(gun_index))
  6639. {
  6640. LOG_INFO("================== S_REASSIGN_CHECK (%x) ================== \n", gun_index + 1);
  6641. ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
  6642. if (ShmSysConfigAndInfo->SysInfo.OrderCharging != NO_DEFINE)
  6643. ShmSysConfigAndInfo->SysInfo.OrderCharging = NO_DEFINE;
  6644. //StopSystemTimeoutDet();
  6645. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable = false;
  6646. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].MaxOutputEnergy = ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy;
  6647. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].MaxOutputDuration = ShmSysConfigAndInfo->SysConfig.MaxChargingDuration;
  6648. LOG_INFO("Max Total Current %d A, Max Total Power %d kW, Total Energy %d kWh, Total Duration %d",
  6649. ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent,
  6650. ShmSysConfigAndInfo->SysConfig.MaxChargingPower,
  6651. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].MaxOutputEnergy,
  6652. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].MaxOutputDuration);
  6653. SetAcContactor(ON);
  6654. SetPCabinetOutputRelay(gun_index, ON);
  6655. GetClockTime(&_SystemStatus_Time[gun_index]);
  6656. }
  6657. time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
  6658. if(ConnectorRequestToCharging(gun_index))
  6659. {
  6660. setChargerMode(gun_index, MODE_REASSIGN);
  6661. }
  6662. else if(time >= WAIT_REASSIGN_TIME)
  6663. {
  6664. if(ShmPsuData->Work_Step != _WORK_CHARGING)
  6665. {
  6666. LOG_INFO("Gun %d Wait PSU Work Step Timeout", gun_index + 1);
  6667. }
  6668. else
  6669. {
  6670. LOG_INFO("Gun %d Request Charging Timeout", gun_index + 1);
  6671. }
  6672. setChargerMode(gun_index, MODE_IDLE);
  6673. }
  6674. }
  6675. break;
  6676. case S_REASSIGN:
  6677. {
  6678. if (isModeChange(gun_index))
  6679. {
  6680. LOG_INFO("================== S_REASSIGN (%x) ================== \n", gun_index + 1);
  6681. //gettimeofday(&_toAverage_time, NULL);
  6682. GetClockTime(&_SystemStatus_Time[gun_index]);
  6683. }
  6684. time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
  6685. if(IsConnectorGroupingCompleted(gun_index))
  6686. {
  6687. setChargerMode(gun_index, MODE_PRECHARGE);
  6688. }
  6689. else if(time >= MAX_REQUEST_CHARGING_TIME)
  6690. {
  6691. LOG_INFO("Gun %d Grouping Timeout", gun_index + 1);
  6692. setChargerMode(gun_index, MODE_IDLE);
  6693. }
  6694. }
  6695. break;
  6696. case S_PREPARNING:
  6697. {
  6698. if (isModeChange(gun_index))
  6699. {
  6700. LOG_INFO("================== S_PREPARNING (%x) ================== \n", gun_index + 1);
  6701. //StopGunInfoTimeoutDet(gun_index);
  6702. //StartGunInfoTimeoutDet(gun_index, Timeout_Preparing);
  6703. SetAcContactor(ON);
  6704. GetClockTime(&_SystemStatus_Time[gun_index]);
  6705. }
  6706. time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
  6707. if ((chargingInfo[gun_index]->AvailableChargingPower > 10) && time >= MIN_WAIT_PREPARNING_TIME)
  6708. {
  6709. setChargerMode(gun_index, MODE_PREPARE_FOR_EV);
  6710. continue;
  6711. }
  6712. if (isEvBoardStopChargeFlag(gun_index) == YES)
  6713. {
  6714. // 板端或後臺要求停止
  6715. LOG_INFO("********** Gun %d Alarm Stop (S_PREPARNING) **********", gun_index + 1);
  6716. if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "") == EQUAL)
  6717. {
  6718. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
  6719. }
  6720. ChargingAlarmProcess(gun_index);
  6721. }
  6722. else if(isNormalStopChargeFlag(gun_index) == YES)
  6723. {
  6724. LOG_INFO("********** Gun %d Normal Stop (S_PREPARNING) %s**********", gun_index + 1,
  6725. chargingInfo[gun_index]->ChargingStopFlag.bits.ManualStop ? "(ManualStop)" : "");
  6726. if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "") == EQUAL)
  6727. {
  6728. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EVDisconnected");
  6729. }
  6730. ChargingTerminalProcess(gun_index);
  6731. }
  6732. if(time > GUN_PREPARE_TIMEOUT)
  6733. {
  6734. LOG_INFO("********** Gun %d PrepareTimeout **********", gun_index + 1);
  6735. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuNoResource = YES;
  6736. if(strncmp((char *)chargingInfo[gun_index]->ConnectorAlarmCode, "", 6) == EQUAL)
  6737. {
  6738. memcpy(chargingInfo[gun_index]->ConnectorAlarmCode, "012279", 6);
  6739. LOG_INFO("Gun %d No Psu Resource", gun_index + 1);
  6740. }
  6741. if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "") == EQUAL)
  6742. {
  6743. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
  6744. }
  6745. ChargingAlarmProcess(gun_index);
  6746. }
  6747. }
  6748. break;
  6749. case S_PREPARING_FOR_EV: // 等待車端的通訊 (EV 小板),待車端回報後,開始樁端的測試
  6750. {
  6751. if (isModeChange(gun_index))
  6752. {
  6753. LOG_INFO("================== S_PREPARING_FOR_EV (%x) ================== \n", gun_index + 1);
  6754. //strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
  6755. //StopGunInfoTimeoutDet(gun_index);
  6756. //StartGunInfoTimeoutDet(gun_index, Timeout_EvChargingDet);
  6757. GetClockTime(&_SystemStatus_Time[gun_index]);
  6758. }
  6759. time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
  6760. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PermissionRequest)
  6761. {
  6762. setChargerMode(gun_index, MODE_PREPARE_FOR_EVSE);
  6763. }
  6764. // only for test & debug purpose
  6765. else if(ShmChargerInfo->Control.FCharging[gun_index].FCtrl.bits.EnableForceCharging)
  6766. {
  6767. LOG_INFO("Gun %d [Force Charging] S_PREPARING_FOR_EV OK", gun_index + 1);
  6768. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PermissionRequest = true;
  6769. }
  6770. if (isEvBoardStopChargeFlag(gun_index) == YES)
  6771. {
  6772. // 板端或後臺要求停止
  6773. LOG_INFO("********** Gun %d Alarm Stop (S_PREPARING_FOR_EV) **********", gun_index + 1);
  6774. if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "") == EQUAL)
  6775. {
  6776. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
  6777. }
  6778. ChargingAlarmProcess(gun_index);
  6779. }
  6780. else if(isNormalStopChargeFlag(gun_index) == YES)
  6781. {
  6782. LOG_INFO("********** Gun %d Normal Stop (S_PREPARING_FOR_EV) %s**********", gun_index + 1,
  6783. chargingInfo[gun_index]->ChargingStopFlag.bits.ManualStop ? "(ManualStop)" : "");
  6784. if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "") == EQUAL)
  6785. {
  6786. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EVDisconnected");
  6787. }
  6788. ChargingTerminalProcess(gun_index);
  6789. }
  6790. if(time >= GUN_EV_WAIT_TIMEOUT)
  6791. {
  6792. LOG_INFO("********** Gun %d Wait Dispenser Timeout **********", gun_index + 1);
  6793. ChargingTerminalProcess(gun_index);
  6794. }
  6795. }
  6796. break;
  6797. case S_PREPARING_FOR_EVSE: // 等待 RB 通訊及測試,並將狀態回報, CSU 確認 Pass 後,開始進入充電
  6798. {
  6799. if (isModeChange(gun_index))
  6800. {
  6801. LOG_INFO("================== S_PREPARING_FOR_EVSE (%x) ================== \n", gun_index + 1);
  6802. //StopGunInfoTimeoutDet(gun_index);
  6803. //StartGunInfoTimeoutDet(gun_index, Timeout_EvseChargingDet);
  6804. GetClockTime(&_SystemStatus_Time[gun_index]);
  6805. }
  6806. time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
  6807. // only for test & debug purpose
  6808. if(ShmChargerInfo->Control.FCharging[gun_index].FCtrl.bits.EnableForceCharging)
  6809. {
  6810. float voltage = (float)ShmChargerInfo->Control.FCharging[gun_index].FTargetVoltage / 10;
  6811. float current = (float)ShmChargerInfo->Control.FCharging[gun_index].FTargetCurrent / 10;
  6812. if(chargingInfo[gun_index]->EvBatterytargetVoltage != voltage || chargingInfo[gun_index]->EvBatterytargetCurrent != current)
  6813. {
  6814. LOG_INFO("Gun %d Set Force Charging Voltage %4d V, Current: %4d A", gun_index + 1, (int)voltage, (int)current);
  6815. }
  6816. chargingInfo[gun_index]->EvBatterytargetVoltage = voltage;
  6817. chargingInfo[gun_index]->EvBatterytargetCurrent = current;
  6818. }
  6819. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteStatus == _CRS_Charging)
  6820. {
  6821. setChargerMode(gun_index, MODE_CHARGING);
  6822. }
  6823. // only for test & debug purpose
  6824. else if(ShmChargerInfo->Control.FCharging[gun_index].FCtrl.bits.EnableForceCharging)
  6825. {
  6826. if(time >= FORCE_CHARGING_WAIT_EVSE)
  6827. {
  6828. LOG_INFO("Gun %d [Charging Simulation] S_PREPARING_FOR_EVSE OK", gun_index + 1);
  6829. setChargerMode(gun_index, MODE_CHARGING);
  6830. }
  6831. }
  6832. if (isEvBoardStopChargeFlag(gun_index) == YES)
  6833. {
  6834. // 板端或後臺要求停止
  6835. LOG_INFO("********** Gun %d Alarm Stop (S_PREPARING_FOR_EVSE) **********", gun_index + 1);
  6836. if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "") == EQUAL)
  6837. {
  6838. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
  6839. }
  6840. ChargingAlarmProcess(gun_index);
  6841. }
  6842. else if(isNormalStopChargeFlag(gun_index) == YES)
  6843. {
  6844. LOG_INFO("********** Gun %d Normal Stop (S_PREPARING_FOR_EVSE) %s**********", gun_index + 1,
  6845. chargingInfo[gun_index]->ChargingStopFlag.bits.ManualStop ? "(ManualStop)" : "");
  6846. if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "") == EQUAL)
  6847. {
  6848. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EVDisconnected");
  6849. }
  6850. ChargingTerminalProcess(gun_index);
  6851. }
  6852. if(time >= GUN_EVSE_WAIT_TIMEOUT)
  6853. {
  6854. LOG_INFO("********** Gun %d GFD timeout **********", gun_index + 1);
  6855. ChargingTerminalProcess(gun_index);
  6856. }
  6857. }
  6858. break;
  6859. case S_CHARGING: // 剛進入充電狀態,等待 EV 小板要求的輸出電流後開始輸出
  6860. {
  6861. if (isModeChange(gun_index))
  6862. {
  6863. LOG_INFO("================== S_CHARGING (%x) ================== \n", gun_index + 1);
  6864. //StopGunInfoTimeoutDet(gun_index);
  6865. GetClockTime(&_SystemStatus_Time[gun_index]);
  6866. chargingInfo[gun_index]->PresentChargedDuration = 0;
  6867. ChangeStartOrStopDateTime(YES, gun_index);
  6868. OcppStartTransation(gun_index);
  6869. }
  6870. // only for test & debug purpose
  6871. if(ShmChargerInfo->Control.FCharging[gun_index].FCtrl.bits.EnableForceCharging)
  6872. {
  6873. float voltage = (float)ShmChargerInfo->Control.FCharging[gun_index].FTargetVoltage / 10;
  6874. float current = (float)ShmChargerInfo->Control.FCharging[gun_index].FTargetCurrent / 10;
  6875. if(chargingInfo[gun_index]->EvBatterytargetVoltage != voltage || chargingInfo[gun_index]->EvBatterytargetCurrent != current)
  6876. {
  6877. LOG_INFO("Gun %d Set Force Charging Voltage %4d V, Current: %4d A", gun_index + 1, (int)voltage, (int)current);
  6878. }
  6879. chargingInfo[gun_index]->EvBatterytargetVoltage = voltage;
  6880. chargingInfo[gun_index]->EvBatterytargetCurrent = current;
  6881. }
  6882. time = GetSecTimeoutValue(_SystemStatus_Time[gun_index]);
  6883. // 計算 Power
  6884. //chargingInfo[gun_index]->PresentChargingPower = ((float)((chargingInfo[gun_index]->PresentChargingVoltage) * (chargingInfo[gun_index]->PresentChargingCurrent)) / 1000);
  6885. chargingInfo[gun_index]->PresentChargingPower = (((float)((ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteChargingVoltage) * (ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteChargingCurrent))) / 1000 / 100);
  6886. if(time >= (chargingInfo[gun_index]->PresentChargedDuration + ENERAGY_INTERVAL))
  6887. {
  6888. chargingInfo[gun_index]->PresentChargedDuration++;
  6889. float changingPow = (chargingInfo[gun_index]->PresentChargingPower) / 3600;
  6890. if (ShmSysConfigAndInfo->SysConfig.BillingData.isBilling)
  6891. {
  6892. chargingInfo[gun_index]->ChargingFee += changingPow * ShmSysConfigAndInfo->SysConfig.BillingData.Cur_fee;
  6893. }
  6894. chargingInfo[gun_index]->PresentChargedEnergy += changingPow;
  6895. chargingInfo[gun_index]->PowerConsumption += changingPow;
  6896. }
  6897. if (isEvBoardStopChargeFlag(gun_index))
  6898. {
  6899. LOG_INFO("********** Gun %d Alarm Stop (S_CHARGING) **********", gun_index + 1);
  6900. if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "") == EQUAL)
  6901. {
  6902. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
  6903. }
  6904. ChargingAlarmProcess(gun_index);
  6905. }
  6906. else if(isNormalStopChargeFlag(gun_index) == YES)
  6907. {
  6908. LOG_INFO("********** Gun %d Normal Stop (S_CHARGING) %s**********", gun_index + 1,
  6909. chargingInfo[gun_index]->ChargingStopFlag.bits.ManualStop ? "(ManualStop)" : "");
  6910. if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "") == EQUAL)
  6911. {
  6912. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EVDisconnected");
  6913. }
  6914. ChargingTerminalProcess(gun_index);
  6915. }
  6916. else if(CheckBackendChargingTimeout(gun_index) ||
  6917. CheckBackendChargingEnergy(gun_index))
  6918. {
  6919. LOG_INFO("********** Gun %d Backend Stop (S_CHARGING) **********", gun_index + 1);
  6920. // 板端或後臺要求停止
  6921. ChargingTerminalProcess(gun_index);
  6922. }
  6923. else if(ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionConf)
  6924. {
  6925. if(Ocpp_CheckInvalidId(gun_index))
  6926. {
  6927. LOG_INFO("********** Gun %d Backend InvalidId Stop (S_CHARGING) **********", gun_index + 1);
  6928. ChargingTerminalProcess(gun_index);
  6929. }
  6930. }
  6931. if(ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionConf)
  6932. {
  6933. ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionConf = NO;
  6934. if(strcmp((char *)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Accepted") == EQUAL)
  6935. {
  6936. LOG_INFO("Gun %d OCPP Start Transaction Accepted, Id = %d", gun_index + 1, ShmOCPP16Data->StartTransaction[gun_index].ResponseTransactionId);
  6937. }
  6938. }
  6939. }
  6940. break;
  6941. case S_ALARM:
  6942. case S_TERMINATING:
  6943. {
  6944. if (isModeChange(gun_index))
  6945. {
  6946. if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "") == EQUAL)
  6947. {
  6948. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Other");
  6949. }
  6950. if (chargingInfo[gun_index]->SystemStatus == S_ALARM)
  6951. {
  6952. LOG_INFO("================== S_ALARM (%x) ================== \n", gun_index + 1);
  6953. UpdateErrorCodeToOcpp(gun_index);
  6954. if (strcmp((char *)chargingInfo[gun_index]->StartDateTime, "") != EQUAL)
  6955. {
  6956. OcppStopTransation(gun_index);
  6957. }
  6958. TheEndCharging(gun_index);
  6959. }
  6960. else
  6961. {
  6962. LOG_INFO("================== S_TERMINATING (%x) ================== \n", gun_index + 1);
  6963. }
  6964. //StopGunInfoTimeoutDet(gun_index);
  6965. GetClockTime(&_SystemStatus_Time[gun_index]);
  6966. }
  6967. time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
  6968. if (chargingInfo[gun_index]->SystemStatus == S_ALARM)
  6969. {
  6970. if(time >= GUN_COMP_WAIT_TIMEOUT)
  6971. {
  6972. if(!ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable)
  6973. {
  6974. LOG_INFO ("********** Gun %d psu is releasable **********\n", gun_index + 1);
  6975. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable = true;
  6976. }
  6977. }
  6978. if((ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteStatus == _CRS_Idle || ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Enable == false) &&
  6979. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable)
  6980. {
  6981. setChargerMode(gun_index, MODE_IDLE);
  6982. }
  6983. }
  6984. else
  6985. {
  6986. setChargerMode(gun_index, MODE_COMPLETE);
  6987. }
  6988. }
  6989. break;
  6990. case S_COMPLETE:
  6991. {
  6992. if (isModeChange(gun_index))
  6993. {
  6994. LOG_INFO("================== S_COMPLETE (%x) ================== \n", gun_index + 1);
  6995. if (strcmp((char *)chargingInfo[gun_index]->StartDateTime, "") != EQUAL)
  6996. {
  6997. OcppStopTransation(gun_index);
  6998. }
  6999. TheEndCharging(gun_index);
  7000. GetClockTime(&_SystemStatus_Time[gun_index]);
  7001. }
  7002. time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
  7003. if(time >= GUN_COMP_WAIT_TIMEOUT)
  7004. {
  7005. if(!ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable)
  7006. {
  7007. LOG_INFO ("********** Gun %d psu is releasable **********", gun_index + 1);
  7008. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable = true;
  7009. }
  7010. }
  7011. if((ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteStatus == _CRS_Idle || ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Enable == false) &&
  7012. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable)
  7013. {
  7014. setChargerMode(gun_index, MODE_IDLE);
  7015. }
  7016. }
  7017. break;
  7018. case S_CCS_PRECHARGE_ST0:
  7019. if (isModeChange(gun_index))
  7020. {
  7021. LOG_INFO("CCS Precharge Processing 1....................%x \n", gun_index);
  7022. //StopGunInfoTimeoutDet(gun_index);
  7023. //StartGunInfoTimeoutDet(gun_index, Timeout_ForCcsPrechargeDet);
  7024. }
  7025. break;
  7026. case S_CCS_PRECHARGE_ST1:
  7027. if (isModeChange(gun_index))
  7028. {
  7029. LOG_INFO("CCS Precharge Processing 2....................%x \n", gun_index);
  7030. }
  7031. break;
  7032. }
  7033. }
  7034. if (ShmSysConfigAndInfo->SysInfo.SystemPage != _LCM_NONE)
  7035. {
  7036. ChangeLcmByIndex(ShmSysConfigAndInfo->SysInfo.SystemPage);
  7037. }
  7038. else
  7039. {
  7040. bool dcPageRun = true;
  7041. if (dcPageRun)
  7042. ChangeLcmByIndex(ShmSysConfigAndInfo->SysInfo.ConnectorPage);
  7043. }
  7044. TryFeedWatchdog();
  7045. usleep(whileLoopTime);
  7046. }
  7047. return FAIL;
  7048. }