main.c 220 KB

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