main.c 314 KB

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