main.c 279 KB

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