main.c 237 KB

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