main.c 297 KB

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