main.c 236 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497
  1. #include "define.h"
  2. #include "main.h"
  3. //#define CDFA_CERTIFICATE // Only enable for CDFA certificate to send receipt by Phihong back end API
  4. //==========================
  5. // System basic sample constant
  6. //==========================
  7. #define is_error(ptr) ((unsigned long)ptr > (unsigned long)-4000L)
  8. #define ARRAY_SIZE(A) (sizeof(A) / sizeof(A[0]))
  9. #define PASS 1
  10. #define FAIL -1
  11. #define YES 1
  12. #define NO 0
  13. #define ON 1
  14. #define OFF 0
  15. #define BUFFER_SIZE 128
  16. //==========================
  17. // Timeout constant define
  18. //==========================
  19. #define TIMEOUT_SPEC_HANDSHAKING 180
  20. #define TIMEOUT_SPEC_AUTH 15
  21. #define TIMEOUT_SPEC_HANDSHAKING_LED 185
  22. #define TIMEOUT_SPEC_REFRESH_CHARGING_INFO 30
  23. #define TIMEOUT_SPEC_PROFILE_PREPARE 60
  24. #define TIMEOUT_SPEC_BS_HLC_HANDSHAKE 30
  25. #define TIMEOUT_SPEC_EV_READY 30
  26. #define TIMEOUT_SPEC_CCS_HEARTBEAT_COUNT_RESET 10
  27. #define TIMEOUT_SPEC_CCS_HANDSHAKE 120
  28. #define TIMEOUT_SPEC_PWN_CHANGE 5
  29. #define TIMEOUT_SPEC_POWERSAVING_LCD 120
  30. #define TIMEOUT_SPEC_POWERSAVING_RFID 120
  31. #define TIMEOUT_SPEC_POWERSAVING_METER 120
  32. #define TIMEOUT_SPEC_POWERSAVING_LED_STATUS 120
  33. #define TIMEOUT_SPEC_CEHCK_POWER_CONSUMPTION 15
  34. #define TIMEOUT_SPEC_UPGRADE 300
  35. #define TIMEOUT_SPEC_RESET_WIFI_MODULE 300
  36. #define TIMEOUT_SPEC_STOPSUM_DISP 15
  37. //==========================
  38. // GPIO constant define
  39. //==========================
  40. #define GPIO_OUT_RST_RFID 62
  41. #define GPIO_OUT_RST_4G 114
  42. #define GPIO_OUT_RST_4G_WIFI 59
  43. #define GPIO_OUT_RST_QCA 115
  44. #define GPIO_OUT_RST_ETH 56
  45. #define GPIO_IN_WAKEUP 63
  46. #define MtdBlockSize 0x300000
  47. #define DB_FILE "/Storage/ChargeLog/localCgargingRecord.db"
  48. //==========================
  49. // Declare method
  50. //==========================
  51. void trim(char *s);
  52. int mystrcmp(char *p1,char *p2);
  53. void substr(char *dest, const char* src, unsigned int start, unsigned int cnt);
  54. void split(char **arr, char *str, const char *del);
  55. int isReachableInternet();
  56. int isRouteFail();
  57. int InitRfidPort(void);
  58. int GetCardSerialNumber();
  59. void setLedMotion(unsigned char gun_index,unsigned char led_mode);
  60. void setRequest(unsigned char gun_index,unsigned char isOn);
  61. void setSpeaker(unsigned char isOn, unsigned char speaker_mode);
  62. //==========================
  63. // Declare RFID module type
  64. //==========================
  65. #define MODULE_EWT 0
  66. int wtdFd = -1;
  67. int rfidFd = -1;
  68. char* rfidPortName = "/dev/ttyS2";
  69. RFID rfid;
  70. char *valid_Internet[2] = {"8.8.8.8", "180.76.76.76"};
  71. //==========================
  72. // Declare share memory
  73. //==========================
  74. struct SysConfigAndInfo *ShmSysConfigAndInfo;
  75. struct StatusCodeData *ShmStatusCodeData;
  76. struct PsuData *ShmPsuData;
  77. struct CHAdeMOData *ShmCHAdeMOData;
  78. struct CcsData *ShmCcsData;
  79. struct PrimaryMcuData *ShmPrimaryMcuData;
  80. struct FanModuleData *ShmFanModuleData;
  81. struct RelayModuleData *ShmRelayModuleData;
  82. struct OCPP16Data *ShmOCPP16Data;
  83. struct OCPP20Data *ShmOCPP20Data;
  84. struct OCPP16Data *ShmOCPP16DataPH;
  85. struct Charger *ShmCharger;
  86. struct DISPENSER *ShmDispenser;
  87. struct timespec startTime[AC_QUANTITY][TMR_IDX_CNT];
  88. struct timespec startChargingTime[AC_QUANTITY];
  89. struct timespec endChargingTime[AC_QUANTITY];
  90. sqlite3 *localDb;
  91. struct SysConfigData SysConfigOrg;
  92. ParsingRatedCur modelnameInfo={0};
  93. //=================================
  94. // Common routine
  95. //=================================
  96. void trim(char *s)
  97. {
  98. int i=0, j, k, l=0;
  99. while((s[i]==' ')||(s[i]=='\t')||(s[i]=='\n'))
  100. i++;
  101. j = strlen(s)-1;
  102. while((s[j]==' ')||(s[j]=='\t')||(s[j]=='\n'))
  103. j--;
  104. if(i==0 && j==strlen(s)-1) { }
  105. else if(i==0) s[j+1] = '\0';
  106. else {
  107. for(k=i; k<=j; k++) s[l++] = s[k];
  108. s[l] = '\0';
  109. }
  110. }
  111. int mystrcmp(char *p1,char *p2)
  112. {
  113. while(*p1==*p2)
  114. {
  115. if(*p1=='\0' || *p2=='\0')
  116. break;
  117. p1++;
  118. p2++;
  119. }
  120. if(*p1=='\0' && *p2=='\0')
  121. return(PASS);
  122. else
  123. return(FAIL);
  124. }
  125. void substr(char *dest, const char* src, unsigned int start, unsigned int cnt)
  126. {
  127. strncpy(dest, src + start, cnt);
  128. dest[cnt] = 0;
  129. }
  130. void split(char **arr, char *str, const char *del)
  131. {
  132. char *s = strtok(str, del);
  133. while(s != NULL)
  134. {
  135. *arr++ = s;
  136. s = strtok(NULL, del);
  137. }
  138. }
  139. int StoreLogMsg(const char *fmt, ...)
  140. {
  141. char Buf[4096+256];
  142. char buffer[4096];
  143. time_t CurrentTime;
  144. struct tm *tm;
  145. struct timeval tv;
  146. va_list args;
  147. va_start(args, fmt);
  148. int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
  149. va_end(args);
  150. memset(Buf,0,sizeof(Buf));
  151. CurrentTime = time(NULL);
  152. tm=localtime(&CurrentTime);
  153. gettimeofday(&tv, NULL); // get microseconds, 10^-6
  154. if((ShmSysConfigAndInfo->SysConfig.ModelName != NULL) && (ShmSysConfigAndInfo->SysConfig.SerialNumber != NULL) && (strlen((char*)ShmSysConfigAndInfo->SysConfig.ModelName) >= 14))
  155. {
  156. sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/SystemLog/[%04d.%02d]%s_%s_SystemLog",
  157. tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec,
  158. buffer,
  159. tm->tm_year+1900,tm->tm_mon+1,
  160. ShmSysConfigAndInfo->SysConfig.ModelName,
  161. ShmSysConfigAndInfo->SysConfig.SerialNumber);
  162. }
  163. else
  164. {
  165. sprintf(Buf,"echo -n \"[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s\" >> /Storage/SystemLog/[%04d.%02d]SystemLog",
  166. tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec,
  167. buffer,
  168. tm->tm_year+1900,tm->tm_mon+1);
  169. }
  170. #ifdef SystemLogMessage
  171. system(Buf);
  172. #endif
  173. #ifdef ConsloePrintLog
  174. printf("[%04d.%02d.%02d %02d:%02d:%02d.%06ld]%s", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,tv.tv_usec, buffer);
  175. #endif
  176. return rc;
  177. }
  178. void refreshStartTimer(struct timespec *timer)
  179. {
  180. clock_gettime(CLOCK_MONOTONIC, timer);
  181. }
  182. int getDiffSecNow(struct timespec timer)
  183. {
  184. struct timespec timerNow;
  185. clock_gettime(CLOCK_MONOTONIC, &timerNow);
  186. return (int)((((unsigned long)(timerNow.tv_sec - timer.tv_sec) * 1000) + ((unsigned long)((timerNow.tv_nsec / 1000000) - (timer.tv_nsec / 1000000))))/1000);
  187. }
  188. int getDiffSecBetween(struct timespec start, struct timespec end)
  189. {
  190. return (int)((((unsigned long)(end.tv_sec - start.tv_sec) * 1000) + ((unsigned long)((end.tv_nsec / 1000000) - (start.tv_nsec / 1000000))))/1000);
  191. }
  192. long long DiffTimebWithNow(struct timeb ST)
  193. {
  194. //return milli-second
  195. struct timeb ET;
  196. long long StartTime,StopTime;
  197. ftime(&ET);
  198. StartTime=(long long)ST.time;
  199. StopTime=(long long)ET.time;
  200. return ((StopTime-StartTime)*1000) + (ET.millitm-ST.millitm);
  201. }
  202. long long DiffTimeb(struct timeb ST, struct timeb ET)
  203. {
  204. //return milli-second
  205. long long StartTime,StopTime;
  206. StartTime=(long long)ST.time;
  207. StopTime=(long long)ET.time;
  208. return ((StopTime-StartTime)*1000) + (ET.millitm-ST.millitm);
  209. }
  210. int DiffTimebWithNowSec(struct timeb ST)
  211. {
  212. //return milli-second
  213. struct timeb ET;
  214. unsigned int StartTime,StopTime;
  215. ftime(&ET);
  216. StartTime=(unsigned int)ST.time;
  217. StopTime=(unsigned int)ET.time;
  218. return (StopTime-StartTime);
  219. }
  220. int isOvertNow(uint8_t *start)
  221. {
  222. int result = YES;
  223. struct ParsingResult
  224. {
  225. int result;
  226. int scanedElement;
  227. int year;
  228. int month;
  229. int mday;
  230. int hour;
  231. int min;
  232. int sec;
  233. int tz_hour;
  234. int tz_min;
  235. float minSec;
  236. }parsingResult;
  237. struct tm tmStart;
  238. struct timeb tbStart;
  239. memset(&parsingResult, 0x00, sizeof(struct ParsingResult));
  240. if(strstr((char*)start, ".") != NULL)
  241. {
  242. // Original data with mini second
  243. if(strstr((char*)start, "Z") != NULL)
  244. {
  245. // Original data with Z
  246. parsingResult.scanedElement = sscanf((char*)start, "%d-%d-%dT%d:%d:%d.%fZ",
  247. &parsingResult.year,
  248. &parsingResult.month,
  249. &parsingResult.mday,
  250. &parsingResult.hour,
  251. &parsingResult.min,
  252. &parsingResult.sec,
  253. &parsingResult.minSec);
  254. }
  255. else
  256. {
  257. // Original data without Z
  258. parsingResult.scanedElement = sscanf((char*)start, "%d-%d-%dT%d:%d:%d.%f%d:%d",
  259. &parsingResult.year,
  260. &parsingResult.month,
  261. &parsingResult.mday,
  262. &parsingResult.hour,
  263. &parsingResult.min,
  264. &parsingResult.sec,
  265. &parsingResult.minSec,
  266. &parsingResult.tz_hour,
  267. &parsingResult.tz_min);
  268. }
  269. }
  270. else
  271. {
  272. // Original data without mini second
  273. if(strstr((char*)start, "Z") != NULL)
  274. {
  275. // Original data with Z
  276. parsingResult.scanedElement = sscanf((char*)start, "%d-%d-%dT%d:%d:%dZ",
  277. &parsingResult.year,
  278. &parsingResult.month,
  279. &parsingResult.mday,
  280. &parsingResult.hour,
  281. &parsingResult.min,
  282. &parsingResult.sec);
  283. }
  284. else
  285. {
  286. // Original data without Z
  287. parsingResult.scanedElement = sscanf((char*)start, "%d-%d-%dT%d:%d:%d%d:%d",
  288. &parsingResult.year,
  289. &parsingResult.month,
  290. &parsingResult.mday,
  291. &parsingResult.hour,
  292. &parsingResult.min,
  293. &parsingResult.sec,
  294. &parsingResult.tz_hour,
  295. &parsingResult.tz_min);
  296. }
  297. }
  298. if(parsingResult.scanedElement >= 6)
  299. {
  300. tmStart.tm_year = parsingResult.year - 1900;
  301. tmStart.tm_mon = parsingResult.month - 1;
  302. tmStart.tm_mday = parsingResult.mday;
  303. tmStart.tm_hour = parsingResult.hour;
  304. tmStart.tm_min = parsingResult.min;
  305. tmStart.tm_sec = parsingResult.sec;
  306. tmStart.tm_gmtoff = 0;
  307. tbStart.time = mktime(&tmStart);
  308. tbStart.timezone = 0;
  309. tbStart.millitm = 0;
  310. tbStart.time -= (parsingResult.tz_hour*3600) + (parsingResult.tz_min*60*(parsingResult.tz_hour>=0?1:-1));
  311. if(DiffTimebWithNowSec(tbStart) <= 0)
  312. result = NO;
  313. else
  314. result = YES;
  315. }
  316. else
  317. {
  318. DEBUG_WARN("Start date parsing error.\n");
  319. }
  320. return result;
  321. }
  322. void getDateTimeString(char* result)
  323. {
  324. time_t CurrentTime;
  325. struct tm *tm;
  326. CurrentTime = time(NULL);
  327. tm=localtime(&CurrentTime);
  328. sprintf(result, "%04d.%02d.%02d %02d:%02d:%02d", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec);
  329. }
  330. int getCurrentYear()
  331. {
  332. int result = 0;
  333. time_t CurrentTime;
  334. struct tm *tm;
  335. CurrentTime = time(NULL);
  336. tm=localtime(&CurrentTime);
  337. result = (tm->tm_year + 1900);
  338. return result;
  339. }
  340. unsigned long long getAvailableMemory()
  341. {
  342. long pages = sysconf(_SC_AVPHYS_PAGES);
  343. long page_size = sysconf(_SC_PAGE_SIZE);
  344. return pages * page_size;
  345. }
  346. unsigned int isKernelSupportNAT()
  347. {
  348. unsigned int result = NO;
  349. unsigned int version = 0;
  350. FILE *fp;
  351. char cmd[256];
  352. char buf[512];
  353. // Get IP address & net mask
  354. strcpy(cmd, "uname -v");
  355. fp = popen(cmd, "r");
  356. if(fp != NULL)
  357. {
  358. if(fgets(buf, sizeof(buf), fp) != NULL)
  359. {
  360. sscanf(buf, "#%d", &version);
  361. //DEBUG_INFO("Kernel version: %d\n", version);
  362. if(version >= 30)
  363. result = YES;
  364. }
  365. }
  366. pclose(fp);
  367. return result;
  368. }
  369. int getEth0MacAddress()
  370. {
  371. int result = PASS;
  372. FILE *fp;
  373. char cmd[256];
  374. char buf[512];
  375. char tmp[512];
  376. strcpy(cmd, "ifconfig eth0");
  377. fp = popen(cmd, "r");
  378. if(fp != NULL)
  379. {
  380. while(fgets(buf, sizeof(buf), fp) != NULL)
  381. {
  382. if(strstr(buf, "eth0") > 0)
  383. {
  384. result = PASS;
  385. }
  386. if(strstr(buf, "eth0 Link encap:Ethernet HWaddr") > 0)
  387. {
  388. sscanf(buf, "%*s%*s%*s%*s%s", tmp);
  389. strcpy((char*)ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthMacAddress, tmp);
  390. }
  391. }
  392. }
  393. pclose(fp);
  394. return result;
  395. }
  396. int isUap0up(void)
  397. {
  398. int result = FAIL;
  399. FILE *fp;
  400. char cmd[256];
  401. char buf[512];
  402. strcpy(cmd, "ifconfig uap0");;
  403. fp = popen(cmd, "r");
  404. if(fp != NULL)
  405. {
  406. while(fgets(buf, sizeof(buf), fp) != NULL)
  407. {
  408. if(strstr(buf, "uap0") > 0)
  409. {
  410. result = PASS;
  411. }
  412. }
  413. }
  414. pclose(fp);
  415. return result;
  416. }
  417. char* getSystemModeName(unsigned char mode)
  418. {
  419. char* result;
  420. switch(mode)
  421. {
  422. case SYS_MODE_BOOTING:
  423. result = "booting";
  424. break;
  425. case SYS_MODE_IDLE:
  426. result = "idle";
  427. break;
  428. case SYS_MODE_AUTHORIZING:
  429. result = "authorizing";
  430. break;
  431. case SYS_MODE_PREPARING:
  432. result = "preparing";
  433. break;
  434. case SYS_MODE_CHARGING:
  435. result = "charging";
  436. break;
  437. case SYS_MODE_TERMINATING:
  438. result = "terminating";
  439. break;
  440. case SYS_MODE_COMPLETE:
  441. result = "complete";
  442. break;
  443. case SYS_MODE_ALARM:
  444. result = "alarm";
  445. break;
  446. case SYS_MODE_FAULT:
  447. result = "fault";
  448. break;
  449. case SYS_MODE_MAINTAIN:
  450. result = "maintain";
  451. break;
  452. case SYS_MODE_RESERVATION:
  453. result = "reservation";
  454. break;
  455. case SYS_MODE_BOOKING:
  456. result = "booking";
  457. break;
  458. case SYS_MODE_DEBUG:
  459. result = "debug";
  460. break;
  461. case SYS_MODE_UPDATE:
  462. result = "upgrade";
  463. break;
  464. default:
  465. result = "unknown";
  466. break;
  467. }
  468. return result;
  469. }
  470. void setChargerMode(unsigned char gun_index, unsigned char mode)
  471. {
  472. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus = ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus;
  473. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus = mode;
  474. DEBUG_INFO("Gun-%02d mode switch from %s to %s\n", gun_index, getSystemModeName(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus), getSystemModeName(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus));
  475. }
  476. unsigned char isMode(unsigned char gun_index, unsigned char mode)
  477. {
  478. return ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == mode)?YES:NO);
  479. }
  480. unsigned char isModeChange(unsigned char gun_index)
  481. {
  482. unsigned char result = NO;
  483. if(!isMode(gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus))
  484. {
  485. result = YES;
  486. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus = ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus;
  487. }
  488. return result;
  489. }
  490. int isGpioInitialized(unsigned int gpio)
  491. {
  492. int result = FAIL;
  493. char gpioPath[64];
  494. sprintf(gpioPath, "/sys/class/gpio/gpio%d/value", gpio);
  495. if((access(gpioPath, F_OK)) != -1)
  496. {
  497. result = PASS;
  498. }
  499. return result;
  500. }
  501. void gpio_set_value(unsigned int gpio, unsigned int value)
  502. {
  503. int fd;
  504. char buf[256];
  505. sprintf(buf, "/sys/class/gpio/gpio%d/value", gpio);
  506. fd = open(buf, O_WRONLY);
  507. if (fd < 0)
  508. {
  509. DEBUG_ERROR("GPIO-%d set %d fail.\n", gpio, value);
  510. return;
  511. }
  512. if (value)
  513. write(fd, "1", 2);
  514. else
  515. write(fd, "0", 2);
  516. close(fd);
  517. }
  518. int gpio_get_value(unsigned int gpio)
  519. {
  520. int fd;
  521. char buf[256];
  522. char ch;
  523. int8_t result = FAIL;
  524. sprintf(buf, "/sys/class/gpio/gpio%d/value", gpio);
  525. fd = open(buf, O_RDONLY);
  526. if (fd < 0)
  527. {
  528. DEBUG_ERROR("GPIO-%d get fail\n", gpio);
  529. return result;
  530. }
  531. read(fd, &ch, 1);
  532. if (ch != '0')
  533. result = 1;
  534. else
  535. result = 0;
  536. close(fd);
  537. return result;
  538. }
  539. int presentChargedEnergyClear(unsigned char gun_index)
  540. {
  541. int result = FAIL;
  542. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy = 0;
  543. memset(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].presentChargedEnergyPeriod, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].presentChargedEnergyPeriod)*sizeof(float));
  544. result = PASS;
  545. return result;
  546. }
  547. float presentChargedEnergyTotal(unsigned char gun_index)
  548. {
  549. float result = 0.0f;
  550. for(int idx=0;idx<ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].presentChargedEnergyPeriod);idx++)
  551. {
  552. result += ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].presentChargedEnergyPeriod[idx];
  553. }
  554. return result;
  555. }
  556. int presentChargedEnergyUpdate(unsigned char gun_index)
  557. {
  558. int result = FAIL;
  559. time_t CurrentTime;
  560. struct tm *tm;
  561. CurrentTime = time(NULL);
  562. tm=localtime(&CurrentTime);
  563. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==1)
  564. {
  565. // Resolution: 0.0001 kwh
  566. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].presentChargedEnergyPeriod[tm->tm_hour] += (((float)(ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption - ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption_at_start))/10000.0) - presentChargedEnergyTotal(gun_index);
  567. }
  568. else
  569. {
  570. // Resolution: 0.0001 kwh
  571. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].presentChargedEnergyPeriod[tm->tm_hour] += ((((float)(ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption - ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption_at_start))/10000.0) +
  572. (((float)(ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption - ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption_at_start))/10000.0) +
  573. (((float)(ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption - ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption_at_start))/10000.0))
  574. - presentChargedEnergyTotal(gun_index);
  575. }
  576. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy = presentChargedEnergyTotal(gun_index);
  577. return result;
  578. }
  579. //======================================================
  580. // OCPP routine
  581. //======================================================
  582. void ocpp_process_start()
  583. {
  584. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  585. system("/root/OcppBackend &");
  586. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  587. system("/root/OcppBackend20 &");
  588. }
  589. uint8_t ocpp_get_isRemoteStartWait()
  590. {
  591. uint8_t result = OFF;
  592. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  593. {
  594. result = ShmOCPP16Data->MsMsg.bits.isRemoteStartWaitReq;
  595. }
  596. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  597. {
  598. result = ShmOCPP20Data->MsMsg.bits.isRemoteStartWaitReq;
  599. }
  600. return result;
  601. }
  602. uint8_t ocpp_get_connection_status()
  603. {
  604. uint8_t result = OFF;
  605. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  606. {
  607. result = ShmOCPP16Data->OcppConnStatus;
  608. }
  609. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  610. {
  611. result = ShmOCPP20Data->OcppConnStatus;
  612. }
  613. return result;
  614. }
  615. uint16_t ocpp_get_connection_timeout()
  616. {
  617. uint16_t result = TIMEOUT_SPEC_HANDSHAKING;
  618. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  619. {
  620. if(strcmp((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData,"") != 0)
  621. {
  622. result = atoi((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData);
  623. }
  624. }
  625. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  626. {
  627. if(strcmp((char *)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_EVConnectionTimeOut].variableAttribute[0].value,"") != 0)
  628. {
  629. result = atoi((char *)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_EVConnectionTimeOut].variableAttribute[0].value);
  630. }
  631. }
  632. return result;
  633. }
  634. uint8_t ocpp_get_update_firmware_req()
  635. {
  636. uint8_t result = NO;
  637. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  638. {
  639. result = ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq;
  640. }
  641. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  642. {
  643. result = ShmOCPP20Data->MsMsg.bits.UpdateFirmwareReq;
  644. }
  645. return result;
  646. }
  647. uint8_t ocpp_get_reset_req()
  648. {
  649. uint8_t result = NO;
  650. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  651. {
  652. result = ShmOCPP16Data->MsMsg.bits.ResetReq;
  653. }
  654. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  655. {
  656. result = ShmOCPP20Data->MsMsg.bits.ResetReq;
  657. }
  658. return result;
  659. }
  660. void ocpp_boot_info_sync()
  661. {
  662. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  663. {
  664. memcpy((char*)ShmOCPP16Data->OcppServerURL, (char*)ShmSysConfigAndInfo->SysConfig.OcppServerURL, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.OcppServerURL));
  665. memcpy((char*)ShmOCPP16Data->ChargeBoxId, (char*)ShmSysConfigAndInfo->SysConfig.ChargeBoxId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.ChargeBoxId));
  666. sprintf((char*)ShmOCPP16Data->BootNotification.CpFwVersion, (char*)ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev);
  667. sprintf((char*)ShmOCPP16Data->BootNotification.CpMeterSerialNumber, "N/A");
  668. switch(ShmSysConfigAndInfo->SysConfig.ModelName[3])
  669. {
  670. case 'M':
  671. case 'Z':
  672. sprintf((char*)ShmOCPP16Data->BootNotification.CpMeterType, "MID");
  673. break;
  674. case 'P':
  675. sprintf((char*)ShmOCPP16Data->BootNotification.CpMeterType, "PTB");
  676. break;
  677. case 'I':
  678. sprintf((char*)ShmOCPP16Data->BootNotification.CpMeterType, "TIC");
  679. break;
  680. case 'U':
  681. sprintf((char*)ShmOCPP16Data->BootNotification.CpMeterType, "UL");
  682. break;
  683. default:
  684. sprintf((char*)ShmOCPP16Data->BootNotification.CpMeterType, "N/A");
  685. break;
  686. }
  687. }
  688. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  689. {
  690. memcpy((char*)ShmOCPP20Data->OcppServerURL, (char*)ShmSysConfigAndInfo->SysConfig.OcppServerURL, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.OcppServerURL));
  691. memcpy((char*)ShmOCPP20Data->ChargeBoxId, (char*)ShmSysConfigAndInfo->SysConfig.ChargeBoxId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.ChargeBoxId));
  692. sprintf((char*)ShmOCPP20Data->BootNotification.chargingStation.firmwareVersion, (char*)ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev);
  693. }
  694. }
  695. void ocpp_set_remotestart(uint8_t gun_index, uint8_t status)
  696. {
  697. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  698. {
  699. if(ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStartTransactionReq != status)
  700. ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStartTransactionReq = status;
  701. }
  702. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  703. {
  704. if(ShmOCPP20Data->CsMsg.bits[gun_index].RequestStartTransactionReq != status)
  705. ShmOCPP20Data->CsMsg.bits[gun_index].RequestStartTransactionReq = status;
  706. }
  707. }
  708. void ocpp_set_remotestop(uint8_t gun_index, uint8_t status)
  709. {
  710. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  711. {
  712. if(ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStopTransactionReq != status)
  713. ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStopTransactionReq = status;
  714. }
  715. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  716. {
  717. if(ShmOCPP20Data->CsMsg.bits[gun_index].RequestStopTransactionReq != status)
  718. ShmOCPP20Data->CsMsg.bits[gun_index].RequestStopTransactionReq = status;
  719. }
  720. }
  721. uint8_t ocpp_get_remotestart(uint8_t gun_index)
  722. {
  723. uint8_t result = OFF;
  724. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  725. {
  726. result = ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStartTransactionReq;
  727. }
  728. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  729. {
  730. result = ShmOCPP20Data->CsMsg.bits[gun_index].RequestStartTransactionReq;
  731. }
  732. return result;
  733. }
  734. void ocpp_copy_userid_from_remotestart(uint8_t gun_index)
  735. {
  736. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  737. {
  738. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmOCPP16Data->RemoteStartTransaction[gun_index].IdTag, ARRAY_SIZE(ShmOCPP16Data->RemoteStartTransaction[gun_index].IdTag));
  739. }
  740. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  741. {
  742. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmOCPP20Data->RequestStartTransaction[gun_index].idToken.idToken, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  743. }
  744. }
  745. uint8_t ocpp_get_remotestop(uint8_t gun_index)
  746. {
  747. uint8_t result = OFF;
  748. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  749. {
  750. result = ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStopTransactionReq;
  751. }
  752. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  753. {
  754. result = ShmOCPP20Data->CsMsg.bits[gun_index].RequestStopTransactionReq;
  755. }
  756. return result;
  757. }
  758. void ocpp_set_auth_req(uint8_t status, ...)
  759. {
  760. va_list args;
  761. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  762. {
  763. if(ShmOCPP16Data->SpMsg.bits.AuthorizeReq != status)
  764. {
  765. if(status == ON)
  766. memset(ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status, 0x00, ARRAY_SIZE(ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status));
  767. ShmOCPP16Data->SpMsg.bits.AuthorizeReq = status;
  768. }
  769. }
  770. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  771. {
  772. if(ShmOCPP20Data->SpMsg.bits.AuthorizeReq != status)
  773. {
  774. if(status == ON)
  775. {
  776. memset(&ShmOCPP20Data->Authorize.Response_idTokenInfo, 0x00, sizeof(struct IdTokenInfoType));
  777. va_start(args, status);
  778. sprintf((char*)ShmOCPP20Data->Authorize.idToken.type, "%s", va_arg(args, char*));
  779. va_end(args);
  780. }
  781. ShmOCPP20Data->SpMsg.bits.AuthorizeReq = status;
  782. }
  783. }
  784. }
  785. uint8_t ocpp_get_auth_req()
  786. {
  787. uint8_t result = OFF;
  788. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  789. {
  790. result = ShmOCPP16Data->SpMsg.bits.AuthorizeReq;
  791. }
  792. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  793. {
  794. result = ShmOCPP20Data->SpMsg.bits.AuthorizeReq;
  795. }
  796. return result;
  797. }
  798. void ocpp_set_auth_conf(uint8_t status)
  799. {
  800. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  801. {
  802. if(ShmOCPP16Data->SpMsg.bits.AuthorizeConf != status)
  803. ShmOCPP16Data->SpMsg.bits.AuthorizeConf = status;
  804. }
  805. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  806. {
  807. if(ShmOCPP20Data->SpMsg.bits.AuthorizeConf != status)
  808. ShmOCPP20Data->SpMsg.bits.AuthorizeConf = status;
  809. }
  810. }
  811. uint8_t ocpp_get_auth_conf()
  812. {
  813. uint8_t result = OFF;
  814. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  815. {
  816. result = ShmOCPP16Data->SpMsg.bits.AuthorizeConf;
  817. }
  818. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  819. {
  820. result = ShmOCPP20Data->SpMsg.bits.AuthorizeConf;
  821. }
  822. return result;
  823. }
  824. uint8_t ocpp_get_auth_result(uint8_t isValidParent, ...)
  825. {
  826. uint8_t result = OFF;
  827. va_list args;
  828. uint8_t gun_index;
  829. if(isValidParent)
  830. {
  831. va_start(args, isValidParent);
  832. gun_index = va_arg(args, int);
  833. va_end(args);
  834. switch(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus)
  835. {
  836. case SYS_MODE_AUTHORIZING:
  837. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  838. {
  839. if((strcmp((char*)ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status, "Accepted")==0))
  840. result = PASS;
  841. }
  842. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  843. {
  844. if((strcmp((char*)ShmOCPP20Data->Authorize.Response_idTokenInfo.status, "Accepted")==0))
  845. result = PASS;
  846. }
  847. break;
  848. case SYS_MODE_CHARGING:
  849. case SYS_MODE_TERMINATING:
  850. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  851. {
  852. /*
  853. DEBUG_INFO("==========================================\n");
  854. DEBUG_INFO("=== OCPP GETTING AUTHORIZE RESULT 1.6 ====\n");
  855. DEBUG_INFO("==========================================\n");
  856. DEBUG_INFO("Authorize.ResponseIdTagInfo.ParentIdTag : %s \n", ShmOCPP16Data->Authorize.ResponseIdTagInfo.ParentIdTag);
  857. DEBUG_INFO("StartTransaction[%d].ResponseIdTagInfo.ParentIdTag : %s \n", gun_index ,ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.ParentIdTag);
  858. */
  859. if((strcmp((char*)ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status, "Accepted")==0) &&
  860. (strcmp((char*)ShmOCPP16Data->Authorize.ResponseIdTagInfo.ParentIdTag, (char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.ParentIdTag)==0))
  861. result = PASS;
  862. }
  863. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  864. {
  865. /*
  866. DEBUG_INFO("==========================================\n");
  867. DEBUG_INFO("=== OCPP GETTING AUTHORIZE RESULT 2.0 ====\n");
  868. DEBUG_INFO("==========================================\n");
  869. DEBUG_INFO("Authorize.Response_idTokenInfo.groupIdToken.idToken : %s \n", ShmOCPP20Data->Authorize.Response_idTokenInfo.groupIdToken.idToken);
  870. DEBUG_INFO("TransactionEvent[%d].Response_idTokenInfo.groupIdToken.idToken : %s \n", gun_index, ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.groupIdToken.idToken);
  871. */
  872. if((strcmp((char*)ShmOCPP20Data->Authorize.Response_idTokenInfo.status, "Accepted")==0) &&
  873. (strcmp((char*)ShmOCPP20Data->Authorize.Response_idTokenInfo.groupIdToken.idToken, (char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.groupIdToken.idToken)==0))
  874. result = PASS;
  875. }
  876. break;
  877. default:
  878. break;
  879. }
  880. }
  881. else
  882. {
  883. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  884. {
  885. if((strcmp((char*)ShmOCPP16Data->Authorize.ResponseIdTagInfo.Status, "Accepted")==0))
  886. result = PASS;
  887. }
  888. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  889. {
  890. if((strcmp((char*)ShmOCPP20Data->Authorize.Response_idTokenInfo.status, "Accepted")==0))
  891. result = PASS;
  892. }
  893. }
  894. //DEBUG_INFO("Authorize result : %s \n", ((result == PASS)?"Pass":"Fail"));
  895. return result;
  896. }
  897. uint8_t ocpp_get_unlocker_req(uint8_t gun_index)
  898. {
  899. uint8_t result = OFF;
  900. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  901. {
  902. result = ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor;
  903. }
  904. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  905. {
  906. result = ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor;
  907. }
  908. return result;
  909. }
  910. void ocpp_set_unlocker_req(uint8_t gun_index, uint8_t status)
  911. {
  912. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  913. {
  914. if(ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor != status)
  915. ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor = status;
  916. }
  917. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  918. {
  919. if(ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor != status)
  920. ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor = status;
  921. }
  922. }
  923. void ocpp_set_starttransaction_req(uint8_t gun_index, uint8_t status)
  924. {
  925. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  926. {
  927. if(ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionReq != status)
  928. ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionReq = status;
  929. }
  930. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  931. {
  932. if(ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventReq != status)
  933. ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventReq = status;
  934. }
  935. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.MaintainServerURL,"") != 0)
  936. {
  937. if(ShmOCPP16DataPH->CpMsg.bits[gun_index].StartTransactionReq != status)
  938. ShmOCPP16DataPH->CpMsg.bits[gun_index].StartTransactionReq = status;
  939. }
  940. }
  941. void ocpp_set_starttransaction_conf(uint8_t gun_index, uint8_t status)
  942. {
  943. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  944. {
  945. if(ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionConf != status)
  946. ShmOCPP16Data->CpMsg.bits[gun_index].StartTransactionConf = status;
  947. }
  948. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  949. {
  950. if(ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventConf != status)
  951. ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventConf = status;
  952. }
  953. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.MaintainServerURL,"") != 0)
  954. {
  955. if(ShmOCPP16DataPH->CpMsg.bits[gun_index].StartTransactionConf != status)
  956. ShmOCPP16DataPH->CpMsg.bits[gun_index].StartTransactionConf = status;
  957. }
  958. }
  959. void ocpp_set_stoptransaction_req(uint8_t gun_index, uint8_t status)
  960. {
  961. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  962. {
  963. if(ShmOCPP16Data->CpMsg.bits[gun_index].StopTransactionReq != status)
  964. ShmOCPP16Data->CpMsg.bits[gun_index].StopTransactionReq = status;
  965. }
  966. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  967. {
  968. if(ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventReq != status)
  969. ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventReq = status;
  970. }
  971. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.MaintainServerURL,"") != 0)
  972. {
  973. if(ShmOCPP16DataPH->CpMsg.bits[gun_index].StopTransactionReq != status)
  974. ShmOCPP16DataPH->CpMsg.bits[gun_index].StopTransactionReq = status;
  975. }
  976. }
  977. void ocpp_set_stoptransaction_conf(uint8_t gun_index, uint8_t status)
  978. {
  979. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  980. {
  981. if(ShmOCPP16Data->CpMsg.bits[gun_index].StopTransactionConf != status)
  982. {
  983. ShmOCPP16Data->CpMsg.bits[gun_index].StopTransactionConf = status;
  984. }
  985. }
  986. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  987. {
  988. if(ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventConf != status)
  989. {
  990. ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventConf = status;
  991. }
  992. }
  993. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.MaintainServerURL,"") != 0)
  994. {
  995. if(ShmOCPP16DataPH->CpMsg.bits[gun_index].StopTransactionConf != status)
  996. ShmOCPP16DataPH->CpMsg.bits[gun_index].StopTransactionConf = status;
  997. }
  998. }
  999. void ocpp_copy_userid_to_starttransaction(uint8_t gun_index)
  1000. {
  1001. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  1002. {
  1003. memcpy((char*)ShmOCPP16Data->StartTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmOCPP16Data->StartTransaction[gun_index].IdTag));
  1004. }
  1005. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  1006. {
  1007. memcpy((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId));
  1008. }
  1009. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.MaintainServerURL,"") != 0)
  1010. {
  1011. memcpy((char*)ShmOCPP16DataPH->StartTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmOCPP16DataPH->StartTransaction[gun_index].IdTag));
  1012. }
  1013. }
  1014. uint8_t ocpp_get_starttransaction_result(uint8_t gun_index)
  1015. {
  1016. uint8_t result = PASS;
  1017. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  1018. {
  1019. if(strstr((char*)ShmOCPP16Data->ConfigurationTable.CoreProfile[StopTransactionOnInvalidId].ItemData, "TRUE"))
  1020. {
  1021. if((strcmp((char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Blocked")==0) ||
  1022. (strcmp((char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Expired")==0) ||
  1023. (strcmp((char*)ShmOCPP16Data->StartTransaction[gun_index].ResponseIdTagInfo.Status, "Invalid")==0))
  1024. result = NO;
  1025. }
  1026. }
  1027. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  1028. {
  1029. if(strstr((char*)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_StopTxOnInvalidId].variableAttribute[0].value, "TRUE"))
  1030. {
  1031. if((strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Blocked")==0) ||
  1032. (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Expired")==0) ||
  1033. (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Invalid")==0) ||
  1034. (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NoCredit")==0) ||
  1035. (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NotAllowedTypeEVSE")==0) ||
  1036. (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NotAtThisLocation")==0) ||
  1037. (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "NotAtThisTime")==0) ||
  1038. (strcmp((char*)ShmOCPP20Data->TransactionEvent[gun_index].Response_idTokenInfo.status, "Unknown")==0))
  1039. result = NO;
  1040. }
  1041. }
  1042. return result;
  1043. }
  1044. uint8_t ocpp_get_maxcharging_profileId()
  1045. {
  1046. uint8_t result = 0;
  1047. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  1048. {
  1049. result = ShmOCPP16Data->MaxChargingProfile.ChargingProfileId;
  1050. }
  1051. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  1052. {
  1053. result = ShmOCPP20Data->MaxChargingProfile.id;
  1054. }
  1055. return result;
  1056. }
  1057. uint8_t ocpp_get_smartcharging_profileId(uint8_t gun_index)
  1058. {
  1059. uint8_t result = 0;
  1060. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  1061. {
  1062. result = ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfileId;
  1063. }
  1064. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  1065. {
  1066. result = ShmOCPP20Data->SmartChargingProfile[gun_index].id;
  1067. }
  1068. return result;
  1069. }
  1070. void ocpp_reset_smartcharging_profileId(uint8_t gun_index)
  1071. {
  1072. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  1073. {
  1074. ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfileId = 0;
  1075. }
  1076. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  1077. {
  1078. ShmOCPP20Data->SmartChargingProfile[gun_index].id = 0;
  1079. }
  1080. }
  1081. uint8_t ocpp_get_profile_req(uint8_t gun_index)
  1082. {
  1083. uint8_t result = OFF;
  1084. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  1085. {
  1086. result = ShmOCPP16Data->CSUMsg.bits[gun_index].ChargingProfileReq;
  1087. }
  1088. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  1089. {
  1090. result = ShmOCPP20Data->CSUMsg.bits[gun_index].ChargingProfileReq;
  1091. }
  1092. return result;
  1093. }
  1094. void ocpp_set_profile_req(uint8_t gun_index, uint8_t status)
  1095. {
  1096. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  1097. {
  1098. if(ShmOCPP16Data->CSUMsg.bits[gun_index].ChargingProfileReq != status)
  1099. ShmOCPP16Data->CSUMsg.bits[gun_index].ChargingProfileReq = status;
  1100. }
  1101. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  1102. {
  1103. if(ShmOCPP20Data->CSUMsg.bits[gun_index].ChargingProfileReq != status)
  1104. ShmOCPP20Data->CSUMsg.bits[gun_index].ChargingProfileReq = status;
  1105. }
  1106. }
  1107. uint8_t ocpp_get_profile_conf(uint8_t gun_index)
  1108. {
  1109. uint8_t result = OFF;
  1110. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  1111. {
  1112. result = ShmOCPP16Data->CSUMsg.bits[gun_index].ChargingProfileConf;
  1113. }
  1114. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  1115. {
  1116. result = ShmOCPP20Data->CSUMsg.bits[gun_index].ChargingProfileConf;
  1117. }
  1118. return result;
  1119. }
  1120. void ocpp_set_profile_conf(uint8_t gun_index, uint8_t status)
  1121. {
  1122. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  1123. {
  1124. if(ShmOCPP16Data->CSUMsg.bits[gun_index].ChargingProfileConf != status)
  1125. ShmOCPP16Data->CSUMsg.bits[gun_index].ChargingProfileConf = status;
  1126. }
  1127. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  1128. {
  1129. if(ShmOCPP20Data->CSUMsg.bits[gun_index].ChargingProfileConf != status)
  1130. ShmOCPP20Data->CSUMsg.bits[gun_index].ChargingProfileConf = status;
  1131. }
  1132. }
  1133. uint8_t ocpp_get_StopTransactionOnEVSideDisconnect()
  1134. {
  1135. uint8_t result = OFF;
  1136. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  1137. {
  1138. if(strcmp((char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[StopTransactionOnEVSideDisconnect].ItemData, "TRUE") == 0)
  1139. result = ON;
  1140. }
  1141. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  1142. {
  1143. if(strcmp((char *)ShmOCPP20Data->ControllerComponentVariable[TxCtrlr_StopTxOnEVSideDisconnect].variableAttribute[0].value, "TRUE") == 0)
  1144. result = ON;
  1145. }
  1146. return result;
  1147. }
  1148. uint8_t ocpp_get_cancelreservation_req(uint8_t gun_index)
  1149. {
  1150. uint8_t result = OFF;
  1151. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  1152. {
  1153. result = ShmOCPP16Data->CsMsg.bits[gun_index].CancelReservationReq;
  1154. }
  1155. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  1156. {
  1157. result = ShmOCPP20Data->CsMsg.bits[gun_index].CancelReservationReq;
  1158. }
  1159. return result;
  1160. }
  1161. void ocpp_set_cancelreservation_req(uint8_t gun_index, uint8_t status)
  1162. {
  1163. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  1164. {
  1165. if(ShmOCPP16Data->CsMsg.bits[gun_index].CancelReservationReq != status)
  1166. ShmOCPP16Data->CsMsg.bits[gun_index].CancelReservationReq = status;
  1167. if(ShmOCPP16Data->CsMsg.bits[gun_index].CancelReservationReq == OFF)
  1168. ShmOCPP16Data->CsMsg.bits[gun_index].CancelReservationConf = ON;
  1169. }
  1170. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  1171. {
  1172. if(ShmOCPP20Data->CsMsg.bits[gun_index].CancelReservationReq != status)
  1173. ShmOCPP20Data->CsMsg.bits[gun_index].CancelReservationReq = status;
  1174. if(ShmOCPP20Data->CsMsg.bits[gun_index].CancelReservationReq == OFF)
  1175. ShmOCPP20Data->CsMsg.bits[gun_index].CancelReservationConf = ON;
  1176. }
  1177. }
  1178. uint8_t ocpp_compare_reserve_id_with_user(uint8_t gun_index)
  1179. {
  1180. uint8_t result = OFF;
  1181. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  1182. {
  1183. if(strcmp((char*)ShmSysConfigAndInfo->SysConfig.UserId, (char*)ShmOCPP16Data->ReserveNow[gun_index].IdTag) == 0)
  1184. result = ON;
  1185. }
  1186. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  1187. {
  1188. if(strcmp((char*)ShmSysConfigAndInfo->SysConfig.UserId, (char*)ShmOCPP20Data->ReserveNow[gun_index].idToken.idToken) == 0)
  1189. result = ON;
  1190. }
  1191. return result;
  1192. }
  1193. uint8_t ocpp_compare_reserve_id_with_remote_user(uint8_t gun_index)
  1194. {
  1195. uint8_t result = OFF;
  1196. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  1197. {
  1198. if(strcmp((char*)ShmOCPP16Data->RemoteStartTransaction[gun_index].IdTag, (char*)ShmOCPP16Data->ReserveNow[gun_index].IdTag) == 0)
  1199. {
  1200. result = ON;
  1201. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmOCPP16Data->RemoteStartTransaction[gun_index].IdTag, ARRAY_SIZE(ShmOCPP16Data->RemoteStartTransaction[gun_index].IdTag));
  1202. }
  1203. }
  1204. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  1205. {
  1206. if(strcmp((char*)ShmOCPP20Data->RequestStartTransaction[gun_index].idToken.idToken, (char*)ShmOCPP20Data->ReserveNow[gun_index].idToken.idToken) == 0)
  1207. {
  1208. result = ON;
  1209. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmOCPP20Data->RequestStartTransaction[gun_index].idToken.idToken, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  1210. }
  1211. }
  1212. return result;
  1213. }
  1214. uint8_t ocpp_isAuthorizeRemoteStart()
  1215. {
  1216. uint8_t result = NO;
  1217. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  1218. {
  1219. if(strstr((char*)ShmOCPP16Data->ConfigurationTable.CoreProfile[AuthorizeRemoteTxRequests].ItemData, "TRUE"))
  1220. {
  1221. result = YES;
  1222. }
  1223. }
  1224. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  1225. {
  1226. if(strstr((char*)ShmOCPP20Data->ControllerComponentVariable[AuthCtrlr_AuthorizeRemoteStart].variableAttribute[0].value, "TRUE"))
  1227. {
  1228. result = YES;
  1229. }
  1230. }
  1231. return result;
  1232. }
  1233. uint8_t ocpp_get_freevend_idtag(uint8_t * userId)
  1234. {
  1235. uint8_t result = NO;
  1236. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  1237. {
  1238. strcpy((char*)userId, (char*)ShmOCPP16Data->ConfigurationTable.CoreProfile[FreeVendIdtag].ItemData);
  1239. result = YES;
  1240. }
  1241. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  1242. {
  1243. strcpy((char*)userId, (char*)ShmOCPP20Data->ControllerComponentVariable[ChargingStation_FreeVendIdtag].variableAttribute[0].value);
  1244. result = YES;
  1245. }
  1246. return result;
  1247. }
  1248. //======================================================
  1249. // Check interface status
  1250. //======================================================
  1251. int isInterfaceUp(const char *interface)
  1252. {
  1253. int result = FAIL;
  1254. FILE *fp;
  1255. char cmd[256];
  1256. char buf[512];
  1257. strcpy(cmd, "ifconfig");;
  1258. fp = popen(cmd, "r");
  1259. if(fp != NULL)
  1260. {
  1261. while(fgets(buf, sizeof(buf), fp) != NULL)
  1262. {
  1263. if(strstr(buf, interface) > 0)
  1264. {
  1265. result = PASS;
  1266. }
  1267. }
  1268. }
  1269. pclose(fp);
  1270. return result;
  1271. }
  1272. //======================================================
  1273. // Create all share memory
  1274. //======================================================
  1275. int CreatShareMemory()
  1276. {
  1277. int result = PASS;
  1278. int MeterSMId;
  1279. //creat ShmSysConfigAndInfo
  1280. if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo), IPC_CREAT | 0777)) < 0)
  1281. {
  1282. DEBUG_ERROR("shmget ShmSysConfigAndInfo NG\n");
  1283. result = FAIL;
  1284. }
  1285. else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  1286. {
  1287. DEBUG_ERROR("shmat ShmSysConfigAndInfo NG\n");
  1288. result = FAIL;
  1289. }
  1290. memset(ShmSysConfigAndInfo,0,sizeof(struct SysConfigAndInfo));
  1291. //creat ShmPsuData
  1292. if ((MeterSMId = shmget(ShmPsuKey, sizeof(struct PsuData), IPC_CREAT | 0777)) < 0)
  1293. {
  1294. DEBUG_ERROR("shmget ShmPsuData NG\n");
  1295. result = FAIL;
  1296. }
  1297. else if ((ShmPsuData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  1298. {
  1299. DEBUG_ERROR("shmat ShmPsuData NG\n");
  1300. result = FAIL;
  1301. }
  1302. else
  1303. {}
  1304. //creat ShmStatusCodeData
  1305. if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData), IPC_CREAT | 0777)) < 0)
  1306. {
  1307. DEBUG_ERROR("shmget ShmStatusCodeData NG\n");
  1308. result = FAIL;
  1309. }
  1310. else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  1311. {
  1312. DEBUG_ERROR("shmat ShmStatusCodeData NG\n");
  1313. result = FAIL;
  1314. }
  1315. memset(ShmStatusCodeData, 0, sizeof(struct StatusCodeData));
  1316. //creat ShmPrimaryMcuData
  1317. if ((MeterSMId = shmget(ShmPrimaryMcuKey, sizeof(struct PrimaryMcuData), IPC_CREAT | 0777)) < 0)
  1318. {
  1319. DEBUG_ERROR("shmget ShmPrimaryMcuData NG\n");
  1320. result = FAIL;
  1321. }
  1322. else if ((ShmPrimaryMcuData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  1323. {
  1324. DEBUG_ERROR("shmat ShmPrimaryMcuData NG\n");
  1325. result = FAIL;
  1326. }
  1327. memset(ShmPrimaryMcuData,0,sizeof(struct PrimaryMcuData));
  1328. //creat ShmOCPP16Data
  1329. if ((MeterSMId = shmget(ShmOcppModuleKey, sizeof(struct OCPP16Data), IPC_CREAT | 0777)) < 0)
  1330. {
  1331. DEBUG_ERROR("shmget ShmOCPP16Data NG\n");
  1332. result = FAIL;
  1333. }
  1334. else if ((ShmOCPP16Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  1335. {
  1336. DEBUG_ERROR("shmat ShmOCPP16Data NG\n");
  1337. result = FAIL;
  1338. }
  1339. memset(ShmOCPP16Data,0,sizeof(struct OCPP16Data));
  1340. //creat ShmOCPP20Data
  1341. if ((MeterSMId = shmget(ShmOcpp20ModuleKey, sizeof(struct OCPP20Data), IPC_CREAT | 0777)) < 0)
  1342. {
  1343. DEBUG_ERROR("shmget OCPP20Data NG\n");
  1344. result = FAIL;
  1345. }
  1346. else if ((ShmOCPP20Data = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  1347. {
  1348. DEBUG_ERROR("shmat OCPP20Data NG\n");
  1349. result = FAIL;
  1350. }
  1351. memset(ShmOCPP20Data,0,sizeof(struct OCPP20Data));
  1352. //creat ShmCharger
  1353. if ((MeterSMId = shmget(ShmChargerKey, sizeof(struct Charger), IPC_CREAT | 0777)) < 0)
  1354. {
  1355. DEBUG_ERROR("shmget ShmCharger NG\n");
  1356. result = FAIL;
  1357. }
  1358. else if ((ShmCharger = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  1359. {
  1360. DEBUG_ERROR("shmat ShmCharger NG\n");
  1361. result = FAIL;
  1362. }
  1363. memset(ShmCharger,0,sizeof(struct Charger));
  1364. //creat ShmOCPP16DataPH
  1365. if ((MeterSMId = shmget(ShmOcppPHModuleKey, sizeof(struct OCPP16Data), IPC_CREAT|0777)) < 0)
  1366. {
  1367. DEBUG_ERROR("shmget ShmOCPP16DataPH NG\n");
  1368. result = FAIL;
  1369. }
  1370. else if ((ShmOCPP16DataPH = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  1371. {
  1372. DEBUG_ERROR("shmat ShmOCPP16DataPH NG\n");
  1373. result = FAIL;
  1374. }
  1375. else
  1376. {}
  1377. //creat ShmDispenser
  1378. if ((MeterSMId = shmget(ShmDispenserKey, sizeof(struct DISPENSER), IPC_CREAT | 0777)) < 0)
  1379. {
  1380. DEBUG_ERROR("shmget ShmDispenser NG\n");
  1381. result = FAIL;
  1382. }
  1383. else if ((ShmDispenser = shmat(MeterSMId, NULL, 0)) == (void *) -1)
  1384. {
  1385. DEBUG_ERROR("shmat ShmDispenser NG\n");
  1386. result = FAIL;
  1387. }
  1388. memset(ShmDispenser,0,sizeof(struct DISPENSER));
  1389. ShmSysConfigAndInfo->SysInfo.InternetConn = OFF;
  1390. return result;
  1391. }
  1392. //======================================================
  1393. // Call WEBAPI to mail receipt (Only for CDFA verify)
  1394. //======================================================
  1395. #ifdef CDFA_CERTIFICATE
  1396. int sendReceiptMail(char *startDateTime, char *stopDateTime, char *receiptInfo)
  1397. {
  1398. int result = FAIL;
  1399. char reciever[128];
  1400. char subject[128];
  1401. char content[8192];
  1402. char priceDetail[4098]={0};
  1403. char cmdBuf[8192];
  1404. double totalEnergy;
  1405. double totalPrice;
  1406. json_object *detailPrice = json_tokener_parse(receiptInfo);
  1407. if(!is_error(detailPrice))
  1408. {
  1409. if(json_object_object_get(detailPrice, "totalChargedEnergy") != NULL)
  1410. totalEnergy = json_object_get_double(json_object_object_get(detailPrice, "totalChargedEnergy"));
  1411. if(json_object_object_get(detailPrice, "totalPrice") != NULL)
  1412. totalPrice = json_object_get_double(json_object_object_get(detailPrice, "totalPrice"));
  1413. if(json_object_object_get(detailPrice, "receiptDetail") != NULL)
  1414. {
  1415. for(int idx=0;idx<json_object_array_length(json_object_object_get(detailPrice, "receiptDetail"));idx++)
  1416. {
  1417. sprintf(priceDetail, "%s---%02d:00, %.4f KWH @ $ %.2f = $ %.2f<br/>\n", priceDetail
  1418. , json_object_get_int(json_object_object_get(json_object_array_get_idx(json_object_object_get(detailPrice, "receiptDetail"), idx), "hour"))
  1419. , json_object_get_double(json_object_object_get(json_object_array_get_idx(json_object_object_get(detailPrice, "receiptDetail"), idx), "chargedEnergy"))
  1420. , json_object_get_double(json_object_object_get(json_object_array_get_idx(json_object_object_get(detailPrice, "receiptDetail"), idx), "unitPrice"))
  1421. , json_object_get_double(json_object_object_get(json_object_array_get_idx(json_object_object_get(detailPrice, "receiptDetail"), idx), "periodPrice")));
  1422. }
  1423. }
  1424. }
  1425. json_object_put(detailPrice);
  1426. // Generate mail content
  1427. sprintf(reciever, "folus_wen@phihong.com.tw");
  1428. sprintf(subject, "Charging Receipt From %s", ShmSysConfigAndInfo->SysConfig.chargePointVendor);
  1429. sprintf(content, "<img src=\"https://www.phihong.com/images/logo.png\"/><br/>\n"
  1430. "<h1>Receipt of charging on %s</h1><br/>\n"
  1431. "<b>Location Name:</b> CDFA Lab<br/>\n"
  1432. "<b>Location Address:</b> xxxxxxxxxxx<br/>\n"
  1433. "<b>EVSE ID:</b> %s<br/>\n"
  1434. "<b>Maximum Rate of Energy Transfer:</b> 11.5 KW AC<br/>\n"
  1435. "<b>Charging start date time:</b> %s<br/>\n"
  1436. "<b>Charging stop date time:</b> %s<br/>\n"
  1437. "<b>Energy Delivered:</b> %.4f KWH<br/>\n"
  1438. "<b>Cost of Charging:</b><br/>\n"
  1439. "%s"
  1440. "***Total charged cost: $ %.2f<br/>\n"
  1441. "<br/>\n"
  1442. "<br/>\n"
  1443. "%s<br/>\n"
  1444. "47800 Fremont Blvd.<br/>\n"
  1445. "Fremont, CA 94538, USA<br/>\n", startDateTime
  1446. , ShmSysConfigAndInfo->SysConfig.ChargeBoxId
  1447. , startDateTime
  1448. , stopDateTime
  1449. , totalEnergy
  1450. , priceDetail
  1451. , totalPrice
  1452. , ShmSysConfigAndInfo->SysConfig.chargePointVendor);
  1453. json_object *post = json_object_new_object();
  1454. json_object_object_add(post, "Receiver", json_object_new_string(reciever));
  1455. json_object_object_add(post, "Subject", json_object_new_string(subject));
  1456. json_object_object_add(post, "Body", json_object_new_string(content));
  1457. json_object_object_add(post, "UseHtml", json_object_new_boolean(1));
  1458. // Call WEBAPI
  1459. sprintf(cmdBuf, "curl -X POST -k -d '%s' -H \"Content-Type: application/json\" https://ocpp.phihong.com.tw:5014/api/Notification/ &", json_object_to_json_string_ext(post, JSON_C_TO_STRING_PLAIN));
  1460. system(cmdBuf);
  1461. //DEBUG_INFO("cmdBuf: %s\n", cmdBuf);
  1462. json_object_put(post);
  1463. return result;
  1464. }
  1465. #endif /* CDFA_CERTIFICATE */
  1466. //======================================================
  1467. // SQLite3 related routine
  1468. //======================================================
  1469. int getReceiptInfo(uint8_t gun_index, char *receiptInfo)
  1470. {
  1471. int result = PASS;
  1472. double totalEnergy=0.0;
  1473. double totalPrice=0.0;
  1474. json_object *receipt = json_object_new_object();
  1475. json_object *receiptAry = json_object_new_array();
  1476. for(uint8_t idxHour=0;idxHour<ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].presentChargedEnergyPeriod);idxHour++)
  1477. {
  1478. json_object *receiptDetail = json_object_new_object();
  1479. json_object_object_add(receiptDetail, "hour", json_object_new_int(idxHour));
  1480. json_object_object_add(receiptDetail, "chargedEnergy", json_object_new_double(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].presentChargedEnergyPeriod[idxHour]));
  1481. json_object_object_add(receiptDetail, "unitPrice", json_object_new_double(ShmSysConfigAndInfo->SysConfig.BillingData.Fee[idxHour]));
  1482. json_object_object_add(receiptDetail, "periodPrice", json_object_new_double(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].presentChargedEnergyPeriod[idxHour]*ShmSysConfigAndInfo->SysConfig.BillingData.Fee[idxHour]));
  1483. totalEnergy += ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].presentChargedEnergyPeriod[idxHour];
  1484. totalPrice += ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].presentChargedEnergyPeriod[idxHour]*ShmSysConfigAndInfo->SysConfig.BillingData.Fee[idxHour];
  1485. json_object_array_add(receiptAry, receiptDetail);
  1486. }
  1487. json_object_object_add(receipt, "receiptDetail", receiptAry);
  1488. json_object_object_add(receipt, "totalChargedEnergy", json_object_new_double(totalEnergy));
  1489. json_object_object_add(receipt, "totalPrice", json_object_new_double(totalPrice));
  1490. json_object_object_add(receipt, "serviceProvider", json_object_new_string((char*)ShmSysConfigAndInfo->SysConfig.chargePointVendor));
  1491. json_object_object_add(receipt, "serviceProviderAddress", json_object_new_string("Address"));
  1492. json_object_object_add(receipt, "serviceProviderTel", json_object_new_string("TEL"));
  1493. json_object_object_add(receipt, "chargerBoxId", json_object_new_string((char*)ShmSysConfigAndInfo->SysConfig.ChargeBoxId));
  1494. sprintf(receiptInfo, "%s", json_object_to_json_string_ext(receipt, JSON_C_TO_STRING_PLAIN));
  1495. json_object_put(receipt);
  1496. //DEBUG_INFO("receiptInfo: %s\n", receiptInfo);
  1497. return result;
  1498. }
  1499. int DB_Open(sqlite3 *db)
  1500. {
  1501. int result = PASS;
  1502. char* errMsg = NULL;
  1503. char* createRecordSql="CREATE TABLE IF NOT EXISTS charging_record("
  1504. "idx integer primary key AUTOINCREMENT, "
  1505. "reservationId text, "
  1506. "transactionId text, "
  1507. "startMethod text, "
  1508. "userId text, "
  1509. "dateTimeStart text, "
  1510. "dateTimeStop text,"
  1511. "socStart text, "
  1512. "socStop text, "
  1513. "chargeEnergy text, "
  1514. "stopReason text, "
  1515. "finalCost text"
  1516. ");";
  1517. char* createRecordBufSql="CREATE TABLE IF NOT EXISTS charging_record_buffer("
  1518. "reservationId text, "
  1519. "transactionId text, "
  1520. "startMethod text, "
  1521. "userId text, "
  1522. "dateTimeStart text, "
  1523. "dateTimeStop text,"
  1524. "socStart text, "
  1525. "socStop text, "
  1526. "chargeEnergy text, "
  1527. "stopReason text, "
  1528. "finalCost text"
  1529. ");";
  1530. char* createCfgSql="CREATE TABLE IF NOT EXISTS `config` ( "
  1531. "`idx` INTEGER PRIMARY KEY AUTOINCREMENT, "
  1532. "`item` TEXT NOT NULL, "
  1533. "`connector` INTEGER NOT NULL, "
  1534. "`val` TEXT NOT NULL, unique(item,connector) on conflict replace);";
  1535. //sqlite3_config(SQLITE_CONFIG_URI, 1);
  1536. if(sqlite3_open(DB_FILE, &db))
  1537. {
  1538. result = FAIL;
  1539. DEBUG_ERROR( "Can't open database: %s\n", sqlite3_errmsg(db));
  1540. sqlite3_close(db);
  1541. }
  1542. else
  1543. {
  1544. DEBUG_INFO( "Local charging record database open successfully.\n");
  1545. if (sqlite3_exec(db, createRecordSql, 0, 0, &errMsg) != SQLITE_OK)
  1546. {
  1547. result = FAIL;
  1548. DEBUG_ERROR( "Create local charging record table error message: %s\n", errMsg);
  1549. }
  1550. else
  1551. {
  1552. DEBUG_INFO( "Opened local charging record table successfully\n");
  1553. }
  1554. if (sqlite3_exec(db, createRecordBufSql, 0, 0, &errMsg) != SQLITE_OK)
  1555. {
  1556. result = FAIL;
  1557. DEBUG_ERROR( "Create local charging record buffer table error message: %s\n", errMsg);
  1558. }
  1559. else
  1560. {
  1561. DEBUG_INFO( "Opened local charging record buffer table successfully\n");
  1562. }
  1563. if (sqlite3_exec(db, createCfgSql, 0, 0, &errMsg) != SQLITE_OK)
  1564. {
  1565. result = FAIL;
  1566. DEBUG_ERROR( "Create local config table error message: %s\n", errMsg);
  1567. }
  1568. else
  1569. {
  1570. DEBUG_INFO( "Opened local config table successfully\n");
  1571. }
  1572. sqlite3_close(db);
  1573. }
  1574. return result;
  1575. }
  1576. int DB_Check_Record_Buf(sqlite3 *db, int gun_index)
  1577. {
  1578. int result = PASS;
  1579. char* errMsg = NULL;
  1580. char sqlStr[4096];
  1581. char **rs;
  1582. int rows, cols;
  1583. if(sqlite3_open(DB_FILE, &db))
  1584. {
  1585. result = FAIL;
  1586. DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
  1587. sqlite3_close(db);
  1588. }
  1589. else
  1590. {
  1591. sqlite3_get_table(db, "select * from charging_record_buffer", &rs, &rows, &cols, &errMsg);
  1592. if(rows>0)
  1593. {
  1594. // Copy record buffer
  1595. for(int idxRow=1;idxRow<=rows;idxRow++)
  1596. {
  1597. if(strcmp(rs[(idxRow*cols)+3], "0") == 0)
  1598. {
  1599. result = false;
  1600. }
  1601. sprintf(sqlStr, "insert into charging_record(reservationId, transactionId, startMethod, userId, dateTimeStart, dateTimeStop, socStart, socStop, chargeEnergy, stopReason, finalCost) "
  1602. "values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');",
  1603. rs[(idxRow*cols)+0],
  1604. rs[(idxRow*cols)+1],
  1605. rs[(idxRow*cols)+2],
  1606. rs[(idxRow*cols)+3],
  1607. rs[(idxRow*cols)+4],
  1608. rs[(idxRow*cols)+5],
  1609. rs[(idxRow*cols)+6],
  1610. rs[(idxRow*cols)+7],
  1611. rs[(idxRow*cols)+8],
  1612. rs[(idxRow*cols)+9],
  1613. rs[(idxRow*cols)+10]);
  1614. if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
  1615. {
  1616. result = FAIL;
  1617. DEBUG_INFO( "Copy local charging record buffer error message: %s\n", errMsg);
  1618. }
  1619. else
  1620. {
  1621. DEBUG_INFO( "Copy local charging record buffer successfully\n");
  1622. }
  1623. #ifdef CDFA_CERTIFICATE
  1624. // Only for CDFA certificate
  1625. sendReceiptMail(rs[(idxRow*cols)+4],
  1626. rs[(idxRow*cols)+5],
  1627. rs[(idxRow*cols)+10]);
  1628. #endif /* CDFA_CERTIFICATE */
  1629. }
  1630. // Delete buffer
  1631. if (sqlite3_exec(db, "delete from charging_record_buffer", 0, 0, &errMsg) != SQLITE_OK)
  1632. {
  1633. result = FAIL;
  1634. DEBUG_INFO( "Delete local charging record buffer error message: %s\n", errMsg);
  1635. }
  1636. else
  1637. {
  1638. DEBUG_INFO( "Delete local charging record buffer successfully\n");
  1639. }
  1640. }
  1641. else
  1642. {
  1643. DEBUG_INFO("There is not any charging record buffer.\n", gun_index);
  1644. }
  1645. sqlite3_free_table(rs);
  1646. sqlite3_close(db);
  1647. }
  1648. return result;
  1649. }
  1650. int DB_Update_Record_Buf(sqlite3 *db, int gun_index)
  1651. {
  1652. int result = PASS;
  1653. char* errMsg = NULL;
  1654. char sqlStr[4096];
  1655. char receiptInfo[2048];
  1656. getReceiptInfo(gun_index, receiptInfo);
  1657. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  1658. {
  1659. sprintf(sqlStr, "insert into charging_record_buffer(reservationId, transactionId, startMethod, userId, dateTimeStart, dateTimeStop, socStart, socStop, chargeEnergy, stopReason, finalCost) "
  1660. "values('%d', '%d', '%d', '%s', '%s', '%s', '%d', '%d', '%f', '%s', '%s');",
  1661. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId,
  1662. ShmOCPP16Data->StartTransaction[gun_index].ResponseTransactionId,
  1663. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod,
  1664. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId,
  1665. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime,
  1666. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime,
  1667. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
  1668. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
  1669. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy,
  1670. "Power Loss",
  1671. #ifdef CDFA_CERTIFICATE
  1672. receiptInfo);// Only for CDFA certificate
  1673. #else
  1674. ShmOCPP16Data->Cost.FinalCost[gun_index].description);
  1675. #endif /* CDFA_CERTIFICATE */
  1676. }
  1677. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  1678. {
  1679. sprintf(sqlStr, "insert into charging_record_buffer(reservationId, transactionId, startMethod, userId, dateTimeStart, dateTimeStop, socStart, socStop, chargeEnergy, stopReason, finalCost) "
  1680. #ifdef CDFA_CERTIFICATE
  1681. "values('%d', '%s', '%d', '%s', '%s', '%s', '%d', '%d', '%f', '%s', '%s');",
  1682. #else
  1683. "values('%d', '%s', '%d', '%s', '%s', '%s', '%d', '%d', '%f', '%s', '%f');",
  1684. #endif /* CDFA_CERTIFICATE */
  1685. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId,
  1686. ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.transactionId,
  1687. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod,
  1688. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId,
  1689. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime,
  1690. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime,
  1691. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
  1692. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
  1693. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy,
  1694. "Power Loss",
  1695. #ifdef CDFA_CERTIFICATE
  1696. //receiptInfo);// Only for CDFA certificate
  1697. #else
  1698. ShmOCPP20Data->CostUpdated.totalCost);
  1699. #endif /* CDFA_CERTIFICATE */
  1700. }
  1701. if(sqlite3_open(DB_FILE, &db))
  1702. {
  1703. result = FAIL;
  1704. DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
  1705. sqlite3_close(db);
  1706. }
  1707. else
  1708. {
  1709. // Delete buffer
  1710. if (sqlite3_exec(db, "delete from charging_record_buffer", 0, 0, &errMsg) != SQLITE_OK)
  1711. {
  1712. result = FAIL;
  1713. DEBUG_INFO( "Delete local charging record buffer error message: %s\n", errMsg);
  1714. }
  1715. else
  1716. {
  1717. //DEBUG_INFO( "Delete local charging record buffer successfully\n");
  1718. }
  1719. // Insert record buffer
  1720. if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
  1721. {
  1722. result = FAIL;
  1723. DEBUG_INFO( "Insert local charging record buffer error message: %s\n", errMsg);
  1724. }
  1725. else
  1726. {
  1727. //DEBUG_INFO( "Insert local charging record buffer successfully\n");
  1728. }
  1729. sqlite3_close(db);
  1730. }
  1731. return result;
  1732. }
  1733. int DB_Insert_Record(sqlite3 *db, int gun_index)
  1734. {
  1735. int result = PASS;
  1736. char* errMsg = NULL;
  1737. char sqlStr[4096];
  1738. char receiptInfo[2048];
  1739. getReceiptInfo(gun_index, receiptInfo);
  1740. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  1741. {
  1742. sprintf(sqlStr, "insert into charging_record(reservationId, transactionId, startMethod, userId, dateTimeStart, dateTimeStop, socStart, socStop, chargeEnergy, stopReason, finalCost) "
  1743. "values('%d', '%d', '%d', '%s', '%s', '%s', '%d', '%d', '%f', '%s', '%s');",
  1744. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId,
  1745. ShmOCPP16Data->StartTransaction[gun_index].ResponseTransactionId,
  1746. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod,
  1747. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId,
  1748. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime,
  1749. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime,
  1750. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
  1751. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
  1752. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy,
  1753. ShmOCPP16Data->StopTransaction[gun_index].StopReason,
  1754. #ifdef CDFA_CERTIFICATE
  1755. receiptInfo);// Only for CDFA certificate
  1756. #else
  1757. ShmOCPP16Data->Cost.FinalCost[gun_index].description);
  1758. #endif /* CDFA_CERTIFICATE */
  1759. }
  1760. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  1761. {
  1762. sprintf(sqlStr, "insert into charging_record(reservationId, transactionId, startMethod, userId, dateTimeStart, dateTimeStop, socStart, socStop, chargeEnergy, stopReason, finalCost) "
  1763. #ifdef CDFA_CERTIFICATE
  1764. "values('%d', '%s', '%d', '%s', '%s', '%s', '%d', '%d', '%f', '%s', '%s');",
  1765. #else
  1766. "values('%d', '%s', '%d', '%s', '%s', '%s', '%d', '%d', '%f', '%s', '%f');",
  1767. #endif /* CDFA_CERTIFICATE */
  1768. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId,
  1769. ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.transactionId,
  1770. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod,
  1771. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId,
  1772. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime,
  1773. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime,
  1774. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
  1775. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].EvBatterySoc,
  1776. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy,
  1777. ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason,
  1778. #ifdef CDFA_CERTIFICATE
  1779. receiptInfo);// Only for CDFA certificate
  1780. #else
  1781. ShmOCPP20Data->CostUpdated.totalCost);
  1782. #endif /* CDFA_CERTIFICATE */
  1783. }
  1784. //DEBUG_INFO("sqlStr= %s\n", sqlStr);
  1785. if(sqlite3_open(DB_FILE, &db))
  1786. {
  1787. result = FAIL;
  1788. DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
  1789. sqlite3_close(db);
  1790. }
  1791. else
  1792. {
  1793. // Delete buffer
  1794. if (sqlite3_exec(db, "delete from charging_record_buffer", 0, 0, &errMsg) != SQLITE_OK)
  1795. {
  1796. result = FAIL;
  1797. DEBUG_INFO( "Delete local charging record buffer error message: %s\n", errMsg);
  1798. }
  1799. else
  1800. {
  1801. DEBUG_INFO( "Delete local charging record buffer successfully\n");
  1802. }
  1803. // Insert charging record
  1804. if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
  1805. {
  1806. result = FAIL;
  1807. DEBUG_INFO( "Insert local charging record error message: %s\n", errMsg);
  1808. }
  1809. else
  1810. {
  1811. DEBUG_INFO( "Insert local charging record successfully\n");
  1812. }
  1813. sprintf(sqlStr, "delete from charging_record where (idx < (select idx from charging_record order by idx desc limit 1)-2000) and (dateTimeStop < '%04d.01.01 00:00:00');", (getCurrentYear()-3));
  1814. if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
  1815. {
  1816. result = FAIL;
  1817. DEBUG_INFO( "delete local charging error message: %s\n", errMsg);
  1818. }
  1819. else
  1820. {
  1821. DEBUG_INFO( "delete local charging record successfully\n");
  1822. }
  1823. sqlite3_close(db);
  1824. }
  1825. #ifdef CDFA_CERTIFICATE
  1826. // Only for CDFA certificate
  1827. sendReceiptMail((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime,
  1828. (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime,
  1829. receiptInfo);
  1830. #endif
  1831. return result;
  1832. }
  1833. int DB_Update_Operactive(sqlite3 *db, uint8_t gun_index, uint8_t isOperactive)
  1834. {
  1835. uint8_t result = false;
  1836. char* errMsg = NULL;
  1837. char sqlStr[1024];
  1838. srand(time(NULL));
  1839. if(sqlite3_open(DB_FILE, &db))
  1840. {
  1841. result = FAIL;
  1842. DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
  1843. sqlite3_close(db);
  1844. }
  1845. else
  1846. {
  1847. sprintf(sqlStr, "insert or replace into config (item, connector, val) values('isOperactive', %d, %d);", gun_index, isOperactive);
  1848. //DEBUG_INFO("sqlStr= %s\n", sqlStr);
  1849. if (sqlite3_exec(db, sqlStr, 0, 0, &errMsg) != SQLITE_OK)
  1850. {
  1851. result = FAIL;
  1852. DEBUG_INFO( "update config error message: %s\n", errMsg);
  1853. }
  1854. else
  1855. {
  1856. DEBUG_INFO("update connector-%d config item isOperactive to %d\n", gun_index, isOperactive);
  1857. }
  1858. sqlite3_close(db);
  1859. }
  1860. return result;
  1861. }
  1862. int DB_Get_Operactive(sqlite3 *db, uint8_t gun_index)
  1863. {
  1864. uint8_t result = true;
  1865. char* errMsg = NULL;
  1866. char sqlStr[1024];
  1867. char **rs;
  1868. int rows, cols;
  1869. sprintf(sqlStr, "select * from config where item='isOperactive' and connector=%d;", gun_index);
  1870. //DEBUG_INFO("sqlStr= %s\n", sqlStr);
  1871. if(sqlite3_open(DB_FILE, &db))
  1872. {
  1873. result = FAIL;
  1874. DEBUG_INFO( "Can't open database: %s\n", sqlite3_errmsg(db));
  1875. sqlite3_close(db);
  1876. }
  1877. else
  1878. {
  1879. sqlite3_get_table(db, sqlStr, &rs, &rows, &cols, &errMsg);
  1880. if(rows>0)
  1881. {
  1882. for(int idxRow=1;idxRow<=rows;idxRow++)
  1883. {
  1884. if(strcmp(rs[(idxRow*cols)+3], "0") == 0)
  1885. {
  1886. result = false;
  1887. }
  1888. DEBUG_INFO("Query connector-%d isOperactive: %s\n", gun_index, rs[(idxRow*cols)+3]);
  1889. }
  1890. }
  1891. else
  1892. {
  1893. DEBUG_INFO("Query connector-%d fail, default value as operactive.\n", gun_index);
  1894. }
  1895. sqlite3_free_table(rs);
  1896. sqlite3_close(db);
  1897. }
  1898. return result;
  1899. }
  1900. //======================================================
  1901. // Peripheral initial
  1902. //======================================================
  1903. int InitWatchDog()
  1904. {
  1905. int fd;
  1906. int timeout = 330;
  1907. system("/usr/bin/fuser -k /dev/watchdog");
  1908. sleep(1);
  1909. system("echo V > /dev/watchdog");
  1910. sleep(1);
  1911. fd=open("/dev/watchdog", O_RDWR);
  1912. if(fd<=0)
  1913. {
  1914. DEBUG_ERROR("System watch dog initial fail.\n");
  1915. }
  1916. ioctl(fd, _IOWR('W', 6, int), &timeout);
  1917. return fd;
  1918. }
  1919. void InitGPIO()
  1920. {
  1921. /*****************0~3, 4 bank, bank x 32+ num*********************/
  1922. /***************************************************************/
  1923. /*************** INPUT PIN ***************************************/
  1924. /***************************************************************/
  1925. /***************************************************************/
  1926. /*************** OUTPUT PIN ************************************/
  1927. /***************************************************************/
  1928. /*MCU request:GPIO3_20 => H:ON; L:OFF*/
  1929. system("echo 116 > /sys/class/gpio/export");
  1930. system("echo \"out\" > /sys/class/gpio/gpio116/direction");
  1931. system("echo 0 > /sys/class/gpio/gpio116/value");
  1932. /*Rfid:GPIO0_19 => Reset_PING H:ON; L:OFF*/
  1933. system("echo 19 > /sys/class/gpio/export");
  1934. system("echo \"out\" > /sys/class/gpio/gpio19/direction");
  1935. system("echo 1 > /sys/class/gpio/gpio19/value");
  1936. /*Speaker:GPIO2_1 => H:ON; L:OFF*/
  1937. system("echo 65 > /sys/class/gpio/export");
  1938. system("echo \"out\" > /sys/class/gpio/gpio65/direction");
  1939. system("echo 0 > /sys/class/gpio/gpio65/value");
  1940. /*Ethernet RST:GPIO1_24 => H:ON; L:OFF*/
  1941. system("echo 56 > /sys/class/gpio/export");
  1942. system("echo \"out\" > /sys/class/gpio/gpio56/direction");
  1943. system("echo 0 > /sys/class/gpio/gpio56/value");
  1944. /*4G RST:GPIO3_18 => H:OFF; L:ON*/
  1945. system("echo 114 > /sys/class/gpio/export");
  1946. system("echo \"out\" > /sys/class/gpio/gpio114/direction");
  1947. system("echo 1 > /sys/class/gpio/gpio114/value");
  1948. /*4G/WIFI RST:GPIO1_27 => H:OFF; L:ON*/
  1949. system("echo 59 > /sys/class/gpio/export");
  1950. system("echo \"out\" > /sys/class/gpio/gpio59/direction");
  1951. system("echo 1 > /sys/class/gpio/gpio59/value");
  1952. /*RFID ICC:GPIO0_20 => H:ON; L:OFF*/
  1953. system("echo 20 > /sys/class/gpio/export");
  1954. system("echo \"in\" > /sys/class/gpio/gpio20/direction");
  1955. /*QCA7000 interrupt:GPIO2_00 => H:ON; L:OFF*/
  1956. system("echo 64 > /sys/class/gpio/export");
  1957. system("echo \"in\" > /sys/class/gpio/gpio64/direction");
  1958. /*QCA7000 Reset:GPIO3_19 => H:ON; L:OFF*/
  1959. system("echo 115 > /sys/class/gpio/export");
  1960. system("echo \"out\" > /sys/class/gpio/gpio115/direction");
  1961. system("echo 0 > /sys/class/gpio/gpio115/value");
  1962. /*RFID RST: GPIO1_30 => H:OFF; L:ON*/
  1963. system("echo 62 > /sys/class/gpio/export");
  1964. system("echo \"out\" > /sys/class/gpio/gpio62/direction");
  1965. system("echo 0 > /sys/class/gpio/gpio62/value");
  1966. /*Wake up button GPIO1_31 => H:OFF; L:ON*/
  1967. system("echo 63 > /sys/class/gpio/export");
  1968. system("echo \"in\" > /sys/class/gpio/gpio64/direction");
  1969. sleep(1);
  1970. system("echo 1 > /sys/class/gpio/gpio56/value");
  1971. system("echo 0 > /sys/class/gpio/gpio114/value");
  1972. system("echo 0 > /sys/class/gpio/gpio59/value");
  1973. system("echo 1 > /sys/class/gpio/gpio115/value");
  1974. sleep(1);
  1975. DEBUG_INFO("Initial GPIO OK\n");
  1976. }
  1977. int LoadSysConfigAndInfo(struct SysConfigData *ptr)
  1978. {
  1979. int fd,wrd;
  1980. unsigned char *buf;
  1981. unsigned int ChkSum,ChkSumOrg;
  1982. if((buf=malloc(MtdBlockSize))==NULL)
  1983. {
  1984. DEBUG_ERROR("malloc buffer NG,rebooting..\n");
  1985. if(ShmStatusCodeData!=NULL)
  1986. {
  1987. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
  1988. }
  1989. sleep(5);
  1990. system("reboot -f");
  1991. sleep(5);
  1992. system("reboot -f");
  1993. }
  1994. memset(buf, 0, MtdBlockSize);
  1995. //================================================
  1996. // Load configuration from mtdblock10
  1997. //================================================
  1998. system("nanddump /dev/mtd10 -f /mnt/EvseConfig.bin");
  1999. fd = open("/mnt/EvseConfig.bin", O_RDWR);
  2000. if (fd < 0)
  2001. {
  2002. free(buf);
  2003. DEBUG_ERROR("open mtdblock10 NG,rebooting..\n");
  2004. if(ShmStatusCodeData!=NULL)
  2005. {
  2006. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
  2007. }
  2008. sleep(5);
  2009. system("reboot -f");
  2010. sleep(5);
  2011. system("reboot -f");
  2012. }
  2013. wrd=read(fd, buf, MtdBlockSize);
  2014. close(fd);
  2015. if(wrd<MtdBlockSize)
  2016. {
  2017. free(buf);
  2018. DEBUG_ERROR("read SysConfigData data NG,rebooting..\n");
  2019. if(ShmStatusCodeData!=NULL)
  2020. {
  2021. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
  2022. }
  2023. sleep(5);
  2024. system("reboot -f");
  2025. sleep(5);
  2026. system("reboot -f");
  2027. }
  2028. ChkSum=0;
  2029. for(wrd=ARRAY_SIZE(ptr->CsuBootLoadFwRev);wrd<MtdBlockSize-4;wrd++)
  2030. {
  2031. ChkSum+=buf[wrd];
  2032. }
  2033. memcpy(&ChkSumOrg,buf+(MtdBlockSize-4),sizeof(ChkSumOrg));
  2034. memcpy(&ptr->ModelName,buf+(ARRAY_SIZE(ptr->CsuBootLoadFwRev)),ARRAY_SIZE(ptr->ModelName));
  2035. memcpy(&ptr->SerialNumber,buf+(ARRAY_SIZE(ptr->CsuBootLoadFwRev)+ARRAY_SIZE(ptr->ModelName)+ARRAY_SIZE(ptr->AcModelName)),ARRAY_SIZE(ptr->SerialNumber));
  2036. //================================================
  2037. // Load configuration from mtdblock11
  2038. //================================================
  2039. if(ChkSum!=ChkSumOrg)
  2040. {
  2041. DEBUG_ERROR("Primary SysConfigData checksum NG, read backup\n");
  2042. system("nanddump /dev/mtd11 -f /mnt/EvseConfig.bin");
  2043. fd = open("/mnt/EvseConfig.bin", O_RDWR);
  2044. if (fd < 0)
  2045. {
  2046. free(buf);
  2047. DEBUG_ERROR("open mtdblock11 (backup) NG,rebooting..\n");
  2048. if(ShmStatusCodeData!=NULL)
  2049. {
  2050. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
  2051. }
  2052. sleep(5);
  2053. system("reboot -f");
  2054. sleep(5);
  2055. system("reboot -f");
  2056. }
  2057. memset(buf, 0, MtdBlockSize);
  2058. wrd=read(fd, buf,MtdBlockSize);
  2059. close(fd);
  2060. if(wrd<MtdBlockSize)
  2061. {
  2062. free(buf);
  2063. DEBUG_ERROR("read backup SysConfigData data NG,rebooting..\n");
  2064. if(ShmStatusCodeData!=NULL)
  2065. {
  2066. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
  2067. }
  2068. sleep(5);
  2069. system("reboot -f");
  2070. sleep(5);
  2071. system("reboot -f");
  2072. }
  2073. ChkSum=0;
  2074. for(wrd=ARRAY_SIZE(ptr->CsuBootLoadFwRev);wrd<MtdBlockSize-4;wrd++)
  2075. {
  2076. ChkSum+=buf[wrd];
  2077. }
  2078. memcpy(&ChkSumOrg,buf+(MtdBlockSize-4),sizeof(ChkSumOrg));
  2079. //================================================
  2080. // Load configuration from mtdblock12 (Factory default)
  2081. //================================================
  2082. if(ChkSum!=ChkSumOrg)
  2083. {
  2084. DEBUG_WARN("backup SysConfigData checksum NG, read Factory default\n");
  2085. system("nanddump /dev/mtd12 -f /mnt/EvseConfig.bin");
  2086. fd = open("/mnt/EvseConfig.bin", O_RDWR);
  2087. if (fd < 0)
  2088. {
  2089. DEBUG_ERROR("open mtdblock12 (Factory default) NG,rebooting..\n");
  2090. free(buf);
  2091. if(ShmStatusCodeData!=NULL)
  2092. {
  2093. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
  2094. }
  2095. sleep(5);
  2096. system("reboot -f");
  2097. sleep(5);
  2098. system("reboot -f");
  2099. }
  2100. memset(buf, 0, MtdBlockSize);
  2101. wrd=read(fd, buf,MtdBlockSize);
  2102. close(fd);
  2103. if(wrd<MtdBlockSize)
  2104. {
  2105. DEBUG_ERROR("read factory default SysConfigData data NG,rebooting..\n");
  2106. free(buf);
  2107. if(ShmStatusCodeData!=NULL)
  2108. {
  2109. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed=1;
  2110. }
  2111. sleep(5);
  2112. system("reboot -f");
  2113. sleep(5);
  2114. system("reboot -f");
  2115. }
  2116. ChkSum=0;
  2117. for(wrd=ARRAY_SIZE(ptr->CsuBootLoadFwRev);wrd<MtdBlockSize-4;wrd++)
  2118. {
  2119. ChkSum+=buf[wrd];
  2120. }
  2121. memcpy(&ChkSumOrg,buf+(MtdBlockSize-4),sizeof(ChkSumOrg));
  2122. memcpy(buf+(ARRAY_SIZE(ptr->CsuBootLoadFwRev)), &ptr->ModelName, ARRAY_SIZE(ptr->ModelName));
  2123. memcpy(buf+(ARRAY_SIZE(ptr->CsuBootLoadFwRev)+ARRAY_SIZE(ptr->ModelName)+ARRAY_SIZE(ptr->AcModelName)), &ptr->SerialNumber, ARRAY_SIZE(ptr->SerialNumber));
  2124. if(ChkSum!=ChkSumOrg)
  2125. {
  2126. DEBUG_WARN("factory default SysConfigData checksum NG, restore factory default\n");
  2127. free(buf);
  2128. system("cd /root;./Module_FactoryConfig -m");
  2129. system("rm -f /Storage/OCPP/OCPPConfiguration");
  2130. system("sync");
  2131. sleep(5);
  2132. system("reboot -f");
  2133. sleep(5);
  2134. system("reboot -f");
  2135. return FAIL;
  2136. }
  2137. }
  2138. }
  2139. //load OK
  2140. memcpy((struct SysConfigData *)ptr,buf,sizeof(struct SysConfigData));
  2141. free(buf);
  2142. system("rm -f /mnt/EvseConfig.bin");
  2143. // SysConfig in flash is empty (0xffffffff)
  2144. if((strlen((char*)ShmSysConfigAndInfo->SysConfig.ModelName) > ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.ModelName)) ||
  2145. (strlen((char*)ShmSysConfigAndInfo->SysConfig.SerialNumber) > ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SerialNumber)) ||
  2146. (strlen((char*)ShmSysConfigAndInfo->SysConfig.SystemId) > ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SystemId)) ||
  2147. (ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient == 0xff))
  2148. {
  2149. if(strlen((char*)ShmSysConfigAndInfo->SysConfig.ModelName) > ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.ModelName))
  2150. {
  2151. memset(ShmSysConfigAndInfo->SysConfig.ModelName, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.ModelName));
  2152. }
  2153. if(strlen((char*)ShmSysConfigAndInfo->SysConfig.SerialNumber) > ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SerialNumber))
  2154. {
  2155. memset(ShmSysConfigAndInfo->SysConfig.SerialNumber, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SerialNumber));
  2156. }
  2157. if(strlen((char*)ShmSysConfigAndInfo->SysConfig.SystemId) > ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SystemId))
  2158. {
  2159. memset(ShmSysConfigAndInfo->SysConfig.SystemId, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SystemId));
  2160. }
  2161. if(ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient == 0xff)
  2162. {
  2163. DEBUG_INFO("Ethernet dhcp config is null.\n");
  2164. }
  2165. if(strlen((char*)ShmSysConfigAndInfo->SysConfig.ModelName) == 0x00)
  2166. {
  2167. DEBUG_INFO("Model name over length.\n");
  2168. }
  2169. if(strlen((char*)ShmSysConfigAndInfo->SysConfig.SerialNumber) == 0x00)
  2170. {
  2171. DEBUG_INFO("Model serial number over length.\n");
  2172. }
  2173. if(strlen((char*)ShmSysConfigAndInfo->SysConfig.SystemId) == 0x00)
  2174. {
  2175. DEBUG_INFO("SystemId over length.\n");
  2176. }
  2177. system("cd /root;./Module_FactoryConfig -m");
  2178. sleep(3);
  2179. system("/usr/bin/run_evse_restart.sh");
  2180. }
  2181. DEBUG_INFO("Load SysConfigData OK\n");
  2182. ShmCharger->isCcsEnable = OFF;
  2183. for(uint8_t idx=0;idx<3;idx++)
  2184. {
  2185. if(ShmSysConfigAndInfo->SysConfig.ModelName[7+idx] == '7')
  2186. ShmCharger->isCcsEnable = ON;
  2187. }
  2188. ShmSysConfigAndInfo->SysConfig.AcPhaseCount = ((ShmSysConfigAndInfo->SysConfig.ModelName[2]=='Y') ||
  2189. (ShmSysConfigAndInfo->SysConfig.ModelName[2]=='D') ||
  2190. (ShmSysConfigAndInfo->SysConfig.ModelName[2]=='W')
  2191. ?3:1);
  2192. RatedCurrentParsing((char*)ShmSysConfigAndInfo->SysConfig.ModelName, &modelnameInfo);
  2193. if(modelnameInfo.GetGunCount == 0)
  2194. {
  2195. modelnameInfo.GetGunCount = 1;
  2196. DEBUG_WARN("Model name parsing error, force assign gun count to 1.\n");
  2197. }
  2198. DEBUG_INFO("Model name parsing gun count: %d\n", modelnameInfo.GetGunCount);
  2199. return PASS;
  2200. }
  2201. int StoreUsrConfigData(struct SysConfigData *UsrData)
  2202. {
  2203. int result = PASS;
  2204. int fd,wrd;
  2205. unsigned int i,Chk;
  2206. unsigned char *ptr, *BufTmp;
  2207. Chk=0;
  2208. ptr=(unsigned char *)UsrData;
  2209. if((BufTmp=malloc(MtdBlockSize))!=NULL)
  2210. {
  2211. memset(BufTmp,0,MtdBlockSize);
  2212. memcpy(BufTmp,ptr,sizeof(struct SysConfigData));
  2213. for(i=0;i<MtdBlockSize-4;i++)
  2214. Chk+=*(BufTmp+i);
  2215. memcpy(BufTmp+MtdBlockSize-4, &Chk, 4);
  2216. // Output configuration to file.
  2217. fd = open("/mnt/EvseConfig.bin", O_RDWR|O_CREAT);
  2218. if (fd < 0)
  2219. {
  2220. DEBUG_ERROR("open /mnt/EvseConfig.bin NG\n");
  2221. free(BufTmp);
  2222. return 0;
  2223. }
  2224. wrd=write(fd, BufTmp, MtdBlockSize);
  2225. close(fd);
  2226. if(wrd<MtdBlockSize)
  2227. {
  2228. DEBUG_ERROR("write /mnt/EvseConfig.bin NG\n");
  2229. free(BufTmp);
  2230. return 0;
  2231. }
  2232. DEBUG_INFO("EvseConfig write to file in /mnt OK.\n");
  2233. DEBUG_INFO("Erase /dev/mtd10.\n");
  2234. runShellCmd("flash_erase /dev/mtd10 0 0");
  2235. DEBUG_INFO("Write /dev/mtd10.\n");
  2236. runShellCmd("nandwrite -p /dev/mtd10 /mnt/EvseConfig.bin");
  2237. DEBUG_INFO("Erase /dev/mtd11.\n");
  2238. runShellCmd("flash_erase /dev/mtd11 0 0");
  2239. DEBUG_INFO("Write /dev/mtd11.\n");
  2240. runShellCmd("nandwrite -p /dev/mtd11 /mnt/EvseConfig.bin");
  2241. system("rm -f /mnt/EvseConfig.bin");
  2242. DEBUG_INFO("EvseConfig write to flash OK\n");
  2243. }
  2244. else
  2245. {
  2246. DEBUG_ERROR("alloc BlockSize NG\r\n");
  2247. result = FAIL;
  2248. }
  2249. if(BufTmp!=NULL)
  2250. free(BufTmp);
  2251. return result;
  2252. }
  2253. void InitEthernet()
  2254. {
  2255. pid_t pid;
  2256. uint8_t cnt_pingDNS_Fail;
  2257. char tmpbuf[256];
  2258. unsigned int natInterface = 0;
  2259. // Detele bridge interface
  2260. system("/sbin/ifconfig uap0 down");
  2261. system("/sbin/ifconfig br0 down");
  2262. system("/usr/sbin/brctl delbr br0");
  2263. //Init Eth0 for internet
  2264. memset(tmpbuf,0,256);
  2265. sprintf(tmpbuf,"/sbin/ifconfig eth0 %s netmask %s up &",
  2266. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress,
  2267. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress);
  2268. DEBUG_INFO("eth0 config as ip: %s, netmask: %s\n", ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress,
  2269. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress);
  2270. system(tmpbuf);
  2271. memset(tmpbuf,0,256);
  2272. sprintf(tmpbuf,"route add default gw %s eth0 &",
  2273. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthGatewayAddress);
  2274. system(tmpbuf);
  2275. system("ifconfig lo up &");
  2276. system("/sbin/ifconfig eth0:1 192.168.201.201 netmask 255.255.255.248 up &");
  2277. //system("/sbin/ethtool -s eth0 speed 10 duplex full autoneg off");
  2278. //Run DHCP client if enabled
  2279. system("killall udhcpc");
  2280. system("rm -rf /etc/resolv.conf");
  2281. system("echo nameserver 8.8.8.8 >> /etc/resolv.conf"); //Google DNS server
  2282. system("echo nameserver 180.76.76.76 >> /etc/resolv.conf"); //Baidu DNS server
  2283. if(ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient==0)
  2284. {
  2285. sprintf(tmpbuf, "/sbin/udhcpc -i eth0 -x hostname:CSU3_%s -s /root/dhcp_script/eth0.script > /dev/null &", ShmSysConfigAndInfo->SysConfig.SystemId);
  2286. system(tmpbuf);
  2287. }
  2288. // Upgrade system id to /etc/hostname
  2289. sprintf(tmpbuf, "echo %s > /etc/hostname", ShmSysConfigAndInfo->SysConfig.SystemId);
  2290. system(tmpbuf);
  2291. // Ethernet MAC address
  2292. getEth0MacAddress();
  2293. //check internet status
  2294. pid = fork();
  2295. if(pid == 0)
  2296. {
  2297. for(;;)
  2298. {
  2299. if(ShmDispenser->gun_info.primaryMcuState.rotatory_switch != ROTARY_SWITCH_E_DISPENSER)
  2300. {
  2301. if(isRouteFail())
  2302. {
  2303. //DEBUG_ERROR("eth0 not in route, restart eth0.\n");
  2304. system("/sbin/ifconfig eth0 down;/sbin/ifconfig eth0 up");
  2305. if((ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient==0))
  2306. {
  2307. system("pgrep -f \"udhcpc -i eth0\" | xargs kill");
  2308. sprintf(tmpbuf, "/sbin/udhcpc -i eth0 -x hostname:CSU3_%s -s /root/dhcp_script/eth0.script > /dev/null &", ShmSysConfigAndInfo->SysConfig.SystemId);
  2309. system(tmpbuf);
  2310. }
  2311. else
  2312. {
  2313. system("pgrep -f \"udhcpc -i eth0\" | xargs kill");
  2314. memset(tmpbuf,0,256);
  2315. sprintf(tmpbuf,"/sbin/ifconfig eth0 %s netmask %s up &",
  2316. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress,
  2317. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress);
  2318. system(tmpbuf);
  2319. memset(tmpbuf,0,256);
  2320. sprintf(tmpbuf,"route add default gw %s eth0 &",
  2321. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthGatewayAddress);
  2322. system(tmpbuf);
  2323. }
  2324. }
  2325. if(isReachableInternet() == PASS)
  2326. {
  2327. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet=OFF;
  2328. cnt_pingDNS_Fail = 0;
  2329. }
  2330. else
  2331. {
  2332. if(cnt_pingDNS_Fail >= 3)
  2333. {
  2334. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet=ON;
  2335. if(!ShmSysConfigAndInfo->SysInfo.OcppConnStatus)
  2336. {
  2337. if((ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthDhcpClient==0))
  2338. {
  2339. system("pgrep -f \"udhcpc -i eth0\" | xargs kill");
  2340. sprintf(tmpbuf, "/sbin/udhcpc -i eth0 -x hostname:CSU3_%s -s /root/dhcp_script/eth0.script > /dev/null &", ShmSysConfigAndInfo->SysConfig.SystemId);
  2341. system(tmpbuf);
  2342. }
  2343. else
  2344. {
  2345. system("pgrep -f \"udhcpc -i eth0\" | xargs kill");
  2346. memset(tmpbuf,0,256);
  2347. sprintf(tmpbuf,"/sbin/ifconfig eth0 %s netmask %s up &",
  2348. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress,
  2349. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress);
  2350. system(tmpbuf);
  2351. memset(tmpbuf,0,256);
  2352. sprintf(tmpbuf,"route add default gw %s eth0 &",
  2353. ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthGatewayAddress);
  2354. system(tmpbuf);
  2355. }
  2356. cnt_pingDNS_Fail = 0;
  2357. }
  2358. }
  2359. else
  2360. {
  2361. cnt_pingDNS_Fail++;
  2362. }
  2363. }
  2364. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet &&
  2365. ((ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode == 0) || ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi) &&
  2366. ((ShmSysConfigAndInfo->SysConfig.TelecomInterface.TelcomEnabled == 0) || ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi))
  2367. {
  2368. ShmSysConfigAndInfo->SysInfo.InternetConn = OFF;
  2369. }
  2370. else
  2371. {
  2372. ShmSysConfigAndInfo->SysInfo.InternetConn = ON;
  2373. }
  2374. //============================================================
  2375. // Priority for internet 0 : First / 1 : Second / 2: Third
  2376. //============================================================
  2377. if(!ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet)
  2378. {
  2379. system("/sbin/ifmetric eth0 0");
  2380. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  2381. {
  2382. system("/sbin/ifmetric mlan0 1");
  2383. }
  2384. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  2385. {
  2386. system("/sbin/ifmetric ppp0 2");
  2387. }
  2388. if(isKernelSupportNAT() == YES)
  2389. {
  2390. if(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode == 2)
  2391. {
  2392. if(natInterface != 1)
  2393. {
  2394. system("/sbin/iptables -t nat -F");
  2395. system("/sbin/iptables -A POSTROUTING -t nat -s 192.168.10.0/24 -o eth0 -j MASQUERADE");
  2396. natInterface = 1;
  2397. }
  2398. }
  2399. else
  2400. {
  2401. system("/sbin/iptables -t nat -F");
  2402. }
  2403. }
  2404. }
  2405. else if(!ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi)
  2406. {
  2407. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  2408. {
  2409. system("/sbin/ifmetric eth0 1");
  2410. system("/sbin/ifmetric mlan0 0");
  2411. }
  2412. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  2413. {
  2414. system("/sbin/ifmetric ppp0 2");
  2415. }
  2416. }
  2417. else if(!ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi)
  2418. {
  2419. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  2420. {
  2421. system("/sbin/ifmetric mlan0 2");
  2422. }
  2423. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  2424. {
  2425. system("/sbin/ifmetric eth0 1");
  2426. system("/sbin/ifmetric ppp0 0");
  2427. }
  2428. if(isKernelSupportNAT() == YES)
  2429. {
  2430. if(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode == 2)
  2431. {
  2432. if(natInterface != 2)
  2433. {
  2434. system("/sbin/iptables -t nat -F");
  2435. system("/sbin/iptables -A POSTROUTING -t nat -s 192.168.10.0/24 -o ppp0 -j MASQUERADE");
  2436. natInterface = 2;
  2437. }
  2438. }
  2439. else
  2440. {
  2441. system("/sbin/iptables -t nat -F");
  2442. }
  2443. }
  2444. }
  2445. else
  2446. {
  2447. if(isKernelSupportNAT() == YES)
  2448. {
  2449. if(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode == 2)
  2450. {
  2451. system("/sbin/iptables -t nat -F");
  2452. natInterface = 0;
  2453. }
  2454. }
  2455. }
  2456. if(!ShmSysConfigAndInfo->SysInfo.OcppConnStatus &&
  2457. (((ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode == 1) && (ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi == ON)) || (((ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode == 2) && (ShmStatusCodeData->InfoCode.InfoEvents.bits.ApDisconnectViaWiFi == ON)))))
  2458. {
  2459. if(getDiffSecNow(startTime[0][TMR_IDX_RESET_WIFI]) > TIMEOUT_SPEC_RESET_WIFI_MODULE)
  2460. {
  2461. DEBUG_WARN("WIFI/4G module reset.\n");
  2462. gpio_set_value(GPIO_OUT_RST_4G_WIFI, ON);
  2463. sleep(1);
  2464. gpio_set_value(GPIO_OUT_RST_4G_WIFI, OFF);
  2465. }
  2466. }
  2467. else
  2468. {
  2469. refreshStartTimer(&startTime[0][TMR_IDX_RESET_WIFI]);
  2470. }
  2471. }
  2472. else
  2473. {
  2474. if(ShmDispenser->gun_info.mcuFlag.isReadFwVerPass ||
  2475. ShmDispenser->gun_info.mcuFlag.isSetModelNamePass ||
  2476. ShmDispenser->gun_info.mcuFlag.isSetSerialNumberPass)
  2477. {
  2478. system("pgrep -f \"udhcpc -i eth0\" | xargs kill");
  2479. system("/sbin/ifconfig eth0:1 192.168.201.202 netmask 255.255.255.248 up &");
  2480. }
  2481. }
  2482. // Bridge ethernet to uap0 to get dynamic ip address
  2483. if(ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharging &&
  2484. (ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode == 2) &&
  2485. (isUap0up() == PASS) &&
  2486. (access("/sys/class/net/br0/address", F_OK) == -1))
  2487. {
  2488. sleep(10);
  2489. system("/usr/sbin/brctl addbr br0");
  2490. system("/usr/sbin/brctl addif br0 eth0");
  2491. system("/usr/sbin/brctl addif br0 uap0");
  2492. system("/sbin/ifconfig br0 192.168.10.200 up");
  2493. system("/bin/sed -i '/interface/d' /etc/udhcpd.conf");
  2494. system("/bin/echo 'interface br0' >> /etc/udhcpd.conf");
  2495. system("kill udhcpd");
  2496. system("/usr/sbin/udhcpd /etc/udhcpd.conf");
  2497. DEBUG_INFO("Bridge uap0 & eth0 for local power sharing by ethernet.\n");
  2498. }
  2499. sleep(5);
  2500. }
  2501. }
  2502. DEBUG_INFO("Initial Ethernet OK\n");
  2503. }
  2504. int SpawnTask()
  2505. {
  2506. system ("pkill Module_");
  2507. system ("pkill OcppBackend");
  2508. /*
  2509. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  2510. {
  2511. system("/root/Module_4g &");
  2512. }
  2513. if(ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W' || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  2514. {
  2515. system("/root/Module_Wifi &");
  2516. }*/
  2517. system("/root/Module_EventLogging &");
  2518. ocpp_process_start();
  2519. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0)
  2520. DEBUG_INFO("OCPP URL is empty, need to create a configuration table !!!\n");
  2521. //system ("/root/Module_AlarmDetect &");
  2522. system ("/root/Module_InternalComm &");
  2523. //system ("/root/Module_Speaker &");
  2524. system ("/root/Module_ProduceUtils &");
  2525. //system ("/root/Module_LcmControl &");
  2526. system ("/root/Module_Cabinet &");
  2527. system ("/root/Module_Dispenser &");
  2528. return PASS;
  2529. }
  2530. int InitQca7000()
  2531. {
  2532. int result = PASS;
  2533. system("/sbin/rmmod qcaspi");
  2534. if(isKernelSupportNAT() == YES)
  2535. system("/sbin/insmod /lib/qcaspi_nat.ko");
  2536. else
  2537. system("/sbin/insmod /lib/qcaspi.ko");
  2538. sleep(2);
  2539. system("/sbin/ifconfig eth1 192.168.0.11 netmask 255.255.255.0 up");
  2540. sleep(1);
  2541. return result;
  2542. }
  2543. int Initialization(uint8_t gun_index)
  2544. {
  2545. int result = PASS;
  2546. InitGPIO();
  2547. InitEthernet();
  2548. if(InitQca7000() != PASS)
  2549. {
  2550. DEBUG_ERROR("QCA7000 initial fail.\n");
  2551. result = FAIL;
  2552. }
  2553. if(DB_Open(localDb) != PASS)
  2554. {
  2555. DEBUG_ERROR("Local database initial fail.\n");
  2556. result = FAIL;
  2557. }
  2558. if((rfidFd = InitRfidPort()) == FAIL)
  2559. {
  2560. DEBUG_ERROR("RFID port initial fail.\n");
  2561. result = FAIL;
  2562. }
  2563. if((wtdFd = InitWatchDog()) == FAIL)
  2564. {
  2565. DEBUG_ERROR("Watchdog initial fail.\n");
  2566. result = FAIL;
  2567. }
  2568. if(result == PASS)
  2569. DEBUG_INFO("Initialization OK.\n");
  2570. else
  2571. DEBUG_INFO("Initialization Fail.\n");
  2572. ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
  2573. return result;
  2574. }
  2575. //===============================================
  2576. // Get firmware version
  2577. //===============================================
  2578. void get_firmware_version(unsigned char gun_index)
  2579. {
  2580. FILE *fp;
  2581. char cmd[512];
  2582. char buf[512];
  2583. if(gun_index == 0)
  2584. {
  2585. // Get CSU hardware version
  2586. sprintf((char*)ShmSysConfigAndInfo->SysInfo.CsuHwRev, "REV.XXXXXXX");
  2587. // Get CSU boot loader version
  2588. memcpy(ShmSysConfigAndInfo->SysInfo.CsuBootLoadFwRev, ShmSysConfigAndInfo->SysConfig.CsuBootLoadFwRev, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.CsuBootLoadFwRev));
  2589. // Get CSU kernel version
  2590. sprintf(cmd, "/bin/uname -r");
  2591. fp = popen(cmd, "r");
  2592. if(fp == NULL)
  2593. sprintf((char*)ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev, "Unknown version");
  2594. else
  2595. {
  2596. while(fgets(buf, sizeof(buf), fp) != NULL)
  2597. {
  2598. memcpy(ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev, buf, strlen(buf)-1);
  2599. }
  2600. }
  2601. // Get MCU firmware version
  2602. strcpy((char*)ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev, ShmCharger->gun_info[gun_index].ver.Version_FW);
  2603. // Get CSU root file system version
  2604. sprintf((char*)ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev, "D0.01.00.0000.00");
  2605. // Get AC connector type from model name
  2606. for(uint8_t idx=0;idx<3;idx++)
  2607. {
  2608. switch(ShmSysConfigAndInfo->SysConfig.ModelName[7+idx])
  2609. {
  2610. case '1':
  2611. // J1772 Plug
  2612. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '4';
  2613. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '4';
  2614. break;
  2615. case '2':
  2616. // J1772 Socket
  2617. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '1';
  2618. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '1';
  2619. break;
  2620. case '3':
  2621. // CE Plug
  2622. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '5';
  2623. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '5';
  2624. break;
  2625. case '4':
  2626. // CE Socket
  2627. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '2';
  2628. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '2';
  2629. break;
  2630. case '5':
  2631. // GB Plug
  2632. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '6';
  2633. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '6';
  2634. break;
  2635. case '6':
  2636. // GB Socket
  2637. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '3';
  2638. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '3';
  2639. break;
  2640. }
  2641. }
  2642. // Get network option from model name
  2643. switch(ShmSysConfigAndInfo->SysConfig.ModelName[10])
  2644. {
  2645. case 'B':
  2646. case 'U':
  2647. //Blue tooth
  2648. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '3';
  2649. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[9] = '3';
  2650. break;
  2651. case 'W':
  2652. // WIFI
  2653. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '1';
  2654. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[9] = '1';
  2655. break;
  2656. case 'T':
  2657. // 3G/4G
  2658. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '2';
  2659. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[9] = '2';
  2660. break;
  2661. case 'D':
  2662. // WIFI + 4G
  2663. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '5';
  2664. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[9] = '5';
  2665. break;
  2666. default:
  2667. // LAN
  2668. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '0';
  2669. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[9] = '0';
  2670. break;
  2671. }
  2672. // Get rating power from model name
  2673. memcpy(&ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[10], &ShmSysConfigAndInfo->SysConfig.ModelName[4], 0x03);
  2674. memcpy(&ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[10], &ShmSysConfigAndInfo->SysConfig.ModelName[4], 0x03);
  2675. // Get vender code from model name
  2676. memcpy(&ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[14], &ShmSysConfigAndInfo->SysConfig.ModelName[12], 0x02);
  2677. memcpy(&ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[14], &ShmSysConfigAndInfo->SysConfig.ModelName[12], 0x02);
  2678. DEBUG_INFO("========================================\n");
  2679. DEBUG_INFO("------------- Cabinet info -------------\n");
  2680. DEBUG_INFO("Model: %s\n", ShmSysConfigAndInfo->SysConfig.ModelName);
  2681. DEBUG_INFO("CSU hardware version: %s\n", ShmSysConfigAndInfo->SysInfo.CsuHwRev);
  2682. DEBUG_INFO("CSU boot loader version: %s\n", ShmSysConfigAndInfo->SysInfo.CsuBootLoadFwRev);
  2683. DEBUG_INFO("CSU kernel version: %s\n", ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev);
  2684. DEBUG_INFO("CSU root file system version: %s\n", ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev);
  2685. DEBUG_INFO("========================================\n");
  2686. }
  2687. //===========================================
  2688. // Put info to dispenser share memory
  2689. //===========================================
  2690. // Get CSU boot loader version
  2691. memcpy(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuBootLoadFwRev, ShmSysConfigAndInfo->SysConfig.CsuBootLoadFwRev, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.CsuBootLoadFwRev));
  2692. // Get CSU kernel version
  2693. sprintf(cmd, "/bin/uname -r");
  2694. fp = popen(cmd, "r");
  2695. if(fp == NULL)
  2696. sprintf((char*)ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuKernelFwRev, "Unknown version");
  2697. else
  2698. {
  2699. while(fgets(buf, sizeof(buf), fp) != NULL)
  2700. {
  2701. memcpy(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuKernelFwRev, buf, strlen(buf)-1);
  2702. }
  2703. }
  2704. // Get MCU firmware version
  2705. strcpy((char*)ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev, ShmCharger->gun_info[gun_index].ver.Version_FW);
  2706. // Get CSU root file system version
  2707. sprintf((char*)ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev, "D0.01.00.0000.00");
  2708. // Get AC connector type from model name
  2709. for(uint8_t idx=0;idx<3;idx++)
  2710. {
  2711. switch(ShmDispenser->ConfigData.ModelName[7+idx])
  2712. {
  2713. case '1':
  2714. // J1772 Plug
  2715. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[6] = '4';
  2716. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[6] = '4';
  2717. break;
  2718. case '2':
  2719. // J1772 Socket
  2720. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[6] = '1';
  2721. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[6] = '1';
  2722. break;
  2723. case '3':
  2724. // CE Plug
  2725. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[6] = '5';
  2726. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[6] = '5';
  2727. break;
  2728. case '4':
  2729. // CE Socket
  2730. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[6] = '2';
  2731. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[6] = '2';
  2732. break;
  2733. case '5':
  2734. // GB Plug
  2735. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[6] = '6';
  2736. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[6] = '6';
  2737. break;
  2738. case '6':
  2739. // GB Socket
  2740. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[6] = '3';
  2741. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[6] = '3';
  2742. break;
  2743. }
  2744. }
  2745. // Get network option from model name
  2746. switch(ShmDispenser->ConfigData.ModelName[10])
  2747. {
  2748. case 'B':
  2749. case 'U':
  2750. //Blue tooth
  2751. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[9] = '3';
  2752. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[9] = '3';
  2753. break;
  2754. case 'W':
  2755. // WIFI
  2756. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[9] = '1';
  2757. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[9] = '1';
  2758. break;
  2759. case 'T':
  2760. // 3G/4G
  2761. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[9] = '2';
  2762. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[9] = '2';
  2763. break;
  2764. case 'D':
  2765. // WIFI + 4G
  2766. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[9] = '5';
  2767. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[9] = '5';
  2768. break;
  2769. default:
  2770. // LAN
  2771. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[9] = '0';
  2772. ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[9] = '0';
  2773. break;
  2774. }
  2775. // Get rating power from model name
  2776. memcpy(&ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[10], &ShmDispenser->ConfigData.ModelName[4], 0x03);
  2777. memcpy(&ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[10], &ShmDispenser->ConfigData.ModelName[4], 0x03);
  2778. // Get vender code from model name
  2779. memcpy(&ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev[14], &ShmDispenser->ConfigData.ModelName[12], 0x02);
  2780. memcpy(&ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev[14], &ShmDispenser->ConfigData.ModelName[12], 0x02);
  2781. DEBUG_INFO("========================================\n");
  2782. DEBUG_INFO("----------- Dispenser-%01d info -----------\n", (gun_index+1));
  2783. DEBUG_INFO("CSU boot loader version: %s\n", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuBootLoadFwRev);
  2784. DEBUG_INFO("CSU kernel version: %s\n", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuKernelFwRev);
  2785. DEBUG_INFO("CSU root file system version: %s\n", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuRootFsFwRev);
  2786. DEBUG_INFO("CSU MCU firmware version: %s\n", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[gun_index].CsuPrimFwRev);
  2787. DEBUG_INFO("========================================\n");
  2788. }
  2789. //===============================================
  2790. // Upgrade firmware
  2791. //===============================================
  2792. int upgrade_check()
  2793. {
  2794. int result = PASS;
  2795. int fd;
  2796. DIR *dir;
  2797. struct dirent *file;
  2798. char cmd[512];
  2799. long int MaxLen=48*1024*1024, ImageLen=0, wrd;
  2800. if ((dir = opendir ("/mnt")) != NULL)
  2801. {
  2802. refreshStartTimer(&startTime[0][TMR_IDX_UPGRADE]);
  2803. /* print all the files and directories within directory */
  2804. while ((file = readdir (dir)) != NULL)
  2805. {
  2806. if((strlen(file->d_name)>2))
  2807. {
  2808. // Wait for MCU upgrade finish.
  2809. while(ShmCharger->gun_info[0].mcuFlag.isMcuUpgradeReq || (modelnameInfo.GetGunCount>1?ShmCharger->gun_info[1].mcuFlag.isMcuUpgradeReq:FALSE))sleep(1);
  2810. // Wait for LCM upgrade finish.
  2811. while(ShmCharger->isUpgradeLcmReq)sleep(1);
  2812. memset(&ShmCharger->fwUpgradeInfo, 0xFF, sizeof(Fw_Upgrade_Info));
  2813. DEBUG_INFO("New firmware file: %s\n", file->d_name);
  2814. sprintf(ShmCharger->fwUpgradeInfo.location, "/mnt/%s", file->d_name);
  2815. if((fd=open(ShmCharger->fwUpgradeInfo.location, O_RDONLY)) >= 0)
  2816. {
  2817. unsigned char *ptr = malloc(MaxLen); //-48 is take out the header
  2818. memset(ptr, 0xFF, MaxLen); //-48 is take out the header
  2819. ImageLen = read(fd, ptr, MaxLen);
  2820. close(fd);
  2821. ShmCharger->fwUpgradeInfo.fwType = ((ptr[0x13]<<0) | (ptr[0x12]<<8) | (ptr[0x11]<<16) | (ptr[0x10]<<24));
  2822. substr(ShmCharger->fwUpgradeInfo.modelName, (char *)ptr, 0, 0x10);
  2823. DEBUG_INFO("New firmware type: %X\n", ShmCharger->fwUpgradeInfo.fwType);
  2824. DEBUG_INFO("New firmware model name: %s, %s\n", ShmCharger->fwUpgradeInfo.modelName, ShmSysConfigAndInfo->SysConfig.ModelName);
  2825. if((ShmCharger->fwUpgradeInfo.modelName[0] == ShmSysConfigAndInfo->SysConfig.ModelName[0]) &&
  2826. (ShmCharger->fwUpgradeInfo.modelName[1] == ShmSysConfigAndInfo->SysConfig.ModelName[1]) &&
  2827. (ShmCharger->fwUpgradeInfo.modelName[7] == ShmSysConfigAndInfo->SysConfig.ModelName[7]) &&
  2828. (ShmCharger->fwUpgradeInfo.modelName[8] == ShmSysConfigAndInfo->SysConfig.ModelName[8]) &&
  2829. (ShmCharger->fwUpgradeInfo.modelName[9] == ShmSysConfigAndInfo->SysConfig.ModelName[9]) &&
  2830. (ShmCharger->fwUpgradeInfo.modelName[11] == ShmSysConfigAndInfo->SysConfig.ModelName[11]) &&
  2831. (ShmCharger->fwUpgradeInfo.modelName[12] == ShmSysConfigAndInfo->SysConfig.ModelName[12]) &&
  2832. (ShmCharger->fwUpgradeInfo.modelName[13] == ShmSysConfigAndInfo->SysConfig.ModelName[13]) &&
  2833. (ShmCharger->fwUpgradeInfo.fwType>0))
  2834. {
  2835. switch(ShmCharger->fwUpgradeInfo.fwType)
  2836. {
  2837. case CSU_MLO:
  2838. case CSU_BOOTLOADER:
  2839. case CSU_KERNEL_CONFIGURATION:
  2840. case CSU_KERNEL_IMAGE:
  2841. case CSU_ROOT_FILE_SYSTEM:
  2842. case CSU_USER_CONFIGURATION:
  2843. case CSU_PRIMARY_CONTROLLER:
  2844. case AC_WALLMOUNT_CONTROLLER:
  2845. // Put image file
  2846. for(uint8_t gun_index=0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  2847. {
  2848. char cmd[768];
  2849. if(gun_index>0)
  2850. {
  2851. sprintf(cmd, "ftpput -u root -p y42j/4cj84 192.168.201.%d /mnt/%s %s", (201+gun_index), file->d_name, file->d_name);
  2852. if(system(cmd) != 0)
  2853. {
  2854. DEBUG_ERROR("FTP put %s to dispenser-%d fail\n", file->d_name, gun_index);
  2855. result = FAIL;
  2856. }
  2857. else
  2858. {
  2859. DEBUG_INFO("FTP put %s to dispenser-%d finish\n", file->d_name, gun_index);
  2860. }
  2861. }
  2862. }
  2863. break;
  2864. case LCM:
  2865. fd = open("/mnt/lcm.zip", O_RDWR | O_CREAT | O_EXCL);
  2866. if (fd < 0)
  2867. {
  2868. DEBUG_ERROR("Can not create lcm.zip file.\n");
  2869. result = FAIL;
  2870. }
  2871. else
  2872. {
  2873. // Write image to flash
  2874. DEBUG_INFO("Writing data to lcm.zip file...\n");
  2875. wrd=write(fd, ptr+48, ImageLen-48);
  2876. close(fd);
  2877. DEBUG_INFO(">> lcm.zip Written length: 0x%x\n", wrd);
  2878. if(wrd != (ImageLen-48))
  2879. {
  2880. result = FAIL;
  2881. }
  2882. else
  2883. {
  2884. runShellCmd("mkdir -p /mnt/lcd");
  2885. runShellCmd("unzip /mnt/lcm.zip -d /mnt/lcd");
  2886. sprintf(cmd, "yes|rm %s", ShmCharger->fwUpgradeInfo.location);
  2887. system(cmd);
  2888. system("rm -f /mnt/lcm.zip");
  2889. result = PASS;
  2890. }
  2891. }
  2892. ShmCharger->isUpgradeLcmReq = ON;
  2893. sleep(10);
  2894. break;
  2895. default:
  2896. result = FAIL;
  2897. DEBUG_WARN("Image file is unknown type.\n");
  2898. sprintf(cmd, "yes|rm %s", ShmCharger->fwUpgradeInfo.location);
  2899. system(cmd);
  2900. break;
  2901. }
  2902. }
  2903. else
  2904. {
  2905. result = FAIL;
  2906. DEBUG_ERROR("Model name and Firmware type error.\n");
  2907. sprintf(cmd, "yes|rm %s", ShmCharger->fwUpgradeInfo.location);
  2908. system(cmd);
  2909. }
  2910. free(ptr);
  2911. }
  2912. else
  2913. {
  2914. result = FAIL;
  2915. DEBUG_ERROR("New firmware open error.\n");
  2916. }
  2917. }
  2918. else
  2919. {
  2920. if(strlen(file->d_name) >= 3)
  2921. {
  2922. result = FAIL;
  2923. DEBUG_ERROR("File name error.\n");
  2924. }
  2925. else
  2926. {
  2927. DEBUG_ERROR("Searching file.\n");
  2928. }
  2929. }
  2930. }
  2931. closedir (dir);
  2932. // Wait dispenser upgrade result
  2933. if(result != FAIL)
  2934. {
  2935. uint8_t isCompleted = ON;
  2936. for(uint8_t gun_index=0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  2937. ShmCharger->gun_info[gun_index].isUpgradeReq = ON;
  2938. do
  2939. {
  2940. isCompleted = ON;
  2941. for(uint8_t gun_index=0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  2942. {
  2943. isCompleted &= ShmCharger->gun_info[gun_index].isUpgradeEnd;
  2944. }
  2945. sleep(1);
  2946. }while((getDiffSecNow(startTime[0][TMR_IDX_UPGRADE]) < TIMEOUT_SPEC_UPGRADE) && !isCompleted);
  2947. for(uint8_t gun_index=0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  2948. {
  2949. result &= ShmCharger->gun_info[gun_index].isUpgradePASS;
  2950. }
  2951. result &= (getDiffSecNow(startTime[0][TMR_IDX_UPGRADE]) <= TIMEOUT_SPEC_UPGRADE);
  2952. if(getDiffSecNow(startTime[0][TMR_IDX_UPGRADE]) > TIMEOUT_SPEC_UPGRADE)DEBUG_INFO("Upgrade process timeout.\n");
  2953. }
  2954. }
  2955. else
  2956. {
  2957. result = FAIL;
  2958. DEBUG_ERROR("/mnt does not valid.\n");
  2959. }
  2960. return result;
  2961. }
  2962. //===============================================
  2963. // Check RFID is match with start user
  2964. //===============================================
  2965. int isMatchStartUser(unsigned char gun_index)
  2966. {
  2967. uint8_t tmpUser[32];
  2968. if(ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian)
  2969. {
  2970. // Big endian
  2971. switch(rfid.snType)
  2972. {
  2973. case RFID_SN_TYPE_6BYTE:
  2974. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5]);
  2975. break;
  2976. case RFID_SN_TYPE_7BYTE:
  2977. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6]);
  2978. break;
  2979. case RFID_SN_TYPE_10BYTE:
  2980. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6], rfid.currentCard[7], rfid.currentCard[8], rfid.currentCard[9]);
  2981. break;
  2982. case RFID_SN_TYPE_4BYTE:
  2983. default:
  2984. sprintf((char*)tmpUser, "%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3]);
  2985. break;
  2986. }
  2987. }
  2988. else
  2989. {
  2990. // Little endian
  2991. switch(rfid.snType)
  2992. {
  2993. case RFID_SN_TYPE_6BYTE:
  2994. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  2995. break;
  2996. case RFID_SN_TYPE_7BYTE:
  2997. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  2998. break;
  2999. case RFID_SN_TYPE_10BYTE:
  3000. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[9], rfid.currentCard[8], rfid.currentCard[7], rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  3001. break;
  3002. case RFID_SN_TYPE_4BYTE:
  3003. default:
  3004. sprintf((char*)tmpUser, "%02X%02X%02X%02X", rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  3005. break;
  3006. }
  3007. }
  3008. DEBUG_INFO("==== isMatchStartUser ==== \n");
  3009. DEBUG_INFO("tmpUser : %s \n", tmpUser);
  3010. DEBUG_INFO("StartUserId : %s \n", ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId);
  3011. DEBUG_INFO("========================== \n");
  3012. return ((strcmp((char*)tmpUser, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId)==0)?YES:NO);
  3013. }
  3014. int isMatchPresentUser()
  3015. {
  3016. uint8_t tmpUser[32];
  3017. if(ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian)
  3018. {
  3019. // Big endian
  3020. switch(rfid.snType)
  3021. {
  3022. case RFID_SN_TYPE_6BYTE:
  3023. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5]);
  3024. break;
  3025. case RFID_SN_TYPE_7BYTE:
  3026. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6]);
  3027. break;
  3028. case RFID_SN_TYPE_10BYTE:
  3029. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6], rfid.currentCard[7], rfid.currentCard[8], rfid.currentCard[9]);
  3030. break;
  3031. case RFID_SN_TYPE_4BYTE:
  3032. default:
  3033. sprintf((char*)tmpUser, "%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3]);
  3034. break;
  3035. }
  3036. }
  3037. else
  3038. {
  3039. // Little endian
  3040. switch(rfid.snType)
  3041. {
  3042. case RFID_SN_TYPE_6BYTE:
  3043. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  3044. break;
  3045. case RFID_SN_TYPE_7BYTE:
  3046. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  3047. break;
  3048. case RFID_SN_TYPE_10BYTE:
  3049. sprintf((char*)tmpUser, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[9], rfid.currentCard[8], rfid.currentCard[7], rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  3050. break;
  3051. case RFID_SN_TYPE_4BYTE:
  3052. default:
  3053. sprintf((char*)tmpUser, "%02X%02X%02X%02X", rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  3054. break;
  3055. }
  3056. }
  3057. DEBUG_INFO("==== isMatchPresentUser ==== \n");
  3058. DEBUG_INFO("tmpUser : %s \n", tmpUser);
  3059. DEBUG_INFO("UserId : %s \n", ShmSysConfigAndInfo->SysConfig.UserId);
  3060. DEBUG_INFO("============================ \n");
  3061. return ((strcmp((char*)tmpUser, (char*)ShmSysConfigAndInfo->SysConfig.UserId)==0)?YES:NO);
  3062. }
  3063. //===============================================
  3064. // Read RFID Serial Number
  3065. //===============================================
  3066. int GetCardSerialNumber()
  3067. {
  3068. int isSuccess = FAIL;
  3069. int module_type = MODULE_EWT;
  3070. if(getRequestCardSN(rfidFd,module_type,&rfid))
  3071. {
  3072. if(rfid.cardType == ISO14443A)
  3073. {
  3074. if(rfid.snType == RFID_SN_TYPE_4BYTE)
  3075. {
  3076. isSuccess = PASS;
  3077. }
  3078. else if (rfid.snType == RFID_SN_TYPE_7BYTE)
  3079. {
  3080. isSuccess = PASS;
  3081. }
  3082. sethaltCard(rfidFd,module_type);
  3083. }
  3084. else if(rfid.cardType == IS014443B)
  3085. {
  3086. isSuccess = PASS;
  3087. }
  3088. else if(rfid.cardType == FELICA)
  3089. {
  3090. isSuccess = PASS;
  3091. }
  3092. else
  3093. {}
  3094. }
  3095. else
  3096. {}
  3097. return isSuccess;
  3098. }
  3099. //===============================================
  3100. // Set led motion
  3101. //===============================================
  3102. void setLedMotion(unsigned char gun_index,unsigned char led_mode)
  3103. {
  3104. switch(led_mode)
  3105. {
  3106. case LED_ACTION_INIT:
  3107. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_INIT;
  3108. break;
  3109. case LED_ACTION_IDLE:
  3110. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_IDLE;
  3111. break;
  3112. case LED_ACTION_AUTHED:
  3113. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_AUTHED;
  3114. break;
  3115. case LED_ACTION_CONNECTED:
  3116. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_CONNECTED;
  3117. break;
  3118. case LED_ACTION_CHARGING:
  3119. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_CHARGING;
  3120. break;
  3121. case LED_ACTION_STOP:
  3122. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_STOP;
  3123. break;
  3124. case LED_ACTION_ALARM:
  3125. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_ALARM;
  3126. break;
  3127. case LED_ACTION_MAINTAIN:
  3128. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_MAINTAIN;
  3129. break;
  3130. case LED_ACTION_RFID_PASS:
  3131. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_RFID_PASS;
  3132. break;
  3133. case LED_ACTION_RFID_FAIL:
  3134. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_RFID_FAIL;
  3135. break;
  3136. case LED_ACTION_BLE_CONNECT:
  3137. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_BLE_CONNECT;
  3138. break;
  3139. case LED_ACTION_BLE_DISABLE:
  3140. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_BLE_DISABLE;
  3141. break;
  3142. case LED_ACTION_DEBUG:
  3143. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_DEBUG;
  3144. break;
  3145. case LED_ACTION_ALL_OFF:
  3146. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_ALL_OFF;
  3147. break;
  3148. case LED_RELAY_ON:
  3149. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_RELAY_ON;
  3150. break;
  3151. case LED_RELAY_OFF:
  3152. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_RELAY_OFF;
  3153. break;
  3154. case LED_ACTION_HANDSHAKE_FAIL:
  3155. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_HANDSHAKE_FAIL;
  3156. break;
  3157. case LED_ACTION_INTERNET_DISCONNECT:
  3158. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_INTERNET_DISCONNECT;
  3159. break;
  3160. case LED_ACTION_RESTORE_SETTING:
  3161. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_RESTORE_SETTING;
  3162. break;
  3163. case LED_ACTION_IDLE_BACKEND_CONNECTED:
  3164. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_IDLE_BACKEND_CONNECTED;
  3165. break;
  3166. case LED_ACTION_IDLE_BACKEND_CONNECTED_SLEEP:
  3167. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_IDLE_BACKEND_CONNECTED_SLEEP;
  3168. break;
  3169. case LED_ACTION_IDLE_BACKEND_DISCONNECTED:
  3170. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_IDLE_BACKEND_DISCONNECTED;
  3171. break;
  3172. case LED_ACTION_IDLE_BACKEND_DISCONNECTED_SLEEP:
  3173. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_IDLE_BACKEND_DISCONNECTED_SLEEP;
  3174. break;
  3175. case LED_ACTION_RESERVATION_MODE:
  3176. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_RESERVATION_MODE;
  3177. break;
  3178. }
  3179. }
  3180. //===============================================
  3181. // Request on/off set
  3182. //===============================================
  3183. void setRequest(unsigned char gun_index,unsigned char isOn)
  3184. {
  3185. if(isOn == ON)
  3186. {
  3187. if(ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest == OFF)
  3188. {
  3189. ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest = ON;
  3190. DEBUG_INFO("Gun-%d permission request: ON \n",gun_index);
  3191. }
  3192. }
  3193. else
  3194. {
  3195. if(ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest == ON)
  3196. {
  3197. ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest = OFF;
  3198. DEBUG_INFO("Gun-%d permission request: OFF \n",gun_index);
  3199. }
  3200. }
  3201. }
  3202. //===============================================
  3203. // Request on/off get
  3204. //===============================================
  3205. int getRequest(unsigned char gun_index)
  3206. {
  3207. return ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest;
  3208. }
  3209. //===============================================
  3210. // Relay on/off set
  3211. //===============================================
  3212. void setRelay(unsigned char gun_index,unsigned char isOn)
  3213. {
  3214. if(isOn == ON)
  3215. {
  3216. if(ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn == OFF)
  3217. {
  3218. switch(ShmCharger->gun_info[gun_index].chargingMode)
  3219. {
  3220. case CHARGING_MODE_BS:
  3221. case CHARGING_MODE_HLC:
  3222. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = ON;
  3223. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][0] = 0x01;
  3224. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][1] = 0x01;
  3225. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][2] = 0x01;
  3226. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  3227. DEBUG_INFO("Gun-%d Output relay status: ON. [CHARGING_MODE_BS] \n",gun_index);
  3228. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  3229. DEBUG_INFO("Gun-%d Output relay status: ON. [CHARGING_MODE_HLC] \n",gun_index);
  3230. break;
  3231. case CHARGING_MODE_SOCKETE:
  3232. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = ON;
  3233. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][3] = 0x01;
  3234. DEBUG_INFO("Gun-%d Output relay status: ON. [CHARGING_MODE_SOCKETE] \n",gun_index);
  3235. break;
  3236. default:
  3237. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = ON;
  3238. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][0] = 0x01;
  3239. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][1] = 0x01;
  3240. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][2] = 0x01;
  3241. DEBUG_INFO("Gun-%d Output relay status: ON. [DEFFAULT] \n",gun_index);
  3242. break;
  3243. }
  3244. }
  3245. }
  3246. else
  3247. {
  3248. if(ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn == ON)
  3249. {
  3250. switch(ShmCharger->gun_info[gun_index].chargingMode)
  3251. {
  3252. case CHARGING_MODE_BS:
  3253. case CHARGING_MODE_HLC:
  3254. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = OFF;
  3255. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][0] = 0;
  3256. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][1] = 0;
  3257. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][2] = 0;
  3258. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  3259. DEBUG_INFO("Gun-%d Output relay status: OFF. [CHARGING_MODE_BS] \n",gun_index);
  3260. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  3261. DEBUG_INFO("Gun-%d Output relay status: OFF. [CHARGING_MODE_HLC] \n",gun_index);
  3262. break;
  3263. case CHARGING_MODE_SOCKETE:
  3264. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = OFF;
  3265. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][3] = 0;
  3266. DEBUG_INFO("Gun-%d Output relay status: OFF. [CHARGING_MODE_SOCKETE] \n",gun_index);
  3267. break;
  3268. default:
  3269. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = OFF;
  3270. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][0] = 0;
  3271. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][1] = 0;
  3272. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][2] = 0;
  3273. DEBUG_INFO("Gun-%d Output relay status: OFF. [DEFFAULT] \n",gun_index);
  3274. break;
  3275. }
  3276. }
  3277. }
  3278. }
  3279. //===============================================
  3280. // Relay on/off get
  3281. //===============================================
  3282. int getRelay(unsigned char gun_index)
  3283. {
  3284. return ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn;
  3285. }
  3286. //===============================================
  3287. // Set speaker on/off request
  3288. //===============================================
  3289. void setSpeaker(unsigned char isOn, unsigned char speaker_mode)
  3290. {
  3291. if(isOn == ON)
  3292. {
  3293. ShmCharger->isSpeakerOn = ON;
  3294. ShmCharger->speaker_type = speaker_mode;
  3295. }
  3296. }
  3297. //===============================================
  3298. // Initialization RFID communication port
  3299. //===============================================
  3300. int InitRfidPort()
  3301. {
  3302. int uartO2 = open(rfidPortName, O_RDWR);
  3303. struct termios tios;
  3304. if (uartO2 != FAIL)
  3305. {
  3306. ioctl (uartO2, TCGETS, &tios);
  3307. tios.c_cflag = B19200 | CS8 | CLOCAL | CREAD;
  3308. tios.c_lflag = 0;
  3309. tios.c_iflag = 0;
  3310. tios.c_oflag = 0;
  3311. tios.c_cc[VMIN] = 0;
  3312. tios.c_cc[VTIME] = (unsigned char) 1;
  3313. tios.c_lflag = 0;
  3314. tcflush(uartO2, TCIFLUSH);
  3315. ioctl(uartO2, TCSETS, &tios);
  3316. }
  3317. if (uartO2 < 0)
  3318. {
  3319. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RfidModuleCommFail = 1;
  3320. }
  3321. return uartO2;
  3322. }
  3323. //===============================================
  3324. // Check internet access status
  3325. //===============================================
  3326. int isReachableInternet()
  3327. {
  3328. int result = FAIL;
  3329. FILE *fp;
  3330. char cmd[256];
  3331. char buf[512];
  3332. char tmp[512];
  3333. // Get ip address & net mask
  3334. strcpy(cmd, "ifconfig eth0");
  3335. fp = popen(cmd, "r");
  3336. if (fp != NULL)
  3337. {
  3338. while(fgets(buf, sizeof(buf), fp) != NULL)
  3339. {
  3340. if (strstr(buf, "inet addr:") > 0)
  3341. {
  3342. sscanf(buf, "%*s%s", tmp);
  3343. substr(tmp, tmp, strspn(tmp, "addr:"), strlen(buf)-strspn(tmp, "addr:"));
  3344. if (strcmp(tmp, (char *)ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress) != 0)
  3345. {
  3346. strcpy((char *) ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress, tmp);
  3347. }
  3348. sscanf(buf, "%*s%*s%*s%s", tmp);
  3349. substr(tmp, tmp, strspn(tmp, "Mask:"), strlen(buf)-strspn(tmp, "Mask:"));
  3350. if (strcmp(tmp, (char *)ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress) != 0)
  3351. {
  3352. strcpy((char *) ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress, tmp);
  3353. }
  3354. }
  3355. }
  3356. }
  3357. pclose(fp);
  3358. memset(buf, 0x00, sizeof(buf));
  3359. // Get gateway
  3360. fp = popen("ip route", "r");
  3361. if(fp != NULL)
  3362. {
  3363. while(fgets(buf, sizeof(buf), fp) != NULL)
  3364. {
  3365. if((strstr(buf, "default") != NULL) && (strstr(buf, "eth0") != NULL))
  3366. break;
  3367. }
  3368. if(strstr(buf, "default") != NULL)
  3369. {
  3370. sscanf(buf, "%*s%*s%s", tmp);
  3371. substr((char*)ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthGatewayAddress, tmp, 0, strlen(tmp));
  3372. }
  3373. }
  3374. pclose(fp);
  3375. memset(buf, 0x00, sizeof(buf));
  3376. // Check internet access ability
  3377. for(int idx=0;idx<ARRAY_SIZE(valid_Internet);idx++)
  3378. {
  3379. sprintf(cmd, "ping -c 1 -w 3 -I eth0 %s", valid_Internet[idx]);
  3380. fp = popen(cmd, "r");
  3381. if(fp != NULL)
  3382. {
  3383. while(fgets(buf, sizeof(buf), fp) != NULL)
  3384. {
  3385. if(strstr(buf, "transmitted") > 0)
  3386. {
  3387. //sscanf(buf, "%*s%*s%*s%*s%*s%*s%s", tmp);
  3388. if(strstr(buf,"100%") != NULL)
  3389. {
  3390. }
  3391. else
  3392. {
  3393. result = PASS;
  3394. }
  3395. //DEBUG_INFO("%s",buf);
  3396. //DEBUG_INFO("%s\n",tmp);
  3397. }
  3398. }
  3399. }
  3400. pclose(fp);
  3401. }
  3402. return result;
  3403. }
  3404. int isRouteFail()
  3405. {
  3406. int result = YES;
  3407. FILE *fp;
  3408. char buf[512];
  3409. fp = popen("route -n", "r");
  3410. if(fp != NULL)
  3411. {
  3412. while(fgets(buf, sizeof(buf), fp) != NULL)
  3413. {
  3414. if(strstr(buf, "eth0") != NULL)
  3415. result = NO;
  3416. }
  3417. }
  3418. pclose(fp);
  3419. return result;
  3420. }
  3421. //===============================================
  3422. // Check reservation date is expired
  3423. //===============================================
  3424. int isReservationExpired(unsigned char gun_index)
  3425. {
  3426. int result = NO;
  3427. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3428. {
  3429. if(isOvertNow(ShmOCPP16Data->ReserveNow[gun_index].ExpiryDate))
  3430. result = YES;
  3431. }
  3432. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3433. {
  3434. if(isOvertNow(ShmOCPP20Data->ReserveNow[gun_index].expiryDateTime))
  3435. result = YES;
  3436. }
  3437. return result;
  3438. }
  3439. //===============================================
  3440. // Check charging profile related date routine
  3441. //===============================================
  3442. int isProfileValid(uint8_t gun_index)
  3443. {
  3444. int result = NO;
  3445. struct tm tmFrom, tmTo;
  3446. struct timeb tbFrom, tbTo;
  3447. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3448. {
  3449. if((sscanf((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ValidFrom, "%4d-%2d-%2dT%2d:%2d:%2d", &tmFrom.tm_year, &tmFrom.tm_mon, &tmFrom.tm_mday, &tmFrom.tm_hour, &tmFrom.tm_min, &tmFrom.tm_sec) == 6) &&
  3450. (sscanf((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ValidTo, "%4d-%2d-%2dT%2d:%2d:%2d", &tmTo.tm_year, &tmTo.tm_mon, &tmTo.tm_mday, &tmTo.tm_hour, &tmTo.tm_min, &tmTo.tm_sec) == 6))
  3451. {
  3452. tmFrom.tm_year -= 1900;
  3453. tmFrom.tm_mon -= 1;
  3454. tbFrom.time = mktime(&tmFrom);
  3455. tmTo.tm_year -= 1900;
  3456. tmTo.tm_mon -= 1;
  3457. tbTo.time = mktime(&tmTo);
  3458. DEBUG_INFO("Valid from compare Now: %d\n", DiffTimebWithNow(tbFrom));
  3459. DEBUG_INFO("Valid to compare Now: %d\n", DiffTimebWithNow(tbTo));
  3460. if((DiffTimebWithNow(tbFrom)>=0) && (DiffTimebWithNow(tbTo)<=0))
  3461. {
  3462. result = YES;
  3463. }
  3464. }
  3465. else
  3466. {
  3467. DEBUG_WARN("ValidFrom or ValidTo date parsing error.\n");
  3468. }
  3469. }
  3470. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3471. {
  3472. if((sscanf((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].validFrom, "%4d-%2d-%2dT%2d:%2d:%2d", &tmFrom.tm_year, &tmFrom.tm_mon, &tmFrom.tm_mday, &tmFrom.tm_hour, &tmFrom.tm_min, &tmFrom.tm_sec) == 6) &&
  3473. (sscanf((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].validTo, "%4d-%2d-%2dT%2d:%2d:%2d", &tmTo.tm_year, &tmTo.tm_mon, &tmTo.tm_mday, &tmTo.tm_hour, &tmTo.tm_min, &tmTo.tm_sec) == 6))
  3474. {
  3475. tmFrom.tm_year -= 1900;
  3476. tmFrom.tm_mon -= 1;
  3477. tbFrom.time = mktime(&tmFrom);
  3478. tmTo.tm_year -= 1900;
  3479. tmTo.tm_mon -= 1;
  3480. tbTo.time = mktime(&tmTo);
  3481. DEBUG_INFO("Valid from compare Now: %d\n", DiffTimebWithNow(tbFrom));
  3482. DEBUG_INFO("Valid to compare Now: %d\n", DiffTimebWithNow(tbTo));
  3483. if((DiffTimebWithNow(tbFrom)>=0) && (DiffTimebWithNow(tbTo)<=0))
  3484. {
  3485. result = YES;
  3486. }
  3487. }
  3488. else
  3489. {
  3490. DEBUG_WARN("ValidFrom or ValidTo date parsing error.\n");
  3491. }
  3492. }
  3493. return result;
  3494. }
  3495. int getMaxScheduleStart()
  3496. {
  3497. int result = -1;
  3498. struct tm tmScheduleStart;;
  3499. struct timeb tbScheduleStart;
  3500. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3501. {
  3502. if((sscanf((char*)ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.StartSchedule, "%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))
  3503. {
  3504. tmScheduleStart.tm_year -= 1900;
  3505. tmScheduleStart.tm_mon -= 1;
  3506. tbScheduleStart.time = mktime(&tmScheduleStart);
  3507. tbScheduleStart.millitm = 0;
  3508. result = DiffTimebWithNow(tbScheduleStart)/1000;
  3509. //DEBUG_INFO("Max schedule start compare Now(seconds): %d\n", result);
  3510. }
  3511. else
  3512. {
  3513. DEBUG_WARN("Max schedule start date parsing error.\n");
  3514. }
  3515. }
  3516. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3517. {
  3518. if((sscanf((char*)ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].startSchedule, "%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))
  3519. {
  3520. tmScheduleStart.tm_year -= 1900;
  3521. tmScheduleStart.tm_mon -= 1;
  3522. tbScheduleStart.time = mktime(&tmScheduleStart);
  3523. tbScheduleStart.millitm = 0;
  3524. result = DiffTimebWithNow(tbScheduleStart)/1000;
  3525. //DEBUG_INFO("Max schedule start compare Now(seconds): %d\n", result);
  3526. }
  3527. else
  3528. {
  3529. DEBUG_WARN("Max schedule start date parsing error.\n");
  3530. }
  3531. }
  3532. return result;
  3533. }
  3534. int getScheduleStart(int gun_index)
  3535. {
  3536. int result = -1;
  3537. struct tm tmScheduleStart;;
  3538. struct timeb tbScheduleStart;
  3539. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3540. {
  3541. if((sscanf((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.StartSchedule, "%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))
  3542. {
  3543. tmScheduleStart.tm_year -= 1900;
  3544. tmScheduleStart.tm_mon -= 1;
  3545. tbScheduleStart.time = mktime(&tmScheduleStart);
  3546. tbScheduleStart.millitm = 0;
  3547. result = DiffTimebWithNow(tbScheduleStart)/1000;
  3548. //DEBUG_INFO("Schedule start compare Now(seconds): %d\n", result);
  3549. }
  3550. else
  3551. {
  3552. DEBUG_WARN("Schedule start date parsing error.\n");
  3553. }
  3554. }
  3555. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3556. {
  3557. if((sscanf((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].startSchedule, "%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))
  3558. {
  3559. tmScheduleStart.tm_year -= 1900;
  3560. tmScheduleStart.tm_mon -= 1;
  3561. tbScheduleStart.time = mktime(&tmScheduleStart);
  3562. tbScheduleStart.millitm = 0;
  3563. result = DiffTimebWithNow(tbScheduleStart)/1000;
  3564. //DEBUG_INFO("Schedule start compare Now(seconds): %d\n", result);
  3565. }
  3566. else
  3567. {
  3568. DEBUG_WARN("Schedule start date parsing error.\n");
  3569. }
  3570. }
  3571. return result;
  3572. }
  3573. int getStartSinceToday()
  3574. {
  3575. int result = -1;
  3576. time_t t;
  3577. struct tm *tmStartToday;
  3578. struct timeb tbStartToday;
  3579. t=time(NULL);
  3580. tmStartToday=localtime(&t);
  3581. tmStartToday->tm_hour = 0;
  3582. tmStartToday->tm_min = 0;
  3583. tmStartToday->tm_sec = 0;
  3584. tbStartToday.time = mktime(tmStartToday);
  3585. result = DiffTimebWithNow(tbStartToday)/1000;
  3586. //DEBUG_INFO("Start today compare Now(seconds): %d\n", result);
  3587. return result;
  3588. }
  3589. int getStartSinceWeek()
  3590. {
  3591. int result = -1;
  3592. time_t t;
  3593. struct tm *tmStartWeek;
  3594. struct timeb tbStartWeek;
  3595. t=time(NULL);
  3596. tmStartWeek=localtime(&t);
  3597. t-=86400*tmStartWeek->tm_wday;
  3598. tmStartWeek=localtime(&t);
  3599. tmStartWeek->tm_hour = 0;
  3600. tmStartWeek->tm_min = 0;
  3601. tmStartWeek->tm_sec = 0;
  3602. tbStartWeek.time = mktime(tmStartWeek);
  3603. result = DiffTimebWithNow(tbStartWeek)/1000;
  3604. //DEBUG_INFO("Start week compare Now(seconds): %d\n", result);
  3605. return result;
  3606. }
  3607. //===============================================
  3608. // Valid from local white list
  3609. //===============================================
  3610. int isValidLocalWhiteCard()
  3611. {
  3612. uint8_t result = FAIL;
  3613. for(uint8_t idx=0;idx<ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.LocalWhiteCard);idx++)
  3614. {
  3615. if(strcmp((char*)ShmSysConfigAndInfo->SysConfig.UserId, (char*)ShmSysConfigAndInfo->SysConfig.LocalWhiteCard[idx]) == 0)
  3616. {
  3617. result = PASS;
  3618. }
  3619. }
  3620. return result;
  3621. }
  3622. //==========================================
  3623. // Check routine
  3624. //==========================================
  3625. void checkTask()
  3626. {
  3627. /*
  3628. * TODO:
  3629. * 1. Rotary switch define change with system specification
  3630. */
  3631. // Task run only on cabinet
  3632. if(ShmDispenser->gun_info.primaryMcuState.rotatory_switch != ROTARY_SWITCH_E_DISPENSER)
  3633. {
  3634. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  3635. {
  3636. if(system("pidof -s Module_4g > /dev/null") != 0)
  3637. {
  3638. DEBUG_INFO("Module_4g not running, restart it.\n");
  3639. system("/root/Module_4g &");
  3640. }
  3641. }
  3642. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  3643. {
  3644. if(system("pidof -s Module_Wifi > /dev/null") != 0)
  3645. {
  3646. DEBUG_INFO("Module_Wifi not running, restart it.\n");
  3647. system("/root/Module_Wifi &");
  3648. }
  3649. }
  3650. if((strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") != 0) && !ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharging)
  3651. {
  3652. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3653. {
  3654. if((time((time_t*)NULL) - ShmOCPP16Data->procDogTime) > 180)
  3655. {
  3656. DEBUG_WARN("OcppBackend watch dog timeout task restart.\n");
  3657. ShmOCPP16Data->procDogTime = time((time_t*)NULL);
  3658. system("killall OcppBackend");
  3659. sleep(3);
  3660. ocpp_process_start();
  3661. }
  3662. if(system("pidof -s OcppBackend > /dev/null") != 0)
  3663. {
  3664. DEBUG_INFO("OcppBackend not running, restart it.\n");
  3665. ocpp_process_start();
  3666. }
  3667. }
  3668. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3669. {
  3670. if((time((time_t*)NULL) - ShmOCPP20Data->procDogTime) > 180)
  3671. {
  3672. DEBUG_WARN("OcppBackend20 watch dog timeout task restart.\n");
  3673. ShmOCPP20Data->procDogTime = time((time_t*)NULL);
  3674. system("killall OcppBackend20");
  3675. sleep(3);
  3676. ocpp_process_start();
  3677. }
  3678. if(system("pidof -s OcppBackend20 > /dev/null") != 0)
  3679. {
  3680. DEBUG_INFO("OcppBackend20 not running, restart it.\n");
  3681. ocpp_process_start();
  3682. }
  3683. }
  3684. }
  3685. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.MaintainServerURL,"") != 0 && !ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharging)
  3686. {
  3687. if(system("pidof -s OcppBackendPH > /dev/null") != 0)
  3688. {
  3689. DEBUG_INFO("OcppBackendPH not running, restart it.\n");
  3690. system("/root/OcppBackendPH &");
  3691. }
  3692. }
  3693. if(system("pidof -s Module_Speaker > /dev/null") != 0)
  3694. {
  3695. DEBUG_INFO("Module_Speaker not running, restart it.\n");
  3696. system("/root/Module_Speaker &");
  3697. }
  3698. if(system("pidof -s Module_LcmControl > /dev/null") != 0)
  3699. {
  3700. DEBUG_INFO("Module_LcmControl not running, restart it.\n");
  3701. system ("/root/Module_LcmControl &");
  3702. }
  3703. if((system("pidof -s Module_PowerSharing > /dev/null") != 0) &&
  3704. ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharging)
  3705. {
  3706. DEBUG_INFO("Module_PowerSharing not running, restart it.\n");
  3707. system ("/root/Module_PowerSharing &");
  3708. }
  3709. /*
  3710. if((system("pidof -s Module_InitUpgrade > /dev/null") != 0) &&
  3711. ShmSysConfigAndInfo->SysConfig.isReqFirstUpgrade)
  3712. {
  3713. DEBUG_INFO("Module_InitUpgrade not running, restart it.\n");
  3714. system ("/root/Module_InitUpgrade &");
  3715. }*/
  3716. if(system("pidof -s Module_AlarmDetect > /dev/null") != 0)
  3717. {
  3718. DEBUG_INFO("Module_AlarmDetect not running, restart it.\n");
  3719. system("/root/Module_AlarmDetect &");
  3720. }
  3721. }
  3722. // Task run both on cabinet and dispenser
  3723. if(system("pidof -s Module_EventLogging > /dev/null") != 0)
  3724. {
  3725. DEBUG_INFO("Module_EventLogging not running, restart it.\n");
  3726. system("/root/Module_EventLogging &");
  3727. }
  3728. if(system("pidof -s Module_InternalComm > /dev/null") != 0)
  3729. {
  3730. DEBUG_INFO("Module_InternalComm not running, restart it.\n");
  3731. system("/root/Module_InternalComm &");
  3732. }
  3733. if(system("pidof -s Module_ProduceUtils > /dev/null") != 0)
  3734. {
  3735. DEBUG_INFO("Module_ProduceUtils not running, restart it.\n");
  3736. system ("/root/Module_ProduceUtils &");
  3737. }
  3738. if((system("pidof -s Module_Cabinet > /dev/null") != 0))
  3739. {
  3740. DEBUG_INFO("Module_Cabinet not running, restart it.\n");
  3741. system ("/root/Module_Cabinet &");
  3742. }
  3743. if((system("pidof -s Module_Dispenser > /dev/null") != 0))
  3744. {
  3745. DEBUG_INFO("Module_Dispenser not running, restart it.\n");
  3746. system ("/root/Module_Dispenser &");
  3747. }
  3748. if(ShmCharger->isCcsEnable == ON)
  3749. {
  3750. if((system("pidof -s CsuComm > /dev/null") != 0))
  3751. {
  3752. DEBUG_INFO("CsuComm not running, restart it.\n");
  3753. system ("/root/CsuComm &");
  3754. }
  3755. if((system("pidof -s SeccComm > /dev/null") != 0))
  3756. {
  3757. sleep(3);
  3758. DEBUG_INFO("SeccComm not running, restart it.\n");
  3759. system ("/root/SeccComm &");
  3760. }
  3761. }
  3762. }
  3763. void checkConnectionTimeout()
  3764. {
  3765. if((system("pidof -s OcppBackend > /dev/null") != 0) && (system("pidof -s OcppBackend20 > /dev/null") != 0))
  3766. {
  3767. ShmCharger->timeoutSpec.Present_Timeout_Spec = TIMEOUT_SPEC_HANDSHAKING;
  3768. //DEBUG_INFO("Handshaking timeout specification follow by initial setting : %d s \n", TIMEOUT_SPEC_HANDSHAKING/1000);
  3769. }
  3770. else
  3771. {
  3772. ShmCharger->timeoutSpec.Present_Timeout_Spec = ocpp_get_connection_timeout();
  3773. /*
  3774. if((ShmCharger->timeoutSpec.Setting_Timeout_Spec) < TIMEOUT_SPEC_BS_HLC_HANDSHAKE)
  3775. {
  3776. ShmCharger->timeoutSpec.Present_Timeout_Spec = (TIMEOUT_SPEC_BS_HLC_HANDSHAKE+10);
  3777. //DEBUG_INFO("Handshaking timeout specification follow by OCPP Configuration : Fail. Value can't be zero or less than zero.\n.");
  3778. }
  3779. else
  3780. {
  3781. ShmCharger->timeoutSpec.Present_Timeout_Spec = (ShmCharger->timeoutSpec.Setting_Timeout_Spec);
  3782. //DEBUG_INFO("Handshaking timeout specification follow by OCPP Configuration : Pass...\n.");
  3783. }*/
  3784. //DEBUG_INFO("Handshaking timeout specification follow by OCPP Configuration : %s s \n.",ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData);
  3785. }
  3786. }
  3787. void checkReset()
  3788. {
  3789. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3790. {
  3791. if(ShmOCPP16Data->MsMsg.bits.ResetReq)
  3792. {
  3793. if((!isMode(0, SYS_MODE_CHARGING) && !isMode(0, SYS_MODE_TERMINATING) && !isMode(0, SYS_MODE_COMPLETE)) &&
  3794. ((modelnameInfo.GetGunCount==2)?(!isMode(1, SYS_MODE_CHARGING) && !isMode(1, SYS_MODE_TERMINATING) && !isMode(1, SYS_MODE_COMPLETE)):TRUE) &&
  3795. ((modelnameInfo.GetGunCount==3)?(!isMode(2, SYS_MODE_CHARGING) && !isMode(2, SYS_MODE_TERMINATING) && !isMode(2, SYS_MODE_COMPLETE)):TRUE))
  3796. {
  3797. ShmOCPP16Data->MsMsg.bits.ResetReq = OFF;
  3798. sprintf((char*)ShmOCPP16Data->Reset.ResponseStatus, "Accepted");
  3799. ShmOCPP16Data->MsMsg.bits.ResetConf = ON;
  3800. DEBUG_INFO("%s reset request by OCPP.\n", ShmOCPP16Data->Reset.Type);
  3801. if(strcmp((char*)ShmOCPP16Data->Reset.Type, "Hard") == 0)
  3802. {
  3803. for(int gun_index=0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  3804. {
  3805. ShmCharger->gun_info[gun_index].isResetHardReq = ON;
  3806. setLedMotion(gun_index,LED_ACTION_INIT);
  3807. }
  3808. }
  3809. else
  3810. {
  3811. for(int gun_index=0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  3812. {
  3813. ShmCharger->gun_info[gun_index].isResetSoftReq = ON;
  3814. setLedMotion(gun_index,LED_ACTION_INIT);
  3815. }
  3816. }
  3817. sleep(2);
  3818. }
  3819. }
  3820. }
  3821. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3822. {
  3823. if(ShmOCPP20Data->MsMsg.bits.ResetReq)
  3824. {
  3825. if((!isMode(0, SYS_MODE_CHARGING) && !isMode(0, SYS_MODE_TERMINATING) && !isMode(0, SYS_MODE_COMPLETE)) &&
  3826. ((modelnameInfo.GetGunCount==2)?(!isMode(1, SYS_MODE_CHARGING) && !isMode(1, SYS_MODE_TERMINATING) && !isMode(1, SYS_MODE_COMPLETE)):TRUE) &&
  3827. ((modelnameInfo.GetGunCount==3)?(!isMode(2, SYS_MODE_CHARGING) && !isMode(2, SYS_MODE_TERMINATING) && !isMode(2, SYS_MODE_COMPLETE)):TRUE))
  3828. {
  3829. ShmOCPP20Data->MsMsg.bits.ResetReq = OFF;
  3830. sprintf((char*)ShmOCPP20Data->Reset.Response_status, "Accepted");
  3831. ShmOCPP20Data->MsMsg.bits.ResetConf = ON;
  3832. DEBUG_INFO("%s reset request by OCPP.\n", ShmOCPP20Data->Reset.type);
  3833. if(strcmp((char*)ShmOCPP20Data->Reset.type, "Immediate") == 0)
  3834. {
  3835. for(int gun_index=0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  3836. {
  3837. ShmCharger->gun_info[gun_index].isResetHardReq = ON;
  3838. setLedMotion(gun_index,LED_ACTION_INIT);
  3839. }
  3840. }
  3841. else
  3842. {
  3843. for(int gun_index=0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  3844. {
  3845. ShmCharger->gun_info[gun_index].isResetSoftReq = ON;
  3846. setLedMotion(gun_index,LED_ACTION_INIT);
  3847. }
  3848. }
  3849. sleep(2);
  3850. }
  3851. }
  3852. }
  3853. if(ShmDispenser->gun_info.isResetHardReq)
  3854. {
  3855. system("sync");
  3856. sleep(5);
  3857. system("reboot -f");
  3858. sleep(5);
  3859. system("reboot -f");
  3860. }
  3861. else if(ShmDispenser->gun_info.isResetSoftReq)
  3862. {
  3863. sleep(5);
  3864. close(wtdFd);
  3865. system("/usr/bin/run_evse_restart.sh");
  3866. }
  3867. }
  3868. void checkReservation(uint8_t gun_index)
  3869. {
  3870. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3871. {
  3872. if(ShmOCPP16Data->CsMsg.bits[gun_index].ReserveNowReq)
  3873. {
  3874. ShmOCPP16Data->CsMsg.bits[gun_index].ReserveNowReq = OFF;
  3875. ShmOCPP16Data->CsMsg.bits[gun_index].ReserveNowConf = ON;
  3876. if(isMode(gun_index, SYS_MODE_IDLE) && !isReservationExpired(gun_index))
  3877. {
  3878. sleep(5);
  3879. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId = ShmOCPP16Data->ReserveNow[gun_index].ReservationId;
  3880. setChargerMode(gun_index, SYS_MODE_RESERVATION);
  3881. }
  3882. DEBUG_INFO("Reservation request on gun-%d.\n", gun_index);
  3883. }
  3884. }
  3885. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3886. {
  3887. if(ShmOCPP20Data->CsMsg.bits[gun_index].ReserveNowReq)
  3888. {
  3889. ShmOCPP20Data->CsMsg.bits[gun_index].ReserveNowReq = OFF;
  3890. ShmOCPP20Data->CsMsg.bits[gun_index].ReserveNowConf = ON;
  3891. if(isMode(gun_index, SYS_MODE_IDLE) && !isReservationExpired(gun_index))
  3892. {
  3893. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId = ShmOCPP20Data->ReserveNow[gun_index].id;
  3894. setChargerMode(gun_index, SYS_MODE_RESERVATION);
  3895. }
  3896. DEBUG_INFO("Reservation request on gun-%d.\n", gun_index);
  3897. }
  3898. }
  3899. }
  3900. void checkUnlocker(uint8_t gun_index)
  3901. {
  3902. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3903. {
  3904. if(ShmOCPP16Data->CsMsg.bits[gun_index].UnlockConnectorReq == ON)
  3905. {
  3906. ShmOCPP16Data->CsMsg.bits[gun_index].UnlockConnectorReq = OFF;
  3907. sprintf((char*)ShmOCPP16Data->UnlockConnector[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].ResponseStatus, "NotSupported");
  3908. ShmOCPP16Data->CsMsg.bits[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].UnlockConnectorConf = ON;
  3909. ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor = ON;
  3910. }
  3911. }
  3912. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3913. {
  3914. if(ShmOCPP20Data->CsMsg.bits[gun_index].UnlockConnectorReq == ON)
  3915. {
  3916. ShmOCPP20Data->CsMsg.bits[gun_index].UnlockConnectorReq = OFF;
  3917. sprintf((char*)ShmOCPP20Data->UnlockConnector[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].Response_status, "UnlockFailed");
  3918. ShmOCPP20Data->CsMsg.bits[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].UnlockConnectorConf = ON;
  3919. ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor = ON;
  3920. }
  3921. }
  3922. }
  3923. void checkAvailability(uint8_t gun_index)
  3924. {
  3925. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3926. {
  3927. if(ShmOCPP16Data->CsMsg.bits[gun_index].ChangeAvailabilityReq)
  3928. {
  3929. if(strcmp((char*)ShmOCPP16Data->ChangeAvailability[gun_index].Type, "Operative") == 0)
  3930. {
  3931. DB_Update_Operactive(localDb, gun_index, true);
  3932. ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
  3933. }
  3934. else
  3935. {
  3936. DB_Update_Operactive(localDb, gun_index, false);
  3937. ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
  3938. }
  3939. ShmOCPP16Data->CsMsg.bits[gun_index].ChangeAvailabilityReq = OFF;
  3940. }
  3941. }
  3942. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3943. {
  3944. if(ShmOCPP20Data->CsMsg.bits[gun_index].ChangeAvailabilityReq)
  3945. {
  3946. if(strcmp((char*)ShmOCPP20Data->ChangeAvailability[gun_index].operationalStatus, "Operative") == 0)
  3947. {
  3948. DB_Update_Operactive(localDb, gun_index, true);
  3949. ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
  3950. }
  3951. else
  3952. {
  3953. DB_Update_Operactive(localDb, gun_index, false);
  3954. ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
  3955. }
  3956. ShmOCPP20Data->CsMsg.bits[gun_index].ChangeAvailabilityReq = OFF;
  3957. }
  3958. }
  3959. }
  3960. void checkChargingProfileLimit(uint8_t gun_index)
  3961. {
  3962. static struct PreviousData
  3963. {
  3964. uint16_t targetCurrent;
  3965. uint16_t current_limit;
  3966. }previousData[3];
  3967. uint16_t targetMaxCurrent = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
  3968. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3969. {
  3970. // Get profile charging profile limit
  3971. if((ocpp_get_smartcharging_profileId(gun_index) > 0))
  3972. {
  3973. // Checking limitation
  3974. for(uint8_t idx_period=0;idx_period<ARRAY_SIZE(ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod);idx_period++)
  3975. {
  3976. if((getScheduleStart(gun_index) >= ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod[idx_period].StartPeriod) &&
  3977. ((idx_period == 0) || (ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod[idx_period].StartPeriod > 0))
  3978. )
  3979. {
  3980. ShmCharger->gun_info[gun_index].targetCurrent = (mystrcmp((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingRateUnit,"W")==PASS?ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod[idx_period].Limit/(220*ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod[idx_period].NumberPhases):ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod[idx_period].Limit);
  3981. //DEBUG_INFO("ShmCharger->gun_info[%d].targetCurrent on period[%d]: %d\n", gun_index, idx_period, ShmCharger->gun_info[gun_index].targetCurrent);
  3982. }
  3983. else
  3984. break;
  3985. }
  3986. }
  3987. else
  3988. {
  3989. ShmCharger->gun_info[gun_index].targetCurrent = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
  3990. }
  3991. // Get max charging profile limit
  3992. if((ocpp_get_maxcharging_profileId() > 0))
  3993. {
  3994. // Checking limitation
  3995. for(uint8_t idx_period=0;idx_period<ARRAY_SIZE(ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod);idx_period++)
  3996. {
  3997. if((getMaxScheduleStart() >= ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[idx_period].StartPeriod) &&
  3998. ((idx_period == 0) || (ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[idx_period].StartPeriod > 0))
  3999. )
  4000. {
  4001. targetMaxCurrent = (mystrcmp((char*)ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingRateUnit,"W")==PASS?ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[idx_period].Limit/(220*ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[idx_period].NumberPhases):ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[idx_period].Limit);
  4002. //DEBUG_INFO("targetMaxCurrent on period[%d]: %d\n", idx_period, targetMaxCurrent);
  4003. }
  4004. else
  4005. break;
  4006. }
  4007. }
  4008. // Compare target current is over max current for EVSE limit
  4009. if(gun_index == 0)
  4010. {
  4011. if(ShmCharger->gun_info[gun_index].targetCurrent > targetMaxCurrent)
  4012. ShmCharger->gun_info[gun_index].targetCurrent = targetMaxCurrent;
  4013. }
  4014. else
  4015. {
  4016. if((ShmCharger->gun_info[gun_index-1].targetCurrent + ShmCharger->gun_info[gun_index].targetCurrent) > targetMaxCurrent)
  4017. ShmCharger->gun_info[gun_index].targetCurrent = (targetMaxCurrent - ShmCharger->gun_info[gun_index-1].targetCurrent);
  4018. }
  4019. }
  4020. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  4021. {
  4022. // Get profile charging profile limit
  4023. if((ocpp_get_smartcharging_profileId(gun_index) > 0))
  4024. {
  4025. // Checking limitation
  4026. for(uint8_t idx_period=0;idx_period<ARRAY_SIZE(ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod);idx_period++)
  4027. {
  4028. if((getScheduleStart(gun_index) >= ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod[idx_period].startPeriod) &&
  4029. ((idx_period == 0) || (ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod[idx_period].startPeriod > 0))
  4030. )
  4031. {
  4032. ShmCharger->gun_info[gun_index].targetCurrent = (mystrcmp((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingRateUnit,"W")==PASS?ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod[idx_period].limit/(220*ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod[idx_period].numberPhases):ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod[idx_period].limit);
  4033. //DEBUG_INFO("ShmCharger->gun_info[%d].targetCurrent on period[%d]: %d\n", gun_index, idx_period, ShmCharger->gun_info[gun_index].targetCurrent);
  4034. }
  4035. else
  4036. break;
  4037. }
  4038. }
  4039. else
  4040. {
  4041. ShmCharger->gun_info[gun_index].targetCurrent = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
  4042. }
  4043. // Get max charging profile limit
  4044. if((ocpp_get_maxcharging_profileId() > 0))
  4045. {
  4046. // Checking limitation
  4047. for(uint8_t idx_period=0;idx_period<ARRAY_SIZE(ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingSchedulePeriod);idx_period++)
  4048. {
  4049. if((getMaxScheduleStart() >= ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingSchedulePeriod[idx_period].startPeriod) &&
  4050. ((idx_period == 0) || (ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingSchedulePeriod[idx_period].startPeriod > 0))
  4051. )
  4052. {
  4053. targetMaxCurrent = (mystrcmp((char*)ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingRateUnit,"W")==PASS?ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingSchedulePeriod[idx_period].limit/(220*ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingSchedulePeriod[idx_period].numberPhases):ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingSchedulePeriod[idx_period].limit);
  4054. //DEBUG_INFO("targetMaxCurrent on period[%d]: %d\n", idx_period, targetMaxCurrent);
  4055. }
  4056. else
  4057. break;
  4058. }
  4059. }
  4060. // Compare target current is over max current for EVSE limit
  4061. if(gun_index == 0)
  4062. {
  4063. if(ShmCharger->gun_info[gun_index].targetCurrent > targetMaxCurrent)
  4064. ShmCharger->gun_info[gun_index].targetCurrent = targetMaxCurrent;
  4065. }
  4066. else
  4067. {
  4068. if((ShmCharger->gun_info[gun_index-1].targetCurrent + ShmCharger->gun_info[gun_index].targetCurrent) > targetMaxCurrent)
  4069. ShmCharger->gun_info[gun_index].targetCurrent = (targetMaxCurrent - ShmCharger->gun_info[gun_index-1].targetCurrent);
  4070. }
  4071. }
  4072. if(ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent == 0)
  4073. {
  4074. ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmCharger->gun_info[gun_index].primaryMcuState.rating_current)?ShmCharger->gun_info[gun_index].primaryMcuState.rating_current:ShmCharger->gun_info[gun_index].targetCurrent);
  4075. ShmCharger->gun_info[gun_index].targetCurrent = ((1 <= ShmCharger->gun_info[gun_index].targetCurrent) && (ShmCharger->gun_info[gun_index].targetCurrent <= 5)?6:ShmCharger->gun_info[gun_index].targetCurrent);
  4076. }
  4077. else
  4078. {
  4079. ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent)?ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent:ShmCharger->gun_info[gun_index].targetCurrent);
  4080. ShmCharger->gun_info[gun_index].targetCurrent = ((1 <= ShmCharger->gun_info[gun_index].targetCurrent) && (ShmCharger->gun_info[gun_index].targetCurrent <= 5)?6:ShmCharger->gun_info[gun_index].targetCurrent);
  4081. }
  4082. if(ShmCharger->gun_info[gun_index].targetCurrent != previousData[gun_index].targetCurrent)
  4083. {
  4084. DEBUG_INFO("SysConfig.MaxChargingCurrent: %d\n", ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent);
  4085. DEBUG_INFO("gun-%02d target current: %d\n", gun_index, ShmCharger->gun_info[gun_index].targetCurrent);
  4086. previousData[gun_index].targetCurrent = ShmCharger->gun_info[gun_index].targetCurrent;
  4087. }
  4088. if(ShmCharger->gun_info[gun_index].primaryMcuState.current_limit != previousData[gun_index].current_limit)
  4089. {
  4090. DEBUG_INFO("gun-%02d mcu current_limit: %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuState.current_limit);
  4091. previousData[gun_index].current_limit = ShmCharger->gun_info[gun_index].primaryMcuState.current_limit;
  4092. }
  4093. }
  4094. void checkStopReason(uint8_t gun_index)
  4095. {
  4096. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  4097. {
  4098. memset(ShmOCPP16Data->StopTransaction[gun_index].IdTag, 0x00, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  4099. if(!ocpp_get_starttransaction_result(gun_index))
  4100. {
  4101. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "DeAuthorized");
  4102. }
  4103. else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_EMERGENCY_STOP)
  4104. {
  4105. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EmergencyStop");
  4106. }
  4107. else if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)
  4108. {
  4109. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EVDisconnected");
  4110. memcpy((char*)ShmOCPP16Data->StopTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  4111. }
  4112. else if(ShmOCPP16Data->MsMsg.bits.ResetReq)
  4113. {
  4114. if(strcmp((char*)ShmOCPP16Data->Reset.Type, "Hard")==0)
  4115. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "HardReset");
  4116. else
  4117. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "SoftReset");
  4118. }
  4119. else if(ShmCharger->gun_info[gun_index].rfidReq || ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop)
  4120. {
  4121. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
  4122. if(!isMatchStartUser(gun_index))
  4123. {
  4124. memcpy((char*)ShmOCPP16Data->StopTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  4125. }
  4126. else
  4127. {
  4128. memcpy((char*)ShmOCPP16Data->StopTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  4129. }
  4130. DEBUG_INFO("Gun-%d [ IdTag ] : %s \n", gun_index, ShmOCPP16Data->StopTransaction[gun_index].IdTag);
  4131. }
  4132. else if(ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStopTransactionReq)
  4133. {
  4134. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Remote");
  4135. }
  4136. else if(ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor == ON)
  4137. {
  4138. sprintf((char*)ShmOCPP16Data->StopTransaction[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].StopReason, "UnlockCommand");
  4139. }
  4140. else
  4141. {
  4142. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Other");
  4143. }
  4144. DEBUG_INFO("Gun-%d : StopReason [ %s ]...\n",gun_index,ShmOCPP16Data->StopTransaction[gun_index].StopReason);
  4145. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  4146. presentChargedEnergyUpdate(gun_index);
  4147. DEBUG_INFO("PresentChargedEnergy Gun-[%d] : %.4f \n",gun_index ,ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy);
  4148. ShmOCPP16Data->CpMsg.bits[gun_index].StopTransactionReq = ON;
  4149. }
  4150. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  4151. {
  4152. memset(ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, 0x00, ARRAY_SIZE(ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken));
  4153. if(!ocpp_get_starttransaction_result(gun_index))
  4154. {
  4155. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "DeAuthorized");
  4156. }
  4157. else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_EMERGENCY_STOP)
  4158. {
  4159. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "EmergencyStop");
  4160. }
  4161. else if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)
  4162. {
  4163. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "EVDisconnected");
  4164. memcpy((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId));
  4165. }
  4166. else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_GROUND_FAIL)
  4167. {
  4168. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "GroundFault");
  4169. }
  4170. else if(ShmOCPP20Data->MsMsg.bits.ResetReq)
  4171. {
  4172. if(strcmp((char*)ShmOCPP20Data->Reset.type, "Immediate")==0)
  4173. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "ImmediateReset");
  4174. else
  4175. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "OnIdle");
  4176. }
  4177. else if(ShmCharger->gun_info[gun_index].rfidReq || ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop)
  4178. {
  4179. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Local");
  4180. if(!isMatchStartUser(gun_index))
  4181. {
  4182. memcpy((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, (char*)ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken));
  4183. }
  4184. else
  4185. {
  4186. memcpy((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId));
  4187. }
  4188. DEBUG_INFO("Gun-%d [ idToken ] : %s \n", gun_index, ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken);
  4189. }
  4190. else if((ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_L1_OVER_CURRENT) ||
  4191. (ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_L2_OVER_CURRENT) ||
  4192. (ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_L3_OVER_CURRENT))
  4193. {
  4194. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "OvercurrentFault");
  4195. }
  4196. else if(ShmOCPP20Data->CsMsg.bits[gun_index].RequestStopTransactionReq)
  4197. {
  4198. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Remote");
  4199. }
  4200. else if(ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor == ON)
  4201. {
  4202. sprintf((char*)ShmOCPP20Data->TransactionEvent[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].transactionInfo.stoppedReason, "UnlockCommand");
  4203. }
  4204. else
  4205. {
  4206. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Other");
  4207. }
  4208. DEBUG_INFO("Gun-%d : StopReason [ %s ]...\n", gun_index, ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason);
  4209. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  4210. presentChargedEnergyUpdate(gun_index);
  4211. DEBUG_INFO("PresentChargedEnergy Gun-[%d] : %.4f \n",gun_index ,ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy);
  4212. ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventReq = ON;
  4213. }
  4214. // Maintain server
  4215. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.MaintainServerURL,"") != 0)
  4216. {
  4217. memcpy(ShmOCPP16DataPH->StopTransaction[gun_index].StopReason, ShmOCPP16Data->StopTransaction[gun_index].StopReason, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].StopReason));
  4218. memcpy(ShmOCPP16DataPH->StopTransaction[gun_index].IdTag, ShmOCPP16Data->StopTransaction[gun_index].IdTag, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  4219. ShmOCPP16DataPH->CpMsg.bits[gun_index].StopTransactionReq = ON;
  4220. }
  4221. }
  4222. void checkRemoteUpgradeStatus()
  4223. {
  4224. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  4225. {
  4226. if(strcmp((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "DownloadFailed")==0)
  4227. {
  4228. DEBUG_INFO("Firmware remote upgraded fail...\n");
  4229. ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq = OFF;
  4230. ShmCharger->isUpdateSuccess = NO;
  4231. }
  4232. else if(strcmp((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Downloaded")==0)
  4233. {
  4234. DEBUG_INFO("Firmware remote upgrading...\n");
  4235. sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installing");
  4236. sleep(1);
  4237. ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  4238. ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq = OFF;
  4239. if(upgrade_check() == PASS)
  4240. {
  4241. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == ON)
  4242. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = OFF;
  4243. ShmCharger->isUpdateSuccess = YES;
  4244. DEBUG_INFO("Remote update success.\n");
  4245. }
  4246. else
  4247. {
  4248. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == OFF)
  4249. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = ON;
  4250. ShmCharger->isUpdateSuccess = NO;
  4251. DEBUG_INFO("Remote update fail.\n");
  4252. }
  4253. }
  4254. else
  4255. {}
  4256. }
  4257. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  4258. {
  4259. if(strcmp((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "DownloadFailed")==0)
  4260. {
  4261. DEBUG_INFO("Firmware remote upgraded fail...\n");
  4262. ShmOCPP20Data->MsMsg.bits.UpdateFirmwareReq = OFF;
  4263. ShmCharger->isUpdateSuccess = NO;
  4264. }
  4265. else if(strcmp((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "Downloaded")==0)
  4266. {
  4267. DEBUG_INFO("Firmware remote upgrading...\n");
  4268. sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installing");
  4269. ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  4270. ShmOCPP20Data->MsMsg.bits.UpdateFirmwareReq = OFF;
  4271. if(upgrade_check() == PASS)
  4272. {
  4273. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == ON)
  4274. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = OFF;
  4275. ShmCharger->isUpdateSuccess = YES;
  4276. DEBUG_INFO("Remote update success.\n");
  4277. }
  4278. else
  4279. {
  4280. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == OFF)
  4281. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = ON;
  4282. ShmCharger->isUpdateSuccess = NO;
  4283. DEBUG_INFO("Remote update fail.\n");
  4284. }
  4285. }
  4286. else
  4287. {}
  4288. }
  4289. }
  4290. void checkHandshakeTime()
  4291. {
  4292. // Handskake timer needs to refresh
  4293. if(ShmCharger->gun_info[ShmCharger->gun_selectd].isHandshakeTimerRefresh == YES)
  4294. refreshStartTimer(&startTime[0][TMR_IDX_GUN_DETECT]);
  4295. // Timer for lcm to shows
  4296. ShmCharger->timeoutSpec.Handshake_Timeout = (ocpp_get_connection_timeout() - getDiffSecNow(startTime[0][TMR_IDX_GUN_DETECT]));
  4297. }
  4298. void checkRfidAuthrize()
  4299. {
  4300. static uint8_t isCheckdResult = FALSE;
  4301. if(!ShmCharger->isAuthrizing)
  4302. {
  4303. // Read RFID
  4304. if(GetCardSerialNumber() != FAIL)
  4305. {
  4306. uint8_t isSnStart = FALSE;
  4307. uint8_t bufferRFID[ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId)];
  4308. if(ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian)
  4309. {
  4310. // Big endian
  4311. switch(rfid.snType)
  4312. {
  4313. case RFID_SN_TYPE_6BYTE:
  4314. sprintf((char*)bufferRFID, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5]);
  4315. break;
  4316. case RFID_SN_TYPE_7BYTE:
  4317. sprintf((char*)bufferRFID, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6]);
  4318. break;
  4319. case RFID_SN_TYPE_10BYTE:
  4320. sprintf((char*)bufferRFID, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3], rfid.currentCard[4], rfid.currentCard[5], rfid.currentCard[6], rfid.currentCard[7], rfid.currentCard[8], rfid.currentCard[9]);
  4321. break;
  4322. case RFID_SN_TYPE_4BYTE:
  4323. default:
  4324. sprintf((char*)bufferRFID, "%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3]);
  4325. break;
  4326. }
  4327. }
  4328. else
  4329. {
  4330. // Little endian
  4331. switch(rfid.snType)
  4332. {
  4333. case RFID_SN_TYPE_6BYTE:
  4334. sprintf((char*)bufferRFID, "%02X%02X%02X%02X%02X%02X", rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  4335. break;
  4336. case RFID_SN_TYPE_7BYTE:
  4337. sprintf((char*)bufferRFID, "%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  4338. break;
  4339. case RFID_SN_TYPE_10BYTE:
  4340. sprintf((char*)bufferRFID, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", rfid.currentCard[9], rfid.currentCard[8], rfid.currentCard[7], rfid.currentCard[6], rfid.currentCard[5], rfid.currentCard[4], rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  4341. break;
  4342. case RFID_SN_TYPE_4BYTE:
  4343. default:
  4344. sprintf((char*)bufferRFID, "%02X%02X%02X%02X", rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  4345. break;
  4346. }
  4347. }
  4348. DEBUG_INFO("Authorize request User Id : %s\n", bufferRFID);
  4349. //DEBUG_INFO("Authorize request User Id : %s\n", ShmSysConfigAndInfo->SysConfig.UserId);
  4350. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4351. ShmCharger->gun_info[gun_index].resultAuthorization = UNKNOW_RFID;
  4352. // Check SN already start
  4353. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4354. {
  4355. if(isMatchStartUser(gun_index) || (isMatchPresentUser(gun_index) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_PREPARING)))
  4356. {
  4357. DEBUG_INFO("%s running on connector-%02d.\n", ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, gun_index);
  4358. isSnStart = TRUE;
  4359. ShmCharger->gun_info[gun_index].rfidReq = ON;
  4360. ocpp_set_auth_conf(ON);
  4361. setLedMotion(gun_index,LED_ACTION_RFID_PASS);
  4362. setSpeaker(ON, SPEAKER_SHORT);
  4363. sleep(3);
  4364. break;
  4365. }
  4366. }
  4367. // Request authorize if isSnStart is false
  4368. if(!isSnStart)
  4369. {
  4370. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, bufferRFID, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  4371. refreshStartTimer(&startTime[0][TMR_IDX_AUTH]);
  4372. ocpp_set_auth_conf(OFF);
  4373. ocpp_set_auth_req(ON, "ISO14443");
  4374. setLedMotion(0,LED_ACTION_AUTHED);
  4375. ShmCharger->isAuthrizing = TRUE;
  4376. ShmCharger->isGetAuthResult = FALSE;
  4377. isCheckdResult = FALSE;
  4378. //sleep(1);
  4379. }
  4380. }
  4381. }
  4382. else
  4383. {
  4384. // Wait authorize result
  4385. if(!ocpp_get_auth_conf() && (getDiffSecNow(startTime[0][TMR_IDX_AUTH]) > TIMEOUT_SPEC_AUTH))
  4386. {
  4387. // Authorization timeout process.
  4388. DEBUG_WARN("Authorize timeout !!!\n");
  4389. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4390. {
  4391. ShmCharger->gun_info[gun_index].resultAuthorization = UNVALIDATED_RFID;
  4392. setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
  4393. }
  4394. setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
  4395. sleep(3);
  4396. ShmCharger->isAuthrizing = FALSE;
  4397. }
  4398. else
  4399. {
  4400. if(ocpp_get_auth_conf() ||
  4401. (!ocpp_get_connection_status() && ((ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE) || (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_NOCHARGE))) ||
  4402. (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST) && (getDiffSecNow(startTime[0][TMR_IDX_AUTH]) > 2))
  4403. )
  4404. {
  4405. if(ocpp_get_auth_result(NO) ||
  4406. (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE)) ||
  4407. (!ocpp_get_connection_status() && (isValidLocalWhiteCard() == PASS) && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST)))
  4408. {
  4409. if(!isCheckdResult)
  4410. {
  4411. DEBUG_INFO("Authorize pass.\n");
  4412. setSpeaker(ON, SPEAKER_SHORT);
  4413. refreshStartTimer(&startTime[0][TMR_IDX_GUN_DETECT]);
  4414. ShmCharger->isGetAuthResult = TRUE;
  4415. isCheckdResult = TRUE;
  4416. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0)
  4417. {
  4418. ocpp_set_auth_conf(ON);
  4419. }
  4420. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4421. ShmCharger->gun_info[gun_index].resultAuthorization = VALIDATED_RFID;
  4422. }
  4423. if(getDiffSecNow(startTime[0][TMR_IDX_GUN_DETECT]) < ocpp_get_connection_timeout())
  4424. {
  4425. checkHandshakeTime();
  4426. if(GetCardSerialNumber() != FAIL)
  4427. {
  4428. if(isMatchPresentUser())
  4429. {
  4430. DEBUG_INFO("Cancel present user.\n");
  4431. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4432. {
  4433. setLedMotion(gun_index,LED_ACTION_IDLE);
  4434. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  4435. }
  4436. ShmCharger->isAuthrizing = FALSE;
  4437. }
  4438. }
  4439. else
  4440. {
  4441. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4442. {
  4443. if(getDiffSecNow(startTime[0][TMR_IDX_GUN_DETECT]) < 3)
  4444. setLedMotion(gun_index,LED_ACTION_RFID_PASS);
  4445. else
  4446. setLedMotion(gun_index,LED_ACTION_AUTHED);
  4447. if((((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_IDLE) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_RESERVATION)) && (((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)) || (ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn == ON))) ||
  4448. ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_PREPARING) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B) && (ShmCharger->gun_selectd == gun_index)) ||
  4449. (((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_CHARGING) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_TERMINATING)) && (ShmCharger->gun_selectd == gun_index))
  4450. )
  4451. {
  4452. DEBUG_INFO("Connector-%02d action detect.\n", gun_index);
  4453. ShmCharger->isAuthrizing = FALSE;
  4454. ShmCharger->gun_info[gun_index].rfidReq = ON;
  4455. break;
  4456. }
  4457. }
  4458. }
  4459. }
  4460. else
  4461. {
  4462. DEBUG_INFO("Connector action detect timeout.\n");
  4463. ShmCharger->isAuthrizing = FALSE;
  4464. ShmCharger->isGetAuthResult = TRUE;
  4465. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4466. {
  4467. setLedMotion(gun_index,LED_ACTION_IDLE);
  4468. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  4469. }
  4470. }
  4471. }
  4472. else
  4473. {
  4474. DEBUG_INFO("Authorize fail.\n");
  4475. ShmCharger->isAuthrizing = FALSE;
  4476. ShmCharger->isGetAuthResult = TRUE;
  4477. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4478. {
  4479. ShmCharger->gun_info[gun_index].resultAuthorization = UNVALIDATED_RFID;
  4480. setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
  4481. }
  4482. setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
  4483. sleep(3);
  4484. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4485. {
  4486. setLedMotion(gun_index,LED_ACTION_IDLE);
  4487. }
  4488. }
  4489. }
  4490. }
  4491. }
  4492. }
  4493. //======================================================
  4494. // Main process
  4495. //======================================================
  4496. int main(void)
  4497. {
  4498. //==================================================
  4499. // Create all share memory
  4500. //==================================================
  4501. if(CreatShareMemory()==0)
  4502. {
  4503. DEBUG_ERROR("CreatShareMemory NG\n");
  4504. if(ShmStatusCodeData!=NULL)
  4505. {
  4506. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=1;
  4507. }
  4508. sleep(5);
  4509. system("reboot -f");
  4510. sleep(5);
  4511. system("reboot -f");
  4512. }
  4513. else
  4514. {
  4515. LoadSysConfigAndInfo(&ShmSysConfigAndInfo->SysConfig);
  4516. DEBUG_INFO("CreatShareMemory OK\n");
  4517. }
  4518. if(SpawnTask() != PASS)
  4519. {
  4520. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = ON;
  4521. DEBUG_ERROR("Task spawn fail.\n");
  4522. }
  4523. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  4524. {
  4525. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus = 0xff;
  4526. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].Index = 0xff;
  4527. ShmCharger->gun_info[gun_index].primaryMcuState.rotatory_switch = 0xff;
  4528. ShmCharger->gun_info[gun_index].mcuResetRequest.isMcuResetRequest = ON;
  4529. ShmCharger->gun_info[gun_index].isSetBreatheLedTiming = OFF;
  4530. ShmCharger->gun_info[gun_index].isSetLedBrightness = OFF;
  4531. ShmCharger->gun_selectd = 0;
  4532. }
  4533. //==================================================
  4534. // Main loop
  4535. //==================================================
  4536. for(;;)
  4537. {
  4538. //==============================================
  4539. // Period check for 10 seconds
  4540. //==============================================
  4541. if(getDiffSecNow(startTime[0][TMR_IDX_CHECK_TASK]) > 10)
  4542. {
  4543. //==============================================
  4544. // Check task processing
  4545. //==============================================
  4546. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[0].SystemStatus != SYS_MODE_BOOTING)
  4547. checkTask();
  4548. //==============================================
  4549. // Check connection timeout specification
  4550. //==============================================
  4551. checkConnectionTimeout();
  4552. refreshStartTimer(&startTime[0][TMR_IDX_CHECK_TASK]);
  4553. }
  4554. //==============================================
  4555. // Check remote reset request
  4556. //==============================================
  4557. checkReset();
  4558. //==============================================
  4559. // Connector loop
  4560. //==============================================
  4561. /*
  4562. * TODO:
  4563. * 1. Rotary switch define change with system specification
  4564. */
  4565. // Only process main logic on cabinet
  4566. if(ShmDispenser->gun_info.primaryMcuState.rotatory_switch != ROTARY_SWITCH_E_DISPENSER)
  4567. {
  4568. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4569. {
  4570. //==============================================
  4571. // Synchronize share memory from OCPP struct
  4572. //==============================================
  4573. ShmSysConfigAndInfo->SysInfo.OcppConnStatus = ocpp_get_connection_status();
  4574. //==============================================
  4575. // Check RFID authorization
  4576. //==============================================
  4577. // The user is not allowed to use RFID when the system change to under those modes.
  4578. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_ALARM) &&
  4579. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_FAULT) &&
  4580. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_DEBUG) &&
  4581. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_UPDATE) &&
  4582. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_BOOTING) &&
  4583. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_COMPLETE) &&
  4584. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_MAINTAIN))
  4585. {
  4586. checkRfidAuthrize();
  4587. }
  4588. //==============================================
  4589. // Something need run in Idle mode
  4590. //==============================================
  4591. if(((ShmSysConfigAndInfo->SysInfo.AcChargingData[0].SystemStatus==SYS_MODE_IDLE) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[0].SystemStatus==SYS_MODE_ALARM) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[0].SystemStatus==SYS_MODE_DEBUG)) &&
  4592. ((modelnameInfo.GetGunCount==2)?((ShmSysConfigAndInfo->SysInfo.AcChargingData[1].SystemStatus==SYS_MODE_IDLE) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[1].SystemStatus==SYS_MODE_ALARM) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[1].SystemStatus==SYS_MODE_DEBUG)):true) &&
  4593. ((modelnameInfo.GetGunCount==3)?((ShmSysConfigAndInfo->SysInfo.AcChargingData[2].SystemStatus==SYS_MODE_IDLE) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[2].SystemStatus==SYS_MODE_ALARM) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[2].SystemStatus==SYS_MODE_DEBUG)):true))
  4594. {
  4595. // Check restore factory setting request
  4596. if(ShmSysConfigAndInfo->SysInfo.FactoryConfiguration)
  4597. {
  4598. // Set led to initial
  4599. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4600. {
  4601. setLedMotion(gun_index,LED_ACTION_INIT);
  4602. }
  4603. sleep(5);
  4604. system("cd /root;./Module_FactoryConfig -m");
  4605. system("rm -f /Storage/OCPP/OCPPConfiguration");
  4606. system("sync");
  4607. sleep(5);
  4608. system("reboot -f");
  4609. sleep(5);
  4610. system("reboot -f");
  4611. }
  4612. // Check upgrade firmware request
  4613. if(ShmSysConfigAndInfo->SysInfo.FirmwareUpdate ||
  4614. ocpp_get_update_firmware_req())
  4615. {
  4616. // If available memory too small, free memory cache first
  4617. if(getAvailableMemory() < (200*1024*1024))
  4618. {
  4619. DEBUG_INFO("Available memory (%.2f Bytes) less than 200 MBytes, free cache first.\n", getAvailableMemory()/(1024*1024.0));
  4620. system("echo 3 > /proc/sys/vm/drop_caches");
  4621. }
  4622. ShmCharger->isUpdateSuccess = NO;
  4623. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4624. {
  4625. setLedMotion(gun_index,LED_ACTION_MAINTAIN);
  4626. setChargerMode(gun_index, SYS_MODE_UPDATE);
  4627. }
  4628. }
  4629. }
  4630. //==========================================
  4631. // Power saving logic
  4632. //==========================================
  4633. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus > SYS_MODE_BOOTING)
  4634. {
  4635. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)
  4636. {
  4637. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_STATE_B]);
  4638. }
  4639. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_ALARM) ||
  4640. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_FAULT) ||
  4641. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_UPDATE) ||
  4642. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_MAINTAIN) ||
  4643. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_CHARGING) ||
  4644. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_TERMINATING) ||
  4645. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_COMPLETE))
  4646. {
  4647. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
  4648. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_RFID]);
  4649. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_METER]);
  4650. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]);
  4651. }
  4652. else
  4653. {
  4654. if((ShmCharger->gun_info[ShmCharger->gun_selectd].isHandshakeTimerRefresh == YES) ||
  4655. (gpio_get_value(GPIO_IN_WAKEUP) == OFF) ||
  4656. (ShmCharger->gun_info[gun_index].GPIO_Input.Button_Mode_Switch == ON) ||
  4657. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus != ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus) ||
  4658. (((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_IDLE) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_PREPARING) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_RESERVATION)) &&
  4659. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B) &&
  4660. (getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_STATE_B]) < 10)))
  4661. {
  4662. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
  4663. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_RFID]);
  4664. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_METER]);
  4665. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]);
  4666. if(((gpio_get_value(GPIO_IN_WAKEUP) == OFF) || (ShmCharger->gun_info[gun_index].GPIO_Input.Button_Mode_Switch == ON)) &&
  4667. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_IDLE) &&
  4668. (getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_CHECK_POWER_CONSUMPTION]) > TIMEOUT_SPEC_CEHCK_POWER_CONSUMPTION))
  4669. {
  4670. ShmCharger->gun_info[gun_index].isCheckPowerConsumption = YES;
  4671. refreshStartTimer(&startTime[gun_index][TMR_IDX_LCM_POWER_CONSUMPTION]);
  4672. }
  4673. }
  4674. else
  4675. {
  4676. refreshStartTimer(&startTime[gun_index][TMR_IDX_CHECK_POWER_CONSUMPTION]);
  4677. if((getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_LCM_POWER_CONSUMPTION]) > TIMEOUT_SPEC_CEHCK_POWER_CONSUMPTION))
  4678. {
  4679. ShmCharger->gun_info[gun_index].isCheckPowerConsumption = NO;
  4680. }
  4681. }
  4682. }
  4683. if(getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_LCD]) > TIMEOUT_SPEC_POWERSAVING_LCD)
  4684. {
  4685. if(ShmCharger->isLcdOn == ON)
  4686. {
  4687. DEBUG_INFO("LCD into power saving...%d\n", getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_LCD]));
  4688. ShmCharger->isLcdOn = OFF;
  4689. }
  4690. }
  4691. else
  4692. {
  4693. if(ShmCharger->isLcdOn == OFF)
  4694. {
  4695. DEBUG_INFO("LCD exit power saving...%d\n", getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_LCD]));
  4696. ShmCharger->isLcdOn = ON;
  4697. }
  4698. }
  4699. if(getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_RFID]) > TIMEOUT_SPEC_POWERSAVING_RFID)
  4700. {
  4701. if(gpio_get_value(GPIO_OUT_RST_RFID) == ON)
  4702. {
  4703. DEBUG_INFO("RFID into power saving...%d\n", getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_RFID]));
  4704. gpio_set_value(GPIO_OUT_RST_RFID, OFF);
  4705. }
  4706. }
  4707. else
  4708. {
  4709. if(gpio_get_value(GPIO_OUT_RST_RFID) == OFF)
  4710. {
  4711. DEBUG_INFO("RFID exit power saving...%d\n", getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_RFID]));
  4712. gpio_set_value(GPIO_OUT_RST_RFID, ON);
  4713. }
  4714. }
  4715. if(getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_METER]) > TIMEOUT_SPEC_POWERSAVING_METER)
  4716. {
  4717. if(ShmCharger->gun_info[gun_index].isMeterOn)
  4718. {
  4719. DEBUG_INFO("Meter into power saving...%d\n", getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_METER]));
  4720. ShmCharger->gun_info[gun_index].isMeterOn = OFF;
  4721. }
  4722. }
  4723. else
  4724. {
  4725. if(!ShmCharger->gun_info[gun_index].isMeterOn)
  4726. {
  4727. DEBUG_INFO("Meter exit power saving...%d\n", getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_METER]));
  4728. ShmCharger->gun_info[gun_index].isMeterOn = ON;
  4729. }
  4730. }
  4731. if(getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]) > TIMEOUT_SPEC_POWERSAVING_LED_STATUS)
  4732. {
  4733. if(ShmCharger->gun_info[gun_index].isSleepOn == NO)
  4734. {
  4735. DEBUG_INFO("LED status into power saving...%d\n", getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]));
  4736. ShmCharger->gun_info[gun_index].isSleepOn = YES;
  4737. }
  4738. }
  4739. else
  4740. {
  4741. if(ShmCharger->gun_info[gun_index].isSleepOn == YES)
  4742. {
  4743. DEBUG_INFO("LED status exit power saving...%d\n", getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]));
  4744. ShmCharger->gun_info[gun_index].isSleepOn = NO;
  4745. }
  4746. }
  4747. }
  4748. //==========================================
  4749. // Synchronize current rating value from MCU
  4750. //==========================================
  4751. ShmSysConfigAndInfo->SysConfig.RatingCurrent = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
  4752. //==========================================
  4753. // Assign connector location index for OCPP
  4754. //==========================================
  4755. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].Index = gun_index;
  4756. //==========================================
  4757. // Synchronize present charging power
  4758. //==========================================
  4759. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount == 1)
  4760. {
  4761. if(ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON)
  4762. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingVoltage*ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrent)/1000.0;
  4763. else
  4764. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = 0;
  4765. }
  4766. else
  4767. {
  4768. if(ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON)
  4769. {
  4770. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = (((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingVoltage*ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrent)/1000.0) +
  4771. ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingVoltageL2*ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrentL2)/1000.0) +
  4772. ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingVoltageL3*ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrentL3)/1000.0));
  4773. }
  4774. else
  4775. {
  4776. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = 0;
  4777. }
  4778. }
  4779. //==========================================
  4780. // Check initialization "PASS" or "FAIL"
  4781. //==========================================
  4782. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[0].SystemStatus != SYS_MODE_BOOTING)
  4783. {
  4784. // Alarm event check
  4785. if((ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode>0) || ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CCSboardStestFail || ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAcOutputOCP)
  4786. {
  4787. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_ALARM)
  4788. {
  4789. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_UPDATE)
  4790. {
  4791. setChargerMode(gun_index, SYS_MODE_ALARM);
  4792. }
  4793. }
  4794. }
  4795. }
  4796. //==========================================
  4797. // Reservation request check
  4798. //==========================================
  4799. checkReservation(gun_index);
  4800. //==========================================
  4801. // Change availability check
  4802. //==========================================
  4803. checkAvailability(gun_index);
  4804. if(ShmCharger->gun_info[gun_index].isOperactive)
  4805. {
  4806. if(isMode(gun_index, SYS_MODE_MAINTAIN))
  4807. {
  4808. setChargerMode(gun_index, SYS_MODE_IDLE);
  4809. }
  4810. }
  4811. else
  4812. {
  4813. if(isMode(gun_index, SYS_MODE_IDLE))
  4814. {
  4815. setChargerMode(gun_index, SYS_MODE_MAINTAIN);
  4816. }
  4817. }
  4818. //==========================================
  4819. // Unlock Connector signal check
  4820. //==========================================
  4821. checkUnlocker(gun_index);
  4822. //==========================================
  4823. // Connector process
  4824. //==========================================
  4825. switch(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus)
  4826. {
  4827. case SYS_MODE_BOOTING:
  4828. if(isModeChange(gun_index))
  4829. {
  4830. setLedMotion(gun_index,LED_ACTION_INIT);
  4831. //CSU Initialization & task spawn
  4832. if(Initialization(gun_index) != PASS)
  4833. {
  4834. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = ON;
  4835. }
  4836. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
  4837. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_RFID]);
  4838. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_METER]);
  4839. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_STATE_B]);
  4840. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]);
  4841. refreshStartTimer(&startTime[gun_index][TMR_IDX_LCM_POWER_CONSUMPTION]);
  4842. }
  4843. if(ShmCharger->gun_info[gun_index].mcuFlag.isReadFwVerPass &&
  4844. ShmCharger->gun_info[gun_index].mcuFlag.isSetModelNamePass &&
  4845. ShmCharger->gun_info[gun_index].mcuFlag.isSetSerialNumberPass)
  4846. {
  4847. // OCPP BootNotification info set
  4848. DEBUG_INFO("==========================================\n");
  4849. DEBUG_INFO("System ID: %s\n",ShmSysConfigAndInfo->SysConfig.SystemId);
  4850. DEBUG_INFO("==========================================\n");
  4851. DEBUG_INFO("=== OCPP BootNotification information ====\n");
  4852. ocpp_boot_info_sync();
  4853. DEBUG_INFO("OcppServerURL: %s\n",ShmSysConfigAndInfo->SysConfig.OcppServerURL);
  4854. DEBUG_INFO("ChargeBoxId: %s\n",ShmSysConfigAndInfo->SysConfig.ChargeBoxId);
  4855. DEBUG_INFO("ChargePointVendor: %s\n",ShmSysConfigAndInfo->SysConfig.chargePointVendor);
  4856. DEBUG_INFO("==========================================\n");
  4857. DEBUG_INFO("========== Set Wifi information ==========\n");
  4858. DEBUG_INFO("Wifi mode: %d\n", ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode);
  4859. DEBUG_INFO("Wifi SSID: %s\n", ShmSysConfigAndInfo->SysConfig.AthInterface.WifiSsid);
  4860. DEBUG_INFO("Wifi password: %s\n", ShmSysConfigAndInfo->SysConfig.AthInterface.WifiPassword);
  4861. DEBUG_INFO("==========================================\n");
  4862. // Default Ethernet / Wifi / 4G to 1:disconnected
  4863. switch(ShmSysConfigAndInfo->SysConfig.ModelName[10])
  4864. {
  4865. case 'E':
  4866. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
  4867. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = OFF;
  4868. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = OFF;
  4869. break;
  4870. case 'W':
  4871. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
  4872. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = ON;
  4873. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = OFF;
  4874. break;
  4875. case 'T':
  4876. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
  4877. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = OFF;
  4878. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = ON;
  4879. break;
  4880. case 'D':
  4881. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
  4882. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = ON;
  4883. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = ON;
  4884. break;
  4885. }
  4886. // Default LCM brightness to 100
  4887. ShmCharger->isLcdOn = ON;
  4888. // Defaule led status to not sleep mode
  4889. ShmCharger->gun_info[gun_index].isSleepOn = NO;
  4890. // If Web Server OPCC URL is empty kill Module_OcppBackend
  4891. if((strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0) || ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharging)
  4892. {
  4893. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0)
  4894. DEBUG_INFO("URL is empty kill Module_OcppBackend...\n");
  4895. if(ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharging)
  4896. DEBUG_INFO("Local power sharing enable kill Module_OcppBackend...\n");
  4897. system ("pkill OcppBackend");
  4898. }
  4899. // If rotate switch equal zero, the system needs to change Debug mode
  4900. if(ShmCharger->gun_info[gun_index].primaryMcuState.rotatory_switch == 0)
  4901. setChargerMode(gun_index, SYS_MODE_DEBUG);
  4902. else
  4903. {
  4904. if((isGpioInitialized(GPIO_OUT_RST_RFID) == PASS) &&
  4905. (isGpioInitialized(GPIO_IN_WAKEUP) == PASS) &&
  4906. (isGpioInitialized(GPIO_OUT_RST_ETH) == PASS) &&
  4907. (isGpioInitialized(GPIO_OUT_RST_4G) == PASS) &&
  4908. (isGpioInitialized(GPIO_OUT_RST_QCA) == PASS))
  4909. {
  4910. //==================================================
  4911. // Get firmware version
  4912. //==================================================
  4913. sleep(3);
  4914. get_firmware_version(gun_index);
  4915. setChargerMode(gun_index, SYS_MODE_IDLE);
  4916. }
  4917. }
  4918. }
  4919. break;
  4920. case SYS_MODE_IDLE:
  4921. if(isModeChange(gun_index))
  4922. {
  4923. setLedMotion(gun_index,LED_ACTION_IDLE);
  4924. setRelay(gun_index, OFF);
  4925. setRequest(gun_index,OFF);
  4926. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  4927. ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart = OFF;
  4928. ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop = OFF;
  4929. ocpp_set_remotestart(gun_index, OFF);
  4930. ocpp_set_remotestop(gun_index, OFF);
  4931. ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode = 0x00;
  4932. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = 0;
  4933. presentChargedEnergyClear(gun_index);
  4934. ShmCharger->gun_info[gun_index].targetCurrent = 0xFF;
  4935. ocpp_set_unlocker_req(gun_index, OFF);
  4936. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId = -1;
  4937. // Response StopTransactionConf
  4938. ocpp_set_stoptransaction_conf(gun_index, OFF);
  4939. memset(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId));
  4940. ShmCharger->gun_info[gun_index].isDoEvReadyOnce = OFF;
  4941. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  4942. DB_Check_Record_Buf(localDb, gun_index);
  4943. }
  4944. // LED status in Idle mode
  4945. if(!ShmCharger->isAuthrizing)
  4946. {
  4947. if(ocpp_get_isRemoteStartWait())
  4948. {
  4949. ShmCharger->gun_info[gun_index].isSleepOn = OFF;
  4950. setLedMotion(gun_index, LED_ACTION_AUTHED);
  4951. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
  4952. checkHandshakeTime();
  4953. }
  4954. else
  4955. {
  4956. if(ShmSysConfigAndInfo->SysInfo.OcppConnStatus == ON)
  4957. {
  4958. if(ShmCharger->gun_info[gun_index].rfidReq == OFF)
  4959. {
  4960. if(ShmCharger->gun_info[gun_index].isSleepOn == NO)
  4961. setLedMotion(gun_index, LED_ACTION_IDLE_BACKEND_CONNECTED);
  4962. else
  4963. setLedMotion(gun_index, LED_ACTION_IDLE_BACKEND_CONNECTED_SLEEP);
  4964. }
  4965. }
  4966. else
  4967. {
  4968. if(ShmCharger->gun_info[gun_index].rfidReq == OFF)
  4969. {
  4970. if(ShmCharger->gun_info[gun_index].isSleepOn == NO)
  4971. setLedMotion(gun_index, LED_ACTION_IDLE_BACKEND_DISCONNECTED);
  4972. else
  4973. setLedMotion(gun_index, LED_ACTION_IDLE_BACKEND_DISCONNECTED_SLEEP);
  4974. }
  4975. }
  4976. }
  4977. }
  4978. if(((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B)) ||
  4979. ((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)) ||
  4980. ((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) && (ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn == ON)) ||
  4981. (ShmCharger->gun_info[gun_index].rfidReq == ON) ||
  4982. (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart == ON) ||
  4983. (ocpp_get_remotestart(gun_index) == ON) ||
  4984. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStart == ON))
  4985. {
  4986. if((ShmCharger->gun_info[gun_index].rfidReq == ON))
  4987. {
  4988. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_RFID;
  4989. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_ISO14443;
  4990. DEBUG_INFO("Start Method : RFID...\n");
  4991. }
  4992. else if(ocpp_get_remotestart(gun_index))
  4993. {
  4994. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_BACKEND;
  4995. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_Central;
  4996. ocpp_copy_userid_from_remotestart(gun_index);
  4997. setSpeaker(ON, SPEAKER_SHORT);
  4998. DEBUG_INFO("Start Method : BACKEND...\n");
  4999. }
  5000. else if(ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart == ON)
  5001. {
  5002. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_BLE;
  5003. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_Local;
  5004. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmCharger->gun_info[gun_index].bleLoginCentralId.id, ARRAY_SIZE(ShmCharger->gun_info[gun_index].bleLoginCentralId.id));
  5005. setSpeaker(ON, SPEAKER_SHORT);
  5006. DEBUG_INFO("Start Method : BLE...\n");
  5007. }
  5008. else
  5009. {
  5010. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_FREE;
  5011. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_NoAuthorization;
  5012. //memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmSysConfigAndInfo->SysConfig.SerialNumber, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SerialNumber));
  5013. ocpp_get_freevend_idtag(ShmSysConfigAndInfo->SysConfig.UserId);
  5014. setSpeaker(ON, SPEAKER_SHORT);
  5015. DEBUG_INFO("Start Method : FREE...\n");
  5016. }
  5017. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  5018. ocpp_set_remotestart(gun_index, OFF);
  5019. ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart = OFF;
  5020. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStart = OFF;
  5021. // Get target current
  5022. ocpp_set_profile_req(gun_index, ON);
  5023. sleep(1);
  5024. checkChargingProfileLimit(gun_index);
  5025. setChargerMode(gun_index, SYS_MODE_AUTHORIZING);
  5026. }
  5027. else
  5028. {}
  5029. break;
  5030. case SYS_MODE_AUTHORIZING:
  5031. if(isModeChange(gun_index))
  5032. {
  5033. refreshStartTimer(&startTime[gun_index][TMR_IDX_AUTH]);
  5034. if(ocpp_isAuthorizeRemoteStart() && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod == START_METHOD_BACKEND))
  5035. {
  5036. DEBUG_INFO("Remote start request authorize.\n");
  5037. ocpp_set_auth_req(ON, "ISO14443");
  5038. }
  5039. }
  5040. if(getDiffSecNow(startTime[gun_index][TMR_IDX_AUTH]) > TIMEOUT_SPEC_AUTH)
  5041. {
  5042. // Authorization timeout process.
  5043. setSpeaker(ON, SPEAKER_INTERVAL_3COUNT);
  5044. setLedMotion(gun_index, LED_ACTION_RFID_FAIL);
  5045. sleep(3);
  5046. setChargerMode(gun_index, SYS_MODE_IDLE);
  5047. DEBUG_WARN("Authorize timeout !!!\n");
  5048. }
  5049. else
  5050. {
  5051. switch(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod)
  5052. {
  5053. case START_METHOD_BACKEND:
  5054. if(ocpp_isAuthorizeRemoteStart())
  5055. {
  5056. if(ocpp_get_auth_conf())
  5057. {
  5058. if(ocpp_get_auth_result(gun_index))
  5059. {
  5060. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  5061. DEBUG_INFO("Authorize pass.\n");
  5062. setSpeaker(ON, SPEAKER_SHORT);
  5063. setLedMotion(gun_index, LED_ACTION_RFID_PASS);
  5064. setChargerMode(gun_index, SYS_MODE_PREPARING);
  5065. }
  5066. else
  5067. {
  5068. DEBUG_INFO("Authorize fail.\n");
  5069. setSpeaker(ON, SPEAKER_INTERVAL_3COUNT);
  5070. setLedMotion(gun_index, LED_ACTION_RFID_FAIL);
  5071. sleep(3);
  5072. setChargerMode(gun_index, SYS_MODE_IDLE);
  5073. }
  5074. ocpp_set_auth_conf(OFF);
  5075. }
  5076. }
  5077. else
  5078. {
  5079. setChargerMode(gun_index, SYS_MODE_PREPARING);
  5080. }
  5081. break;
  5082. case START_METHOD_RFID:
  5083. case START_METHOD_BLE:
  5084. case START_METHOD_FREE:
  5085. default:
  5086. setChargerMode(gun_index, SYS_MODE_PREPARING);
  5087. break;
  5088. }
  5089. }
  5090. break;
  5091. case SYS_MODE_PREPARING:
  5092. if(isModeChange(gun_index))
  5093. {
  5094. refreshStartTimer(&startTime[0][TMR_IDX_GUN_DETECT]);
  5095. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  5096. setLedMotion(gun_index, LED_ACTION_AUTHED);
  5097. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  5098. if(ShmCharger->isCcsEnable)refreshStartTimer(&startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]);
  5099. }
  5100. // If control pilot detect Bx, skip watch dog time out.
  5101. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B) ||
  5102. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C))
  5103. {
  5104. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  5105. if(!getRequest(gun_index))
  5106. {
  5107. setRequest(gun_index, ON);
  5108. setLedMotion(gun_index, LED_ACTION_CONNECTED);
  5109. DEBUG_INFO("Set Request On.\n");
  5110. }
  5111. switch(ShmCharger->gun_info[gun_index].ccsHandshakeState)
  5112. {
  5113. case HANDSHAKE_DUTY_5:
  5114. break;
  5115. case HANDSHAKE_DUTY_5_CHECK:
  5116. refreshStartTimer(&startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]);
  5117. DEBUG_INFO("HLC slac handshake start.\n");
  5118. break;
  5119. case HANDSHAKE_CCS:
  5120. //CCS handshake timeout
  5121. if(getDiffSecNow(startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]) > TIMEOUT_SPEC_BS_HLC_HANDSHAKE)
  5122. {
  5123. DEBUG_INFO("HLC %d secs slac handshake timeout.\n", TIMEOUT_SPEC_BS_HLC_HANDSHAKE);
  5124. }
  5125. if((ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission == OFF) && (ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty != CCS_PWM_DUTY_5))
  5126. {
  5127. DEBUG_INFO("Wait CCS give up negotiagting.\n");
  5128. }
  5129. //CCS status check
  5130. if((16 < ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus) && (ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus < 254))
  5131. {
  5132. DEBUG_INFO("Enter HLC Mode charging.\n");
  5133. }
  5134. break;
  5135. case HANDSHAKE_CP_STATE_E:
  5136. //if(ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)
  5137. {
  5138. // restore normal CP PWM duty
  5139. // Determine max charging current to MCU
  5140. DEBUG_INFO("Determine max charging current to MCU.\n");
  5141. ocpp_set_profile_req(gun_index, ON);
  5142. sleep(1);
  5143. checkChargingProfileLimit(gun_index);
  5144. }
  5145. break;
  5146. case HANDSHAKE_SET_MAX_CURRENT:
  5147. case HANDSHAKE_BS_MODE:
  5148. DEBUG_INFO("Enter BS Mode charging.\n");
  5149. checkChargingProfileLimit(gun_index);
  5150. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)
  5151. setRelay(gun_index,ON);
  5152. if((ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON) || (ShmCharger->gun_info[gun_index].targetCurrent == 0))
  5153. {
  5154. ocpp_set_unlocker_req(gun_index, OFF);
  5155. presentChargedEnergyClear(gun_index);
  5156. getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime);
  5157. ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption;
  5158. ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption;
  5159. ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption;
  5160. ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption;
  5161. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==1)
  5162. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  5163. else
  5164. {
  5165. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[0] = (ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption/10000.0);
  5166. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[1] = (ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption/10000.0);
  5167. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[2] = (ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption/10000.0);
  5168. }
  5169. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  5170. ocpp_copy_userid_to_starttransaction(gun_index);
  5171. ocpp_set_starttransaction_req(gun_index, ON);
  5172. refreshStartTimer(&startChargingTime[gun_index]);
  5173. setChargerMode(gun_index, SYS_MODE_CHARGING);
  5174. }
  5175. break;
  5176. case HANDSHAKE_HLC_MODE:
  5177. if(ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_START_MODE)//powerDelivery
  5178. {
  5179. if(ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn == OFF)
  5180. {
  5181. setRelay(gun_index,ON);
  5182. ShmCharger->gun_info[gun_index].isCCSStartTransation = ON;
  5183. DEBUG_INFO("HANDSHAKE_HLC_MODE:setRelay ON\n");
  5184. }
  5185. }
  5186. if((ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON) &&
  5187. (ShmCharger->gun_info[gun_index].isCCSStartTransation == ON))
  5188. {
  5189. DEBUG_INFO("HANDSHAKE_HLC_MODE:Relay ON done\n");
  5190. ocpp_set_unlocker_req(gun_index, OFF);
  5191. presentChargedEnergyClear(gun_index);
  5192. getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime);
  5193. ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption;
  5194. ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption;
  5195. ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption;
  5196. ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption;
  5197. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==1)
  5198. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  5199. else
  5200. {
  5201. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[0] = (ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption/10000.0);
  5202. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[1] = (ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption/10000.0);
  5203. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[2] = (ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption/10000.0);
  5204. }
  5205. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  5206. ocpp_copy_userid_to_starttransaction(gun_index);
  5207. ocpp_set_starttransaction_req(gun_index, ON);
  5208. ShmCharger->gun_info[gun_index].isCCSStartTransation = OFF;
  5209. setChargerMode(gun_index, SYS_MODE_CHARGING);
  5210. DEBUG_INFO("set SYS_MODE_CHARGING\n");
  5211. refreshStartTimer(&startChargingTime[gun_index]);
  5212. refreshStartTimer(&startTime[gun_index][TMR_IDX_CCS_HEARTBEAT_COUNT_RESET]);
  5213. }
  5214. //120 sec timeout
  5215. if(getDiffSecNow(startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]) > TIMEOUT_SPEC_CCS_HANDSHAKE)
  5216. {
  5217. setLedMotion(gun_index, LED_ACTION_HANDSHAKE_FAIL);
  5218. if(getDiffSecNow(startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]) > (TIMEOUT_SPEC_CCS_HANDSHAKE+5))
  5219. {
  5220. DEBUG_INFO("CCS 120 secs handshake timeout, change to BS Mode...\n");
  5221. if((ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission == OFF) && (ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty != CCS_PWM_DUTY_5))
  5222. {
  5223. DEBUG_INFO("Wait CCS give up negotiagting.\n");
  5224. }
  5225. }
  5226. }
  5227. break;
  5228. default:
  5229. break;
  5230. }
  5231. }
  5232. else if(ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEMode)
  5233. {
  5234. DEBUG_INFO("Enter Socket-E Mode charging.\n");
  5235. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_SOCKETE;
  5236. if(ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn == ON)
  5237. setRelay(gun_index,ON);
  5238. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  5239. ocpp_copy_userid_to_starttransaction(gun_index);
  5240. ocpp_set_starttransaction_req(gun_index, ON);
  5241. refreshStartTimer(&startChargingTime[gun_index]);
  5242. setChargerMode(gun_index, SYS_MODE_CHARGING);
  5243. }
  5244. // Unplug charging gun to Idle mode
  5245. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A) && (ShmCharger->gun_info[gun_index].isGunPlugged == YES))
  5246. {
  5247. DEBUG_INFO("Charging gun is plugged before.\n");
  5248. setChargerMode(gun_index, SYS_MODE_IDLE);
  5249. }
  5250. // Use RFID card to stop handshaking
  5251. if((ShmCharger->gun_info[gun_index].rfidReq == ON) && isMatchPresentUser(gun_index))
  5252. {
  5253. DEBUG_INFO("Use RFID card to stop handshaking.\n");
  5254. setChargerMode(gun_index, SYS_MODE_IDLE);
  5255. }
  5256. else
  5257. {
  5258. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  5259. }
  5260. checkHandshakeTime();
  5261. if(getDiffSecNow(startTime[gun_index][TMR_IDX_HANDSHAKING]) > ShmCharger->timeoutSpec.Present_Timeout_Spec)
  5262. {
  5263. setLedMotion(gun_index, LED_ACTION_HANDSHAKE_FAIL);
  5264. DEBUG_INFO("Handshaking timeout...%d\n", ShmCharger->timeoutSpec.Present_Timeout_Spec);
  5265. if(getDiffSecNow(startTime[gun_index][TMR_IDX_HANDSHAKING]) > (ShmCharger->timeoutSpec.Present_Timeout_Spec+5))
  5266. {
  5267. setChargerMode(gun_index, SYS_MODE_IDLE);
  5268. }
  5269. }
  5270. break;
  5271. case SYS_MODE_CHARGING:
  5272. if(isModeChange(gun_index))
  5273. {
  5274. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  5275. //ftime(&startChargingTime[gun_index]);
  5276. refreshStartTimer(&startTime[gun_index][TMR_IDX_REFRESH_CHARGING_INFO]);
  5277. refreshStartTimer(&startTime[gun_index][TMR_IDX_PROFILE_PREPARE]);
  5278. refreshStartTimer(&startTime[gun_index][TMR_IDX_PWN_CHANGE]);
  5279. ocpp_set_auth_req(OFF);
  5280. ocpp_set_profile_req(gun_index, ON);
  5281. ShmCharger->gun_info[gun_index].isChargerStopByCondition = NO;
  5282. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  5283. }
  5284. //if time up, clear CCS MSG count
  5285. if((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) &&
  5286. (getDiffSecNow(startTime[gun_index][TMR_IDX_CCS_HEARTBEAT_COUNT_RESET]) > TIMEOUT_SPEC_CCS_HEARTBEAT_COUNT_RESET))
  5287. {
  5288. refreshStartTimer(&startTime[gun_index][TMR_IDX_CCS_HEARTBEAT_COUNT_RESET]);
  5289. }
  5290. if((ShmCharger->gun_info[gun_index].rfidReq == ON) ||
  5291. (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop == ON) ||
  5292. ocpp_get_remotestop(gun_index) ||
  5293. (ocpp_get_connection_status() && !ocpp_get_starttransaction_result(gun_index)) ||
  5294. ((ShmCharger->gun_info[gun_index].chargingMode != CHARGING_MODE_SOCKETE) && ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState != CP_STATE_C) ||
  5295. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE) && !ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn) ||
  5296. ocpp_get_reset_req() ||
  5297. ocpp_get_unlocker_req(gun_index) ||
  5298. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop == ON) ||
  5299. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && (ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_STOP_MODE)) ||
  5300. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_RENEGOTIATE_MODE) ||
  5301. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_STANDBY_MODE) ||
  5302. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && ((49 <= ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus) && (ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus <= 255))))
  5303. {
  5304. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  5305. }
  5306. else
  5307. {
  5308. // Charging session info calculation
  5309. setLedMotion(gun_index,LED_ACTION_CHARGING);
  5310. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==1)
  5311. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  5312. else
  5313. {
  5314. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[0] = (ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption/10000.0);
  5315. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[1] = (ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption/10000.0);
  5316. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[2] = (ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption/10000.0);
  5317. }
  5318. refreshStartTimer(&endChargingTime[gun_index]);
  5319. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = getDiffSecBetween(startChargingTime[gun_index], endChargingTime[gun_index]);
  5320. presentChargedEnergyUpdate(gun_index);
  5321. // Response StartTransactionConf
  5322. ocpp_set_starttransaction_conf(gun_index, OFF);
  5323. // Charging profile preparation
  5324. if(getDiffSecNow(startTime[gun_index][TMR_IDX_PROFILE_PREPARE]) > TIMEOUT_SPEC_PROFILE_PREPARE)
  5325. {
  5326. if(!ocpp_get_profile_conf(gun_index))
  5327. {
  5328. ocpp_set_profile_req(gun_index, ON);
  5329. refreshStartTimer(&startTime[gun_index][TMR_IDX_PROFILE_PREPARE]);
  5330. }
  5331. else
  5332. {
  5333. ocpp_set_profile_conf(gun_index, OFF);
  5334. }
  5335. }
  5336. // Checking profile id > 0 and current time is between charging profile validFrom & validTo
  5337. checkChargingProfileLimit(gun_index);
  5338. // Charging session target current check if OCPP disconnect and power sharing server connected
  5339. if(!ocpp_get_connection_status() && ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharging)
  5340. {
  5341. if(ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer)
  5342. ShmCharger->gun_info[gun_index].targetCurrent = ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent;
  5343. else
  5344. {
  5345. if(ShmCharger->gun_info[gun_index].targetCurrent != 0)
  5346. DEBUG_WARN("Disconnect from power sharing server, target current set to 0.\n");
  5347. ShmCharger->gun_info[gun_index].targetCurrent = 0;
  5348. }
  5349. }
  5350. // Charging session local limit condition check
  5351. if(ocpp_get_connection_status())
  5352. {
  5353. // On-line max condition check
  5354. if((ShmSysConfigAndInfo->SysConfig.MaxChargingDuration > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60)))
  5355. {
  5356. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  5357. {
  5358. setRelay(gun_index, OFF);
  5359. ShmCharger->gun_info[gun_index].isChargerStopByCondition = YES;
  5360. }
  5361. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  5362. {
  5363. setRelay(gun_index, OFF);
  5364. }
  5365. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  5366. DEBUG_INFO("Connector-%d charging duration(%d) already over max duration(%d) in second.\n", gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration, (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60));
  5367. }
  5368. else if((ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy)))
  5369. {
  5370. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  5371. {
  5372. setRelay(gun_index, OFF);
  5373. ShmCharger->gun_info[gun_index].isChargerStopByCondition = YES;
  5374. }
  5375. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  5376. {
  5377. setRelay(gun_index, OFF);
  5378. }
  5379. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  5380. DEBUG_INFO("Connector-%d charging energy(%.2f) already over max energy(%.2f) in KWH.\n", gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy, ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy));
  5381. }
  5382. else
  5383. {
  5384. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  5385. {
  5386. ShmCharger->gun_info[gun_index].isChargerStopByCondition = NO;
  5387. if(ShmCharger->gun_info[gun_index].targetCurrent>0)
  5388. setRelay(gun_index, ON);
  5389. else
  5390. setRelay(gun_index, OFF);
  5391. }
  5392. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  5393. {
  5394. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)
  5395. setRelay(gun_index, ON);
  5396. }
  5397. }
  5398. }
  5399. else
  5400. {
  5401. // Off-line max condition check
  5402. if((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) ||
  5403. ((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_ENABLE) && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy != OFF_POLICY_NOCHARGE)))
  5404. {
  5405. if(((ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeDuration > 0) ? (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeDuration*60)) : (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60))))
  5406. {
  5407. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  5408. {
  5409. setRelay(gun_index, OFF);
  5410. ShmCharger->gun_info[gun_index].isChargerStopByCondition = YES;
  5411. }
  5412. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  5413. {
  5414. setRelay(gun_index, OFF);
  5415. }
  5416. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  5417. DEBUG_INFO("Connector-%d charging duration(%d) already over off-line max duration(%d) in second.\n", gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration, (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60));
  5418. }
  5419. else if(((ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy > 0) ? (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy)) : (ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy))))
  5420. {
  5421. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  5422. {
  5423. setRelay(gun_index, OFF);
  5424. ShmCharger->gun_info[gun_index].isChargerStopByCondition = YES;
  5425. }
  5426. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  5427. {
  5428. setRelay(gun_index, OFF);
  5429. }
  5430. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  5431. DEBUG_INFO("Connector-%d charging energy(%.2f) already over off-line max energy(%.2f) in KWH.\n", gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy, ((float)ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy));
  5432. }
  5433. else
  5434. {
  5435. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  5436. {
  5437. ShmCharger->gun_info[gun_index].isChargerStopByCondition = NO;
  5438. if(ShmCharger->gun_info[gun_index].targetCurrent>0)
  5439. setRelay(gun_index, ON);
  5440. else
  5441. setRelay(gun_index, OFF);
  5442. }
  5443. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  5444. {
  5445. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)
  5446. setRelay(gun_index, ON);
  5447. }
  5448. }
  5449. }
  5450. else
  5451. {
  5452. if(ShmCharger->gun_info[gun_index].primaryMcuState.relay_state > 0)
  5453. DEBUG_INFO("Connector-%d can not charging in off line\n", gun_index);
  5454. setRelay(gun_index, OFF);
  5455. }
  5456. }
  5457. // Debug information
  5458. if(getDiffSecNow(startTime[gun_index][TMR_IDX_REFRESH_CHARGING_INFO]) > TIMEOUT_SPEC_REFRESH_CHARGING_INFO)
  5459. {
  5460. getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime);
  5461. DB_Update_Record_Buf(localDb, gun_index);
  5462. refreshStartTimer(&startTime[gun_index][TMR_IDX_REFRESH_CHARGING_INFO]);
  5463. }
  5464. }
  5465. break;
  5466. case SYS_MODE_TERMINATING:
  5467. if(isModeChange(gun_index))
  5468. {
  5469. if(!ShmCharger->gun_info[gun_index].primaryMcuState.relay_state)
  5470. {
  5471. setLedMotion(gun_index, LED_ACTION_STOP);
  5472. }
  5473. else
  5474. {}
  5475. getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime);
  5476. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  5477. }
  5478. refreshStartTimer(&endChargingTime[gun_index]);
  5479. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration != 0)
  5480. {
  5481. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = getDiffSecBetween(startChargingTime[gun_index], endChargingTime[gun_index]);
  5482. }
  5483. // End authorize pass
  5484. if(((ShmCharger->gun_info[gun_index].rfidReq == ON) &&isMatchStartUser(gun_index)) ||
  5485. ((ShmCharger->gun_info[gun_index].rfidReq == ON) && ocpp_get_auth_result(YES, gun_index)) ||
  5486. (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE) && (ShmCharger->gun_info[gun_index].rfidReq == ON)) ||
  5487. (!ocpp_get_connection_status() && (isValidLocalWhiteCard() == PASS) && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST) && (ShmCharger->gun_info[gun_index].rfidReq == ON)) ||
  5488. (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop == ON) ||
  5489. ocpp_get_remotestop(gun_index) ||
  5490. (ocpp_get_connection_status() && !ocpp_get_starttransaction_result(gun_index)) ||
  5491. ((ShmCharger->gun_info[gun_index].chargingMode != CHARGING_MODE_SOCKETE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A) && ocpp_get_StopTransactionOnEVSideDisconnect()) ||
  5492. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE) && !ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn) ||
  5493. ocpp_get_reset_req() ||
  5494. ocpp_get_unlocker_req(gun_index) ||
  5495. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop == ON) ||
  5496. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && (ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_STOP_MODE)))
  5497. {
  5498. //setRelay(gun_index, OFF);
  5499. setLedMotion(gun_index, LED_ACTION_STOP);
  5500. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  5501. {
  5502. checkStopReason(gun_index);
  5503. setChargerMode(gun_index, SYS_MODE_COMPLETE);
  5504. }
  5505. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  5506. {
  5507. //setChargerMode(gun_index, SYS_MODE_COMPLETE);
  5508. //Cancel CCS task negotiating
  5509. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  5510. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  5511. setRelay(gun_index,OFF);
  5512. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = ON;
  5513. }
  5514. else
  5515. {
  5516. setChargerMode(gun_index, SYS_MODE_COMPLETE);
  5517. }
  5518. }
  5519. else
  5520. {
  5521. // If the charger stops charging, the led should be stoped blink
  5522. if(!ShmCharger->gun_info[gun_index].primaryMcuState.relay_state)
  5523. {
  5524. setLedMotion(gun_index, LED_ACTION_STOP);
  5525. }
  5526. // Charging profile preparation
  5527. if(getDiffSecNow(startTime[gun_index][TMR_IDX_PROFILE_PREPARE]) > TIMEOUT_SPEC_PROFILE_PREPARE)
  5528. {
  5529. if(!ocpp_get_profile_conf(gun_index))
  5530. {
  5531. ocpp_set_profile_req(gun_index, ON);
  5532. refreshStartTimer(&startTime[gun_index][TMR_IDX_PROFILE_PREPARE]);
  5533. }
  5534. else
  5535. {
  5536. ocpp_set_profile_conf(gun_index, OFF);
  5537. }
  5538. }
  5539. // Checking profile id > 0 and current time is between charging profile validFrom & validTo
  5540. checkChargingProfileLimit(gun_index);
  5541. if(!ocpp_get_auth_result(YES, gun_index))
  5542. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  5543. if((((ShmCharger->gun_info[gun_index].chargingMode != CHARGING_MODE_SOCKETE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)) || ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE) && ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn)) &&
  5544. (ShmCharger->gun_info[gun_index].rfidReq != ON) &&
  5545. (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop != ON) &&
  5546. !ocpp_get_remotestop(gun_index) &&
  5547. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop != ON) &&
  5548. !ocpp_get_reset_req() &&
  5549. ocpp_get_starttransaction_result(gun_index) &&
  5550. !(ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60))) &&
  5551. !(ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy))) &&
  5552. !(!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy != OFF_POLICY_NOCHARGE) && ((ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeDuration > 0) ? (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeDuration*60)) : (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60)))) &&
  5553. !(!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy != OFF_POLICY_NOCHARGE) && ((ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy > 0) ? (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy)) : (ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy)))) &&
  5554. (((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && (ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_START_MODE)) || (ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS))
  5555. )
  5556. {
  5557. setChargerMode(gun_index, SYS_MODE_CHARGING);
  5558. }
  5559. }
  5560. if((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) &&
  5561. (ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty == ON) &&
  5562. (ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty == CCS_PWM_DUTY_100))
  5563. {
  5564. DEBUG_INFO("Set PWM duty 100%% go to SYS_MODE_TERMINATING.\n");
  5565. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = OFF;
  5566. checkStopReason(gun_index);
  5567. setChargerMode(gun_index, SYS_MODE_COMPLETE);
  5568. }
  5569. break;
  5570. case SYS_MODE_COMPLETE:
  5571. if(isModeChange(gun_index))
  5572. {
  5573. setLedMotion(gun_index, LED_ACTION_STOP);
  5574. setRelay(gun_index, OFF);
  5575. setRequest(gun_index, OFF);
  5576. refreshStartTimer(&startTime[0][TMR_IDX_DISP_STOPSUM]);
  5577. }
  5578. if(((ShmCharger->gun_info[gun_index].chargingMode != CHARGING_MODE_SOCKETE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A) && (getDiffSecNow(startTime[0][TMR_IDX_DISP_STOPSUM]) >= TIMEOUT_SPEC_STOPSUM_DISP)) ||
  5579. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE) && (!ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn)) ||
  5580. ocpp_get_reset_req())
  5581. {
  5582. sleep(2);
  5583. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  5584. ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop = OFF;
  5585. ocpp_set_remotestop(gun_index, OFF);
  5586. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop = OFF;
  5587. DB_Insert_Record(localDb, gun_index);
  5588. setChargerMode(gun_index, SYS_MODE_IDLE);
  5589. }
  5590. break;
  5591. case SYS_MODE_ALARM:
  5592. setLedMotion(gun_index,LED_ACTION_ALARM);
  5593. setRelay(gun_index, OFF);
  5594. if((ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode == 0) && !ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CCSboardStestFail && !ShmStatusCodeData->AlarmCode.AlarmEvents.bits.SystemAcOutputOCP)
  5595. {
  5596. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus == SYS_MODE_CHARGING) ||
  5597. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus == SYS_MODE_TERMINATING))
  5598. {
  5599. setChargerMode(gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus);
  5600. }
  5601. else
  5602. {
  5603. setChargerMode(gun_index, SYS_MODE_IDLE);
  5604. }
  5605. }
  5606. break;
  5607. case SYS_MODE_FAULT:
  5608. if(isModeChange(gun_index))
  5609. {}
  5610. break;
  5611. case SYS_MODE_MAINTAIN:
  5612. if(isModeChange(gun_index))
  5613. {
  5614. setLedMotion(gun_index,LED_ACTION_MAINTAIN);
  5615. }
  5616. break;
  5617. case SYS_MODE_UPDATE:
  5618. if(isModeChange(gun_index))
  5619. {
  5620. setLedMotion(gun_index,LED_ACTION_MAINTAIN);
  5621. }
  5622. //======================================
  5623. // Check local upgrade firmware request
  5624. //======================================
  5625. if(ShmSysConfigAndInfo->SysInfo.FirmwareUpdate)
  5626. {
  5627. DEBUG_INFO("Firmware local upgrading...\n");
  5628. ShmSysConfigAndInfo->SysInfo.FirmwareUpdate = OFF;
  5629. if(upgrade_check() == PASS)
  5630. {
  5631. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == ON)
  5632. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = OFF;
  5633. ShmCharger->isUpdateSuccess = YES;
  5634. DEBUG_INFO("Local update success.\n");
  5635. }
  5636. else
  5637. {
  5638. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == OFF)
  5639. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = ON;
  5640. ShmCharger->isUpdateSuccess = NO;
  5641. DEBUG_INFO("Local update fail.\n");
  5642. }
  5643. }
  5644. else if(ocpp_get_update_firmware_req())
  5645. {
  5646. //======================================
  5647. // Check remote upgrade firmware request
  5648. //======================================
  5649. checkRemoteUpgradeStatus();
  5650. }
  5651. else
  5652. {
  5653. //======================================
  5654. // Upgrade complete reboot system
  5655. //======================================
  5656. if(!ShmCharger->gun_info[gun_index].mcuFlag.isMcuUpgradeReq && ((modelnameInfo.GetGunCount>1)?!ShmCharger->gun_info[gun_index^1].mcuFlag.isMcuUpgradeReq:YES) && !ShmCharger->isUpgradeLcmReq)
  5657. {
  5658. if(ShmCharger->isUpdateSuccess == YES)
  5659. {
  5660. sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installed");
  5661. ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  5662. sprintf((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "Installed");
  5663. ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  5664. DEBUG_WARN("Firmware upgrade success.\n");
  5665. sleep(5);
  5666. DEBUG_INFO("Firmware upgraded, reboot...\n");
  5667. system("reboot -f");
  5668. sleep(5);
  5669. system("reboot -f");
  5670. }
  5671. else
  5672. {
  5673. sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "InstallationFailed");
  5674. ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  5675. sprintf((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "InstallationFailed");
  5676. ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  5677. DEBUG_WARN("Firmware upgrade fail.\n");
  5678. sleep(5);
  5679. system("rm -rvf /mnt/* ");
  5680. close(wtdFd);
  5681. system("/usr/bin/run_evse_restart.sh");
  5682. }
  5683. }
  5684. }
  5685. break;
  5686. case SYS_MODE_RESERVATION:
  5687. if(isModeChange(gun_index))
  5688. {}
  5689. setLedMotion(gun_index,LED_ACTION_RESERVATION_MODE);
  5690. if(isReservationExpired(gun_index))
  5691. {
  5692. DEBUG_INFO("Reservation: Time's up...\n");
  5693. setChargerMode(gun_index, SYS_MODE_IDLE);
  5694. }
  5695. else if(ocpp_get_cancelreservation_req(gun_index))
  5696. {
  5697. DEBUG_INFO("Reservation: Cancel reservation...\n");
  5698. setChargerMode(gun_index, SYS_MODE_IDLE);
  5699. ocpp_set_cancelreservation_req(gun_index, OFF);
  5700. }
  5701. else
  5702. {
  5703. // Check is there RFID or back end request start
  5704. if((ShmCharger->gun_info[gun_index].rfidReq == ON) ||
  5705. ocpp_get_remotestart(gun_index))
  5706. {
  5707. if((ShmCharger->gun_info[gun_index].rfidReq == ON))
  5708. {
  5709. if(ocpp_compare_reserve_id_with_user(gun_index))
  5710. {
  5711. DEBUG_INFO("Start Method in reservation : RFID...\n");
  5712. DEBUG_INFO("Start request User Id : %s\n", ShmSysConfigAndInfo->SysConfig.UserId);
  5713. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_RFID;
  5714. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_ISO14443;
  5715. setChargerMode(gun_index, SYS_MODE_AUTHORIZING);
  5716. }
  5717. else
  5718. {
  5719. setLedMotion(gun_index,LED_ACTION_IDLE);
  5720. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  5721. DEBUG_INFO("It's not reserve user id.\n");
  5722. }
  5723. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  5724. }
  5725. else if(ocpp_get_remotestart(gun_index))
  5726. {
  5727. if(ocpp_compare_reserve_id_with_remote_user(gun_index))
  5728. {
  5729. DEBUG_INFO("Start Method in reservation: BACKEND...\n");
  5730. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_BACKEND;
  5731. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_Central;
  5732. setChargerMode(gun_index, SYS_MODE_AUTHORIZING);
  5733. }
  5734. ocpp_set_remotestop(gun_index, OFF);
  5735. }
  5736. }
  5737. }
  5738. break;
  5739. case SYS_MODE_BOOKING:
  5740. if(isModeChange(gun_index))
  5741. {}
  5742. break;
  5743. case SYS_MODE_DEBUG:
  5744. if(isModeChange(gun_index))
  5745. {
  5746. setLedMotion(gun_index,LED_ACTION_DEBUG);
  5747. }
  5748. break;
  5749. }
  5750. }
  5751. }
  5752. // System watch dog reset
  5753. write(wtdFd, "a", 1);
  5754. usleep(50000);
  5755. }
  5756. return FAIL;
  5757. }