main.c 267 KB

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