main.c 240 KB

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