main.c 240 KB

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