main.c 266 KB

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