main.c 280 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949
  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.06.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. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.DcInputOVP)
  2838. {
  2839. if (ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess == _EXTRA_ERR_PROCESS_NONE)
  2840. {
  2841. ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess = _EXTRA_ERR_PROCESS_INOVP;
  2842. StopChargingProcessByString(2);
  2843. }
  2844. if (strncmp((char *)chargingInfo[index]->ConnectorAlarmCode, "", 6) == EQUAL)
  2845. {
  2846. if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL1InputOVP == YES)
  2847. memcpy(chargingInfo[index]->ConnectorAlarmCode, "042200", 6);
  2848. else if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL2InputOVP == YES)
  2849. memcpy(chargingInfo[index]->ConnectorAlarmCode, "042201", 6);
  2850. else if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemL3InputOVP == YES)
  2851. memcpy(chargingInfo[index]->ConnectorAlarmCode, "042202", 6);
  2852. else if (ShmStatusCodeData->AlarmCode.AlarmEvents.bits.DcInputOVP == YES)
  2853. memcpy(chargingInfo[index]->ConnectorAlarmCode, "042327", 6);
  2854. }
  2855. if(!chargingInfo[index]->ChargingStopFlag.bits.AlarmStop)
  2856. {
  2857. LOG_INFO("Connector %d RC Board Input OVP Occur %s", index + 1, chargingInfo[index]->ConnectorAlarmCode);
  2858. }
  2859. chargingInfo[index]->ChargingStopFlag.bits.AlarmStop = true;
  2860. }
  2861. else
  2862. {
  2863. if (ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess == _EXTRA_ERR_PROCESS_INOVP)
  2864. {
  2865. ShmSysConfigAndInfo->SysWarningInfo.ExtraErrProcess = _EXTRA_ERR_PROCESS_NONE;
  2866. ReleaseChargingProcessByString(2);
  2867. }
  2868. }
  2869. }
  2870. /*
  2871. //===============================================
  2872. // 確認 GPIO 狀態
  2873. //===============================================
  2874. void gpio_set_value(unsigned int gpio, unsigned int value)
  2875. {
  2876. int fd;
  2877. char buf[MAX_BUF];
  2878. snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%d/value", gpio);
  2879. fd = open(buf, O_WRONLY);
  2880. if (fd < 0)
  2881. {
  2882. perror("gpio/set-value");
  2883. return;
  2884. }
  2885. if (value)
  2886. write(fd, "1", 2);
  2887. else
  2888. write(fd, "0", 2);
  2889. close(fd);
  2890. }
  2891. int gpio_get_value(unsigned int gpio, unsigned int *value)
  2892. {
  2893. int fd;
  2894. char buf[MAX_BUF];
  2895. char ch;
  2896. snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%d/value", gpio);
  2897. fd = open(buf, O_RDONLY);
  2898. if (fd < 0) {
  2899. perror("gpio/get-value");
  2900. return fd;
  2901. }
  2902. read(fd, &ch, 1);
  2903. if (ch != '0') {
  2904. *value = 1;
  2905. } else {
  2906. *value = 0;
  2907. }
  2908. close(fd);
  2909. return 0;
  2910. }
  2911. void CheckGpioInStatus()
  2912. {
  2913. int pinIn[2] = { 27, 47 };
  2914. unsigned int gpioValue = 0;
  2915. for (int i = 0; i < ARRAY_SIZE(pinIn); i++)
  2916. {
  2917. gpio_get_value(pinIn[i], &gpioValue);
  2918. if (gpioValue == 0x01)
  2919. {
  2920. switch(pinIn[i])
  2921. {
  2922. // 小板緊急停止
  2923. case 47:
  2924. {
  2925. for(int i = 0; i < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; i++)
  2926. {
  2927. if (chargingInfo[i]->slotsIndex == 1)
  2928. {
  2929. if (chargingInfo[i]->Type == _Type_Chademo)
  2930. BoardErrOccurByString(i, "023730");
  2931. else if (chargingInfo[i]->Type == _Type_CCS_2)
  2932. BoardErrOccurByString(i, "013627");
  2933. break;
  2934. }
  2935. }
  2936. }
  2937. break;
  2938. case 27:
  2939. {
  2940. for(int i = 0; i < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; i++)
  2941. {
  2942. if (chargingInfo[i]->slotsIndex == 3)
  2943. {
  2944. if (chargingInfo[i]->Type == _Type_Chademo)
  2945. BoardErrOccurByString(i, "023730");
  2946. else if (chargingInfo[i]->Type == _Type_CCS_2)
  2947. BoardErrOccurByString(i, "013627");
  2948. break;
  2949. }
  2950. }
  2951. }
  2952. break;
  2953. }
  2954. }
  2955. else
  2956. {
  2957. switch (pinIn[i])
  2958. {
  2959. // 小板解除緊急停止
  2960. case 47:
  2961. {
  2962. for(int i = 0; i < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; i++)
  2963. {
  2964. if (chargingInfo[i]->slotsIndex == 1)
  2965. {
  2966. if (chargingInfo[i]->Type == _Type_Chademo)
  2967. ReleaseBoardErrOccurByString(i, "023730");
  2968. else if (chargingInfo[i]->Type == _Type_CCS_2)
  2969. ReleaseBoardErrOccurByString(i, "013627");
  2970. break;
  2971. }
  2972. }
  2973. }
  2974. break;
  2975. case 27:
  2976. {
  2977. for (int i = 0; i < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; i++)
  2978. {
  2979. if (chargingInfo[i]->slotsIndex == 3)
  2980. {
  2981. if (chargingInfo[i]->Type == _Type_Chademo)
  2982. ReleaseBoardErrOccurByString(i, "023730");
  2983. else if (chargingInfo[i]->Type == _Type_CCS_2)
  2984. ReleaseBoardErrOccurByString(i, "013627");
  2985. break;
  2986. }
  2987. }
  2988. }
  2989. break;
  2990. }
  2991. }
  2992. }
  2993. }
  2994. */
  2995. //===============================================
  2996. // Main process
  2997. //===============================================
  2998. // 檢查 Byte 中某個 Bit 的值
  2999. // _byte : 欲改變的 byte
  3000. // _bit : 該 byte 的第幾個 bit
  3001. unsigned char DetectBitValue(unsigned char _byte, unsigned char _bit)
  3002. {
  3003. return ( _byte & mask_table[_bit] ) != 0x00;
  3004. }
  3005. // 設定 Byte 中某個 Bit的值
  3006. // _byte : 欲改變的 byte
  3007. // _bit : 該 byte 的第幾個 bit
  3008. // value : 修改的值為 0 or 1
  3009. void SetBitValue(unsigned char *_byte, unsigned char _bit, unsigned char value)
  3010. {
  3011. if(value == 1)
  3012. *_byte |= (1 << _bit);
  3013. else if (value == 0)
  3014. *_byte ^= (1 << _bit);
  3015. }
  3016. void UserScanFunction()
  3017. {
  3018. }
  3019. unsigned char isModeChange(unsigned char gun_index)
  3020. {
  3021. unsigned char result = NO;
  3022. if(chargingInfo[gun_index]->SystemStatus != chargingInfo[gun_index]->PreviousSystemStatus)
  3023. {
  3024. result = YES;
  3025. chargingInfo[gun_index]->PreviousSystemStatus = chargingInfo[gun_index]->SystemStatus;
  3026. }
  3027. return result;
  3028. }
  3029. void ScannerCardProcess()
  3030. {
  3031. }
  3032. struct timespec _StartAuthorizing_Time;
  3033. void PowerCabinetAuthorizingSettingInitial(void)
  3034. {
  3035. ShmSysConfigAndInfo->SysInfo.AuthorizedDispenser = 0;
  3036. ShmSysConfigAndInfo->SysInfo.AuthorizedTarget = 0;
  3037. ShmSysConfigAndInfo->SysInfo.AuthorizedType = _AuthResult_None;
  3038. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_Idle;
  3039. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.StartAuthorize = false;
  3040. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.AuthorizingCompleted = false;
  3041. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.BackendAuthorized = false;
  3042. }
  3043. void AnnounceAccountBalance(unsigned char index, int balance)
  3044. {
  3045. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].Parameter.bits.AnnounceBalance = true;
  3046. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].AccountBalance = balance;
  3047. if(!ShmChargerInfo->Control.TestCtrl.bits.DisableBalance)
  3048. {
  3049. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].Parameter.bits.AccountBalanceRequest = true;
  3050. }
  3051. LOG_INFO("%sAnnounce Account Balance %d To Connector %d",
  3052. ShmChargerInfo->Control.TestCtrl.bits.DisableBalance ? "Do Not " : "", balance, index + 1);
  3053. }
  3054. void FouceAnnounceAccountBalance(unsigned char index)
  3055. {
  3056. if(!ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].Parameter.bits.AnnounceBalance)
  3057. {
  3058. AnnounceAccountBalance(index, 0);
  3059. }
  3060. }
  3061. void CleanConnectorUserIdAndPrice(unsigned char index)
  3062. {
  3063. if(chargingInfo[index]->SystemStatus == S_IDLE)
  3064. {
  3065. LOG_INFO("*********** Connector %d Clean UserId & UserPrice ***********", index + 1);
  3066. memset(chargingInfo[index]->StartUserId, 0x00, 32);
  3067. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].UserPrice = 0;
  3068. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].AccountBalance = -6553500;
  3069. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].Parameter.bits.AnnounceBalance = false;
  3070. }
  3071. }
  3072. void DispenserAuthorizationInitial(unsigned char dispenser)
  3073. {
  3074. LOG_INFO("*********** Dispenser %d Authorizing Initial ***********", dispenser + 1);
  3075. memset(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].UserId, 0x00, 32);
  3076. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_Idle;
  3077. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthTarget = 0;
  3078. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthType = _AuthType_None;
  3079. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult = _AuthResult_None;
  3080. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].Setting.bits.EnableAutoGunSelection = false;
  3081. }
  3082. void ConnectorAuthorizationInitial(unsigned char connector)
  3083. {
  3084. LOG_INFO("*********** Connector %d Authorizing Initial ***********", connector + 1);
  3085. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].AuthorizingType = _AuthType_None;
  3086. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].AuthorizingResult = _AuthResult_None;
  3087. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].Parameter.bits.SwipeRfidConfirm = false;
  3088. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].Parameter.bits.RemoteStartRequest = false;
  3089. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].Parameter.bits.RemoteStartConfirm = false;
  3090. chargingInfo[connector]->RemoteStartFlag = false;
  3091. CleanConnectorUserIdAndPrice(connector);
  3092. }
  3093. void SetAuthorizingTarget(unsigned char dispenser, unsigned char target, unsigned char type)
  3094. {
  3095. memset(ShmSysConfigAndInfo->SysConfig.UserId, 0x00, 32);
  3096. switch(type)
  3097. {
  3098. case _AuthType_RFID:
  3099. LOG_INFO("*********** Dispenser %d Target %02X RFID Authorize ***********", dispenser + 1, target);
  3100. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].UserId, 32);
  3101. break;
  3102. case _AuthType_RemoteStart:
  3103. LOG_INFO("*********** Connector %d Remote Start Authorize ***********", target);
  3104. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmOCPP16Data->RemoteStartTransaction[target - 1].IdTag, 20);
  3105. break;
  3106. }
  3107. if(target == AUTO_GUN_SELECTION)
  3108. {
  3109. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].Setting.bits.EnableAutoGunSelection = true;
  3110. }
  3111. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_Busy;
  3112. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthType = type;
  3113. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.StartAuthorize = true;
  3114. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.AuthorizingCompleted = false;
  3115. ShmSysConfigAndInfo->SysInfo.AuthorizedDispenser = dispenser;
  3116. ShmSysConfigAndInfo->SysInfo.AuthorizedTarget = target;
  3117. ShmSysConfigAndInfo->SysInfo.AuthorizedType = type;
  3118. }
  3119. void OCPPAuthorizingStart(void)
  3120. {
  3121. ShmOCPP16Data->SpMsg.bits.AuthorizeConf = false;
  3122. ShmOCPP16Data->SpMsg.bits.AuthorizeReq = true;
  3123. }
  3124. void AuthorizeTimeoutProcess(void)
  3125. {
  3126. for(int index = 0; index < GENERAL_GUN_QUANTITY; index++)
  3127. {
  3128. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].AuthorizingResult == _AuthResult_Invalid)
  3129. {
  3130. FouceAnnounceAccountBalance(index);
  3131. if(GetTimeoutValue(_ConnectorAuthorizeFail_Time[index]) / uSEC_VAL >= AUTHORIZE_FAIL_TIMEOUT)
  3132. {
  3133. LOG_INFO("*********** Connector id %d Authorized Fail Return ***********", index + 1);
  3134. ConnectorAuthorizationInitial(index);
  3135. }
  3136. }
  3137. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].AuthStatus == _AuthorizeStatus_End)
  3138. {
  3139. int CompletedTime = 0;
  3140. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].AuthTarget != AUTO_GUN_SELECTION)
  3141. {
  3142. CompletedTime = DISPENSER_AUTH_COMP_TIME;
  3143. }
  3144. else
  3145. {
  3146. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].AuthResult == _AuthResult_Valid)
  3147. {
  3148. CompletedTime = ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectorTimeout;
  3149. }
  3150. else
  3151. {
  3152. CompletedTime = AUTHORIZE_FAIL_TIMEOUT;
  3153. }
  3154. }
  3155. if(GetTimeoutValue(_DispenserAuthorizing_Time[index]) / uSEC_VAL >= CompletedTime)
  3156. {
  3157. LOG_INFO("*********** Dispenser id %d Authorized Return ***********", index + 1);
  3158. DispenserAuthorizationInitial(index);
  3159. }
  3160. }
  3161. }
  3162. }
  3163. bool IsNewAuthorizingRequest(void)
  3164. {
  3165. bool NewRequest = false;
  3166. bool FindRemoteStartRequest = false;
  3167. // remote start check
  3168. for(int index = 0; index < GENERAL_GUN_QUANTITY; index++)
  3169. {
  3170. if(ShmOCPP16Data->CsMsg.bits[index].RemoteStartTransactionReq == true)
  3171. {
  3172. unsigned char dispenser = ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].ParentDispensetIndex;
  3173. SetAuthorizingTarget(dispenser, index + 1, _AuthType_RemoteStart);
  3174. ShmOCPP16Data->CsMsg.bits[index].RemoteStartTransactionReq = false;
  3175. chargingInfo[index]->RemoteStartFlag = true;
  3176. FindRemoteStartRequest = true;
  3177. NewRequest = true;
  3178. break;
  3179. }
  3180. }
  3181. if(!FindRemoteStartRequest)
  3182. {
  3183. // local rfid authorize check
  3184. for(int index = 0; index < GENERAL_GUN_QUANTITY; index++)
  3185. {
  3186. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].AuthStatus == _AuthorizeStatus_Idle &&
  3187. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].Setting.bits.AuthorizeRequest == true)
  3188. {
  3189. if(strlen((char *)ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].UserId) > 0)
  3190. {
  3191. SetAuthorizingTarget(index, ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].AuthTarget, _AuthType_RFID);
  3192. NewRequest = true;
  3193. }
  3194. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].Setting.bits.AuthorizeRequest = false;
  3195. }
  3196. }
  3197. }
  3198. return NewRequest;
  3199. }
  3200. void PowerCabinetAuthorizeProcess(void)
  3201. {
  3202. unsigned char dispenser = 0, connector = 0;
  3203. dispenser = ShmSysConfigAndInfo->SysInfo.AuthorizedDispenser;
  3204. AuthorizeTimeoutProcess();
  3205. switch(ShmSysConfigAndInfo->SysInfo.AuthorizedStatus)
  3206. {
  3207. case _AuthorizeStatus_Idle:
  3208. if(IsNewAuthorizingRequest())
  3209. {
  3210. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_Wait;
  3211. }
  3212. break;
  3213. case _AuthorizeStatus_Wait:
  3214. if(ShmSysConfigAndInfo->SysInfo.AuthorizedType == _AuthType_RemoteStart)
  3215. {
  3216. LOG_INFO("*********** Connector %d Remote Start Authorizing Bypass ***********",
  3217. ShmSysConfigAndInfo->SysInfo.AuthorizedTarget);
  3218. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.BackendAuthorized = true;
  3219. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult = _AuthResult_Valid;
  3220. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_Done;
  3221. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_Done;
  3222. }
  3223. else
  3224. {
  3225. if(ShmOCPP16Data->OcppConnStatus)
  3226. {
  3227. LOG_INFO("*********** Dispenser %d OPCC AuthorizeReq ***********", dispenser + 1);
  3228. OCPPAuthorizingStart();
  3229. }
  3230. else
  3231. {
  3232. LOG_INFO("*********** Dispenser %d Start Local Authorizing ***********", dispenser + 1);
  3233. }
  3234. // update start authorizing timeout
  3235. GetClockTime(&_StartAuthorizing_Time);
  3236. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_Busy;
  3237. }
  3238. break;
  3239. case _AuthorizeStatus_Busy:
  3240. if(GetTimeoutValue(_StartAuthorizing_Time) / uSEC_VAL >= AUTHORIZE_TIMEOUT)
  3241. {
  3242. LOG_INFO("*********** Dispenser %d Authorizing Timeout ***********", dispenser + 1);
  3243. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult = _AuthResult_Invalid;
  3244. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_Done;
  3245. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_Done;
  3246. }
  3247. else
  3248. {
  3249. if(ShmOCPP16Data->OcppConnStatus)
  3250. {
  3251. if(ShmOCPP16Data->SpMsg.bits.AuthorizeConf)
  3252. {
  3253. BOOL accept = false;
  3254. if(strcmp((char *)ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status, "Accepted") == EQUAL)
  3255. {
  3256. accept = true;
  3257. }
  3258. LOG_INFO("*********** Dispenser %d OCPP Authorize %s ***********", dispenser + 1, accept ? "OK" : "NG");
  3259. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.BackendAuthorized = true;
  3260. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult = accept ? _AuthResult_Valid : _AuthResult_Invalid;
  3261. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_Done;
  3262. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_Done;
  3263. }
  3264. }
  3265. else
  3266. {
  3267. if(ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_NO_CHARGING)
  3268. {
  3269. LOG_INFO("*********** Dispenser %d No Charging ***********", dispenser + 1);
  3270. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult = _AuthResult_Invalid;
  3271. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_Done;
  3272. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_Done;
  3273. }
  3274. else if(ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_FREE_CHARGING)
  3275. {
  3276. // set authorize pass when offline policy is free charge
  3277. LOG_INFO("*********** Dispenser %d Free Charging ***********", dispenser + 1);
  3278. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult = _AuthResult_Valid;
  3279. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_Done;
  3280. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_Done;
  3281. }
  3282. else if(ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_LOCAL_LIST)
  3283. {
  3284. BOOL find = false;
  3285. // check white list
  3286. for(int i = 0; i < 10; i++)
  3287. {
  3288. if (strcmp((char *)ShmSysConfigAndInfo->SysConfig.LocalWhiteCard[i], "") != EQUAL)
  3289. {
  3290. if (strcmp((char *)ShmSysConfigAndInfo->SysConfig.LocalWhiteCard[i], (char *)ShmSysConfigAndInfo->SysConfig.UserId) == EQUAL)
  3291. {
  3292. find = true;
  3293. LOG_INFO("*********** Dispenser %d White Card OK ***********", dispenser + 1);
  3294. break;
  3295. }
  3296. }
  3297. }
  3298. if(find == false)
  3299. {
  3300. if(ShmChargerInfo->AuthInfo.AuthMode.bits.AutoStartEnable &&
  3301. strcmp((char *)ShmSysConfigAndInfo->SysConfig.UserId, AUTO_START_CHARGING) == EQUAL)
  3302. {
  3303. find = true;
  3304. LOG_INFO("******** Dispenser %d Auto Start Charging ********", dispenser + 1);
  3305. }
  3306. }
  3307. LOG_INFO("*********** Dispenser %d Local Authorization %s ***********", dispenser + 1, find ? "OK" : "NG");
  3308. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult = find ? _AuthResult_Valid : _AuthResult_Invalid;
  3309. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_Done;
  3310. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_Done;
  3311. }
  3312. else
  3313. {
  3314. LOG_INFO("*********** Dispenser %d Invalid Policy ***********", dispenser + 1);
  3315. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult = _AuthResult_Invalid;
  3316. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_Done;
  3317. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_Done;
  3318. }
  3319. }
  3320. }
  3321. break;
  3322. case _AuthorizeStatus_Done:
  3323. if(ShmSysConfigAndInfo->SysInfo.AuthorizedTarget == AUTO_GUN_SELECTION)
  3324. {
  3325. // auto gun selection
  3326. }
  3327. else
  3328. {
  3329. connector = ShmSysConfigAndInfo->SysInfo.AuthorizedTarget - 1;
  3330. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].AuthorizingType = ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthType;
  3331. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].AuthorizingResult = ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult;
  3332. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].GeneralChargingData.SystemStatus == S_IDLE &&
  3333. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult == _AuthResult_Valid)
  3334. {
  3335. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthType == _AuthType_RFID)
  3336. {
  3337. LOG_INFO("*********** Connector %d RFID Authorize OK ***********", connector + 1);
  3338. memcpy(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].GeneralChargingData.StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, 32);
  3339. }
  3340. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthType == _AuthType_RemoteStart)
  3341. {
  3342. LOG_INFO("*********** Connector id %d RemoteAuthorize OK ***********", connector + 1);
  3343. memcpy(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].GeneralChargingData.StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, 32);
  3344. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].Parameter.bits.RemoteStartRequest = true;
  3345. }
  3346. }
  3347. else if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult == _AuthResult_Invalid)
  3348. {
  3349. // update connector authorizing timeout
  3350. GetClockTime(&_ConnectorAuthorizeFail_Time[connector]);
  3351. }
  3352. }
  3353. // authorize completed
  3354. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.AuthorizingCompleted = true;
  3355. // update dispenser authorizing timeout
  3356. GetClockTime(&_DispenserAuthorizing_Time[dispenser]);
  3357. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_End;
  3358. // update authorizing completed timeout
  3359. GetClockTime(&_StartAuthorizing_Time);
  3360. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_End;
  3361. break;
  3362. case _AuthorizeStatus_End:
  3363. if(GetTimeoutValue(_StartAuthorizing_Time) / uSEC_VAL >= AUTHORIZE_COMP_TIMEOUT)
  3364. {
  3365. LOG_INFO("*********** PowerCabinet Authorize Completed ***********");
  3366. PowerCabinetAuthorizingSettingInitial();
  3367. }
  3368. break;
  3369. default:
  3370. // update authorizing completed timeout
  3371. GetClockTime(&_StartAuthorizing_Time);
  3372. ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_End;
  3373. break;
  3374. }
  3375. }
  3376. BOOL IsConnectorAuthorizeSuccess(unsigned char connector)
  3377. {
  3378. BOOL success = false;
  3379. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].AuthorizingResult == _AuthResult_Valid)
  3380. {
  3381. success = true;
  3382. }
  3383. return success;
  3384. }
  3385. BOOL IsAutoGunSelectionAuthorizeSuccess(unsigned char connector)
  3386. {
  3387. BOOL success = false;
  3388. unsigned char dispenser = 0;
  3389. dispenser = ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].ParentDispensetIndex;
  3390. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].Setting.bits.EnableAutoGunSelection &&
  3391. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult == _AuthResult_Valid)
  3392. {
  3393. success = true;
  3394. }
  3395. return success;
  3396. }
  3397. /*
  3398. bool AddGunInfoByConnector(byte typeValue, byte slots)
  3399. {
  3400. bool result = true;
  3401. switch (typeValue)
  3402. {
  3403. case '0': // none
  3404. break;
  3405. case '1': // IEC 62196-2 Type 1/SAE J1772 Plug
  3406. break;
  3407. case '2': // IEC 62196-2 Type 1/SAE J1772 Socket
  3408. break;
  3409. case '3': // IEC 62196-2 Type 2 Plug
  3410. case '4': // IEC 62196-2 Type 2 Socket
  3411. if (AC_QUANTITY > _ac_Index)
  3412. {
  3413. ac_chargingInfo[_acgunIndex] = &ShmSysConfigAndInfo->SysInfo.AcChargingData[_ac_Index];
  3414. // AC 固定 index
  3415. ac_chargingInfo[_acgunIndex]->Index = 0;
  3416. ac_chargingInfo[_acgunIndex]->ReservationId = -1;
  3417. ac_chargingInfo[_acgunIndex]->SystemStatus = S_IDLE;
  3418. ac_chargingInfo[_acgunIndex]->Type = _Type_AC;
  3419. ac_chargingInfo[_acgunIndex]->IsAvailable = YES;
  3420. _ac_Index++;
  3421. _acgunIndex++;
  3422. }
  3423. else
  3424. result = false;
  3425. break;
  3426. case '5': // GB/T AC Plug
  3427. break;
  3428. case '6': // GB/T AC Socket
  3429. break;
  3430. case 'J': // CHAdeMO
  3431. {
  3432. if (CHAdeMO_QUANTITY > _chademoIndex)
  3433. {
  3434. chargingInfo[_gunIndex] = &ShmSysConfigAndInfo->SysInfo.ChademoChargingData[_chademoIndex];
  3435. chargingInfo[_gunIndex]->Index = _gunIndex;
  3436. chargingInfo[_gunIndex]->ReservationId = -1;
  3437. chargingInfo[_gunIndex]->slotsIndex = slots;
  3438. chargingInfo[_gunIndex]->SystemStatus = S_BOOTING;
  3439. chargingInfo[_gunIndex]->Type = _Type_Chademo;
  3440. chargingInfo[_gunIndex]->type_index = _chademoIndex;
  3441. chargingInfo[_gunIndex]->IsAvailable = YES;
  3442. _chademoIndex++;
  3443. _gunIndex++;
  3444. }
  3445. else
  3446. result = false;
  3447. }
  3448. break;
  3449. case 'U': // CCS1 combo
  3450. case 'E': // CCS2 combo
  3451. {
  3452. if (CCS_QUANTITY > _ccsIndex)
  3453. {
  3454. chargingInfo[_gunIndex] = &ShmSysConfigAndInfo->SysInfo.CcsChargingData[_ccsIndex];
  3455. chargingInfo[_gunIndex]->Index = _gunIndex;
  3456. chargingInfo[_gunIndex]->ReservationId = -1;
  3457. chargingInfo[_gunIndex]->slotsIndex = slots;
  3458. chargingInfo[_gunIndex]->SystemStatus = S_BOOTING;
  3459. chargingInfo[_gunIndex]->Type = _Type_CCS_2;
  3460. chargingInfo[_gunIndex]->type_index = _ccsIndex;
  3461. chargingInfo[_gunIndex]->IsAvailable = YES;
  3462. // 現階段預設為走 DIN70121
  3463. ShmCcsData->CommProtocol = _CCS_COMM_V2GMessage_DIN70121;
  3464. _ccsIndex++;
  3465. _gunIndex++;
  3466. }
  3467. else
  3468. result = false;
  3469. }
  3470. break;
  3471. case 'G': // GBT DC
  3472. {
  3473. if (GB_QUANTITY > _gb_Index)
  3474. {
  3475. chargingInfo[_gunIndex] = &ShmSysConfigAndInfo->SysInfo.GbChargingData[_gb_Index];
  3476. chargingInfo[_gunIndex]->Index = _gunIndex;
  3477. chargingInfo[_gunIndex]->ReservationId = -1;
  3478. chargingInfo[_gunIndex]->slotsIndex = slots;
  3479. chargingInfo[_gunIndex]->SystemStatus = S_BOOTING;
  3480. chargingInfo[_gunIndex]->Type = _Type_GB;
  3481. chargingInfo[_gunIndex]->type_index = _gb_Index;
  3482. chargingInfo[_gunIndex]->IsAvailable = YES;
  3483. _gb_Index++;
  3484. _gunIndex++;
  3485. }
  3486. else
  3487. result = false;
  3488. }
  3489. break;
  3490. case 'D': // GBT DC x 2
  3491. break;
  3492. }
  3493. return result;
  3494. }
  3495. */
  3496. unsigned short ParsingRatingPower(char *modelname)
  3497. {
  3498. char strVal[3], strExp[2];
  3499. unsigned short value = 0, exponent = 0;
  3500. memset(strVal, 0x00, sizeof(strVal));
  3501. memset(strExp, 0x00, sizeof(strExp));
  3502. memcpy(strVal, &modelname[4], 2);
  3503. memcpy(strExp, &modelname[6], 1);
  3504. value = atoi(strVal);
  3505. exponent = atoi(strExp);
  3506. if(value < 0 || exponent < 0)
  3507. {
  3508. return 0;
  3509. }
  3510. for(int i = 0; i < exponent; i++)
  3511. {
  3512. value *= 10;
  3513. }
  3514. return value;
  3515. }
  3516. bool CheckConnectorTypeStatus(void)
  3517. {
  3518. bool result = true;
  3519. if (strlen((char *) ShmSysConfigAndInfo->SysConfig.ModelName) >= 14)
  3520. {
  3521. // DO360 for Audi, two gun only
  3522. _gunIndex = ShmChargerInfo->Control.MaxConnector;
  3523. ShmSysConfigAndInfo->SysConfig.TotalConnectorCount = _gunIndex;
  3524. ShmChargerInfo->Control.ChargerRatingPower = ParsingRatingPower((char *)ShmSysConfigAndInfo->SysConfig.ModelName);
  3525. LOG_INFO("DC Gun Count = %d, RatingPower = %d.%d kW",
  3526. ShmSysConfigAndInfo->SysConfig.TotalConnectorCount,
  3527. (ShmChargerInfo->Control.ChargerRatingPower / 10),
  3528. (ShmChargerInfo->Control.ChargerRatingPower % 10));
  3529. if(ShmSysConfigAndInfo->SysConfig.TotalConnectorCount == 0)
  3530. {
  3531. result = false;
  3532. }
  3533. //DO360 charging info default setting
  3534. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  3535. {
  3536. chargingInfo[i] = &ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].GeneralChargingData;
  3537. chargingInfo[i]->Index = (i < ShmSysConfigAndInfo->SysConfig.WiringInfo.MaxConnectorQuantity || i == 0) ? i : 0xFF;
  3538. chargingInfo[i]->Evboard_id = 0x00;
  3539. chargingInfo[i]->ReservationId = -1;
  3540. chargingInfo[i]->slotsIndex = 0;
  3541. chargingInfo[i]->SystemStatus = S_BOOTING;
  3542. chargingInfo[i]->Type = _Type_Unknown;
  3543. chargingInfo[i]->type_index = 0;
  3544. chargingInfo[i]->IsAvailable = YES;
  3545. }
  3546. }
  3547. else
  3548. {
  3549. // Module Name 不正確 - 告警
  3550. result = false;
  3551. }
  3552. return result;
  3553. }
  3554. void KillTaskExceptPrimary()
  3555. {
  3556. ChangeLcmByIndex(_LCM_FIX);
  3557. system("killall Module_CabinetParallel");
  3558. system("killall Module_ChargerSelfTest");
  3559. system("killall Module_LedIndication");
  3560. system("killall Module_EvComm");
  3561. system("killall Module_InternalComm");
  3562. system("killall Module_PsuComm");
  3563. system("killall Module_4g &");
  3564. system("killall Module_Wifi &");
  3565. }
  3566. void KillAllTask()
  3567. {
  3568. ChangeLcmByIndex(_LCM_FIX);
  3569. system("killall Module_CabinetParallel");
  3570. system("killall Module_ChargerSelfTest");
  3571. system("killall Module_LedIndication");
  3572. system("killall Module_EventLogging");
  3573. system("killall Module_PrimaryComm");
  3574. system("killall Module_EvComm");
  3575. system("killall Module_LcmControl");
  3576. system("killall Module_InternalComm");
  3577. system("killall Module_PsuComm");
  3578. system("killall OcppBackend &");
  3579. system("killall Module_4g &");
  3580. system("killall Module_Wifi &");
  3581. }
  3582. int TransferImageViaFTP(char *IpAddress, char *SourcePath)
  3583. {
  3584. int isPass = PASS;
  3585. unsigned char ftpcmdbuf[256];
  3586. LOG_INFO("Transfer image(%s) to ip: %s ", SourcePath, IpAddress);
  3587. //Using ftpput command to transfer upgrade image,
  3588. //User name : root
  3589. //User password : y42j/4cj84
  3590. //Destination : as same as source path
  3591. sprintf((char*)ftpcmdbuf,"ftpput -u root -p y42j/4cj84 %s %s %s", IpAddress, SourcePath, SourcePath);
  3592. if(system((char*)ftpcmdbuf) != 0)
  3593. {
  3594. isPass = FAIL;
  3595. LOG_INFO("Transfer Image NG - FTP put upgrade image to fail");
  3596. }
  3597. else
  3598. {
  3599. LOG_INFO("FTP put Image OK");
  3600. }
  3601. return isPass;
  3602. }
  3603. void TriggerDispenserUpgrade(unsigned char index, char *FileName)
  3604. {
  3605. memset(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].FwFileName, 0x00, 128);
  3606. memcpy(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].FwFileName, FileName, strlen(FileName));
  3607. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[index].Setting.bits.FirmwareUpdateRequest = true;
  3608. LOG_INFO("Trigger dispenser %d to update image [%s]", index + 1, FileName);
  3609. }
  3610. BOOL PutImageToAllDispenser(char *SourcePath, char *FileName)
  3611. {
  3612. int isPass = FAIL;
  3613. BOOL transferred = FALSE;
  3614. for(int i = 0; i < GENERAL_GUN_QUANTITY; i++)
  3615. {
  3616. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[i].Status == _CNS_DispenserMatched)
  3617. {
  3618. char DispenserIpAddress[16];
  3619. memset((char*)DispenserIpAddress, 0x00, 16);
  3620. sprintf((char*)DispenserIpAddress, "%d.%d.%d.%d",
  3621. ((ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[i].IpAddress >> 0) & 0xFF),
  3622. ((ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[i].IpAddress >> 8) & 0xFF),
  3623. ((ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[i].IpAddress >> 16) & 0xFF),
  3624. ((ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[i].IpAddress >> 24) & 0xFF));
  3625. isPass = TransferImageViaFTP(DispenserIpAddress, SourcePath);
  3626. if(isPass == PASS)
  3627. {
  3628. TriggerDispenserUpgrade(ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectionInfo[i].DispenserIndex, FileName);
  3629. }
  3630. transferred = true;
  3631. }
  3632. }
  3633. return transferred;
  3634. }
  3635. BOOL WaitAllDispenserUpgradeCompleted(void)
  3636. {
  3637. BOOL completed = TRUE;
  3638. GetClockTime(&_DispenserUpgrade_time);
  3639. do
  3640. {
  3641. completed = TRUE;
  3642. for(int i = 0; i < GENERAL_GUN_QUANTITY; i++)
  3643. {
  3644. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.FirmwareUpdateRequest ||
  3645. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.FirmwareUpdateConfirm)
  3646. {
  3647. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.FirmwareUpdateCompleted)
  3648. {
  3649. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.FirmwareUpdateRequest = false;
  3650. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.FirmwareUpdateConfirm = false;
  3651. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.FirmwareUpdateCompleted = false;
  3652. LOG_INFO("Dispenser %d Upgrade Success", i + 1);
  3653. }
  3654. else
  3655. {
  3656. completed = FALSE;
  3657. }
  3658. }
  3659. }
  3660. if(GetTimeoutValue(_DispenserUpgrade_time) / uSEC_VAL >= DISPENSER_UPGRADE_TIME)
  3661. {
  3662. LOG_INFO("Wait Upgrade Timeout");
  3663. completed = FALSE;
  3664. break;
  3665. }
  3666. if(completed == FALSE)
  3667. {
  3668. sleep(1);
  3669. }
  3670. }while(!completed);
  3671. return completed;
  3672. }
  3673. void UpgradePrepare(void)
  3674. {
  3675. int count = 0;
  3676. SetAcContactor(OFF);
  3677. if(ShmChargerInfo->Control.CabinetRole == _CROLE_MASTER)
  3678. {
  3679. for(int i = 0; i < MAX_SLAVE_CABINET_QUANTITY; i++)
  3680. {
  3681. if(ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Idle ||
  3682. ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Alarm ||
  3683. ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Charging)
  3684. {
  3685. count++;
  3686. }
  3687. }
  3688. }
  3689. if(count > 0)
  3690. {
  3691. sleep(3);
  3692. }
  3693. else
  3694. {
  3695. sleep(1);
  3696. }
  3697. }
  3698. void TriggerPCabinetUpgrade(unsigned char index, char *FileName)
  3699. {
  3700. memset(ShmChargerInfo->ParallelCabinet.PCabinet[index].FwFileName, 0x00, 128);
  3701. memcpy(ShmChargerInfo->ParallelCabinet.PCabinet[index].FwFileName, FileName, strlen(FileName));
  3702. ShmChargerInfo->ParallelCabinet.PCabinet[index].UpdateRequest = YES;
  3703. LOG_INFO("Trigger PCabinet %d to update image [%s]", index + 1, FileName);
  3704. }
  3705. BOOL PutImageToAllParallelCabinet(char *SourcePath, char *FileName)
  3706. {
  3707. int isPass = FAIL;
  3708. BOOL transferred = FALSE;
  3709. for(int i = 0; i < MAX_SLAVE_CABINET_QUANTITY; i++)
  3710. {
  3711. if(ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Idle ||
  3712. ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Alarm ||
  3713. ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Charging)
  3714. {
  3715. int channel = ShmChargerInfo->ParallelCabinet.PCabinet[i].SocketChannel;
  3716. if(ShmChargerInfo->CabinetConnInfo[channel].Status == _SCONN_MATCHED &&
  3717. ShmChargerInfo->ParallelCabinet.PCUpdateState[i] == Not_Update)
  3718. {
  3719. char PCabinetIpAddress[16];
  3720. memset((char*)PCabinetIpAddress, 0x00, 16);
  3721. sprintf((char*)PCabinetIpAddress, "%d.%d.%d.%d",
  3722. ((ShmChargerInfo->CabinetConnInfo[channel].IpAddress >> 0) & 0xFF),
  3723. ((ShmChargerInfo->CabinetConnInfo[channel].IpAddress >> 8) & 0xFF),
  3724. ((ShmChargerInfo->CabinetConnInfo[channel].IpAddress >> 16) & 0xFF),
  3725. ((ShmChargerInfo->CabinetConnInfo[channel].IpAddress >> 24) & 0xFF));
  3726. isPass = TransferImageViaFTP(PCabinetIpAddress, SourcePath);
  3727. if(isPass == PASS)
  3728. {
  3729. TriggerPCabinetUpgrade(i, FileName);
  3730. }
  3731. transferred = true;
  3732. }
  3733. }
  3734. }
  3735. return transferred;
  3736. }
  3737. BOOL WaitAllPCabinetStartUpgrade(void)
  3738. {
  3739. BOOL isStart = true;
  3740. int count = 0;
  3741. struct timespec _waitStart;
  3742. GetClockTime(&_waitStart);
  3743. do
  3744. {
  3745. isStart = true;
  3746. count = 0;
  3747. for(int i = 0; i < MAX_SLAVE_CABINET_QUANTITY; i++)
  3748. {
  3749. if(ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Idle ||
  3750. ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Alarm ||
  3751. ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Charging)
  3752. {
  3753. count++;
  3754. if(ShmChargerInfo->ParallelCabinet.PCUpdateState[i] != Updating)
  3755. {
  3756. isStart = false;
  3757. }
  3758. }
  3759. }
  3760. if((GetTimeoutValue(_waitStart) / uSEC_VAL) >= START_UPGRADE_TIME)
  3761. {
  3762. isStart = false;
  3763. break;
  3764. }
  3765. usleep(10000);
  3766. }while(!isStart);
  3767. if(isStart && count > 0)
  3768. {
  3769. LOG_INFO("Total %d PCabinet upgrade start...", count);
  3770. }
  3771. else
  3772. {
  3773. if(count > 0)
  3774. {
  3775. LOG_INFO("Wait PCabinet upgrade timeout");
  3776. }
  3777. else
  3778. {
  3779. LOG_INFO("No PCabinet need to upgrade");
  3780. }
  3781. }
  3782. return isStart;
  3783. }
  3784. BOOL WaitAllPCabinetUpgradeCompleted(void)
  3785. {
  3786. BOOL completed = true;
  3787. int count = 0;
  3788. struct timespec _waitCompleted;
  3789. GetClockTime(&_waitCompleted);
  3790. do
  3791. {
  3792. completed = true;
  3793. count = 0;
  3794. for(int i = 0; i < MAX_SLAVE_CABINET_QUANTITY; i++)
  3795. {
  3796. if(ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Idle ||
  3797. ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Alarm ||
  3798. ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Charging)
  3799. {
  3800. count++;
  3801. if(ShmChargerInfo->ParallelCabinet.PCUpdateState[i] != Updated)
  3802. {
  3803. completed = false;
  3804. }
  3805. }
  3806. }
  3807. if((GetTimeoutValue(_waitCompleted) / uSEC_VAL) >= PCABINET_UPGRADE_TIME)
  3808. {
  3809. completed = false;
  3810. break;
  3811. }
  3812. usleep(10000);
  3813. }while(!completed);
  3814. if(completed && count > 0)
  3815. {
  3816. LOG_INFO("Total %d PCabinet upgrade completed!", count);
  3817. }
  3818. else
  3819. {
  3820. if(count > 0)
  3821. {
  3822. LOG_INFO("Wait PCabinet upgrade completed timeout");
  3823. }
  3824. else
  3825. {
  3826. LOG_INFO("Need not to wait PCabinet completed");
  3827. }
  3828. }
  3829. return completed;
  3830. }
  3831. BOOL WaitMCabinetUpgradeCompleted(void)
  3832. {
  3833. BOOL completed = true;
  3834. struct timespec _waitCompleted;
  3835. GetClockTime(&_waitCompleted);
  3836. do
  3837. {
  3838. completed = false;
  3839. if(ShmChargerInfo->SCabinetControl.NeedUpgrade == _R_NoUpgrade)
  3840. {
  3841. completed = true;
  3842. }
  3843. if(ShmChargerInfo->SCabinetControl.SCabinetStatus != _DeviceStatus_Idle &&
  3844. ShmChargerInfo->SCabinetControl.SCabinetStatus != _DeviceStatus_Alarm &&
  3845. ShmChargerInfo->SCabinetControl.SCabinetStatus != _DeviceStatus_Charging)
  3846. {
  3847. completed = false;
  3848. break;
  3849. }
  3850. if((GetTimeoutValue(_waitCompleted) / uSEC_VAL) >= MCABINET_UPGRADE_TIME)
  3851. {
  3852. completed = false;
  3853. break;
  3854. }
  3855. usleep(10000);
  3856. }while(!completed);
  3857. if(completed)
  3858. {
  3859. LOG_INFO("MCabinet upgrade completed!");
  3860. }
  3861. else
  3862. {
  3863. LOG_INFO("Wait MCabinet upgrade timeout or disconnected...");
  3864. }
  3865. return completed;
  3866. }
  3867. bool IsModelNameMatch(char *model)
  3868. {
  3869. if(ShmSysConfigAndInfo->SysConfig.ModelName[0] == model[0] &&
  3870. ShmSysConfigAndInfo->SysConfig.ModelName[1] == model[1] &&
  3871. ShmSysConfigAndInfo->SysConfig.ModelName[7] == model[7] &&
  3872. ShmSysConfigAndInfo->SysConfig.ModelName[8] == model[8] &&
  3873. ShmSysConfigAndInfo->SysConfig.ModelName[9] == model[9] &&
  3874. ShmSysConfigAndInfo->SysConfig.ModelName[11] == model[11] &&
  3875. ShmSysConfigAndInfo->SysConfig.ModelName[12] == model[12] &&
  3876. ShmSysConfigAndInfo->SysConfig.ModelName[13] == model[13])
  3877. {
  3878. return true;
  3879. }
  3880. return false;
  3881. }
  3882. char CheckUpdateProcess()
  3883. {
  3884. char model[32];
  3885. bool support = false;
  3886. bool OneImageOnly = false;
  3887. int isPass = true;
  3888. uint8_t retSucc = 0;
  3889. uint8_t retFail = 0;
  3890. byte target = 0;
  3891. char *new_str = NULL;
  3892. unsigned char *ptr = NULL;
  3893. int fd = 0;
  3894. int uartFd = 0;
  3895. unsigned int Type = 0;
  3896. long int MaxLen = 48 * 1024 * 1024, ImageLen = 0;
  3897. DIR *d;
  3898. struct dirent *dir;
  3899. char cmdBuf[128];
  3900. d = opendir("/mnt/");
  3901. if(d)
  3902. {
  3903. while((dir = readdir(d)) != NULL && !OneImageOnly)
  3904. {
  3905. if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0) {
  3906. continue;
  3907. }
  3908. new_str = calloc(strlen("/mnt/") + strlen(dir->d_name) + 1, sizeof(char));
  3909. strcat(new_str, "/mnt/");
  3910. strcat(new_str, dir->d_name);
  3911. fd = open(new_str, O_RDONLY);
  3912. if(fd < 0)
  3913. {
  3914. close(fd);
  3915. free(new_str);
  3916. continue;
  3917. }
  3918. LOG_INFO("%s\n", new_str);
  3919. ptr = calloc(MaxLen, sizeof(char)); //-48 is take out the header
  3920. memset(ptr, 0xFF, MaxLen); //-48 is take out the header
  3921. //get the image length
  3922. ImageLen = read(fd, ptr, MaxLen);
  3923. if (ImageLen > 20)
  3924. {
  3925. support = false;
  3926. memcpy(model, ptr, 16);
  3927. LOG_INFO("Model: %s", model);
  3928. Type = (((unsigned int)ptr[16]) << 24 | ((unsigned int)ptr[17]) << 16 | ((unsigned int)ptr[18]) << 8 | ((unsigned int)ptr[19]));
  3929. LOG_INFO("Typed...%x", Type);
  3930. //if(strcmp(model, (char *)ShmSysConfigAndInfo->SysConfig.ModelName) == EQUAL)
  3931. if(IsModelNameMatch(model))
  3932. {
  3933. if(ShmChargerInfo->Control.CabinetRole == _CROLE_MASTER)
  3934. {
  3935. PutImageToAllParallelCabinet(new_str, dir->d_name);
  3936. WaitAllPCabinetStartUpgrade();
  3937. }
  3938. if(ShmChargerInfo->Control.CabinetRole == _CROLE_SLAVE && ShmChargerInfo->SCabinetControl.NeedUpgrade)
  3939. {
  3940. ShmChargerInfo->SCabinetControl.UpgradeState = Updating;
  3941. sleep(1);
  3942. }
  3943. switch (Type)
  3944. {
  3945. case 0x10000001:
  3946. case 0x10000002:
  3947. case 0x10000003:
  3948. case 0x10000004:
  3949. case 0x10000005:
  3950. support = true;
  3951. _UpgradeNeedReboot = TRUE;
  3952. isPass = Upgrade_Flash(Type, new_str, (char *)ShmSysConfigAndInfo->SysConfig.ModelName);
  3953. break;
  3954. case 0x10000006: // primary mcu
  3955. case 0x1000000D: // relay board
  3956. case 0x1000000E: // fan board
  3957. case 0x10000014: // led board
  3958. support = true;
  3959. target = 0x00;
  3960. if (Type == 0x10000006)
  3961. {
  3962. target = UPGRADE_PRI;
  3963. }
  3964. else if (Type == 0x1000000D)
  3965. {
  3966. target = UPGRADE_RB;
  3967. }
  3968. else if (Type == 0x1000000E)
  3969. {
  3970. target = UPGRADE_FAN;
  3971. }
  3972. else if (Type == 0x10000014)
  3973. {
  3974. target = UPGRADE_LED;
  3975. }
  3976. uartFd = InitComPort(target);
  3977. if(target == UPGRADE_RB)
  3978. {
  3979. isPass = Upgrade_UART(uartFd, Type, UPGRADE_DORC1, new_str, (char *)ShmSysConfigAndInfo->SysConfig.ModelName);
  3980. if(isPass == PASS)
  3981. {
  3982. retSucc++;
  3983. }
  3984. else
  3985. {
  3986. retFail++;
  3987. }
  3988. LOG_INFO("Upgrade %s", isPass == PASS ? "Success" : "Fail");
  3989. sleep(3);
  3990. isPass = Upgrade_UART(uartFd, Type, UPGRADE_DORC2, new_str, (char *)ShmSysConfigAndInfo->SysConfig.ModelName);
  3991. }
  3992. else
  3993. {
  3994. isPass = Upgrade_UART(uartFd, Type, target, new_str, (char *)ShmSysConfigAndInfo->SysConfig.ModelName);
  3995. }
  3996. close(uartFd);
  3997. break;
  3998. }
  3999. if(support)
  4000. {
  4001. if(isPass == PASS)
  4002. {
  4003. retSucc++;
  4004. }
  4005. else
  4006. {
  4007. retFail++;
  4008. }
  4009. LOG_INFO("Upgrade %s", isPass == PASS ? "Success" : "Fail");
  4010. }
  4011. if(ShmChargerInfo->Control.CabinetRole == _CROLE_MASTER)
  4012. {
  4013. LOG_INFO("MCabinet upgrade completed");
  4014. WaitAllPCabinetUpgradeCompleted();
  4015. }
  4016. if(ShmChargerInfo->Control.CabinetRole == _CROLE_SLAVE && ShmChargerInfo->SCabinetControl.UpgradeState == Updating)
  4017. {
  4018. ShmChargerInfo->SCabinetControl.UpgradeState = Updated;
  4019. LOG_INFO("SCabinet upgrade completed");
  4020. WaitMCabinetUpgradeCompleted();
  4021. }
  4022. }
  4023. else
  4024. {
  4025. if(model[0] == 'D' && (model[1] == 'D' || model[1] == 'X'))
  4026. {
  4027. OneImageOnly = true;
  4028. _UpgradeNeedReboot = TRUE;
  4029. LOG_INFO("Start Put Image To All Dispenser");
  4030. PutImageToAllDispenser(new_str, dir->d_name);
  4031. WaitAllDispenserUpgradeCompleted();
  4032. LOG_INFO("All Dispenser Upgrade Completed");
  4033. }
  4034. }
  4035. }
  4036. sprintf(cmdBuf, "rm -f %s", new_str);
  4037. system(cmdBuf);
  4038. close(fd);
  4039. free(new_str);
  4040. free(ptr);
  4041. }
  4042. }
  4043. free(dir);
  4044. closedir(d);
  4045. if(retFail != 0)
  4046. {
  4047. return FAIL;
  4048. }
  4049. return PASS;
  4050. }
  4051. /*
  4052. void CreateRfidFork()
  4053. {
  4054. pid_t rfidRecPid;
  4055. rfidRecPid = fork();
  4056. if (rfidRecPid == 0)
  4057. {
  4058. while(true)
  4059. {
  4060. // 刷卡判斷
  4061. RFID rfid;
  4062. if (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_NO_CHARGING ||
  4063. !ShmSysConfigAndInfo->SysConfig.isRFID)
  4064. {}
  4065. else if(getRequestCardSN(rfidFd, 0, &rfid))
  4066. {
  4067. PRINTF_FUNC("Get Card..-%s- \n", ShmSysConfigAndInfo->SysConfig.UserId);
  4068. if (strlen((char *)ShmSysConfigAndInfo->SysConfig.UserId) == 0)
  4069. {
  4070. if (ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian == RFID_ENDIAN_LITTLE)
  4071. {
  4072. switch (rfid.snType)
  4073. {
  4074. case RFID_SN_TYPE_6BYTE:
  4075. sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
  4076. "%02X%02X%02X%02X%02X%02X",
  4077. rfid.currentCard[0], rfid.currentCard[1],
  4078. rfid.currentCard[2], rfid.currentCard[3],
  4079. rfid.currentCard[4], rfid.currentCard[5]);
  4080. break;
  4081. case RFID_SN_TYPE_7BYTE:
  4082. sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
  4083. "%02X%02X%02X%02X%02X%02X%02X",
  4084. rfid.currentCard[0], rfid.currentCard[1],
  4085. rfid.currentCard[2], rfid.currentCard[3],
  4086. rfid.currentCard[4], rfid.currentCard[5],
  4087. rfid.currentCard[6]);
  4088. break;
  4089. case RFID_SN_TYPE_10BYTE:
  4090. sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
  4091. "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
  4092. rfid.currentCard[0], rfid.currentCard[1],
  4093. rfid.currentCard[2], rfid.currentCard[3],
  4094. rfid.currentCard[4], rfid.currentCard[5],
  4095. rfid.currentCard[6], rfid.currentCard[7],
  4096. rfid.currentCard[8], rfid.currentCard[9]);
  4097. break;
  4098. case RFID_SN_TYPE_4BYTE:
  4099. sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
  4100. "%02X%02X%02X%02X",
  4101. rfid.currentCard[0], rfid.currentCard[1],
  4102. rfid.currentCard[2], rfid.currentCard[3]);
  4103. break;
  4104. }
  4105. }
  4106. else if (ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian == RFID_ENDIAN_BIG)
  4107. {
  4108. switch (rfid.snType)
  4109. {
  4110. case RFID_SN_TYPE_6BYTE:
  4111. sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
  4112. "%02X%02X%02X%02X%02X%02X",
  4113. rfid.currentCard[5], rfid.currentCard[4],
  4114. rfid.currentCard[3], rfid.currentCard[2],
  4115. rfid.currentCard[1], rfid.currentCard[0]);
  4116. break;
  4117. case RFID_SN_TYPE_7BYTE:
  4118. sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
  4119. "%02X%02X%02X%02X%02X%02X%02X",
  4120. rfid.currentCard[6], rfid.currentCard[5],
  4121. rfid.currentCard[4], rfid.currentCard[3],
  4122. rfid.currentCard[2], rfid.currentCard[1],
  4123. rfid.currentCard[0]);
  4124. break;
  4125. case RFID_SN_TYPE_10BYTE:
  4126. sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
  4127. "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
  4128. rfid.currentCard[9], rfid.currentCard[8],
  4129. rfid.currentCard[7], rfid.currentCard[6],
  4130. rfid.currentCard[5], rfid.currentCard[4],
  4131. rfid.currentCard[3], rfid.currentCard[2],
  4132. rfid.currentCard[1], rfid.currentCard[0]);
  4133. break;
  4134. case RFID_SN_TYPE_4BYTE:
  4135. sprintf((char *) ShmSysConfigAndInfo->SysConfig.UserId,
  4136. "%02X%02X%02X%02X",
  4137. rfid.currentCard[3], rfid.currentCard[2],
  4138. rfid.currentCard[1], rfid.currentCard[0]);
  4139. break;
  4140. }
  4141. }
  4142. LOG_INFOUNC("card number = %s\n", ShmSysConfigAndInfo->SysConfig.UserId);
  4143. }
  4144. }
  4145. sleep(1);
  4146. }
  4147. }
  4148. }
  4149. */
  4150. #if 0
  4151. void StartSystemTimeoutDet(unsigned char flag)
  4152. {
  4153. if (ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag != flag)
  4154. {
  4155. gettimeofday(&ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer, NULL);
  4156. }
  4157. ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag = flag;
  4158. }
  4159. void StopSystemTimeoutDet()
  4160. {
  4161. gettimeofday(&ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer, NULL);
  4162. ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag = Timeout_None;
  4163. }
  4164. void StartGunInfoTimeoutDet(unsigned char gunIndex, unsigned char flag)
  4165. {
  4166. if (gunIndex < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount)
  4167. {
  4168. if (chargingInfo[gunIndex]->TimeoutFlag != flag)
  4169. {
  4170. gettimeofday(&chargingInfo[gunIndex]->TimeoutTimer, NULL);
  4171. }
  4172. chargingInfo[gunIndex]->TimeoutFlag = flag;
  4173. }
  4174. }
  4175. void StopGunInfoTimeoutDet(unsigned char gunIndex)
  4176. {
  4177. if (gunIndex < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount)
  4178. {
  4179. chargingInfo[gunIndex]->TimeoutFlag = Timeout_None;
  4180. }
  4181. }
  4182. #endif
  4183. void TriggerDispenserConnectionTimeoutSetting(void)
  4184. {
  4185. BOOL trigger = FALSE;
  4186. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  4187. {
  4188. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ConnectorQuantity > 0)
  4189. {
  4190. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.ConnectorTimeoutConfigRequest = 1;
  4191. trigger = TRUE;
  4192. }
  4193. }
  4194. if(trigger)
  4195. {
  4196. LOG_INFO("********** Trigger Dispenser Connector Timeout Value: %d **********", ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectorTimeout);
  4197. }
  4198. }
  4199. void CheckConnectionTimeout(void)
  4200. {
  4201. if(system("pidof -s OcppBackend > /dev/null") != 0)
  4202. {
  4203. _connectionTimeout = CONN_PLUG_TIME_OUT;
  4204. }
  4205. else
  4206. {
  4207. if(ShmOCPP16Data->OcppConnStatus &&
  4208. strcmp((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData,"") != 0)
  4209. {
  4210. _connectionTimeout = atoi((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData);
  4211. if(_connectionTimeout <= 0)
  4212. {
  4213. _connectionTimeout = CONN_PLUG_TIME_OUT;
  4214. }
  4215. }
  4216. else
  4217. {
  4218. _connectionTimeout = CONN_PLUG_TIME_OUT;
  4219. }
  4220. }
  4221. if(_connectionTimeout != ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectorTimeout)
  4222. {
  4223. ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectorTimeout = _connectionTimeout;
  4224. TriggerDispenserConnectionTimeoutSetting();
  4225. }
  4226. }
  4227. void CreateTimeoutFork()
  4228. {
  4229. pid_t timeoutPid;
  4230. timeoutPid = fork();
  4231. if (timeoutPid == 0)
  4232. {
  4233. GetClockTime(&_cmdSubPriority_time);
  4234. CheckConnectionTimeout();
  4235. LOG_INFO("Timeout Fork PID = %d", getpid());
  4236. while(true)
  4237. {
  4238. if ((GetTimeoutValue(_cmdSubPriority_time) / 1000) > 5000)
  4239. {
  4240. CheckConnectionTimeout();
  4241. GetClockTime(&_cmdSubPriority_time);
  4242. }
  4243. //printf("Timeout ***********SystemTimeoutFlag = %d, ********\n", ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag);
  4244. // 系統
  4245. // switch(ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag)
  4246. // {
  4247. // case Timeout_SelftestChk:
  4248. // if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) / uSEC_VAL >= SELFTEST_TIMEOUT)
  4249. // {
  4250. // _SelfTestTimeout();
  4251. // StopSystemTimeoutDet();
  4252. // }
  4253. // break;
  4254. // case Timeout_Authorizing:
  4255. // if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) / uSEC_VAL >= AUTHORIZE_TIMEOUT)
  4256. // {
  4257. // _AuthorizedTimeout();
  4258. // StopSystemTimeoutDet();
  4259. // }
  4260. // break;
  4261. // case Timeout_VerifyFail:
  4262. // if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) / uSEC_VAL >= AUTHORIZE_FAIL_TIMEOUT)
  4263. // {
  4264. // _AutoReturnTimeout();
  4265. // StopSystemTimeoutDet();
  4266. // }
  4267. // break;
  4268. // case Timeout_VerifyComp:
  4269. // if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) / uSEC_VAL >= AUTHORIZE_COMP_TIMEOUT)
  4270. // {
  4271. // _AutoReturnTimeout();
  4272. // StopSystemTimeoutDet();
  4273. // }
  4274. // break;
  4275. // case Timeout_WaitPlug:
  4276. // if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) / uSEC_VAL >= _connectionTimeout)
  4277. // {
  4278. // _DetectPlugInTimeout();
  4279. // StopSystemTimeoutDet();
  4280. // }
  4281. // break;
  4282. // case Timeout_ReturnToChargingGunDet:
  4283. // {
  4284. // if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) / uSEC_VAL >= RETURN_TO_CHARGING_PAGE)
  4285. // {
  4286. // DisplayChargingInfo();
  4287. // StopSystemTimeoutDet();
  4288. // }
  4289. // }
  4290. // break;
  4291. // case Timeout_AuthorizingForStop:
  4292. // {
  4293. // if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) / uSEC_VAL >= AUTHORIZE_STOP_TIMEOUT)
  4294. // {
  4295. // strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
  4296. // ClearAuthorizedFlag();
  4297. // StopSystemTimeoutDet();
  4298. // }
  4299. // }
  4300. // break;
  4301. // }
  4302. // 各槍
  4303. // for (byte gun_index = 0; gun_index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun_index++)
  4304. // {
  4305. //printf("Timeout ***********TimeoutFlag = %d, ********\n", chargingInfo[gun_index]->TimeoutFlag);
  4306. // switch(chargingInfo[gun_index]->TimeoutFlag)
  4307. // {
  4308. // case Timeout_Preparing:
  4309. // {
  4310. // if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) / uSEC_VAL >= GUN_PREPARE_TIMEOUT)
  4311. // {
  4312. // _PrepareTimeout(gun_index);
  4313. // StopGunInfoTimeoutDet(gun_index);
  4314. // }
  4315. // }
  4316. // break;
  4317. // case Timeout_EvChargingDet:
  4318. // {
  4319. // if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) / uSEC_VAL >= GUN_EV_WAIT_TIMEOUT)
  4320. // {
  4321. // _DetectEvChargingEnableTimeout(gun_index);
  4322. // StopGunInfoTimeoutDet(gun_index);
  4323. // }
  4324. // }
  4325. // break;
  4326. // case Timeout_EvseChargingDet:
  4327. // {
  4328. // if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) / uSEC_VAL >= GUN_EVSE_WAIT_TIMEOUT)
  4329. // {
  4330. // _DetectEvseChargingEnableTimeout(gun_index);
  4331. // StopGunInfoTimeoutDet(gun_index);
  4332. // }
  4333. // }
  4334. // break;
  4335. // case Timeout_EvseCompleteDet:
  4336. // {
  4337. // if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) / uSEC_VAL >= GUN_COMP_WAIT_TIMEOUT)
  4338. // {
  4339. // StopGunInfoTimeoutDet(gun_index);
  4340. // }
  4341. // }
  4342. // break;
  4343. // case Timeout_ForCcsPrechargeDet:
  4344. // {
  4345. // if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) / uSEC_VAL >= GUN_PRECHARGING_TIMEOUT)
  4346. // {
  4347. // _CcsPrechargeTimeout(gun_index);
  4348. // StopGunInfoTimeoutDet(gun_index);
  4349. // }
  4350. // }
  4351. // break;
  4352. // }
  4353. // }
  4354. sleep(1);
  4355. }
  4356. }
  4357. }
  4358. void CheckFactoryConfigFunction(void)
  4359. {
  4360. if(ShmSysConfigAndInfo->SysInfo.FactoryConfiguration)
  4361. {
  4362. char Buf[256];
  4363. sprintf(Buf, "cd /root;./FactoryConfig -m");
  4364. system(Buf);
  4365. system("rm -f /Storage/OCPP/OCPPConfiguration");
  4366. system("sync");
  4367. sleep(5);
  4368. system("reboot -f");
  4369. sleep(5);
  4370. system("reboot -f");
  4371. }
  4372. }
  4373. void CheckFwUpdateFunction(void)
  4374. {
  4375. char UpdateResult = PASS;
  4376. if (ShmSysConfigAndInfo->SysInfo.FirmwareUpdate == YES)
  4377. {
  4378. ShmChargerInfo->Control.SysCtrl.bits.NeedSelfTest = false;
  4379. UpgradePrepare();
  4380. ShmChargerInfo->Control.PrimaryCtrl.bits.Paused = true;
  4381. ShmChargerInfo->Control.RelayCtrl.bits.Paused = true;
  4382. ShmChargerInfo->Control.FanCtrl.bits.Paused = true;
  4383. LOG_INFO("ftp : update start.");
  4384. TryCloseWatchdog();
  4385. //KillTask();
  4386. ChangeLcmByIndex(_LCM_FIX);
  4387. system("killall Module_PrimaryComm");
  4388. system("killall Module_InternalComm");
  4389. UpdateResult = CheckUpdateProcess();
  4390. if (UpdateResult == PASS)
  4391. {
  4392. LOG_INFO("ftp : update complete.");
  4393. }
  4394. else
  4395. {
  4396. LOG_INFO("ftp : update fail.");
  4397. }
  4398. ShmSysConfigAndInfo->SysInfo.FirmwareUpdate = NO;
  4399. sleep(5);
  4400. if(_UpgradeNeedReboot)
  4401. {
  4402. system("reboot -f");
  4403. }
  4404. else
  4405. {
  4406. KillAllTask();
  4407. system("/usr/bin/run_evse_restart.sh");
  4408. }
  4409. }
  4410. else if(ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq == YES)
  4411. {
  4412. ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq = NO;
  4413. ShmChargerInfo->Control.SysCtrl.bits.NeedSelfTest = false;
  4414. UpgradePrepare();
  4415. ShmChargerInfo->Control.PrimaryCtrl.bits.Paused = true;
  4416. ShmChargerInfo->Control.RelayCtrl.bits.Paused = true;
  4417. ShmChargerInfo->Control.FanCtrl.bits.Paused = true;
  4418. if (strcmp((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Downloaded") == EQUAL)
  4419. {
  4420. LOG_INFO("Backend : update start.");
  4421. TryCloseWatchdog();
  4422. strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "");
  4423. strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installing");
  4424. ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
  4425. //KillTask();
  4426. system("killall Module_PrimaryComm");
  4427. system("killall Module_InternalComm");
  4428. for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++)
  4429. {
  4430. setChargerMode(_index, MODE_UPDATE);
  4431. }
  4432. UpdateResult = CheckUpdateProcess();
  4433. if (UpdateResult == PASS)
  4434. {
  4435. LOG_INFO("Backend : update complete.");
  4436. strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installed");
  4437. }
  4438. else
  4439. {
  4440. LOG_INFO("Backend : update fail.");
  4441. strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "InstallationFailed");
  4442. }
  4443. //strcpy((char *)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installed");
  4444. sleep(1);
  4445. ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = YES;
  4446. sleep(5);
  4447. if(_UpgradeNeedReboot)
  4448. {
  4449. system("reboot -f");
  4450. }
  4451. else
  4452. {
  4453. KillAllTask();
  4454. system("/usr/bin/run_evse_restart.sh");
  4455. }
  4456. }
  4457. }
  4458. }
  4459. void ExecuteWriteWiringInfo(void)
  4460. {
  4461. struct SysConfigData config;
  4462. memcpy(&config, &ShmSysConfigAndInfo->SysConfig, sizeof(struct SysConfigData));
  4463. config.SwitchDebugFlag = NO;
  4464. strcpy((char *) config.UserId, "");
  4465. int result = StoreUsrConfigData(&config);
  4466. if(result != 1)
  4467. {
  4468. LOG_INFO("Store User Config NG");
  4469. }
  4470. else
  4471. {
  4472. LOG_INFO("Store User Config OK");
  4473. }
  4474. }
  4475. struct timespec _WiringInfo_time;
  4476. int CheckWiringInfoUpdate(void)
  4477. {
  4478. if(ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.FlashConfigChanged)
  4479. {
  4480. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.FlashConfigChanged = false;
  4481. LOG_INFO("Flash Config Changed");
  4482. GetClockTime(&_WiringInfo_time);
  4483. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.EnableWriteFlash = true;
  4484. }
  4485. if(ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.EnableWriteFlash)
  4486. {
  4487. // 30s for reboot request timeout
  4488. if((GetTimeoutValue(_WiringInfo_time) / uSEC_VAL) >= WIRING_INFO_DELAY ||
  4489. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.CleanWiringInfo)
  4490. {
  4491. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.EnableWriteFlash = false;
  4492. LOG_INFO("Start Write To Flash");
  4493. pid_t writePid = fork();
  4494. if(writePid == 0)
  4495. {
  4496. ExecuteWriteWiringInfo();
  4497. if(ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.CleanWiringInfo)
  4498. {
  4499. ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.CleanWiringInfo = false;
  4500. ShmChargerInfo->Control.SysCtrl.bits.NeedSoftReset = true;
  4501. LOG_INFO("Clean Wiring Info And Need Soft Reset");
  4502. }
  4503. return NO;
  4504. }
  4505. LOG_INFO("Clean Write Flahs Flag");
  4506. }
  4507. }
  4508. return YES;
  4509. }
  4510. void CheckSoftHardReset(void)
  4511. {
  4512. if(ShmChargerInfo->Control.SysCtrl.bits.NeedSoftReset)
  4513. {
  4514. ShmChargerInfo->Control.SysCtrl.bits.NeedSoftReset = false;
  4515. LOG_INFO("********** Need Soft Reset **********");
  4516. sleep(5);
  4517. system("killall OcppBackend &");
  4518. KillAllTask();
  4519. TryCloseWatchdog();
  4520. system("/usr/bin/run_evse_restart.sh");
  4521. }
  4522. if(ShmChargerInfo->Control.SysCtrl.bits.NeedHardReset)
  4523. {
  4524. ShmChargerInfo->Control.SysCtrl.bits.NeedHardReset = false;
  4525. LOG_INFO("********** Need Hard Reset **********");
  4526. sleep(5);
  4527. system("reboot -f");
  4528. }
  4529. }
  4530. //===============================================
  4531. // Check reservation date is expired
  4532. //===============================================
  4533. int isReservationExpired(unsigned char gun_index)
  4534. {
  4535. int result = NO;
  4536. struct tm expiredDate;
  4537. struct timeb expiredTime;
  4538. if (sscanf((char*) ShmOCPP16Data->ReserveNow[gun_index].ExpiryDate,
  4539. "%4d-%2d-%2dT%2d:%2d:%2d", &expiredDate.tm_year,
  4540. &expiredDate.tm_mon, &expiredDate.tm_mday, &expiredDate.tm_hour,
  4541. &expiredDate.tm_min, &expiredDate.tm_sec) == 6)
  4542. {
  4543. expiredDate.tm_year -= 1900;
  4544. expiredDate.tm_mon -= 1;
  4545. expiredTime.time = mktime(&expiredDate);
  4546. if (!CheckTimeOut(expiredTime))
  4547. {
  4548. result = YES;
  4549. }
  4550. }
  4551. return result;
  4552. }
  4553. struct timespec _Reboot_time;
  4554. void TriggerDispenserHardwareReboot(void)
  4555. {
  4556. BOOL trigger = FALSE;
  4557. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  4558. {
  4559. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ConnectorQuantity > 0)
  4560. {
  4561. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.HardwareRebootConfirm == 0 &&
  4562. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.HardwareRebootRequest == 0)
  4563. {
  4564. trigger = TRUE;
  4565. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.HardwareRebootRequest = 1;
  4566. }
  4567. }
  4568. }
  4569. if(trigger)
  4570. {
  4571. GetClockTime(&_Reboot_time);
  4572. LOG_INFO("********** Trigger Dispenser Hardware Reboot **********");
  4573. }
  4574. }
  4575. BOOL IsDispenserHardwareRebootResponsed(void)
  4576. {
  4577. BOOL response_ok = TRUE;
  4578. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  4579. {
  4580. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ConnectorQuantity > 0)
  4581. {
  4582. if(!ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.HardwareRebootConfirm)
  4583. {
  4584. response_ok = FALSE;
  4585. // 10s for reboot request timeout
  4586. if((GetTimeoutValue(_Reboot_time) / uSEC_VAL) >= REBOOT_TIMEOUT)
  4587. {
  4588. response_ok = TRUE;
  4589. LOG_INFO("Reboot request timeout");
  4590. }
  4591. }
  4592. }
  4593. }
  4594. return response_ok;
  4595. }
  4596. struct timespec _Reset_time;
  4597. void TriggerDispenserSoftwareReset(void)
  4598. {
  4599. BOOL trigger = FALSE;
  4600. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  4601. {
  4602. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ConnectorQuantity > 0)
  4603. {
  4604. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.SoftwareResetConfirm == 0 &&
  4605. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.SoftwareResetRequest == 0)
  4606. {
  4607. trigger = TRUE;
  4608. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.SoftwareResetRequest = 1;
  4609. }
  4610. }
  4611. }
  4612. if(trigger)
  4613. {
  4614. GetClockTime(&_Reset_time);
  4615. LOG_INFO("********** Trigger Dispenser Software Reset **********");
  4616. }
  4617. }
  4618. BOOL IsDispenserSoftwareResetResponsed(void)
  4619. {
  4620. BOOL response_ok = TRUE;
  4621. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  4622. {
  4623. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ConnectorQuantity > 0)
  4624. {
  4625. if(!ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.SoftwareResetConfirm)
  4626. {
  4627. response_ok = FALSE;
  4628. // 10s for reset request timeout
  4629. if((GetTimeoutValue(_Reset_time) / uSEC_VAL) >= RESET_TIMEOUT)
  4630. {
  4631. response_ok = TRUE;
  4632. LOG_INFO("Reset request timeout");
  4633. }
  4634. }
  4635. }
  4636. }
  4637. return response_ok;
  4638. }
  4639. // the unit of return value: 0.01 dollar
  4640. int TariffParsing(char *StringItem, char *TariffCode)
  4641. {
  4642. char *ptrSave, *ptrToken;
  4643. char strSource[128];
  4644. int fee = 0;
  4645. memcpy(strSource, StringItem, 128);
  4646. ptrToken = strtok_r(strSource, ";", &ptrSave);
  4647. while(ptrToken != NULL)
  4648. {
  4649. char *strTariff = strstr(ptrToken, TariffCode);
  4650. if(strTariff != NULL)
  4651. {
  4652. char *strFee = strstr(strTariff, "$");
  4653. if(strFee != NULL)
  4654. {
  4655. strFee++;
  4656. float fFee = atof(strFee);
  4657. fee = (int)(fFee * 100);
  4658. break;
  4659. }
  4660. }
  4661. ptrToken = strtok_r(NULL, ";", &ptrSave);
  4662. }
  4663. return fee;
  4664. }
  4665. void DefaultPriceHandler(char *StrDefaultPrice)
  4666. {
  4667. BOOL trigger = FALSE;
  4668. unsigned int ConnectionFee = 0, CurrentRate = 0, OccupancyFee = 0;
  4669. LOG_INFO("********** Default Price: %s", StrDefaultPrice);
  4670. ConnectionFee = TariffParsing(StrDefaultPrice, "Connection Fee");
  4671. LOG_INFO("********** Connection Fee: %d.%02d **********", (ConnectionFee / 100), (ConnectionFee % 100));
  4672. CurrentRate = TariffParsing(StrDefaultPrice, "Current Rate");
  4673. LOG_INFO("********** Current Rate: %d.%02d **********", (CurrentRate / 100), (CurrentRate % 100));
  4674. OccupancyFee = TariffParsing(StrDefaultPrice, "Occupancy Fee");
  4675. LOG_INFO("********** Occupancy Fee: %d.%02d **********", (OccupancyFee / 100), (OccupancyFee % 100));
  4676. ShmSysConfigAndInfo->SysInfo.DispenserInfo.DefaultPrice = CurrentRate;
  4677. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  4678. {
  4679. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ConnectorQuantity > 0)
  4680. {
  4681. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.DefaultPriceConfigRequest == 0)
  4682. {
  4683. trigger = TRUE;
  4684. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.DefaultPriceConfigRequest = 1;
  4685. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.CurrencyConfigRequest = 1;
  4686. }
  4687. }
  4688. }
  4689. if(trigger)
  4690. {
  4691. LOG_INFO("********** Trigger Dispenser Default Price **********");
  4692. }
  4693. }
  4694. void UserPriceHandler(char *UserId, char *UserPrice)
  4695. {
  4696. unsigned int ConnectionFee = 0, CurrentRate = 0, OccupancyFee = 0;
  4697. int AccountBalance = 0;
  4698. ConnectionFee = TariffParsing((char *)ShmOCPP16Data->Cost.SetUserPrice.price, "Connection Fee");
  4699. CurrentRate = TariffParsing((char *)ShmOCPP16Data->Cost.SetUserPrice.price, "Current Rate");
  4700. OccupancyFee = TariffParsing((char *)ShmOCPP16Data->Cost.SetUserPrice.price, "Occupancy Fee");
  4701. AccountBalance = TariffParsing((char *)ShmOCPP16Data->Cost.SetUserPrice.price, "Account Balance");
  4702. LOG_INFO("********** User Id: %s **********", ShmOCPP16Data->Cost.SetUserPrice.idToken);
  4703. LOG_INFO("********** User Price: %s", ShmOCPP16Data->Cost.SetUserPrice.price);
  4704. LOG_INFO("********** Connection Fee: %d.%02d **********", (ConnectionFee / 100), (ConnectionFee % 100));
  4705. LOG_INFO("********** Current Rate: %d.%02d **********", (CurrentRate / 100), (CurrentRate % 100));
  4706. LOG_INFO("********** Occupancy Fee: %d.%02d **********", (OccupancyFee / 100), (OccupancyFee % 100));
  4707. LOG_INFO("********** Account Balance: %d.%02d **********", (AccountBalance / 100), (AccountBalance % 100));
  4708. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  4709. {
  4710. if(strcmp((char *)ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].GeneralChargingData.StartUserId, UserId) == EQUAL)
  4711. {
  4712. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].UserPrice != CurrentRate ||
  4713. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].AccountBalance != AccountBalance)
  4714. {
  4715. LOG_INFO("********** Connector Id %d User Price %d.%02d, Account Balance %d.%02d **********",
  4716. (i + 1), (CurrentRate / 100), (CurrentRate % 100), (AccountBalance / 100), (AccountBalance % 100));
  4717. }
  4718. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].UserPrice = CurrentRate;
  4719. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].AccountBalance = AccountBalance;
  4720. if(chargingInfo[i]->SystemStatus == S_AUTHORIZING)
  4721. {
  4722. AnnounceAccountBalance(i, AccountBalance);
  4723. }
  4724. }
  4725. }
  4726. }
  4727. void RunningFinalCostHandler(void)
  4728. {
  4729. unsigned int ConnectionFee = 0, SessionFee = 0, OccupancyFee = 0, TotalCost = 0;
  4730. int AccountBalance = 0;
  4731. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  4732. {
  4733. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].GeneralChargingData.SystemStatus >= S_REASSIGN_CHECK &&
  4734. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].GeneralChargingData.SystemStatus <= S_ALARM)
  4735. {
  4736. if(strlen((char *)ShmOCPP16Data->Cost.RunningCost[i].description) > 0)
  4737. {
  4738. ConnectionFee = TariffParsing((char *)ShmOCPP16Data->Cost.RunningCost[i].description, "Connection Fee");
  4739. SessionFee = TariffParsing((char *)ShmOCPP16Data->Cost.RunningCost[i].description, "Session Fee");
  4740. OccupancyFee = TariffParsing((char *)ShmOCPP16Data->Cost.RunningCost[i].description, "Occupancy Fee");
  4741. TotalCost = TariffParsing((char *)ShmOCPP16Data->Cost.RunningCost[i].description, "Total Cost");
  4742. AccountBalance = TariffParsing((char *)ShmOCPP16Data->Cost.RunningCost[i].description, "Account Balance");
  4743. LOG_INFO("********** Connector Id: %d Running Cost **********", (i + 1));
  4744. LOG_INFO("********** Connection Fee: %d.%02d **********", (ConnectionFee / 100), (ConnectionFee % 100));
  4745. LOG_INFO("********** Session Fee: %d.%02d **********", (SessionFee / 100), (SessionFee % 100));
  4746. LOG_INFO("********** Occupancy Fee: %d.%02d **********", (OccupancyFee / 100), (OccupancyFee % 100));
  4747. LOG_INFO("********** Total Cost: %d.%02d **********", (TotalCost / 100), (TotalCost % 100));
  4748. LOG_INFO("********** Account Balance: %d.%02d **********", (AccountBalance / 100), (AccountBalance % 100));
  4749. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].TotalCost != TotalCost ||
  4750. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].AccountBalance != AccountBalance)
  4751. {
  4752. LOG_INFO("********** Connector Id %d Total Cost %d.%02d, Account Balance %d.%02d **********",
  4753. (i + 1), (TotalCost / 100), (TotalCost % 100), (AccountBalance / 100), (AccountBalance % 100));
  4754. }
  4755. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].TotalCost = TotalCost;
  4756. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].AccountBalance = AccountBalance;
  4757. memset(&ShmOCPP16Data->Cost.RunningCost[i], 0x00, sizeof(struct StrcutRunningCost));
  4758. }
  4759. if(strlen((char *)ShmOCPP16Data->Cost.FinalCost[i].description) > 0)
  4760. {
  4761. ConnectionFee = TariffParsing((char *)ShmOCPP16Data->Cost.FinalCost[i].description, "Connection Fee");
  4762. SessionFee = TariffParsing((char *)ShmOCPP16Data->Cost.FinalCost[i].description, "Session Fee");
  4763. OccupancyFee = TariffParsing((char *)ShmOCPP16Data->Cost.FinalCost[i].description, "Occupancy Fee");
  4764. TotalCost = TariffParsing((char *)ShmOCPP16Data->Cost.FinalCost[i].description, "Total Cost");
  4765. AccountBalance = TariffParsing((char *)ShmOCPP16Data->Cost.FinalCost[i].description, "Account Balance");
  4766. LOG_INFO("********** Connector Id: %d Final Cost **********", (i + 1));
  4767. LOG_INFO("********** Connection Fee: %d.%02d **********", (ConnectionFee / 100), (ConnectionFee % 100));
  4768. LOG_INFO("********** Session Fee: %d.%02d **********", (SessionFee / 100), (SessionFee % 100));
  4769. LOG_INFO("********** Occupancy Fee: %d.%02d **********", (OccupancyFee / 100), (OccupancyFee % 100));
  4770. LOG_INFO("********** Total Cost: %d.%02d **********", (TotalCost / 100), (TotalCost % 100));
  4771. LOG_INFO("********** Account Balance: %d.%02d **********", (AccountBalance / 100), (AccountBalance % 100));
  4772. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].TotalCost != TotalCost ||
  4773. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].AccountBalance != AccountBalance)
  4774. {
  4775. LOG_INFO("********** Connector Id %d Total Cost %d.%02d, Account Balance %d.%02d **********",
  4776. (i + 1), (TotalCost / 100), (TotalCost % 100), (AccountBalance / 100), (AccountBalance % 100));
  4777. }
  4778. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].TotalCost = TotalCost;
  4779. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].AccountBalance = AccountBalance;
  4780. memset(&ShmOCPP16Data->Cost.FinalCost[i], 0x00, sizeof(struct StrcutFinalCost));
  4781. }
  4782. }
  4783. }
  4784. }
  4785. struct timespec _Cost_Price_time;
  4786. char MyDefaultPriceString[128];
  4787. struct StrcutSetUserPrice MyUserPrice;
  4788. char MyConnectorRunningCostString[CONNECTOR_QUANTITY][128];
  4789. char MyConnectorFinalCostString[CONNECTOR_QUANTITY][128];
  4790. void CheckOcppCostAndPrice(void)
  4791. {
  4792. // 5s for reboot request timeout
  4793. if((GetTimeoutValue(_Cost_Price_time) / uSEC_VAL) >= OCPP_COST_REQ_INTERVAL)
  4794. {
  4795. GetClockTime(&_Cost_Price_time);
  4796. if(strcmp(MyDefaultPriceString, (char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[DefaultPrice].ItemData) != EQUAL)
  4797. {
  4798. DefaultPriceHandler((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[DefaultPrice].ItemData);
  4799. memcpy(MyDefaultPriceString, ShmOCPP16Data->ConfigurationTable.CoreProfile[DefaultPrice].ItemData, 128);
  4800. }
  4801. if(strlen((char *)ShmOCPP16Data->Cost.SetUserPrice.idToken) > 0 && strlen((char *)ShmOCPP16Data->Cost.SetUserPrice.price) > 0)
  4802. {
  4803. UserPriceHandler((char *)ShmOCPP16Data->Cost.SetUserPrice.idToken, (char *)ShmOCPP16Data->Cost.SetUserPrice.price);
  4804. memset(&ShmOCPP16Data->Cost.SetUserPrice, 0x00, sizeof(struct StrcutSetUserPrice));
  4805. }
  4806. RunningFinalCostHandler();
  4807. }
  4808. }
  4809. //===============================================
  4810. // OCPP
  4811. //===============================================
  4812. void CheckOcppStatus()
  4813. {
  4814. if (ShmOCPP16Data->SpMsg.bits.BootNotificationConf == YES)
  4815. {
  4816. ShmOCPP16Data->SpMsg.bits.BootNotificationConf = NO;
  4817. LOG_INFO("*********************OCPP Boot Notification****************************");
  4818. }
  4819. if (ShmOCPP16Data->MsMsg.bits.ResetReq == YES)
  4820. {
  4821. bool canReset = true;
  4822. if (ShmSysConfigAndInfo->SysWarningInfo.Level != 2)
  4823. {
  4824. for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++)
  4825. {
  4826. if (chargingInfo[_index]->SystemStatus != S_IDLE &&
  4827. chargingInfo[_index]->SystemStatus != S_RESERVATION &&
  4828. chargingInfo[_index]->SystemStatus != S_MAINTAIN)
  4829. {
  4830. canReset = false;
  4831. if (chargingInfo[_index]->SystemStatus >= S_REASSIGN && chargingInfo[_index]->SystemStatus < S_TERMINATING)
  4832. {
  4833. ChargingTerminalProcess(_index);
  4834. }
  4835. }
  4836. }
  4837. }
  4838. if(canReset)
  4839. {
  4840. if(strcmp((char *)ShmOCPP16Data->Reset.Type, "Hard") == EQUAL)
  4841. {
  4842. //trigger dispenser to hardware reboot
  4843. TriggerDispenserHardwareReboot();
  4844. if(IsDispenserHardwareRebootResponsed())
  4845. {
  4846. ShmOCPP16Data->MsMsg.bits.ResetReq = NO;
  4847. sprintf((char*)ShmOCPP16Data->Reset.ResponseStatus, "Accepted");
  4848. LOG_INFO("****** Hard Reboot ******");
  4849. ShmOCPP16Data->MsMsg.bits.ResetConf = YES;
  4850. for(int i = 0; i < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; i++)
  4851. {
  4852. setChargerMode(i, MODE_MAINTAIN);
  4853. }
  4854. sleep(3);
  4855. system("reboot -f");
  4856. }
  4857. }
  4858. if(strcmp((char *)ShmOCPP16Data->Reset.Type, "Soft") == EQUAL)
  4859. {
  4860. //trigger dispenser to software reset
  4861. TriggerDispenserSoftwareReset();
  4862. if(IsDispenserSoftwareResetResponsed())
  4863. {
  4864. ShmOCPP16Data->MsMsg.bits.ResetReq = NO;
  4865. sprintf((char*)ShmOCPP16Data->Reset.ResponseStatus, "Accepted");
  4866. LOG_INFO("****** Soft Reboot ******");
  4867. ShmOCPP16Data->MsMsg.bits.ResetConf = YES;
  4868. for(int i = 0; i < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; i++)
  4869. {
  4870. setChargerMode(i, MODE_MAINTAIN);
  4871. }
  4872. sleep(3);
  4873. system("killall OcppBackend &");
  4874. KillAllTask();
  4875. TryCloseWatchdog();
  4876. system("/usr/bin/run_evse_restart.sh");
  4877. }
  4878. }
  4879. }
  4880. }
  4881. CheckOcppCostAndPrice();
  4882. }
  4883. void OcppStartTransation(byte gunIndex)
  4884. {
  4885. byte _OcppGunIndex = gunIndex;
  4886. strcpy((char *)ShmOCPP16Data->StartTransaction[_OcppGunIndex].IdTag, (char *)chargingInfo[gunIndex]->StartUserId);
  4887. chargingInfo[gunIndex]->EvBatteryStartSoc = chargingInfo[gunIndex]->EvBatterySoc;
  4888. LOG_INFO("Gun index %d, OCPP Start Transation Index %d, IdTag = %s, StartSoc = %d",
  4889. chargingInfo[gunIndex]->Index, _OcppGunIndex, ShmOCPP16Data->StartTransaction[_OcppGunIndex].IdTag, chargingInfo[gunIndex]->EvBatteryStartSoc);
  4890. ShmOCPP16Data->CpMsg.bits[_OcppGunIndex].StartTransactionConf = NO;
  4891. ShmOCPP16Data->CpMsg.bits[_OcppGunIndex].StartTransactionReq = YES;
  4892. }
  4893. void OcppStopTransation(byte gunIndex)
  4894. {
  4895. byte _OcppGunIndex = gunIndex;
  4896. strcpy((char *)ShmOCPP16Data->StopTransaction[_OcppGunIndex].IdTag, (char *)chargingInfo[gunIndex]->StartUserId);
  4897. LOG_INFO("Gun index %d, OCPP Stop Transation Index %d, IdTag = %s, StopSoc = %d",
  4898. chargingInfo[gunIndex]->Index, _OcppGunIndex, ShmOCPP16Data->StopTransaction[_OcppGunIndex].IdTag, chargingInfo[gunIndex]->EvBatterySoc);
  4899. ShmOCPP16Data->CpMsg.bits[_OcppGunIndex].StopTransactionReq = YES;
  4900. }
  4901. // no use
  4902. bool OcppRemoteStop(byte gunIndex)
  4903. {
  4904. byte acDirIndex = ShmSysConfigAndInfo->SysConfig.AcConnectorCount;
  4905. // 有 AC 槍的話
  4906. if (acDirIndex > 0 && gunIndex > 0)
  4907. {
  4908. gunIndex += acDirIndex;
  4909. }
  4910. bool result = ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq;
  4911. if (ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq == YES)
  4912. {
  4913. strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "Remote");
  4914. ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq = NO;
  4915. }
  4916. return result;
  4917. }
  4918. void OcppRemoteStartChk()
  4919. {
  4920. if (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == _OFFLINE_POLICY_NO_CHARGING)
  4921. {}
  4922. else if(!isDetectPlugin())
  4923. {
  4924. // 如果有 AC 槍,則固定是第 2 把槍,所以索引固定為 1
  4925. byte acDirIndex = ShmSysConfigAndInfo->SysConfig.AcConnectorCount;
  4926. for (byte ac_index = 0; ac_index < ShmSysConfigAndInfo->SysConfig.AcConnectorCount; ac_index++)
  4927. {
  4928. if (ShmOCPP16Data->CsMsg.bits[acDirIndex].RemoteStartTransactionReq == YES)
  4929. {
  4930. if (ac_chargingInfo[ac_index]->SystemStatus == S_IDLE ||
  4931. ac_chargingInfo[ac_index]->SystemStatus == S_RESERVATION)
  4932. {
  4933. ShmOCPP16Data->CsMsg.bits[acDirIndex].RemoteStartTransactionReq = NO;
  4934. ac_chargingInfo[ac_index]->RemoteStartFlag = YES;
  4935. ShmSysConfigAndInfo->SysInfo.OrderCharging = YES;
  4936. //ShmSysConfigAndInfo->SysInfo.OrderCharging = DEFAULT_AC_INDEX;
  4937. ShmOCPP16Data->CsMsg.bits[ShmSysConfigAndInfo->SysConfig.TotalConnectorCount + ac_index].RemoteStartTransactionReq = NO;
  4938. DetectPluginStart();
  4939. return;
  4940. }
  4941. ShmOCPP16Data->CsMsg.bits[acDirIndex].RemoteStartTransactionReq = NO;
  4942. }
  4943. }
  4944. byte threeGunIndex = 0;
  4945. byte dcIndex = 0;
  4946. bool isGunUsingStatus = false;
  4947. for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++)
  4948. {
  4949. // 如果有 AC 槍,且 DC 槍也有兩把
  4950. if (acDirIndex == 1 && _index == 1)
  4951. threeGunIndex = 1;
  4952. if (ShmOCPP16Data->CsMsg.bits[_index + threeGunIndex].RemoteStartTransactionReq == YES)
  4953. dcIndex = _index;
  4954. if (chargingInfo[_index]->SystemStatus != S_IDLE)
  4955. {
  4956. isGunUsingStatus = true;
  4957. }
  4958. }
  4959. // 如果是雙槍單模,只認閒置狀態的槍,如果有預約~ 則預約也算被使用
  4960. if (isGunUsingStatus && ShmSysConfigAndInfo->SysInfo.IsAlternatvieConf)
  4961. {
  4962. if (dcIndex == 0)
  4963. threeGunIndex = 0;
  4964. ShmOCPP16Data->CsMsg.bits[dcIndex + threeGunIndex].RemoteStartTransactionReq = NO;
  4965. return;
  4966. }
  4967. if (dcIndex == 0)
  4968. threeGunIndex = 0;
  4969. if (ShmOCPP16Data->CsMsg.bits[dcIndex + threeGunIndex].RemoteStartTransactionReq == YES)
  4970. {
  4971. if (chargingInfo[dcIndex]->SystemStatus == S_IDLE ||
  4972. chargingInfo[dcIndex]->SystemStatus == S_RESERVATION)
  4973. {
  4974. chargingInfo[dcIndex]->RemoteStartFlag = YES;
  4975. ShmSysConfigAndInfo->SysInfo.OrderCharging = YES;
  4976. //ShmSysConfigAndInfo->SysInfo.OrderCharging = gun_index;
  4977. ShmOCPP16Data->CsMsg.bits[dcIndex + threeGunIndex].RemoteStartTransactionReq = NO;
  4978. DetectPluginStart();
  4979. }
  4980. ShmOCPP16Data->CsMsg.bits[dcIndex + threeGunIndex].RemoteStartTransactionReq = NO;
  4981. }
  4982. }
  4983. }
  4984. void ChkOcppStatus(byte gunIndex)
  4985. {
  4986. if(strcmp((char *)ShmOCPP16Data->StatusNotification[gunIndex].ErrorCode, "") == EQUAL)
  4987. {
  4988. if(strcmp((char *)_BackupStatusNotification[gunIndex].ErrorCode, "") != EQUAL)
  4989. {
  4990. strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].ErrorCode, (char *)_BackupStatusNotification[gunIndex].ErrorCode);
  4991. strcpy((char *)ShmOCPP16Data->StatusNotification[gunIndex].VendorErrorCode, (char *)_BackupStatusNotification[gunIndex].VendorErrorCode);
  4992. //LOG_INFO("Gun %d Ocpp StatusNotification Recovery", gunIndex + 1);
  4993. }
  4994. }
  4995. if (chargingInfo[gunIndex]->SystemStatus == S_IDLE &&
  4996. ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowReq == YES)
  4997. {
  4998. ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowReq = NO;
  4999. if (isReservationExpired(gunIndex))
  5000. {
  5001. LOG_INFO("***************ChkOcppStatus: Gun %d OcppReservedStatus********************", gunIndex + 1);
  5002. chargingInfo[gunIndex]->ReservationId = ShmOCPP16Data->ReserveNow[gunIndex].ReservationId;
  5003. chargingInfo[gunIndex]->SystemStatus = S_RESERVATION;
  5004. }
  5005. ShmOCPP16Data->CsMsg.bits[gunIndex].ReserveNowConf = YES;
  5006. }
  5007. if (chargingInfo[gunIndex]->SystemStatus == S_RESERVATION &&
  5008. ShmOCPP16Data->CsMsg.bits[gunIndex].CancelReservationReq == YES)
  5009. {
  5010. ShmOCPP16Data->CsMsg.bits[gunIndex].CancelReservationReq = NO;
  5011. if (isReservationExpired(gunIndex))
  5012. {
  5013. LOG_INFO("***************ChkOcppStatus: Gun %d Cancel OcppReservedStatus********************", gunIndex + 1);
  5014. chargingInfo[gunIndex]->ReservationId = 0;
  5015. chargingInfo[gunIndex]->SystemStatus = S_IDLE;
  5016. }
  5017. ShmOCPP16Data->CsMsg.bits[gunIndex].CancelReservationConf = YES;
  5018. }
  5019. if (ShmOCPP16Data->CsMsg.bits[gunIndex].ChangeAvailabilityReq == YES)
  5020. {
  5021. LOG_INFO("***************ChkOcppStatus: Gun %d OcppChangeAvailability********************", gunIndex + 1);
  5022. ShmOCPP16Data->CsMsg.bits[gunIndex].ChangeAvailabilityReq = NO;
  5023. if(strcmp((char *)ShmOCPP16Data->ChangeAvailability[gunIndex].Type, "Operative") == EQUAL)
  5024. {
  5025. if (isDb_ready)
  5026. DB_Update_Operactive(localDb, gunIndex, true);
  5027. chargingInfo[gunIndex]->IsAvailable = YES;
  5028. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gunIndex].Parameter.bits.AvailabilityRequest = 1;
  5029. if (chargingInfo[gunIndex]->SystemStatus == S_IDLE ||
  5030. chargingInfo[gunIndex]->SystemStatus == S_RESERVATION ||
  5031. chargingInfo[gunIndex]->SystemStatus == S_MAINTAIN)
  5032. {
  5033. setChargerMode(gunIndex, MODE_IDLE);
  5034. }
  5035. }
  5036. else if (strcmp((char *)ShmOCPP16Data->ChangeAvailability[gunIndex].Type, "Inoperative") == EQUAL)
  5037. {
  5038. if (isDb_ready)
  5039. DB_Update_Operactive(localDb, gunIndex, false);
  5040. chargingInfo[gunIndex]->IsAvailable = NO;
  5041. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gunIndex].Parameter.bits.AvailabilityRequest = 1;
  5042. if (chargingInfo[gunIndex]->SystemStatus == S_IDLE ||
  5043. chargingInfo[gunIndex]->SystemStatus == S_RESERVATION ||
  5044. chargingInfo[gunIndex]->SystemStatus == S_MAINTAIN)
  5045. {
  5046. setChargerMode(gunIndex, MODE_MAINTAIN);
  5047. }
  5048. }
  5049. }
  5050. if (ShmOCPP16Data->CsMsg.bits[gunIndex].UnlockConnectorReq == YES)
  5051. {
  5052. ShmOCPP16Data->CsMsg.bits[gunIndex].UnlockConnectorReq = NO;
  5053. if(chargingInfo[gunIndex]->SystemStatus == S_PREPARNING ||
  5054. chargingInfo[gunIndex]->SystemStatus == S_PREPARING_FOR_EV ||
  5055. chargingInfo[gunIndex]->SystemStatus == S_PREPARING_FOR_EVSE ||
  5056. chargingInfo[gunIndex]->SystemStatus == S_CHARGING)
  5057. {
  5058. // 充電中,需停止充電
  5059. strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "UnlockCommand");
  5060. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gunIndex].Parameter.bits.UnlockStopRequest = true;
  5061. LOG_INFO("********** OcppUnlockStop Gun %d **********", gunIndex + 1);
  5062. }
  5063. strcpy((char *)ShmOCPP16Data->UnlockConnector[gunIndex].ResponseStatus, "Unlocked");
  5064. ShmOCPP16Data->CsMsg.bits[gunIndex].UnlockConnectorConf = YES;
  5065. }
  5066. if (ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq == YES)
  5067. {
  5068. ShmOCPP16Data->CsMsg.bits[gunIndex].RemoteStopTransactionReq = NO;
  5069. if(chargingInfo[gunIndex]->SystemStatus == S_PREPARNING ||
  5070. chargingInfo[gunIndex]->SystemStatus == S_PREPARING_FOR_EV ||
  5071. chargingInfo[gunIndex]->SystemStatus == S_PREPARING_FOR_EVSE ||
  5072. chargingInfo[gunIndex]->SystemStatus == S_CHARGING)
  5073. {
  5074. strcpy((char *)ShmOCPP16Data->StopTransaction[gunIndex].StopReason, "Remote");
  5075. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gunIndex].Parameter.bits.RemoteStopRequest = true;
  5076. LOG_INFO("********** OcppRemoteStop Gun %d **********", gunIndex + 1);
  5077. }
  5078. }
  5079. }
  5080. bool CheckBackendChargingTimeout(byte gunIndex)
  5081. {
  5082. bool result = false;
  5083. if (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_ENABLE)
  5084. {
  5085. if (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration > 0)
  5086. {
  5087. if (chargingInfo[gunIndex]->PresentChargedDuration > (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration * 60))
  5088. result = true;
  5089. }
  5090. }
  5091. else if (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE)
  5092. {
  5093. // 隨插即充電的要看 offline
  5094. if (ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeDuration > 0)
  5095. {
  5096. if (chargingInfo[gunIndex]->PresentChargedDuration > (ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeDuration * 60))
  5097. result = true;
  5098. }
  5099. }
  5100. return result;
  5101. }
  5102. bool CheckBackendChargingEnergy(byte gunIndex)
  5103. {
  5104. bool result = false;
  5105. if (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_ENABLE)
  5106. {
  5107. if (ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy > 0)
  5108. {
  5109. if (chargingInfo[gunIndex]->PresentChargedEnergy > ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy)
  5110. result = true;
  5111. }
  5112. }
  5113. else if (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE)
  5114. {
  5115. // 隨插即充電的要看 offline
  5116. if (ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy > 0)
  5117. {
  5118. if (chargingInfo[gunIndex]->PresentChargedEnergy > (ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy))
  5119. result = true;
  5120. }
  5121. }
  5122. return result;
  5123. }
  5124. void InformOcppErrOccur(byte codeType)
  5125. {
  5126. char _error[25];
  5127. switch(codeType)
  5128. {
  5129. case 4: strcpy(_error, "InternalError"); break;
  5130. case 6: strcpy(_error, "NoError"); break;
  5131. case 7: strcpy(_error, "OtherError"); break;
  5132. case 13: strcpy(_error, "UnderVoltage"); break;
  5133. case 14: strcpy(_error, "OverVoltage"); break;
  5134. }
  5135. for (byte gun_index = 0; gun_index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun_index++)
  5136. {
  5137. SetOcppErrorCode(gun_index, _error);
  5138. }
  5139. }
  5140. void SetOcppErrorCode(unsigned char _index, char *errCode)
  5141. {
  5142. strcpy((char *)ShmOCPP16Data->StatusNotification[_index].ErrorCode, errCode);
  5143. strcpy((char *)_BackupStatusNotification[_index].ErrorCode, errCode);
  5144. }
  5145. void SetOcppVendorErrorCode(unsigned char _index, char *vendorCode)
  5146. {
  5147. strcpy((char *)ShmOCPP16Data->StatusNotification[_index].VendorErrorCode, vendorCode);
  5148. strcpy((char *)_BackupStatusNotification[_index].VendorErrorCode, vendorCode);
  5149. }
  5150. //===============================================
  5151. // SQLite3 related routine
  5152. //===============================================
  5153. int DB_Open(sqlite3 *db)
  5154. {
  5155. int result = PASS;
  5156. char* errMsg = NULL;
  5157. char* createRecordSql="CREATE TABLE IF NOT EXISTS charging_record("
  5158. "idx integer primary key AUTOINCREMENT, "
  5159. "reservationId text, "
  5160. "transactionId text, "
  5161. "startMethod text, "
  5162. "userId text, "
  5163. "dateTimeStart text, "
  5164. "dateTimeStop text,"
  5165. "socStart text, "
  5166. "socStop text, "
  5167. "chargeEnergy text, "
  5168. "stopReason text"
  5169. ");";
  5170. char* createCfgSql="CREATE TABLE IF NOT EXISTS `config` ( "
  5171. "`idx` INTEGER PRIMARY KEY AUTOINCREMENT, "
  5172. "`IsAvailable` TEXT NOT NULL, "
  5173. "`connector` INTEGER NOT NULL, "
  5174. "`val` TEXT NOT NULL, unique(IsAvailable,connector) on conflict replace);";
  5175. if(sqlite3_open(DB_FILE, &db))
  5176. {
  5177. result = FAIL;
  5178. LOG_ERROR( "Can't open database: %s", sqlite3_errmsg(db));
  5179. sqlite3_close(db);
  5180. }
  5181. else
  5182. {
  5183. LOG_INFO( "Local charging record database open successfully.");
  5184. if (sqlite3_exec(db, createRecordSql, 0, 0, &errMsg) != SQLITE_OK)
  5185. {
  5186. result = FAIL;
  5187. LOG_INFO( "Create local charging record table error message: %s", errMsg);
  5188. }
  5189. else
  5190. {
  5191. LOG_INFO( "Opened local charging record table successfully");
  5192. }
  5193. if (sqlite3_exec(db, createCfgSql, 0, 0, &errMsg) != SQLITE_OK)
  5194. {
  5195. result = FAIL;
  5196. LOG_INFO( "Create local config table error message: %s", errMsg);
  5197. }
  5198. else
  5199. {
  5200. LOG_INFO( "Opened local config table successfully");
  5201. }
  5202. sqlite3_close(db);
  5203. }
  5204. return result;
  5205. }
  5206. int DB_Insert_Record(sqlite3 *db, int gun_index)
  5207. {
  5208. int result = PASS;
  5209. char* errMsg = NULL;
  5210. char insertSql[1024];
  5211. sprintf(insertSql, "insert into charging_record(reservationId, transactionId, startMethod, userId, dateTimeStart, dateTimeStop, socStart, socStop, chargeEnergy, stopReason) "
  5212. "values('%d', '%d', '%d', '%s', '%s', '%s', '%d', '%d', '%f', '%s');",
  5213. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId,
  5214. ShmOCPP16Data->StartTransaction[gun_index].ResponseTransactionId,
  5215. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod,
  5216. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId,
  5217. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime,
  5218. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime,
  5219. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
  5220. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
  5221. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy,
  5222. ShmOCPP16Data->StopTransaction[gun_index].StopReason);
  5223. if(sqlite3_open("/Storage/ChargeLog/localCgargingRecord.db", &db))
  5224. {
  5225. result = FAIL;
  5226. LOG_ERROR( "Can't open database: %s", sqlite3_errmsg(db));
  5227. sqlite3_close(db);
  5228. }
  5229. else
  5230. {
  5231. LOG_INFO( "Local charging record database open successfully.");
  5232. if (sqlite3_exec(db, insertSql, 0, 0, &errMsg) != SQLITE_OK)
  5233. {
  5234. result = FAIL;
  5235. LOG_INFO( "Insert local charging record error message: %s", errMsg);
  5236. }
  5237. else
  5238. {
  5239. LOG_INFO( "Insert local charging record successfully");
  5240. }
  5241. sqlite3_close(db);
  5242. }
  5243. return result;
  5244. }
  5245. int DB_Update_Operactive(sqlite3 *db, uint8_t gun_index, uint8_t IsAvailable)
  5246. {
  5247. uint8_t result = false;
  5248. char* errMsg = NULL;
  5249. char sqlStr[1024];
  5250. srand(time(NULL));
  5251. if(sqlite3_open(DB_FILE, &db))
  5252. {
  5253. result = FAIL;
  5254. LOG_ERROR( "Can't open database: %s", sqlite3_errmsg(db));
  5255. sqlite3_close(db);
  5256. }
  5257. else
  5258. {
  5259. LOG_INFO( "Local charging record database open successfully (%d).", IsAvailable);
  5260. sprintf(sqlStr, "insert or replace into config (IsAvailable, connector, val) values('IsAvailable', %d, %d);", gun_index, IsAvailable);
  5261. LOG_INFO("sqlStr= %s", sqlStr);
  5262. if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
  5263. {
  5264. result = FAIL;
  5265. LOG_INFO( "update config error message: %s", errMsg);
  5266. }
  5267. else
  5268. {
  5269. LOG_INFO("update connector-%d config item isOperactive to %d", gun_index, IsAvailable);
  5270. }
  5271. sqlite3_close(db);
  5272. }
  5273. return result;
  5274. }
  5275. int DB_Get_Operactive(sqlite3 *db, uint8_t gun_index)
  5276. {
  5277. uint8_t result = true;
  5278. char* errMsg = NULL;
  5279. char sqlStr[1024];
  5280. char **rs;
  5281. int rows, cols;
  5282. sprintf(sqlStr, "select * from config where IsAvailable='IsAvailable' and connector=%d;", gun_index);
  5283. //DEBUG_INFO("sqlStr= %s\r\n", sqlStr);
  5284. if(sqlite3_open(DB_FILE, &db))
  5285. {
  5286. result = FAIL;
  5287. LOG_ERROR( "Can't open database: %s", sqlite3_errmsg(db));
  5288. sqlite3_close(db);
  5289. }
  5290. else
  5291. {
  5292. LOG_INFO( "Local config query database open successfully.");
  5293. sqlite3_get_table(db, sqlStr, &rs, &rows, &cols, &errMsg);
  5294. if(rows>0)
  5295. {
  5296. for(int idxRow=1;idxRow<=rows;idxRow++)
  5297. {
  5298. if(strcmp(rs[(idxRow*cols)+3], "0") == 0)
  5299. {
  5300. result = false;
  5301. }
  5302. LOG_INFO("Query connector-%d isOperactive: %s", gun_index, rs[(idxRow*cols)+3]);
  5303. }
  5304. }
  5305. else
  5306. {
  5307. LOG_INFO("Query connector-%d fail, set default value to operactive.", gun_index);
  5308. }
  5309. sqlite3_free_table(rs);
  5310. sqlite3_close(db);
  5311. }
  5312. return result;
  5313. }
  5314. //===============================================
  5315. // Config process
  5316. //===============================================
  5317. void AddPlugInTimes(byte gunIndex)
  5318. {
  5319. if (chargingInfo[gunIndex]->Type == _Type_Chademo)
  5320. ShmSysConfigAndInfo->SysConfig.ChademoPlugInTimes += 1;
  5321. else if(chargingInfo[gunIndex]->Type == _Type_CCS_2)
  5322. ShmSysConfigAndInfo->SysConfig.Ccs2PlugInTimes += 1;
  5323. else if(chargingInfo[gunIndex]->Type == _Type_GB)
  5324. ShmSysConfigAndInfo->SysConfig.GbPlugInTimes += 1;
  5325. }
  5326. void ChangeStartOrStopDateTime(byte isStart, byte gunIndex)
  5327. {
  5328. char cmdBuf[32];
  5329. struct timeb csuTime;
  5330. struct tm *tmCSU;
  5331. ftime(&csuTime);
  5332. tmCSU = localtime(&csuTime.time);
  5333. sprintf(cmdBuf, "%04d-%02d-%02d %02d:%02d:%02d", tmCSU->tm_year + 1900,
  5334. tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
  5335. tmCSU->tm_sec);
  5336. if (isStart)
  5337. strcpy((char *)chargingInfo[gunIndex]->StartDateTime, cmdBuf);
  5338. else
  5339. strcpy((char *)chargingInfo[gunIndex]->StopDateTime, cmdBuf);
  5340. }
  5341. void zipLogFiles()
  5342. {
  5343. const char* logPath = "/Storage/SystemLog";
  5344. // 獲取目錄
  5345. DIR* pDir = opendir(logPath);
  5346. if (pDir != NULL)
  5347. {
  5348. struct timeb csuTime;
  5349. struct tm *tmCSU;
  5350. ftime(&csuTime);
  5351. tmCSU = localtime(&csuTime.time);
  5352. // LOG_INFO("Time : %04d-%02d-%02d %02d:%02d:%02d \n", tmCSU->tm_year + 1900,
  5353. // tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
  5354. // tmCSU->tm_sec);
  5355. // Read items inside the folder
  5356. struct dirent* pEntry = NULL;
  5357. while ((pEntry = readdir(pDir)) != NULL)
  5358. {
  5359. if (strcmp(pEntry->d_name, ".") != 0 &&
  5360. strcmp(pEntry->d_name, "..") != 0 &&
  5361. strncmp(pEntry->d_name, "[", 1) == 0 &&
  5362. strstr(pEntry->d_name, "tar") < 0)
  5363. {
  5364. char yearC[5];
  5365. unsigned short year = 0;
  5366. char monthC[3];
  5367. unsigned short month = 0;
  5368. yearC[4] = '\0';
  5369. strncpy(yearC, pEntry->d_name + 1, 4);
  5370. monthC[2] = '\0';
  5371. strncpy(monthC, pEntry->d_name + 6, 2);
  5372. year = atoi(yearC);
  5373. month = atoi(monthC);
  5374. if (year != 0)
  5375. {
  5376. if (year < tmCSU->tm_year + 1900 ||
  5377. (year >= tmCSU->tm_year + 1900 && month < tmCSU->tm_mon + 1))
  5378. {
  5379. LOG_INFO("tar file name : %s", pEntry->d_name);
  5380. char file[256];
  5381. memset(file, 0x00, sizeof(file));
  5382. strcat(file, "tar zcvf ");
  5383. strcat(file, logPath);
  5384. strncat(file, "/", 1);
  5385. strcat(file, pEntry->d_name);
  5386. strcat(file, ".tar");
  5387. strncat(file, " ", 1);
  5388. strcat(file, logPath);
  5389. strncat(file, "/", 1);
  5390. strcat(file, pEntry->d_name);
  5391. LOG_INFO("zip = %s \n", file);
  5392. system(file);
  5393. }
  5394. }
  5395. }
  5396. }
  5397. }
  5398. // Close folder
  5399. closedir(pDir);
  5400. }
  5401. void ChangeGunSelectByIndex(byte sel)
  5402. {
  5403. ShmSysConfigAndInfo->SysInfo.CurGunSelected = sel;
  5404. ShmSysConfigAndInfo->SysInfo.CurGunSelectedByAc = NO_DEFINE;
  5405. }
  5406. void StopProcessingLoop()
  5407. {
  5408. for (;;)
  5409. {
  5410. CheckFactoryConfigFunction();
  5411. CheckFwUpdateFunction();
  5412. if (ShmSysConfigAndInfo->SysWarningInfo.Level == 2)
  5413. {
  5414. ChkPrimaryStatus();
  5415. if (ShmSysConfigAndInfo->SysWarningInfo.Level == 0)
  5416. {
  5417. LOG_INFO("Soft reboot for retry self-tets (Primary).");
  5418. KillAllTask();
  5419. sleep(3);
  5420. TryCloseWatchdog();
  5421. system("/usr/bin/run_evse_restart.sh");
  5422. return;
  5423. }
  5424. }
  5425. if(ShmOCPP16Data->MsMsg.bits.ResetReq == YES)
  5426. {
  5427. if(strcmp((char *)ShmOCPP16Data->Reset.Type, "Hard") == EQUAL)
  5428. {
  5429. ShmChargerInfo->Control.SysCtrl.bits.NeedHardReset = true;
  5430. }
  5431. if(strcmp((char *)ShmOCPP16Data->Reset.Type, "Soft") == EQUAL)
  5432. {
  5433. ShmChargerInfo->Control.SysCtrl.bits.NeedSoftReset = true;
  5434. }
  5435. }
  5436. CheckSoftHardReset();
  5437. sleep(1);
  5438. }
  5439. }
  5440. void CreateWatchdog(void)
  5441. {
  5442. wtdFd = InitWatchDog();
  5443. if(wtdFd < 0)
  5444. {
  5445. LOG_INFO("Watchdog Initial Fail");
  5446. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
  5447. }
  5448. else
  5449. {
  5450. LOG_INFO("Watchdog Initial Success");
  5451. }
  5452. }
  5453. void TryCloseWatchdog(void)
  5454. {
  5455. if(wtdFd > 0)
  5456. {
  5457. write(wtdFd, "V", 1);
  5458. close(wtdFd);
  5459. }
  5460. }
  5461. void TryFeedWatchdog(void)
  5462. {
  5463. if(wtdFd > 0)
  5464. {
  5465. write(wtdFd, "a", 1);
  5466. }
  5467. }
  5468. bool IsParallelCabinetIdle(void)
  5469. {
  5470. bool result = true;
  5471. if(ShmChargerInfo->Control.CabinetRole == _CROLE_SLAVE)
  5472. {
  5473. result = false;
  5474. }
  5475. return result;
  5476. }
  5477. bool IsConnectorWholeIdle(void)
  5478. {
  5479. bool result = true;
  5480. for (byte count = 0; count < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; count++)
  5481. {
  5482. if (chargingInfo[count]->SystemStatus != S_IDLE &&
  5483. chargingInfo[count]->SystemStatus != S_RESERVATION &&
  5484. chargingInfo[count]->SystemStatus != S_FAULT &&
  5485. chargingInfo[count]->SystemStatus != S_MAINTAIN)
  5486. {
  5487. result = false;
  5488. break;
  5489. }
  5490. }
  5491. return result;
  5492. }
  5493. void ClearAlarmCodeWhenAcOff()
  5494. {
  5495. if (!ShmSysConfigAndInfo->SysInfo.AcContactorStatus)
  5496. {
  5497. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuNoResource = NO;
  5498. }
  5499. }
  5500. //==========================================
  5501. // Check task processing
  5502. //==========================================
  5503. void CheckTask()
  5504. {
  5505. if(ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T' || ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D')
  5506. {
  5507. if(ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomEnabled == YES)
  5508. {
  5509. if(system("pidof -s Module_4g > /dev/null") != 0 && ShmChargerInfo->Control.SysCtrl.bits.Wifi4gResetEnable == false)
  5510. {
  5511. LOG_ERROR("Module_4g not running, restart it.");
  5512. system("/root/Module_4g &");
  5513. }
  5514. }
  5515. }
  5516. if(ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W' || ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D')
  5517. {
  5518. if(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode != _SYS_WIFI_MODE_DISABLE)
  5519. {
  5520. if(system("pidof -s Module_Wifi > /dev/null") != 0 && ShmChargerInfo->Control.SysCtrl.bits.Wifi4gResetEnable == false)
  5521. {
  5522. LOG_ERROR("Module_Wifi not running, restart it.");
  5523. system("/root/Module_Wifi &");
  5524. }
  5525. }
  5526. }
  5527. if(ShmChargerInfo->Control.CabinetRole != _CROLE_SLAVE &&
  5528. strcmp((char *)ShmSysConfigAndInfo->SysConfig.OcppServerURL, "") != EQUAL &&
  5529. strcmp((char *)ShmSysConfigAndInfo->SysConfig.ChargeBoxId, "") != EQUAL)
  5530. {
  5531. ShmChargerInfo->Control.SysCtrl.bits.BackendEnable = true;
  5532. if((time((time_t*)NULL) - ShmOCPP16Data->procDogTime) > 180)
  5533. {
  5534. LOG_ERROR("OcppBackend watch dog timeout task restart.");
  5535. ShmOCPP16Data->procDogTime = time((time_t*)NULL);
  5536. system("pkill OcppBackend");
  5537. }
  5538. if(system("pidof -s OcppBackend > /dev/null") != 0)
  5539. {
  5540. LOG_ERROR("OcppBackend not running, restart it.");
  5541. system("/root/OcppBackend &");
  5542. }
  5543. }
  5544. else
  5545. {
  5546. ShmChargerInfo->Control.SysCtrl.bits.BackendEnable = false;
  5547. }
  5548. if(system("pidof -s Module_ProduceUtils > /dev/null") != 0)
  5549. {
  5550. LOG_ERROR("Module_ProduceUtils not running, restart it.");
  5551. system ("/root/Module_ProduceUtils &");
  5552. }
  5553. if(system("pidof -s Module_EvComm > /dev/null") != 0)
  5554. {
  5555. LOG_ERROR("Module_EvComm not running, restart it.");
  5556. system ("/root/Module_EvComm &");
  5557. }
  5558. if(system("pidof -s Module_InternalComm > /dev/null") != 0)
  5559. {
  5560. LOG_ERROR("Module_InternalComm not running, restart it.");
  5561. system ("/root/Module_InternalComm &");
  5562. //ShmChargerInfo->Control.SysCtrl.bits.NeedSoftReset = true;
  5563. }
  5564. }
  5565. void InitialDHCP()
  5566. {
  5567. char tmpbuf[256];
  5568. memset(tmpbuf,0,256);
  5569. system("pgrep -f \"udhcpc -i eth0\" | xargs kill");
  5570. sprintf(tmpbuf, "/sbin/udhcpc -i eth0 -x hostname:CSU3_%s -s /root/dhcp_script/eth0.script > /dev/null &", ShmSysConfigAndInfo->SysConfig.SystemId);
  5571. system(tmpbuf);
  5572. }
  5573. void InitialDispenserDhcpServerConfig(void)
  5574. {
  5575. system("echo 'start 192.168.100.10' > /etc/udhcpd_eth1.conf");
  5576. system("echo 'end 192.168.100.20' >> /etc/udhcpd_eth1.conf");
  5577. system("echo 'interface eth1' >> /etc/udhcpd_eth1.conf");
  5578. system("echo 'opt dns 8.8.8.8' >> /etc/udhcpd_eth1.conf");
  5579. system("echo 'option subnet 255.255.255.0' >> /etc/udhcpd_eth1.conf");
  5580. system("echo 'opt router 192.168.100.1' >> /etc/udhcpd_eth1.conf");
  5581. system("echo 'option domain local' >> /etc/udhcpd_eth1.conf");
  5582. system("echo 'option lease 86400' >> /etc/udhcpd_eth1.conf");
  5583. usleep(1000);
  5584. }
  5585. void StartDispenserDhcpServer(void)
  5586. {
  5587. system("pgrep -f \"udhcpd /etc/udhcpd_eth1.conf\" | xargs kill");
  5588. system("/usr/sbin/udhcpd /etc/udhcpd_eth1.conf > /dev/null &");
  5589. }
  5590. //==========================================
  5591. // Check Smart Charging Profile
  5592. //==========================================
  5593. void Ocpp_ProfileReq_Cmd(byte gunIndex)
  5594. {
  5595. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  5596. {
  5597. if(ShmOCPP16Data->CSUMsg.bits[gunIndex].ChargingProfileConf == NO)
  5598. {
  5599. if(ShmOCPP16Data->CSUMsg.bits[gunIndex].ChargingProfileReq == NO)
  5600. {
  5601. ShmOCPP16Data->CSUMsg.bits[gunIndex].ChargingProfileReq = YES;
  5602. }
  5603. }
  5604. }
  5605. }
  5606. bool Ocpp_Chk_ProfileConf_Cmd(byte gunIndex)
  5607. {
  5608. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  5609. {
  5610. if (ShmOCPP16Data->CSUMsg.bits[gunIndex].ChargingProfileConf == YES)
  5611. {
  5612. ShmOCPP16Data->CSUMsg.bits[gunIndex].ChargingProfileConf = NO;
  5613. return true;
  5614. }
  5615. }
  5616. return false;
  5617. }
  5618. int GetStartScheduleTime(unsigned char *time)
  5619. {
  5620. int result = -1;
  5621. struct tm tmScheduleStart;
  5622. struct timeb tbScheduleStart;
  5623. 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))
  5624. {
  5625. tmScheduleStart.tm_year -= 1900;
  5626. tmScheduleStart.tm_mon -= 1;
  5627. tbScheduleStart.time = mktime(&tmScheduleStart);
  5628. tbScheduleStart.millitm = 0;
  5629. result = DiffTimebWithNow(tbScheduleStart) / 1000;
  5630. }
  5631. return result;
  5632. }
  5633. void Ocpp_ChargingProfile_Process(byte _index)
  5634. {
  5635. int _time = 0;
  5636. int _startCount = NO_DEFINE;
  5637. int _maxCount = 0;
  5638. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  5639. {
  5640. if (strcmp((char *)ShmOCPP16Data->SmartChargingProfile[_index].ChargingProfileKind, "Absolute") == EQUAL &&
  5641. ShmOCPP16Data->SmartChargingProfile[_index].ChargingProfileId == YES)
  5642. {
  5643. _time = GetStartScheduleTime(ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.StartSchedule);
  5644. _maxCount = ARRAY_SIZE(ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod);
  5645. _startCount = NO_DEFINE;
  5646. for (byte _count = 0; _count < _maxCount; _count++)
  5647. {
  5648. // 預設最小輸出電流 (MIN_OUTPUT_CUR) A
  5649. if (_time >= ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_count].StartPeriod)
  5650. {
  5651. if ((_count == 0 && ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_count].Limit >= MIN_OUTPUT_CUR) ||
  5652. ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_count].Limit > MIN_OUTPUT_CUR)
  5653. {
  5654. _startCount = _count;
  5655. }
  5656. }
  5657. }
  5658. if (_startCount < _maxCount)
  5659. {
  5660. chargingInfo[_index]->ChargingProfilePower = ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_startCount].Limit * AC_OUTPUT_VOL * ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_startCount].NumberPhases;
  5661. if (chargingInfo[_index]->EvBatterytargetVoltage > 0 &&
  5662. (int)chargingInfo[_index]->PresentChargingVoltage > 0)
  5663. {
  5664. chargingInfo[_index]->ChargingProfileCurrent = (chargingInfo[_index]->ChargingProfilePower / chargingInfo[_index]->PresentChargingVoltage) * 10;
  5665. }
  5666. else
  5667. {
  5668. chargingInfo[_index]->ChargingProfileCurrent = -1;
  5669. }
  5670. }
  5671. else
  5672. {
  5673. chargingInfo[_index]->ChargingProfilePower = -1;
  5674. chargingInfo[_index]->ChargingProfileCurrent = -1;
  5675. }
  5676. }
  5677. else
  5678. {
  5679. chargingInfo[_index]->ChargingProfilePower = -1;
  5680. chargingInfo[_index]->ChargingProfileCurrent = -1;
  5681. }
  5682. }
  5683. else
  5684. {
  5685. chargingInfo[_index]->ChargingProfilePower = -1;
  5686. chargingInfo[_index]->ChargingProfileCurrent = -1;
  5687. }
  5688. if((int)_lastProfilePower[_index] != (int)chargingInfo[_index]->ChargingProfilePower ||
  5689. (int)_lastProfileCurrent[_index] != (int)chargingInfo[_index]->ChargingProfileCurrent)
  5690. {
  5691. LOG_INFO("Gun %d Get Profile - Index = %d, Limit = %f",
  5692. _index + 1, _startCount,
  5693. ShmOCPP16Data->SmartChargingProfile[_index].ChargingSchedule.ChargingSchedulePeriod[_startCount].Limit);
  5694. LOG_INFO("Max: %d kW, Gun %d ChargingProfile Power = %d, Current = %d",
  5695. ShmSysConfigAndInfo->SysInfo.MaxChargingProfilePower == -1 ? (int)ShmSysConfigAndInfo->SysInfo.MaxChargingProfilePower : ((int)ShmSysConfigAndInfo->SysInfo.MaxChargingProfilePower / 1000),
  5696. _index + 1, (int)chargingInfo[_index]->ChargingProfilePower, (int)chargingInfo[_index]->ChargingProfileCurrent);
  5697. }
  5698. _lastProfilePower[_index] = chargingInfo[_index]->ChargingProfilePower;
  5699. _lastProfileCurrent[_index] = chargingInfo[_index]->ChargingProfileCurrent;
  5700. }
  5701. void Ocpp_MaxChargingProfile_Process(void)
  5702. {
  5703. int _time = 0;
  5704. int _startCount = NO_DEFINE;
  5705. int _maxCount = 0;
  5706. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  5707. {
  5708. if (strcmp((char *)ShmOCPP16Data->MaxChargingProfile.ChargingProfileKind, "Absolute") == EQUAL &&
  5709. ShmOCPP16Data->MaxChargingProfile.ChargingProfileId == YES)
  5710. {
  5711. _time = GetStartScheduleTime(ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.StartSchedule);
  5712. _maxCount = ARRAY_SIZE(ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod);
  5713. _startCount = NO_DEFINE;
  5714. for (byte _count = 0; _count < _maxCount; _count++)
  5715. {
  5716. // 預設最小輸出電流 (MIN_OUTPUT_CUR) A
  5717. if (_time >= ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[_count].StartPeriod)
  5718. {
  5719. if ((_count == 0 && ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[_count].Limit >= MIN_OUTPUT_CUR) ||
  5720. ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[_count].Limit > MIN_OUTPUT_CUR)
  5721. {
  5722. _startCount = _count;
  5723. }
  5724. }
  5725. }
  5726. if(_startCount < _maxCount)
  5727. {
  5728. ShmSysConfigAndInfo->SysInfo.MaxChargingProfilePower = ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[_startCount].Limit * AC_OUTPUT_VOL * ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[_startCount].NumberPhases;
  5729. }
  5730. else
  5731. {
  5732. ShmSysConfigAndInfo->SysInfo.MaxChargingProfilePower = -1;
  5733. }
  5734. }
  5735. else
  5736. {
  5737. ShmSysConfigAndInfo->SysInfo.MaxChargingProfilePower = -1;
  5738. }
  5739. }
  5740. else
  5741. {
  5742. ShmSysConfigAndInfo->SysInfo.MaxChargingProfilePower = -1;
  5743. }
  5744. if((int)_lastMaxProfilePower != (int)ShmSysConfigAndInfo->SysInfo.MaxChargingProfilePower)
  5745. {
  5746. LOG_INFO("Charger Get Max Profile - Index = %d, Limit = %f",
  5747. _startCount, ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[_startCount].Limit);
  5748. LOG_INFO("Charger Max Profile Power = %d", (int)ShmSysConfigAndInfo->SysInfo.MaxChargingProfilePower);
  5749. }
  5750. _lastMaxProfilePower = ShmSysConfigAndInfo->SysInfo.MaxChargingProfilePower;
  5751. }
  5752. void CheckSmartChargeProfile(byte _index)
  5753. {
  5754. if(Ocpp_Chk_ProfileConf_Cmd(_index))
  5755. {
  5756. Ocpp_MaxChargingProfile_Process();
  5757. Ocpp_ChargingProfile_Process(_index);
  5758. }
  5759. }
  5760. bool Ocpp_CheckInvalidId(byte _index)
  5761. {
  5762. bool invalid = false;
  5763. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  5764. {
  5765. if(strstr((char *) ShmOCPP16Data->ConfigurationTable.CoreProfile[StopTransactionOnInvalidId].ItemData, "TRUE"))
  5766. {
  5767. if(strcmp((char *)ShmOCPP16Data->StartTransaction[_index].ResponseIdTagInfo.Status, "Blocked") == EQUAL ||
  5768. strcmp((char *)ShmOCPP16Data->StartTransaction[_index].ResponseIdTagInfo.Status, "Expired") == EQUAL ||
  5769. strcmp((char *)ShmOCPP16Data->StartTransaction[_index].ResponseIdTagInfo.Status, "Invalid") == EQUAL)
  5770. {
  5771. invalid = true;
  5772. LOG_INFO("Gun %d Stop Transaction On Invalid Id", _index + 1);
  5773. }
  5774. }
  5775. else
  5776. {
  5777. if(strcmp((char *)ShmOCPP16Data->StartTransaction[_index].ResponseIdTagInfo.Status, "Accepted") != EQUAL)
  5778. {
  5779. invalid = true;
  5780. LOG_INFO("Gun %d Start Transaction Not Accepted", _index + 1);
  5781. }
  5782. }
  5783. }
  5784. return invalid;
  5785. }
  5786. void TheEndCharging(byte gun_index)
  5787. {
  5788. chargingInfo[gun_index]->isRemoteStart = NO;
  5789. //StopGunInfoTimeoutDet(gun_index);
  5790. //StartGunInfoTimeoutDet(gun_index, Timeout_EvseCompleteDet);
  5791. ChangeStartOrStopDateTime(NO, gun_index);
  5792. //DB_Insert_Record(localDb, gun_index);
  5793. }
  5794. void UpdateErrorCodeToOcpp(byte index)
  5795. {
  5796. //printf("ConnectorAlarmCode = %s \n", chargingInfo[index]->ConnectorAlarmCode);
  5797. if (strcmp((char *)chargingInfo[index]->ConnectorAlarmCode, "") != EQUAL)
  5798. {
  5799. SetOcppErrorCode(index, "InternalError");
  5800. SetOcppVendorErrorCode(index, (char *)chargingInfo[index]->ConnectorAlarmCode);
  5801. }
  5802. else if (strcmp((char *)chargingInfo[index]->EvConnAlarmCode, "") != EQUAL)
  5803. {
  5804. SetOcppErrorCode(index, "OtherError");
  5805. SetOcppVendorErrorCode(index, (char *)chargingInfo[index]->EvConnAlarmCode);
  5806. }
  5807. }
  5808. void CheckMiscCommandRequirement(void)
  5809. {
  5810. BOOL NeedAnnouncement = FALSE;
  5811. unsigned char connector = 0;
  5812. if(ShmSysConfigAndInfo->SysInfo.FirmwareUpdate != YES)
  5813. {
  5814. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  5815. {
  5816. NeedAnnouncement = FALSE;
  5817. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].LocalStatus != _DS_None &&
  5818. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].LocalStatus != _DS_Timeout)
  5819. {
  5820. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.ConnectorTimeoutConfigRequest ||
  5821. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.DefaultPriceConfigRequest ||
  5822. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.CurrencyConfigRequest ||
  5823. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.HardwareRebootRequest ||
  5824. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.SoftwareResetRequest ||
  5825. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.BackendStatusRequest ||
  5826. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.EthernetStatusRequest ||
  5827. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.WiFiStatusRequest ||
  5828. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.TelcomModemStatusRequest ||
  5829. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.BillingStatusRequest ||
  5830. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.StopButtonStatusRequest ||
  5831. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.AuthModeConfigRequest ||
  5832. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.EVCCIDConfigRequest)
  5833. {
  5834. NeedAnnouncement = TRUE;
  5835. }
  5836. for(int j = 0; j < ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ConnectorQuantity; j++)
  5837. {
  5838. connector = ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ConnectorID[j] - 1;
  5839. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].Parameter.bits.AvailabilityRequest ||
  5840. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].Parameter.bits.RemoteStartRequest ||
  5841. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].Parameter.bits.AccountBalanceRequest)
  5842. {
  5843. NeedAnnouncement = TRUE;
  5844. }
  5845. }
  5846. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.MiscNeedAnnouncement != NeedAnnouncement)
  5847. {
  5848. if(NeedAnnouncement)
  5849. {
  5850. LOG_INFO("********** Dispenser %d Misc Command Need Announcement **********", i + 1);
  5851. }
  5852. else
  5853. {
  5854. LOG_INFO("********** Dispenser %d Misc Command Announced **********", i + 1);
  5855. }
  5856. }
  5857. }
  5858. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.MiscNeedAnnouncement = NeedAnnouncement;
  5859. }
  5860. }
  5861. }
  5862. void CheckDispenserVersionUpdateRequirement(void)
  5863. {
  5864. }
  5865. bool IsReadyParalleling(void)
  5866. {
  5867. bool ready = true;
  5868. for(int i = 0; i < ShmChargerInfo->Control.MaxConnector; i++)
  5869. {
  5870. if(chargingInfo[i]->SystemStatus != S_IDLE && chargingInfo[i]->SystemStatus != S_MAINTAIN)
  5871. {
  5872. ready = false;
  5873. break;
  5874. }
  5875. }
  5876. return ready;
  5877. }
  5878. void SetParallelingStart(void)
  5879. {
  5880. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  5881. {
  5882. if(chargingInfo[i]->SystemStatus == S_IDLE)
  5883. {
  5884. setChargerMode(i, MODE_MAINTAIN);
  5885. }
  5886. }
  5887. ShmChargerInfo->ParallelCabinet.ParallelStatus = _Parallel_Wait;
  5888. }
  5889. void SetParallelingDone(void)
  5890. {
  5891. unsigned short totalPow = 0;
  5892. totalPow = GetTotalParallelCabinetPower();
  5893. if(totalPow != ShmChargerInfo->ParallelCabinet.TotalParallelPower)
  5894. {
  5895. LOG_INFO("Total Parallel Cabinet Power: %d.%d kW", (totalPow / 10), (totalPow % 10));
  5896. }
  5897. ShmChargerInfo->ParallelCabinet.TotalParallelPower = totalPow;
  5898. ShmChargerInfo->ParallelCabinet.ParallelStatus = _Parallel_None;
  5899. }
  5900. void SetPCabinetOutputRelay(unsigned char index, unsigned char OnOff)
  5901. {
  5902. unsigned char relay = 0;
  5903. if(ShmChargerInfo->Control.CabinetRole == _CROLE_MASTER)
  5904. {
  5905. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  5906. {
  5907. if(ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Idle &&
  5908. ShmChargerInfo->ParallelCabinet.PCabinet[i].ParallelConfirm)
  5909. {
  5910. relay = OnOff == YES ? YES : NO;
  5911. if(ShmChargerInfo->ParallelCabinet.PCabinet[index].OutputRelaySetting[index] != relay)
  5912. {
  5913. LOG_INFO("Set Parallel Cabinet Gun %d Output Relay %s", index + 1, relay == YES ? "ON" : "OFF");
  5914. }
  5915. ShmChargerInfo->ParallelCabinet.PCabinet[i].OutputRelaySetting[index] = relay;
  5916. }
  5917. }
  5918. }
  5919. }
  5920. void SetParallelCabinetAcContactor(unsigned char OnOff)
  5921. {
  5922. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  5923. {
  5924. if(ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Idle &&
  5925. ShmChargerInfo->ParallelCabinet.PCabinet[i].ParallelConfirm)
  5926. {
  5927. ShmChargerInfo->ParallelCabinet.PCabinet[i].AcContactorSetting = OnOff == YES ? YES : NO;
  5928. }
  5929. }
  5930. }
  5931. unsigned short GetTotalParallelCabinetPower(void)
  5932. {
  5933. unsigned short power = 0, slavePow = 0;
  5934. if(ShmChargerInfo->Control.CabinetRole == _CROLE_MASTER)
  5935. {
  5936. for(int i = 0; i < MAX_SLAVE_CABINET_QUANTITY; i++)
  5937. {
  5938. if(ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Idle ||
  5939. ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Alarm ||
  5940. ShmChargerInfo->ParallelCabinet.PCabinet[i].LocalStatus == _DS_Charging)
  5941. {
  5942. slavePow = ParsingRatingPower((char *)ShmChargerInfo->ParallelCabinet.PCabinet[i].ModelName);
  5943. power += slavePow;
  5944. }
  5945. }
  5946. }
  5947. return power;
  5948. }
  5949. unsigned char preParallelStatus = 0;
  5950. void MCabinetParallelingProcess(void)
  5951. {
  5952. bool PsuReInitial = false;
  5953. unsigned char status = 0;
  5954. if(ShmChargerInfo->Control.CabinetRole == _CROLE_MASTER)
  5955. {
  5956. if(IsReadyParalleling())
  5957. {
  5958. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  5959. {
  5960. if(ShmChargerInfo->ParallelCabinet.PCabinet[i].ParallelRequest)
  5961. {
  5962. ShmChargerInfo->ParallelCabinet.PCabinet[i].ParallelRequest = false;
  5963. ShmChargerInfo->ParallelCabinet.PCabinet[i].ParallelConfirm = true;
  5964. PsuReInitial = true;
  5965. }
  5966. }
  5967. if(PsuReInitial)
  5968. {
  5969. SetParallelingStart();
  5970. }
  5971. }
  5972. status = ShmChargerInfo->ParallelCabinet.ParallelStatus;
  5973. switch(status)
  5974. {
  5975. case _Parallel_None:
  5976. if(preParallelStatus != status)
  5977. {
  5978. LOG_INFO("MCabinet Parallel Status [None]");
  5979. GetClockTime(&_Parallel_Time);
  5980. }
  5981. unsigned short totalPow = 0;
  5982. totalPow = GetTotalParallelCabinetPower();
  5983. if(totalPow != ShmChargerInfo->ParallelCabinet.TotalParallelPower)
  5984. {
  5985. LOG_INFO("Total Parallel Cabinet Power: %d.%d kW", (totalPow / 10), (totalPow % 10));
  5986. }
  5987. ShmChargerInfo->ParallelCabinet.TotalParallelPower = totalPow;
  5988. break;
  5989. case _Parallel_Wait:
  5990. if(preParallelStatus != status)
  5991. {
  5992. LOG_INFO("MCabinet Parallel Status [Wait]");
  5993. SetAcContactor(OFF);
  5994. SetParallelCabinetAcContactor(OFF);
  5995. for(int i = 0; i < CONNECTOR_QUANTITY; i++)
  5996. {
  5997. SetPCabinetOutputRelay(i, OFF);
  5998. }
  5999. GetClockTime(&_Parallel_Time);
  6000. }
  6001. if((GetTimeoutValue(_Parallel_Time) / uSEC_VAL) >= PARALLEL_WAIT_TIME)
  6002. {
  6003. ShmChargerInfo->ParallelCabinet.ParallelStatus = _Parallel_Working;
  6004. }
  6005. break;
  6006. case _Parallel_Working:
  6007. if(preParallelStatus != status)
  6008. {
  6009. LOG_INFO("MCabinet Parallel Status [Working]");
  6010. SetAcContactor(ON);
  6011. SetParallelCabinetAcContactor(ON);
  6012. GetClockTime(&_Parallel_Time);
  6013. }
  6014. if(ShmPsuData->Work_Step == _WORK_CHARGING)
  6015. {
  6016. ShmChargerInfo->ParallelCabinet.ParallelStatus = _Parallel_Done;
  6017. }
  6018. break;
  6019. case _Parallel_Done:
  6020. if(preParallelStatus != status)
  6021. {
  6022. LOG_INFO("MCabinet Parallel Status [Done]");
  6023. GetClockTime(&_Parallel_Time);
  6024. }
  6025. if((GetTimeoutValue(_Parallel_Time) / uSEC_VAL) >= PARALLEL_WAIT_TIME)
  6026. {
  6027. SetParallelingDone();
  6028. }
  6029. break;
  6030. }
  6031. preParallelStatus = status;
  6032. }
  6033. }
  6034. void SCabinetControllProcess(void)
  6035. {
  6036. if(ShmChargerInfo->Control.CabinetRole == _CROLE_SLAVE)
  6037. {
  6038. if(ShmChargerInfo->SCabinetControl.SAcContactor)
  6039. {
  6040. SetAcContactor(ON);
  6041. }
  6042. else
  6043. {
  6044. SetAcContactor(OFF);
  6045. }
  6046. unsigned short _parallelRelay = 0;
  6047. for(int i = 0; i < GENERAL_GUN_QUANTITY; i++)
  6048. {
  6049. _parallelRelay = ShmChargerInfo->SCabinetControl.SParallelRelay[i] > 0 ? (1 < i) : 0;
  6050. }
  6051. if(_parallelRelay != ShmChargerInfo->PsuGrouping.ParallelRelayConfig.CtrlValue)
  6052. {
  6053. LOG_INFO("SCabinet Set Parallel Relay %X -> %X", ShmChargerInfo->PsuGrouping.ParallelRelayConfig.CtrlValue, _parallelRelay);
  6054. }
  6055. ShmChargerInfo->PsuGrouping.ParallelRelayConfig.CtrlValue = _parallelRelay;
  6056. }
  6057. }
  6058. void CheckConnectorDisconnectionRecovery(unsigned char connector)
  6059. {
  6060. unsigned char dispenser = 0;
  6061. dispenser = ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].ParentDispensetIndex;
  6062. if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].LocalStatus != _DS_Timeout)
  6063. {
  6064. LOG_INFO("Connector %d Disconnection Recovery", connector + 1);
  6065. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connector].Parameter.bits.Disconnection = false;
  6066. }
  6067. }
  6068. bool ConnectorRequestToCharging(unsigned char connector)
  6069. {
  6070. unsigned char role = 0;
  6071. bool done = false;
  6072. role = ShmPsuGrouping->GroupCollection[connector].Role;
  6073. switch(role)
  6074. {
  6075. case _GROLE_IDLE:
  6076. if(!ShmPsuGrouping->GroupCollection[connector].GroupCtrl.bits.ChargingRequest)
  6077. {
  6078. LOG_INFO("Request Gun %d To Start Charging", connector + 1);
  6079. }
  6080. ShmPsuGrouping->GroupCollection[connector].GroupCtrl.bits.ChargingRequest = true;
  6081. break;
  6082. case _GROLE_MASTER:
  6083. done = true;
  6084. break;
  6085. case _GROLE_SLAVE:
  6086. if(!ShmPsuGrouping->GroupCollection[connector].GroupCtrl.bits.SlaveChargingRequest)
  6087. {
  6088. LOG_INFO("Gun %d Wait For Re-Grouping", connector + 1);
  6089. }
  6090. ShmPsuGrouping->GroupCollection[connector].GroupCtrl.bits.SlaveChargingRequest = true;
  6091. break;
  6092. case _GROLE_REQUEST_TO_CHARGING:
  6093. done = true;
  6094. break;
  6095. default:
  6096. break;
  6097. }
  6098. return done;
  6099. }
  6100. bool IsConnectorGroupingCompleted(unsigned char connector)
  6101. {
  6102. unsigned char role = 0;
  6103. bool completed = false;
  6104. role = ShmPsuGrouping->GroupCollection[connector].Role;
  6105. switch(role)
  6106. {
  6107. case _GROLE_MASTER:
  6108. completed = true;
  6109. break;
  6110. default:
  6111. break;
  6112. }
  6113. return completed;
  6114. }
  6115. void SelfTestFailReason(void)
  6116. {
  6117. char reason[50];
  6118. memset(reason, 0x00, sizeof(reason));
  6119. if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.EmergencyStopTrip)
  6120. {
  6121. StatusCodeCompose(reason, "042251");
  6122. }
  6123. else if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PrimaryStestFail ||
  6124. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RelayboardStestFail ||
  6125. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FanboardStestFail)
  6126. {
  6127. if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RelayboardStestFail)
  6128. {
  6129. StatusCodeCompose(reason, "042280");
  6130. }
  6131. if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FanboardStestFail)
  6132. {
  6133. StatusCodeCompose(reason, "042281");
  6134. }
  6135. if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PrimaryStestFail)
  6136. {
  6137. StatusCodeCompose(reason, "042282");
  6138. }
  6139. }
  6140. else if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcContactStestFail ||
  6141. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuModuleStestFail)
  6142. {
  6143. if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.AcContactStestFail)
  6144. {
  6145. StatusCodeCompose(reason, "042285");
  6146. }
  6147. if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuModuleStestFail)
  6148. {
  6149. StatusCodeCompose(reason, "042286");
  6150. }
  6151. }
  6152. else
  6153. {
  6154. StatusCodeCompose(reason, "Self Test Fail");
  6155. }
  6156. for (byte gun_index = 0; gun_index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun_index++)
  6157. {
  6158. SetOcppErrorCode(gun_index, "InternalError");
  6159. SetOcppVendorErrorCode(gun_index, reason);
  6160. setChargerMode(gun_index, MODE_MAINTAIN);
  6161. }
  6162. }
  6163. int main(void)
  6164. {
  6165. unsigned long time = 0;
  6166. if(CreateShareMemory() == 0)
  6167. {
  6168. #ifdef SystemLogMessage
  6169. LOG_ERROR("CreatShareMemory NG");
  6170. #endif
  6171. if(ShmStatusCodeData!=NULL)
  6172. {
  6173. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory = 1;
  6174. }
  6175. sleep(5);
  6176. system("reboot -f");
  6177. sleep(5);
  6178. system("reboot -f");
  6179. }
  6180. LOG_INFO("\n");
  6181. LOG_INFO("===== Boot and Initialization start =====");
  6182. LOG_INFO("Main Fork PID = %d", getpid());
  6183. if (!InitialSystemDefaultConfig())
  6184. {
  6185. LOG_INFO("InitialSystemDefaultConfig NG");
  6186. StopProcessingLoop();
  6187. }
  6188. LOG_INFO("ModelName: [%s], SN: [%s], SW Version: [%s]",
  6189. ShmSysConfigAndInfo->SysConfig.ModelName, ShmSysConfigAndInfo->SysConfig.SerialNumber, fwVersion);
  6190. LOG_INFO("InitialShareMemoryInfo");
  6191. InitialShareMemoryInfo();
  6192. LOG_INFO("ChargerType (IEC or UL) = %d", ShmSysConfigAndInfo->SysInfo.ChargerType);
  6193. ChangeLcmByIndex(_LCM_INIT);
  6194. if(!InitialChargerSetting())
  6195. {
  6196. isModelNameMatch = false;
  6197. }
  6198. Initialization();
  6199. LOG_INFO("Spawn all Task.");
  6200. SpawnTask();
  6201. if (!isModelNameMatch)
  6202. {
  6203. LOG_INFO("Module Name & HW info none match.");
  6204. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.ModelNameNoneMatchStestFail = YES;
  6205. ChangeLcmByIndex(_LCM_FIX);
  6206. // Module Name 與硬體對應不正確
  6207. LOG_ERROR("Module Name & HW info none match.");
  6208. sleep(3);
  6209. KillAllTask();
  6210. StopProcessingLoop();
  6211. }
  6212. LOG_INFO("Module Name & HW info correct. Initialize.......");
  6213. CreateTimeoutFork();
  6214. SelfTestRun();
  6215. while(ShmSysConfigAndInfo->SysInfo.BootingStatus != BOOT_COMPLETE)
  6216. {
  6217. sleep(1);
  6218. }
  6219. if(ShmSysConfigAndInfo->SysInfo.SelfTestSeq != _STEST_COMPLETE)
  6220. {
  6221. sleep(1);
  6222. SelfTestFailReason();
  6223. }
  6224. else
  6225. {
  6226. for (byte gun_index = 0; gun_index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun_index++)
  6227. {
  6228. setChargerMode(gun_index, MODE_IDLE);
  6229. if(ShmPsuData->PsuGroup[gun_index].GroupPresentPsuQuantity > 0)
  6230. {
  6231. ShmChargerInfo->Control.GunAvailable[gun_index] = YES;
  6232. }
  6233. }
  6234. }
  6235. if(ShmChargerInfo->Control.CabinetRole != _CROLE_SLAVE)
  6236. {
  6237. SetAcContactor(ON);
  6238. SpawnOcppService();
  6239. }
  6240. else
  6241. {
  6242. InitSlaveCabinetEthernet();
  6243. for (byte gun_index = 0; gun_index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun_index++)
  6244. {
  6245. setChargerMode(gun_index, MODE_MAINTAIN);
  6246. }
  6247. }
  6248. // Local DB
  6249. if(DB_Open(localDb) != PASS)
  6250. {
  6251. LOG_INFO("DB_Open fail.");
  6252. isDb_ready = false;
  6253. }
  6254. else
  6255. {
  6256. isDb_ready = true;
  6257. for(int _index=0; _index< ShmSysConfigAndInfo->SysConfig.TotalConnectorCount;_index++)
  6258. {
  6259. chargingInfo[_index]->IsAvailable = DB_Get_Operactive(localDb, _index);
  6260. }
  6261. }
  6262. ChangeLcmByIndex(_LCM_IDLE);
  6263. sleep(1);
  6264. CreateWatchdog();
  6265. // Main loop
  6266. LOG_INFO("%s \n", ShmSysConfigAndInfo->SysInfo.SelfTestSeq == _STEST_COMPLETE ?
  6267. "****************************Main Loop**********************************" :
  6268. "********************** SelfTest Fail **********************");
  6269. GetClockTime(&_cmdMainPriority_time);
  6270. for (;;)
  6271. {
  6272. CheckOcppStatus();
  6273. ChkPrimaryStatus();
  6274. ChkPsuStatus();
  6275. PsuFailureResume();
  6276. if ((IsConnectorWholeIdle() || ShmSysConfigAndInfo->SysInfo.PageIndex == _LCM_FIX) &&
  6277. ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag != Timeout_ReturnToChargingGunDet)
  6278. {
  6279. CheckFactoryConfigFunction();
  6280. CheckFwUpdateFunction();
  6281. }
  6282. if(CheckWiringInfoUpdate() != YES)
  6283. {
  6284. // return fork process
  6285. return 0;
  6286. }
  6287. CheckSoftHardReset();
  6288. StandbyCheck();
  6289. // OCPP 邏輯
  6290. //OcppRemoteStartChk();
  6291. // 讀卡邏輯
  6292. //ScannerCardProcess();
  6293. PowerCabinetAuthorizeProcess();
  6294. // 當 AC 沒有搭上時,清除一些錯誤碼
  6295. ClearAlarmCodeWhenAcOff();
  6296. if ((GetTimeoutValue(_cmdMainPriority_time) / uSEC_VAL) > MAIN_PRIORITY_INTERVAL)
  6297. {
  6298. CheckTask();
  6299. for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++)
  6300. {
  6301. if((chargingInfo[_index]->SystemStatus >= S_PREPARING_FOR_EVSE && chargingInfo[_index]->SystemStatus <= S_CHARGING) ||
  6302. (chargingInfo[_index]->SystemStatus >= S_CCS_PRECHARGE_ST0 && chargingInfo[_index]->SystemStatus <= S_CCS_PRECHARGE_ST1))
  6303. {
  6304. if (chargingInfo[_index]->SystemStatus == S_CHARGING && _ocppProfileChkFlag[_index] == 12)
  6305. {
  6306. Ocpp_ProfileReq_Cmd(_index);
  6307. gunOutputVol[_index] = chargingInfo[_index]->PresentChargingVoltage;
  6308. _ocppProfileChkFlag[_index] = 0;
  6309. }
  6310. else if (chargingInfo[_index]->SystemStatus != S_CHARGING)
  6311. {
  6312. Ocpp_ProfileReq_Cmd(_index);
  6313. _ocppProfileChkFlag[_index] = 0;
  6314. }
  6315. else
  6316. {
  6317. _ocppProfileChkFlag[_index]++;
  6318. }
  6319. }
  6320. }
  6321. GetClockTime(&_cmdMainPriority_time);
  6322. }
  6323. CheckMiscCommandRequirement();
  6324. CheckDispenserVersionUpdateRequirement();
  6325. MCabinetParallelingProcess();
  6326. SCabinetControllProcess();
  6327. for (byte gun_index = 0; gun_index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun_index++)
  6328. {
  6329. //CheckGpioInStatus();
  6330. CheckErrorOccurStatus(gun_index);
  6331. ChkOcppStatus(gun_index);
  6332. if((chargingInfo[gun_index]->SystemStatus >= S_PREPARING_FOR_EVSE && chargingInfo[gun_index]->SystemStatus <= S_CHARGING) ||
  6333. (chargingInfo[gun_index]->SystemStatus >= S_CCS_PRECHARGE_ST0 && chargingInfo[gun_index]->SystemStatus <= S_CCS_PRECHARGE_ST1))
  6334. {
  6335. if(chargingInfo[gun_index]->SystemStatus == S_CHARGING)
  6336. {
  6337. // 進充電後,如果輸出電壓落差大於 10V 則直接繼續看 ChargingProfile
  6338. if (chargingInfo[gun_index]->PresentChargingVoltage >= gunOutputVol[gun_index] + 10 ||
  6339. chargingInfo[gun_index]->PresentChargingVoltage <= gunOutputVol[gun_index] - 10)
  6340. {
  6341. _ocppProfileChkFlag[gun_index] = 12;
  6342. gunOutputVol[gun_index] = chargingInfo[gun_index]->PresentChargingVoltage;
  6343. }
  6344. }
  6345. }
  6346. CheckSmartChargeProfile(gun_index);
  6347. //LOG_INFO("index = %d, ErrorCode = %s \n", gun_index, ShmOCPP16Data->StatusNotification[gun_index].ErrorCode);
  6348. switch(chargingInfo[gun_index]->SystemStatus)
  6349. {
  6350. case S_MAINTAIN:
  6351. if(isModeChange(gun_index))
  6352. {
  6353. if(ShmChargerInfo->Control.CabinetRole == _CROLE_SLAVE)
  6354. {
  6355. LOG_INFO("================== Slave Cabinet %d ==================", ShmChargerInfo->Control.CabinetSwitch - 1);
  6356. }
  6357. LOG_INFO("================== S_MAINTAIN (%x) ================== \n", gun_index + 1);
  6358. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.AvailabilityRequest = true;
  6359. GetClockTime(&_SystemStatus_Time[gun_index]);
  6360. }
  6361. time = GetSecTimeoutValue(_SystemStatus_Time[gun_index]);
  6362. if(ShmSysConfigAndInfo->SysInfo.BootingStatus != BOOT_COMPLETE ||
  6363. ShmSysConfigAndInfo->SysInfo.SelfTestSeq != _STEST_COMPLETE ||
  6364. ShmChargerInfo->Control.CabinetRole == _CROLE_SLAVE)
  6365. {
  6366. break;
  6367. }
  6368. if(chargingInfo[gun_index]->IsAvailable == YES &&
  6369. (ShmChargerInfo->Control.GunAvailable[gun_index] == YES || ShmPsuData->PsuGroup[gun_index].GroupPresentPsuQuantity > 0) &&
  6370. ShmChargerInfo->ParallelCabinet.ParallelStatus == _Parallel_None)
  6371. {
  6372. if(time >= MAINTAIN_RECOVERY_TIME)
  6373. {
  6374. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.AvailabilityRequest = true;
  6375. setChargerMode(gun_index, MODE_IDLE);
  6376. }
  6377. }
  6378. break;
  6379. case S_IDLE:
  6380. case S_RESERVATION:
  6381. case S_FAULT:
  6382. {
  6383. // clean PermissionRequest flag
  6384. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PermissionRequest = false;
  6385. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable = true;
  6386. if(isModeChange(gun_index))
  6387. {
  6388. if (chargingInfo[gun_index]->SystemStatus == S_IDLE)
  6389. {
  6390. LOG_INFO("================== S_IDLE (%x) ================== \n", gun_index + 1);
  6391. chargingInfo[gun_index]->PresentChargedDuration = 0;
  6392. chargingInfo[gun_index]->RemainChargingDuration = 0;
  6393. strcpy((char *)chargingInfo[gun_index]->StartDateTime, "");
  6394. strcpy((char *)chargingInfo[gun_index]->StopDateTime, "");
  6395. strcpy((char *)chargingInfo[gun_index]->StartUserId, "");
  6396. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "");
  6397. ReleaseAlarmCode(gun_index);
  6398. // clean connector information
  6399. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].AuthorizingType = _AuthType_None;
  6400. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].AuthorizingResult = _AuthResult_None;
  6401. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteChargingVoltage = 0;
  6402. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteChargingCurrent = 0;
  6403. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteRemainChargingDuration = 0;
  6404. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteSoc = 0;
  6405. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].UserPrice = 0;
  6406. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].TotalCost = 0;
  6407. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].AccountBalance = -6553500;
  6408. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.AnnounceBalance = false;
  6409. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.StartWaitPlug = false;
  6410. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.NeedCleanAuthorizeInfo = false;
  6411. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.OutputLimitEnable = false;
  6412. chargingInfo[gun_index]->EvBatterytargetVoltage = 0;
  6413. chargingInfo[gun_index]->EvBatterytargetCurrent = 0;
  6414. chargingInfo[gun_index]->EvBatteryMaxVoltage = 0;
  6415. chargingInfo[gun_index]->EvBatterySoc = 0;
  6416. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteTargetVoltage = 0;
  6417. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteTargetCurrent = 0;
  6418. // clean RemoteStart & RemoteStop flag
  6419. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.RemoteStartRequest = false;
  6420. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.RemoteStartConfirm = false;
  6421. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.RemoteStopRequest = false;
  6422. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.RemoteStopConfirm = false;
  6423. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.UnlockStopRequest = false;
  6424. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.UnlockStopConfirm = false;
  6425. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.NormalStopRequest = false;
  6426. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.AlarmStopRequest = false;
  6427. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.FaultStatusRequest = false;
  6428. memset(chargingInfo[gun_index]->ConnectorAlarmCode, 0x00, sizeof(chargingInfo[gun_index]->ConnectorAlarmCode));
  6429. memset(&ShmOCPP16Data->Cost.RunningCost[gun_index], 0x00, sizeof(struct StrcutRunningCost));
  6430. memset(&ShmOCPP16Data->Cost.FinalCost[gun_index], 0x00, sizeof(struct StrcutFinalCost));
  6431. chargingInfo[gun_index]->PresentChargedEnergy = 0;
  6432. chargingInfo[gun_index]->PresentChargingPower = 0;
  6433. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].MaxTotalChargingPower = 0;
  6434. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].MaxTotalChargingCurrent = 0;
  6435. chargingInfo[gun_index]->ChargingProfilePower = -1;
  6436. chargingInfo[gun_index]->ChargingProfileCurrent = -1;
  6437. // clean force charging info
  6438. memset(&ShmChargerInfo->Control.FCharging[gun_index], 0x00, sizeof(ForceCharging));
  6439. }
  6440. else if (chargingInfo[gun_index]->SystemStatus == S_RESERVATION)
  6441. {
  6442. LOG_INFO("================== S_RESERVATION (%x) ================== \n", gun_index + 1);
  6443. ShmOCPP16Data->CsMsg.bits[gun_index].ReserveNowConf = YES;
  6444. }
  6445. else if (chargingInfo[gun_index]->SystemStatus == S_FAULT)
  6446. {
  6447. LOG_INFO("================== S_FAULT (%x) ================== \n", gun_index + 1);
  6448. }
  6449. GetClockTime(&_SystemStatus_Time[gun_index]);
  6450. }
  6451. if (chargingInfo[gun_index]->IsAvailable == NO ||
  6452. (ShmChargerInfo->Control.GunAvailable[gun_index] == NO && ShmPsuData->PsuGroup[gun_index].GroupPresentPsuQuantity == 0))
  6453. {
  6454. setChargerMode(gun_index, MODE_MAINTAIN);
  6455. continue;
  6456. }
  6457. if (ShmSysConfigAndInfo->SysWarningInfo.Level == 2 ||
  6458. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteStatus == _CRS_Alarm ||
  6459. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.FaultStatusRequest ||
  6460. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.Disconnection)
  6461. {
  6462. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.FaultStatusRequest)
  6463. {
  6464. if(strncmp((char *)chargingInfo[gun_index]->ConnectorAlarmCode, "", 6) == EQUAL)
  6465. {
  6466. memcpy(chargingInfo[gun_index]->ConnectorAlarmCode, ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemotenAlarmCode, 6);
  6467. }
  6468. }
  6469. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.FaultStatusRequest = false;
  6470. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.Disconnection)
  6471. {
  6472. if(strncmp((char *)chargingInfo[gun_index]->ConnectorAlarmCode, "", 6) == EQUAL)
  6473. {
  6474. memcpy(chargingInfo[gun_index]->ConnectorAlarmCode, "042304", 6);
  6475. LOG_INFO("Connector %d Disconnect Occur", gun_index + 1);
  6476. }
  6477. }
  6478. if(chargingInfo[gun_index]->SystemStatus != S_FAULT)
  6479. {
  6480. ClearDetectPluginFlag();
  6481. UpdateErrorCodeToOcpp(gun_index);
  6482. setChargerMode(gun_index, MODE_FAULT);
  6483. }
  6484. else
  6485. {
  6486. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.Disconnection)
  6487. {
  6488. CheckConnectorDisconnectionRecovery(gun_index);
  6489. }
  6490. }
  6491. }
  6492. else
  6493. {
  6494. if (chargingInfo[gun_index]->SystemStatus == S_FAULT)
  6495. {
  6496. time = GetSecTimeoutValue(_SystemStatus_Time[gun_index]);
  6497. if(time >= FAULT_RELEASE_TIME)
  6498. {
  6499. ReleaseAlarmCode(gun_index);
  6500. setChargerMode(gun_index, MODE_IDLE);
  6501. }
  6502. break;
  6503. }
  6504. // clean stop charge flag
  6505. chargingInfo[gun_index]->StopChargeFlag = false;
  6506. chargingInfo[gun_index]->ChargingStopFlag.ChargingStopValue = 0;
  6507. { // Idle 正常程序起點
  6508. // 判斷是否有啟用檢查插槍
  6509. if(IsConnectorAuthorizeSuccess(gun_index))
  6510. {
  6511. if(chargingInfo[gun_index]->IsAvailable &&
  6512. chargingInfo[gun_index]->SystemStatus == S_IDLE)
  6513. {
  6514. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].AuthorizingType == _AuthType_RemoteStart)
  6515. {
  6516. LOG_INFO("Connector %d remote start charging", gun_index + 1);
  6517. }
  6518. else if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].AuthorizingType == _AuthType_RFID)
  6519. {
  6520. LOG_INFO("Connector %d swipe rfid start charging", gun_index + 1);
  6521. }
  6522. setChargerMode(gun_index, MODE_AUTHORIZING);
  6523. continue;
  6524. }
  6525. }
  6526. else if(IsAutoGunSelectionAuthorizeSuccess(gun_index))
  6527. {
  6528. if(chargingInfo[gun_index]->IsAvailable &&
  6529. chargingInfo[gun_index]->SystemStatus == S_IDLE &&
  6530. chargingInfo[gun_index]->ConnectorPlugIn &&
  6531. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteStatus == _CRS_Preparing)
  6532. {
  6533. strcpy((char *)chargingInfo[gun_index]->StartUserId, (char *)ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].ParentDispensetIndex].UserId);
  6534. LOG_INFO("Auto Gun Selection %d, CardNumber = %s", gun_index, chargingInfo[gun_index]->StartUserId);
  6535. DispenserAuthorizationInitial(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].ParentDispensetIndex);
  6536. setChargerMode(gun_index, MODE_REASSIGN_CHECK);
  6537. continue;
  6538. }
  6539. }
  6540. else if (chargingInfo[gun_index]->SystemStatus == S_RESERVATION)
  6541. {
  6542. if (!isReservationExpired(gun_index))
  6543. {
  6544. chargingInfo[gun_index]->SystemStatus = S_IDLE;
  6545. }
  6546. }
  6547. // only for test & debug purpose
  6548. else if(ShmChargerInfo->Control.FCharging[gun_index].FCtrl.bits.EnableForceCharging &&
  6549. ShmChargerInfo->Control.FCharging[gun_index].FCtrl.bits.StartForceCharging)
  6550. {
  6551. ShmChargerInfo->Control.FCharging[gun_index].FCtrl.bits.StartForceCharging = false;
  6552. LOG_INFO("Gun %d Start Force Charging", gun_index + 1);
  6553. setChargerMode(gun_index, MODE_REASSIGN_CHECK);
  6554. continue;
  6555. }
  6556. else
  6557. {
  6558. }
  6559. } // Idle 正常程序終點
  6560. }
  6561. }
  6562. break;
  6563. case S_AUTHORIZING:
  6564. if(isModeChange(gun_index))
  6565. {
  6566. LOG_INFO("================== S_AUTHORIZING (%x) ================== \n", gun_index + 1);
  6567. ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
  6568. if (ShmSysConfigAndInfo->SysInfo.OrderCharging != NO_DEFINE)
  6569. ShmSysConfigAndInfo->SysInfo.OrderCharging = NO_DEFINE;
  6570. //StopSystemTimeoutDet();
  6571. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable = false;
  6572. SetAcContactor(ON);
  6573. GetClockTime(&_ConnectorAuthorizing_Time[gun_index]);
  6574. }
  6575. if(GetTimeoutValue(_ConnectorAuthorizing_Time[gun_index]) / uSEC_VAL >= FORCE_BALANCE_TIME)
  6576. {
  6577. FouceAnnounceAccountBalance(gun_index);
  6578. }
  6579. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].AuthorizingType == _AuthType_RemoteStart)
  6580. {
  6581. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.RemoteStartConfirm)
  6582. {
  6583. // sync with dispenser
  6584. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.RemoteStartConfirm = false;
  6585. GetClockTime(&_ConnectorAuthorizing_Time[gun_index]);
  6586. LOG_INFO("Sync with Gun %d through remote start", gun_index + 1);
  6587. FouceAnnounceAccountBalance(gun_index);
  6588. }
  6589. }
  6590. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].AuthorizingType == _AuthType_RFID)
  6591. {
  6592. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.SwipeRfidConfirm)
  6593. {
  6594. // sync with dispenser
  6595. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.SwipeRfidConfirm = false;
  6596. GetClockTime(&_ConnectorAuthorizing_Time[gun_index]);
  6597. LOG_INFO("Sync with Connector %d through swipe rfid", gun_index + 1);
  6598. }
  6599. }
  6600. if(GetTimeoutValue(_ConnectorAuthorizing_Time[gun_index]) / uSEC_VAL >= ShmSysConfigAndInfo->SysInfo.DispenserInfo.ConnectorTimeout)
  6601. {
  6602. if(!chargingInfo[gun_index]->ConnectorPlugIn)
  6603. {
  6604. LOG_INFO("*********** Gun %d Plug In Timeout ***********", gun_index + 1);
  6605. }
  6606. else
  6607. {
  6608. LOG_INFO("*********** Gun %d Preparing State Timeout ***********", gun_index + 1);
  6609. }
  6610. setChargerMode(gun_index, MODE_IDLE);
  6611. ConnectorAuthorizationInitial(gun_index);
  6612. }
  6613. else
  6614. {
  6615. if(chargingInfo[gun_index]->ConnectorPlugIn &&
  6616. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteStatus == _CRS_Preparing)
  6617. {
  6618. AddPlugInTimes(gun_index);
  6619. LOG_INFO("index = %d, CardNumber = %s \n", gun_index, chargingInfo[gun_index]->StartUserId);
  6620. setChargerMode(gun_index, MODE_REASSIGN_CHECK);
  6621. ConnectorAuthorizationInitial(gun_index);
  6622. }
  6623. else if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.NeedCleanAuthorizeInfo)
  6624. {
  6625. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.StartWaitPlug = false;
  6626. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.NeedCleanAuthorizeInfo = false;
  6627. LOG_INFO("*********** Gun %d User Stop Plug In ***********", gun_index + 1);
  6628. setChargerMode(gun_index, MODE_IDLE);
  6629. ConnectorAuthorizationInitial(gun_index);
  6630. }
  6631. else if(isEvBoardStopChargeFlag(gun_index) == YES)
  6632. {
  6633. LOG_INFO("********** Gun %d Alarm Stop (S_AUTHORIZING) **********", gun_index + 1);
  6634. setChargerMode(gun_index, MODE_IDLE);
  6635. ConnectorAuthorizationInitial(gun_index);
  6636. }
  6637. }
  6638. break;
  6639. case S_REASSIGN_CHECK:
  6640. {
  6641. if (isModeChange(gun_index))
  6642. {
  6643. LOG_INFO("================== S_REASSIGN_CHECK (%x) ================== \n", gun_index + 1);
  6644. ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
  6645. if (ShmSysConfigAndInfo->SysInfo.OrderCharging != NO_DEFINE)
  6646. ShmSysConfigAndInfo->SysInfo.OrderCharging = NO_DEFINE;
  6647. //StopSystemTimeoutDet();
  6648. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable = false;
  6649. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].MaxOutputEnergy = ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy;
  6650. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].MaxOutputDuration = ShmSysConfigAndInfo->SysConfig.MaxChargingDuration;
  6651. LOG_INFO("Max Total Current %d A, Max Total Power %d kW, Total Energy %d kWh, Total Duration %d",
  6652. ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent,
  6653. ShmSysConfigAndInfo->SysConfig.MaxChargingPower,
  6654. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].MaxOutputEnergy,
  6655. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].MaxOutputDuration);
  6656. SetAcContactor(ON);
  6657. SetPCabinetOutputRelay(gun_index, ON);
  6658. GetClockTime(&_SystemStatus_Time[gun_index]);
  6659. }
  6660. time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
  6661. if(ConnectorRequestToCharging(gun_index))
  6662. {
  6663. setChargerMode(gun_index, MODE_REASSIGN);
  6664. }
  6665. else if(time >= WAIT_REASSIGN_TIME)
  6666. {
  6667. if(ShmPsuData->Work_Step != _WORK_CHARGING)
  6668. {
  6669. LOG_INFO("Gun %d Wait PSU Work Step Timeout", gun_index + 1);
  6670. }
  6671. else
  6672. {
  6673. LOG_INFO("Gun %d Request Charging Timeout", gun_index + 1);
  6674. }
  6675. setChargerMode(gun_index, MODE_IDLE);
  6676. }
  6677. }
  6678. break;
  6679. case S_REASSIGN:
  6680. {
  6681. if (isModeChange(gun_index))
  6682. {
  6683. LOG_INFO("================== S_REASSIGN (%x) ================== \n", gun_index + 1);
  6684. //gettimeofday(&_toAverage_time, NULL);
  6685. GetClockTime(&_SystemStatus_Time[gun_index]);
  6686. }
  6687. time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
  6688. if(IsConnectorGroupingCompleted(gun_index))
  6689. {
  6690. setChargerMode(gun_index, MODE_PRECHARGE);
  6691. }
  6692. else if(time >= MAX_REQUEST_CHARGING_TIME)
  6693. {
  6694. LOG_INFO("Gun %d Grouping Timeout", gun_index + 1);
  6695. setChargerMode(gun_index, MODE_IDLE);
  6696. }
  6697. }
  6698. break;
  6699. case S_PREPARNING:
  6700. {
  6701. if (isModeChange(gun_index))
  6702. {
  6703. LOG_INFO("================== S_PREPARNING (%x) ================== \n", gun_index + 1);
  6704. //StopGunInfoTimeoutDet(gun_index);
  6705. //StartGunInfoTimeoutDet(gun_index, Timeout_Preparing);
  6706. SetAcContactor(ON);
  6707. GetClockTime(&_SystemStatus_Time[gun_index]);
  6708. }
  6709. time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
  6710. if ((chargingInfo[gun_index]->AvailableChargingPower > 10) && time >= MIN_WAIT_PREPARNING_TIME)
  6711. {
  6712. setChargerMode(gun_index, MODE_PREPARE_FOR_EV);
  6713. continue;
  6714. }
  6715. if (isEvBoardStopChargeFlag(gun_index) == YES)
  6716. {
  6717. // 板端或後臺要求停止
  6718. LOG_INFO("********** Gun %d Alarm Stop (S_PREPARNING) **********", gun_index + 1);
  6719. if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "") == EQUAL)
  6720. {
  6721. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
  6722. }
  6723. ChargingAlarmProcess(gun_index);
  6724. }
  6725. else if(isNormalStopChargeFlag(gun_index) == YES)
  6726. {
  6727. LOG_INFO("********** Gun %d Normal Stop (S_PREPARNING) %s**********", gun_index + 1,
  6728. chargingInfo[gun_index]->ChargingStopFlag.bits.ManualStop ? "(ManualStop)" : "");
  6729. if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "") == EQUAL)
  6730. {
  6731. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EVDisconnected");
  6732. }
  6733. ChargingTerminalProcess(gun_index);
  6734. }
  6735. if(time > GUN_PREPARE_TIMEOUT)
  6736. {
  6737. LOG_INFO("********** Gun %d PrepareTimeout **********", gun_index + 1);
  6738. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuNoResource = YES;
  6739. if(strncmp((char *)chargingInfo[gun_index]->ConnectorAlarmCode, "", 6) == EQUAL)
  6740. {
  6741. memcpy(chargingInfo[gun_index]->ConnectorAlarmCode, "012279", 6);
  6742. LOG_INFO("Gun %d No Psu Resource", gun_index + 1);
  6743. }
  6744. if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "") == EQUAL)
  6745. {
  6746. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
  6747. }
  6748. ChargingAlarmProcess(gun_index);
  6749. }
  6750. }
  6751. break;
  6752. case S_PREPARING_FOR_EV: // 等待車端的通訊 (EV 小板),待車端回報後,開始樁端的測試
  6753. {
  6754. if (isModeChange(gun_index))
  6755. {
  6756. LOG_INFO("================== S_PREPARING_FOR_EV (%x) ================== \n", gun_index + 1);
  6757. //strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
  6758. //StopGunInfoTimeoutDet(gun_index);
  6759. //StartGunInfoTimeoutDet(gun_index, Timeout_EvChargingDet);
  6760. GetClockTime(&_SystemStatus_Time[gun_index]);
  6761. }
  6762. time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
  6763. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PermissionRequest)
  6764. {
  6765. setChargerMode(gun_index, MODE_PREPARE_FOR_EVSE);
  6766. }
  6767. // only for test & debug purpose
  6768. else if(ShmChargerInfo->Control.FCharging[gun_index].FCtrl.bits.EnableForceCharging)
  6769. {
  6770. LOG_INFO("Gun %d [Force Charging] S_PREPARING_FOR_EV OK", gun_index + 1);
  6771. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PermissionRequest = true;
  6772. }
  6773. if (isEvBoardStopChargeFlag(gun_index) == YES)
  6774. {
  6775. // 板端或後臺要求停止
  6776. LOG_INFO("********** Gun %d Alarm Stop (S_PREPARING_FOR_EV) **********", gun_index + 1);
  6777. if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "") == EQUAL)
  6778. {
  6779. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
  6780. }
  6781. ChargingAlarmProcess(gun_index);
  6782. }
  6783. else if(isNormalStopChargeFlag(gun_index) == YES)
  6784. {
  6785. LOG_INFO("********** Gun %d Normal Stop (S_PREPARING_FOR_EV) %s**********", gun_index + 1,
  6786. chargingInfo[gun_index]->ChargingStopFlag.bits.ManualStop ? "(ManualStop)" : "");
  6787. if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "") == EQUAL)
  6788. {
  6789. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EVDisconnected");
  6790. }
  6791. ChargingTerminalProcess(gun_index);
  6792. }
  6793. if(time >= GUN_EV_WAIT_TIMEOUT)
  6794. {
  6795. LOG_INFO("********** Gun %d Wait Dispenser Timeout **********", gun_index + 1);
  6796. ChargingTerminalProcess(gun_index);
  6797. }
  6798. }
  6799. break;
  6800. case S_PREPARING_FOR_EVSE: // 等待 RB 通訊及測試,並將狀態回報, CSU 確認 Pass 後,開始進入充電
  6801. {
  6802. if (isModeChange(gun_index))
  6803. {
  6804. LOG_INFO("================== S_PREPARING_FOR_EVSE (%x) ================== \n", gun_index + 1);
  6805. //StopGunInfoTimeoutDet(gun_index);
  6806. //StartGunInfoTimeoutDet(gun_index, Timeout_EvseChargingDet);
  6807. GetClockTime(&_SystemStatus_Time[gun_index]);
  6808. }
  6809. time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
  6810. // only for test & debug purpose
  6811. if(ShmChargerInfo->Control.FCharging[gun_index].FCtrl.bits.EnableForceCharging)
  6812. {
  6813. float voltage = (float)ShmChargerInfo->Control.FCharging[gun_index].FTargetVoltage / 10;
  6814. float current = (float)ShmChargerInfo->Control.FCharging[gun_index].FTargetCurrent / 10;
  6815. if(chargingInfo[gun_index]->EvBatterytargetVoltage != voltage || chargingInfo[gun_index]->EvBatterytargetCurrent != current)
  6816. {
  6817. LOG_INFO("Gun %d Set Force Charging Voltage %4d V, Current: %4d A", gun_index + 1, (int)voltage, (int)current);
  6818. }
  6819. chargingInfo[gun_index]->EvBatterytargetVoltage = voltage;
  6820. chargingInfo[gun_index]->EvBatterytargetCurrent = current;
  6821. }
  6822. if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteStatus == _CRS_Charging)
  6823. {
  6824. setChargerMode(gun_index, MODE_CHARGING);
  6825. }
  6826. // only for test & debug purpose
  6827. else if(ShmChargerInfo->Control.FCharging[gun_index].FCtrl.bits.EnableForceCharging)
  6828. {
  6829. if(time >= FORCE_CHARGING_WAIT_EVSE)
  6830. {
  6831. LOG_INFO("Gun %d [Charging Simulation] S_PREPARING_FOR_EVSE OK", gun_index + 1);
  6832. setChargerMode(gun_index, MODE_CHARGING);
  6833. }
  6834. }
  6835. if (isEvBoardStopChargeFlag(gun_index) == YES)
  6836. {
  6837. // 板端或後臺要求停止
  6838. LOG_INFO("********** Gun %d Alarm Stop (S_PREPARING_FOR_EVSE) **********", gun_index + 1);
  6839. if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "") == EQUAL)
  6840. {
  6841. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
  6842. }
  6843. ChargingAlarmProcess(gun_index);
  6844. }
  6845. else if(isNormalStopChargeFlag(gun_index) == YES)
  6846. {
  6847. LOG_INFO("********** Gun %d Normal Stop (S_PREPARING_FOR_EVSE) %s**********", gun_index + 1,
  6848. chargingInfo[gun_index]->ChargingStopFlag.bits.ManualStop ? "(ManualStop)" : "");
  6849. if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "") == EQUAL)
  6850. {
  6851. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EVDisconnected");
  6852. }
  6853. ChargingTerminalProcess(gun_index);
  6854. }
  6855. if(time >= GUN_EVSE_WAIT_TIMEOUT)
  6856. {
  6857. LOG_INFO("********** Gun %d GFD timeout **********", gun_index + 1);
  6858. ChargingTerminalProcess(gun_index);
  6859. }
  6860. }
  6861. break;
  6862. case S_CHARGING: // 剛進入充電狀態,等待 EV 小板要求的輸出電流後開始輸出
  6863. {
  6864. if (isModeChange(gun_index))
  6865. {
  6866. LOG_INFO("================== S_CHARGING (%x) ================== \n", gun_index + 1);
  6867. //StopGunInfoTimeoutDet(gun_index);
  6868. GetClockTime(&_SystemStatus_Time[gun_index]);
  6869. chargingInfo[gun_index]->PresentChargedDuration = 0;
  6870. ChangeStartOrStopDateTime(YES, gun_index);
  6871. OcppStartTransation(gun_index);
  6872. }
  6873. // only for test & debug purpose
  6874. if(ShmChargerInfo->Control.FCharging[gun_index].FCtrl.bits.EnableForceCharging)
  6875. {
  6876. float voltage = (float)ShmChargerInfo->Control.FCharging[gun_index].FTargetVoltage / 10;
  6877. float current = (float)ShmChargerInfo->Control.FCharging[gun_index].FTargetCurrent / 10;
  6878. if(chargingInfo[gun_index]->EvBatterytargetVoltage != voltage || chargingInfo[gun_index]->EvBatterytargetCurrent != current)
  6879. {
  6880. LOG_INFO("Gun %d Set Force Charging Voltage %4d V, Current: %4d A", gun_index + 1, (int)voltage, (int)current);
  6881. }
  6882. chargingInfo[gun_index]->EvBatterytargetVoltage = voltage;
  6883. chargingInfo[gun_index]->EvBatterytargetCurrent = current;
  6884. }
  6885. time = GetSecTimeoutValue(_SystemStatus_Time[gun_index]);
  6886. // 計算 Power
  6887. //chargingInfo[gun_index]->PresentChargingPower = ((float)((chargingInfo[gun_index]->PresentChargingVoltage) * (chargingInfo[gun_index]->PresentChargingCurrent)) / 1000);
  6888. chargingInfo[gun_index]->PresentChargingPower = (((float)((ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteChargingVoltage) * (ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteChargingCurrent))) / 1000 / 100);
  6889. if(time >= (chargingInfo[gun_index]->PresentChargedDuration + ENERAGY_INTERVAL))
  6890. {
  6891. chargingInfo[gun_index]->PresentChargedDuration++;
  6892. float changingPow = (chargingInfo[gun_index]->PresentChargingPower) / 3600;
  6893. if (ShmSysConfigAndInfo->SysConfig.BillingData.isBilling)
  6894. {
  6895. chargingInfo[gun_index]->ChargingFee += changingPow * ShmSysConfigAndInfo->SysConfig.BillingData.Cur_fee;
  6896. }
  6897. chargingInfo[gun_index]->PresentChargedEnergy += changingPow;
  6898. chargingInfo[gun_index]->PowerConsumption += changingPow;
  6899. }
  6900. if (isEvBoardStopChargeFlag(gun_index))
  6901. {
  6902. LOG_INFO("********** Gun %d Alarm Stop (S_CHARGING) **********", gun_index + 1);
  6903. if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "") == EQUAL)
  6904. {
  6905. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
  6906. }
  6907. ChargingAlarmProcess(gun_index);
  6908. }
  6909. else if(isNormalStopChargeFlag(gun_index) == YES)
  6910. {
  6911. LOG_INFO("********** Gun %d Normal Stop (S_CHARGING) %s**********", gun_index + 1,
  6912. chargingInfo[gun_index]->ChargingStopFlag.bits.ManualStop ? "(ManualStop)" : "");
  6913. if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "") == EQUAL)
  6914. {
  6915. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EVDisconnected");
  6916. }
  6917. ChargingTerminalProcess(gun_index);
  6918. }
  6919. else if(CheckBackendChargingTimeout(gun_index) ||
  6920. CheckBackendChargingEnergy(gun_index))
  6921. {
  6922. LOG_INFO("********** Gun %d Backend Stop (S_CHARGING) **********", gun_index + 1);
  6923. // 板端或後臺要求停止
  6924. ChargingTerminalProcess(gun_index);
  6925. }
  6926. else if(ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionConf)
  6927. {
  6928. if(Ocpp_CheckInvalidId(gun_index))
  6929. {
  6930. LOG_INFO("********** Gun %d Backend InvalidId Stop (S_CHARGING) **********", gun_index + 1);
  6931. ChargingTerminalProcess(gun_index);
  6932. }
  6933. }
  6934. if(ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionConf)
  6935. {
  6936. ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionConf = NO;
  6937. if(strcmp((char *)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Accepted") == EQUAL)
  6938. {
  6939. LOG_INFO("Gun %d OCPP Start Transaction Accepted, Id = %d", gun_index + 1, ShmOCPP16Data->StartTransaction[gun_index].ResponseTransactionId);
  6940. }
  6941. }
  6942. }
  6943. break;
  6944. case S_ALARM:
  6945. case S_TERMINATING:
  6946. {
  6947. if (isModeChange(gun_index))
  6948. {
  6949. if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "") == EQUAL)
  6950. {
  6951. strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Other");
  6952. }
  6953. if (chargingInfo[gun_index]->SystemStatus == S_ALARM)
  6954. {
  6955. LOG_INFO("================== S_ALARM (%x) ================== \n", gun_index + 1);
  6956. UpdateErrorCodeToOcpp(gun_index);
  6957. if (strcmp((char *)chargingInfo[gun_index]->StartDateTime, "") != EQUAL)
  6958. {
  6959. OcppStopTransation(gun_index);
  6960. }
  6961. TheEndCharging(gun_index);
  6962. }
  6963. else
  6964. {
  6965. LOG_INFO("================== S_TERMINATING (%x) ================== \n", gun_index + 1);
  6966. }
  6967. //StopGunInfoTimeoutDet(gun_index);
  6968. GetClockTime(&_SystemStatus_Time[gun_index]);
  6969. }
  6970. time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
  6971. if (chargingInfo[gun_index]->SystemStatus == S_ALARM)
  6972. {
  6973. if(time >= GUN_COMP_WAIT_TIMEOUT)
  6974. {
  6975. if(!ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable)
  6976. {
  6977. LOG_INFO ("********** Gun %d psu is releasable **********\n", gun_index + 1);
  6978. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable = true;
  6979. }
  6980. }
  6981. if((ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteStatus == _CRS_Idle ||
  6982. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Enable == false ||
  6983. (!chargingInfo[gun_index]->ConnectorPlugIn && ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuFailureAlarm)) &&
  6984. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable)
  6985. {
  6986. setChargerMode(gun_index, MODE_IDLE);
  6987. }
  6988. }
  6989. else
  6990. {
  6991. setChargerMode(gun_index, MODE_COMPLETE);
  6992. }
  6993. }
  6994. break;
  6995. case S_COMPLETE:
  6996. {
  6997. if (isModeChange(gun_index))
  6998. {
  6999. LOG_INFO("================== S_COMPLETE (%x) ================== \n", gun_index + 1);
  7000. if (strcmp((char *)chargingInfo[gun_index]->StartDateTime, "") != EQUAL)
  7001. {
  7002. OcppStopTransation(gun_index);
  7003. }
  7004. TheEndCharging(gun_index);
  7005. GetClockTime(&_SystemStatus_Time[gun_index]);
  7006. }
  7007. time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
  7008. if(time >= GUN_COMP_WAIT_TIMEOUT)
  7009. {
  7010. if(!ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable)
  7011. {
  7012. LOG_INFO ("********** Gun %d psu is releasable **********", gun_index + 1);
  7013. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable = true;
  7014. }
  7015. }
  7016. if((ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteStatus == _CRS_Idle || ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Enable == false) &&
  7017. ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable)
  7018. {
  7019. setChargerMode(gun_index, MODE_IDLE);
  7020. }
  7021. }
  7022. break;
  7023. case S_CCS_PRECHARGE_ST0:
  7024. if (isModeChange(gun_index))
  7025. {
  7026. LOG_INFO("CCS Precharge Processing 1....................%x \n", gun_index);
  7027. //StopGunInfoTimeoutDet(gun_index);
  7028. //StartGunInfoTimeoutDet(gun_index, Timeout_ForCcsPrechargeDet);
  7029. }
  7030. break;
  7031. case S_CCS_PRECHARGE_ST1:
  7032. if (isModeChange(gun_index))
  7033. {
  7034. LOG_INFO("CCS Precharge Processing 2....................%x \n", gun_index);
  7035. }
  7036. break;
  7037. }
  7038. }
  7039. if (ShmSysConfigAndInfo->SysInfo.SystemPage != _LCM_NONE)
  7040. {
  7041. ChangeLcmByIndex(ShmSysConfigAndInfo->SysInfo.SystemPage);
  7042. }
  7043. else
  7044. {
  7045. bool dcPageRun = true;
  7046. if (dcPageRun)
  7047. ChangeLcmByIndex(ShmSysConfigAndInfo->SysInfo.ConnectorPage);
  7048. }
  7049. TryFeedWatchdog();
  7050. usleep(whileLoopTime);
  7051. }
  7052. return FAIL;
  7053. }