main.c 233 KB

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