main.c 310 KB

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