main.c 217 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879
  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:ON; L:OFF*/
  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. return ((strcmp((char*)tmpUser, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId)==0)?YES:NO);
  2586. }
  2587. int isMatchPresentUser()
  2588. {
  2589. uint8_t tmpUser[32];
  2590. if(ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian)
  2591. {
  2592. // Big endian
  2593. switch(rfid.snType)
  2594. {
  2595. case RFID_SN_TYPE_6BYTE:
  2596. 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]);
  2597. break;
  2598. case RFID_SN_TYPE_7BYTE:
  2599. 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]);
  2600. break;
  2601. case RFID_SN_TYPE_10BYTE:
  2602. 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]);
  2603. break;
  2604. case RFID_SN_TYPE_4BYTE:
  2605. default:
  2606. sprintf((char*)tmpUser, "%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3]);
  2607. break;
  2608. }
  2609. }
  2610. else
  2611. {
  2612. // Little endian
  2613. switch(rfid.snType)
  2614. {
  2615. case RFID_SN_TYPE_6BYTE:
  2616. 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]);
  2617. break;
  2618. case RFID_SN_TYPE_7BYTE:
  2619. 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]);
  2620. break;
  2621. case RFID_SN_TYPE_10BYTE:
  2622. 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]);
  2623. break;
  2624. case RFID_SN_TYPE_4BYTE:
  2625. default:
  2626. sprintf((char*)tmpUser, "%02X%02X%02X%02X", rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  2627. break;
  2628. }
  2629. }
  2630. return ((strcmp((char*)tmpUser, (char*)ShmSysConfigAndInfo->SysConfig.UserId)==0)?YES:NO);
  2631. }
  2632. //===============================================
  2633. // Read RFID Serial Number
  2634. //===============================================
  2635. int GetCardSerialNumber()
  2636. {
  2637. int isSuccess = FAIL;
  2638. int module_type = MODULE_EWT;
  2639. if(getRequestCardSN(rfidFd,module_type,&rfid))
  2640. {
  2641. if(rfid.cardType == ISO14443A)
  2642. {
  2643. if(rfid.snType == RFID_SN_TYPE_4BYTE)
  2644. {
  2645. isSuccess = PASS;
  2646. }
  2647. else if (rfid.snType == RFID_SN_TYPE_7BYTE)
  2648. {
  2649. isSuccess = PASS;
  2650. }
  2651. sethaltCard(rfidFd,module_type);
  2652. }
  2653. else if(rfid.cardType == IS014443B)
  2654. {
  2655. isSuccess = PASS;
  2656. }
  2657. else if(rfid.cardType == FELICA)
  2658. {
  2659. isSuccess = PASS;
  2660. }
  2661. else
  2662. {}
  2663. }
  2664. else
  2665. {}
  2666. return isSuccess;
  2667. }
  2668. //===============================================
  2669. // Set led motion
  2670. //===============================================
  2671. void setLedMotion(unsigned char gun_index,unsigned char led_mode)
  2672. {
  2673. switch(led_mode)
  2674. {
  2675. case LED_ACTION_INIT:
  2676. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_INIT;
  2677. break;
  2678. case LED_ACTION_IDLE:
  2679. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_IDLE;
  2680. break;
  2681. case LED_ACTION_AUTHED:
  2682. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_AUTHED;
  2683. break;
  2684. case LED_ACTION_CONNECTED:
  2685. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_CONNECTED;
  2686. break;
  2687. case LED_ACTION_CHARGING:
  2688. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_CHARGING;
  2689. break;
  2690. case LED_ACTION_STOP:
  2691. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_STOP;
  2692. break;
  2693. case LED_ACTION_ALARM:
  2694. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_ALARM;
  2695. break;
  2696. case LED_ACTION_MAINTAIN:
  2697. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_MAINTAIN;
  2698. break;
  2699. case LED_ACTION_RFID_PASS:
  2700. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_RFID_PASS;
  2701. break;
  2702. case LED_ACTION_RFID_FAIL:
  2703. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_RFID_FAIL;
  2704. break;
  2705. case LED_ACTION_BLE_CONNECT:
  2706. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_BLE_CONNECT;
  2707. break;
  2708. case LED_ACTION_BLE_DISABLE:
  2709. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_BLE_DISABLE;
  2710. break;
  2711. case LED_ACTION_DEBUG:
  2712. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_DEBUG;
  2713. break;
  2714. case LED_ACTION_ALL_OFF:
  2715. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_ALL_OFF;
  2716. break;
  2717. case LED_RELAY_ON:
  2718. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_RELAY_ON;
  2719. break;
  2720. case LED_RELAY_OFF:
  2721. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_RELAY_OFF;
  2722. break;
  2723. case LED_ACTION_HANDSHAKE_FAIL:
  2724. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_HANDSHAKE_FAIL;
  2725. break;
  2726. case LED_ACTION_INTERNET_DISCONNECT:
  2727. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_INTERNET_DISCONNECT;
  2728. break;
  2729. }
  2730. }
  2731. //===============================================
  2732. // Request on/off set
  2733. //===============================================
  2734. void setRequest(unsigned char gun_index,unsigned char isOn)
  2735. {
  2736. if(isOn == ON)
  2737. {
  2738. if(ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest == OFF)
  2739. {
  2740. ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest = ON;
  2741. DEBUG_INFO("Gun-%d permission request: ON \n",gun_index);
  2742. }
  2743. }
  2744. else
  2745. {
  2746. if(ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest == ON)
  2747. {
  2748. ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest = OFF;
  2749. DEBUG_INFO("Gun-%d permission request: OFF \n",gun_index);
  2750. }
  2751. }
  2752. }
  2753. //===============================================
  2754. // Request on/off get
  2755. //===============================================
  2756. int getRequest(unsigned char gun_index)
  2757. {
  2758. return ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest;
  2759. }
  2760. //===============================================
  2761. // Relay on/off set
  2762. //===============================================
  2763. void setRelay(unsigned char gun_index,unsigned char isOn)
  2764. {
  2765. if(isOn == ON)
  2766. {
  2767. if(ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn == OFF)
  2768. {
  2769. switch(ShmCharger->gun_info[gun_index].chargingMode)
  2770. {
  2771. case CHARGING_MODE_BS:
  2772. case CHARGING_MODE_HLC:
  2773. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = ON;
  2774. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][0] = 0x01;
  2775. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][1] = 0x01;
  2776. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][2] = 0x01;
  2777. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  2778. DEBUG_INFO("Gun-%d Output relay status: ON. [CHARGING_MODE_BS] \n",gun_index);
  2779. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  2780. DEBUG_INFO("Gun-%d Output relay status: ON. [CHARGING_MODE_HLC] \n",gun_index);
  2781. break;
  2782. case CHARGING_MODE_SOCKETE:
  2783. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = ON;
  2784. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][3] = 0x01;
  2785. DEBUG_INFO("Gun-%d Output relay status: ON. [CHARGING_MODE_SOCKETE] \n",gun_index);
  2786. break;
  2787. default:
  2788. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = ON;
  2789. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][0] = 0x01;
  2790. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][1] = 0x01;
  2791. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][2] = 0x01;
  2792. DEBUG_INFO("Gun-%d Output relay status: ON. [DEFFAULT] \n",gun_index);
  2793. break;
  2794. }
  2795. }
  2796. }
  2797. else
  2798. {
  2799. if(ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn == ON)
  2800. {
  2801. switch(ShmCharger->gun_info[gun_index].chargingMode)
  2802. {
  2803. case CHARGING_MODE_BS:
  2804. case CHARGING_MODE_HLC:
  2805. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = OFF;
  2806. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][0] = 0;
  2807. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][1] = 0;
  2808. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][2] = 0;
  2809. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  2810. DEBUG_INFO("Gun-%d Output relay status: OFF. [CHARGING_MODE_BS] \n",gun_index);
  2811. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  2812. DEBUG_INFO("Gun-%d Output relay status: OFF. [CHARGING_MODE_HLC] \n",gun_index);
  2813. break;
  2814. case CHARGING_MODE_SOCKETE:
  2815. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = OFF;
  2816. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][3] = 0;
  2817. DEBUG_INFO("Gun-%d Output relay status: OFF. [CHARGING_MODE_SOCKETE] \n",gun_index);
  2818. break;
  2819. default:
  2820. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = OFF;
  2821. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][0] = 0;
  2822. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][1] = 0;
  2823. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][2] = 0;
  2824. DEBUG_INFO("Gun-%d Output relay status: OFF. [DEFFAULT] \n",gun_index);
  2825. break;
  2826. }
  2827. }
  2828. }
  2829. }
  2830. //===============================================
  2831. // Relay on/off get
  2832. //===============================================
  2833. int getRelay(unsigned char gun_index)
  2834. {
  2835. return ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn;
  2836. }
  2837. //===============================================
  2838. // Set speaker on/off request
  2839. //===============================================
  2840. void setSpeaker(unsigned char isOn, unsigned char speaker_mode)
  2841. {
  2842. if(isOn == ON)
  2843. {
  2844. ShmCharger->isSpeakerOn = ON;
  2845. ShmCharger->speaker_type = speaker_mode;
  2846. }
  2847. }
  2848. //===============================================
  2849. // Initialization RFID communication port
  2850. //===============================================
  2851. int InitRfidPort()
  2852. {
  2853. int uartO2 = open(rfidPortName, O_RDWR);
  2854. struct termios tios;
  2855. if (uartO2 != FAIL)
  2856. {
  2857. ioctl (uartO2, TCGETS, &tios);
  2858. tios.c_cflag = B19200 | CS8 | CLOCAL | CREAD;
  2859. tios.c_lflag = 0;
  2860. tios.c_iflag = 0;
  2861. tios.c_oflag = 0;
  2862. tios.c_cc[VMIN] = 0;
  2863. tios.c_cc[VTIME] = (unsigned char) 1;
  2864. tios.c_lflag = 0;
  2865. tcflush(uartO2, TCIFLUSH);
  2866. ioctl(uartO2, TCSETS, &tios);
  2867. }
  2868. if (uartO2 < 0)
  2869. {
  2870. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RfidModuleCommFail = 1;
  2871. }
  2872. return uartO2;
  2873. }
  2874. //===============================================
  2875. // Check internet access status
  2876. //===============================================
  2877. int isReachableInternet()
  2878. {
  2879. int result = FAIL;
  2880. FILE *fp;
  2881. char cmd[256];
  2882. char buf[512];
  2883. char tmp[512];
  2884. // Get ip address & net mask
  2885. strcpy(cmd, "ifconfig eth0");
  2886. fp = popen(cmd, "r");
  2887. if (fp != NULL)
  2888. {
  2889. while(fgets(buf, sizeof(buf), fp) != NULL)
  2890. {
  2891. if (strstr(buf, "inet addr:") > 0)
  2892. {
  2893. sscanf(buf, "%*s%s", tmp);
  2894. substr(tmp, tmp, strspn(tmp, "addr:"), strlen(buf)-strspn(tmp, "addr:"));
  2895. if (strcmp(tmp, (char *)ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress) != 0)
  2896. {
  2897. strcpy((char *) ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress, tmp);
  2898. }
  2899. sscanf(buf, "%*s%*s%*s%s", tmp);
  2900. substr(tmp, tmp, strspn(tmp, "Mask:"), strlen(buf)-strspn(tmp, "Mask:"));
  2901. if (strcmp(tmp, (char *)ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress) != 0)
  2902. {
  2903. strcpy((char *) ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress, tmp);
  2904. }
  2905. }
  2906. }
  2907. }
  2908. pclose(fp);
  2909. memset(buf, 0x00, sizeof(buf));
  2910. // Get gateway
  2911. fp = popen("ip route", "r");
  2912. if(fp == NULL)
  2913. result = FAIL;
  2914. else
  2915. {
  2916. while(fgets(buf, sizeof(buf), fp) != NULL)
  2917. {
  2918. if((strstr(buf, "default") != NULL) && (strstr(buf, "eth0") != NULL))
  2919. break;
  2920. }
  2921. if(strstr(buf, "default") != NULL)
  2922. {
  2923. sscanf(buf, "%*s%*s%s", tmp);
  2924. substr((char*)ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthGatewayAddress, tmp, 0, strlen(tmp));
  2925. }
  2926. }
  2927. pclose(fp);
  2928. memset(buf, 0x00, sizeof(buf));
  2929. for(int idx=0;idx<ARRAY_SIZE(valid_Internet);idx++)
  2930. {
  2931. sprintf(cmd, "ping -c 1 -w 3 -I eth0 %s", valid_Internet[idx]);
  2932. fp = popen(cmd, "r");
  2933. if(fp != NULL)
  2934. {
  2935. while(fgets(buf, sizeof(buf), fp) != NULL)
  2936. {
  2937. if(strstr(buf, "transmitted") > 0)
  2938. {
  2939. //sscanf(buf, "%*s%*s%*s%*s%*s%*s%s", tmp);
  2940. if(strstr(buf,"100%") != NULL)
  2941. {
  2942. }
  2943. else
  2944. {
  2945. result = PASS;
  2946. }
  2947. //DEBUG_INFO("%s",buf);
  2948. //DEBUG_INFO("%s\n",tmp);
  2949. }
  2950. }
  2951. }
  2952. pclose(fp);
  2953. }
  2954. return result;
  2955. }
  2956. int isRouteFail()
  2957. {
  2958. int result = YES;
  2959. FILE *fp;
  2960. char buf[512];
  2961. fp = popen("route -n", "r");
  2962. if(fp != NULL)
  2963. {
  2964. while(fgets(buf, sizeof(buf), fp) != NULL)
  2965. {
  2966. if(strstr(buf, "eth0") != NULL)
  2967. result = NO;
  2968. }
  2969. }
  2970. pclose(fp);
  2971. return result;
  2972. }
  2973. //===============================================
  2974. // Check reservation date is expired
  2975. //===============================================
  2976. int isReservationExpired(unsigned char gun_index)
  2977. {
  2978. int result = NO;
  2979. struct tm expiredDate;
  2980. struct timeb expiredTime;
  2981. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  2982. {
  2983. 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)
  2984. {
  2985. expiredDate.tm_year -= 1900;
  2986. expiredDate.tm_mon -= 1;
  2987. expiredTime.time = mktime(&expiredDate);
  2988. if(DiffTimebWithNow(expiredTime)>=0)
  2989. {
  2990. result = YES;
  2991. }
  2992. }
  2993. else
  2994. {
  2995. DEBUG_WARN("Expired date parsing error.\n");
  2996. DEBUG_INFO("Date expired.\n");
  2997. result = YES;
  2998. }
  2999. }
  3000. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3001. {
  3002. 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)
  3003. {
  3004. expiredDate.tm_year -= 1900;
  3005. expiredDate.tm_mon -= 1;
  3006. expiredTime.time = mktime(&expiredDate);
  3007. if(DiffTimebWithNow(expiredTime)>=0)
  3008. {
  3009. result = YES;
  3010. }
  3011. }
  3012. else
  3013. {
  3014. DEBUG_WARN("Expired date parsing error.\n");
  3015. DEBUG_INFO("Date expired.\n");
  3016. result = YES;
  3017. }
  3018. }
  3019. return result;
  3020. }
  3021. //===============================================
  3022. // Check charging profile related date routine
  3023. //===============================================
  3024. int isProfileValid(uint8_t gun_index)
  3025. {
  3026. int result = NO;
  3027. struct tm tmFrom, tmTo;
  3028. struct timeb tbFrom, tbTo;
  3029. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3030. {
  3031. 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) &&
  3032. (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))
  3033. {
  3034. tmFrom.tm_year -= 1900;
  3035. tmFrom.tm_mon -= 1;
  3036. tbFrom.time = mktime(&tmFrom);
  3037. tmTo.tm_year -= 1900;
  3038. tmTo.tm_mon -= 1;
  3039. tbTo.time = mktime(&tmTo);
  3040. DEBUG_INFO("Valid from compare Now: %d\n", DiffTimebWithNow(tbFrom));
  3041. DEBUG_INFO("Valid to compare Now: %d\n", DiffTimebWithNow(tbTo));
  3042. if((DiffTimebWithNow(tbFrom)>=0) && (DiffTimebWithNow(tbTo)<=0))
  3043. {
  3044. result = YES;
  3045. }
  3046. }
  3047. else
  3048. {
  3049. DEBUG_WARN("ValidFrom or ValidTo date parsing error.\n");
  3050. }
  3051. }
  3052. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3053. {
  3054. 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) &&
  3055. (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))
  3056. {
  3057. tmFrom.tm_year -= 1900;
  3058. tmFrom.tm_mon -= 1;
  3059. tbFrom.time = mktime(&tmFrom);
  3060. tmTo.tm_year -= 1900;
  3061. tmTo.tm_mon -= 1;
  3062. tbTo.time = mktime(&tmTo);
  3063. DEBUG_INFO("Valid from compare Now: %d\n", DiffTimebWithNow(tbFrom));
  3064. DEBUG_INFO("Valid to compare Now: %d\n", DiffTimebWithNow(tbTo));
  3065. if((DiffTimebWithNow(tbFrom)>=0) && (DiffTimebWithNow(tbTo)<=0))
  3066. {
  3067. result = YES;
  3068. }
  3069. }
  3070. else
  3071. {
  3072. DEBUG_WARN("ValidFrom or ValidTo date parsing error.\n");
  3073. }
  3074. }
  3075. return result;
  3076. }
  3077. int getScheduleStart(int gun_index)
  3078. {
  3079. int result = -1;
  3080. struct tm tmScheduleStart;;
  3081. struct timeb tbScheduleStart;
  3082. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3083. {
  3084. 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))
  3085. {
  3086. tmScheduleStart.tm_year -= 1900;
  3087. tmScheduleStart.tm_mon -= 1;
  3088. tbScheduleStart.time = mktime(&tmScheduleStart);
  3089. tbScheduleStart.millitm = 0;
  3090. result = DiffTimebWithNow(tbScheduleStart)/1000;
  3091. //DEBUG_INFO("Schedule start compare Now(seconds): %d\n", result);
  3092. }
  3093. else
  3094. {
  3095. DEBUG_WARN("Schedule start date parsing error.\n");
  3096. }
  3097. }
  3098. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3099. {
  3100. 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))
  3101. {
  3102. tmScheduleStart.tm_year -= 1900;
  3103. tmScheduleStart.tm_mon -= 1;
  3104. tbScheduleStart.time = mktime(&tmScheduleStart);
  3105. tbScheduleStart.millitm = 0;
  3106. result = DiffTimebWithNow(tbScheduleStart)/1000;
  3107. //DEBUG_INFO("Schedule start compare Now(seconds): %d\n", result);
  3108. }
  3109. else
  3110. {
  3111. DEBUG_WARN("Schedule start date parsing error.\n");
  3112. }
  3113. }
  3114. return result;
  3115. }
  3116. int getStartSinceToday()
  3117. {
  3118. int result = -1;
  3119. time_t t;
  3120. struct tm *tmStartToday;
  3121. struct timeb tbStartToday;
  3122. t=time(NULL);
  3123. tmStartToday=localtime(&t);
  3124. tmStartToday->tm_hour = 0;
  3125. tmStartToday->tm_min = 0;
  3126. tmStartToday->tm_sec = 0;
  3127. tbStartToday.time = mktime(tmStartToday);
  3128. result = DiffTimebWithNow(tbStartToday)/1000;
  3129. //DEBUG_INFO("Start today compare Now(seconds): %d\n", result);
  3130. return result;
  3131. }
  3132. int getStartSinceWeek()
  3133. {
  3134. int result = -1;
  3135. time_t t;
  3136. struct tm *tmStartWeek;
  3137. struct timeb tbStartWeek;
  3138. t=time(NULL);
  3139. tmStartWeek=localtime(&t);
  3140. t-=86400*tmStartWeek->tm_wday;
  3141. tmStartWeek=localtime(&t);
  3142. tmStartWeek->tm_hour = 0;
  3143. tmStartWeek->tm_min = 0;
  3144. tmStartWeek->tm_sec = 0;
  3145. tbStartWeek.time = mktime(tmStartWeek);
  3146. result = DiffTimebWithNow(tbStartWeek)/1000;
  3147. //DEBUG_INFO("Start week compare Now(seconds): %d\n", result);
  3148. return result;
  3149. }
  3150. //===============================================
  3151. // Valid from local white list
  3152. //===============================================
  3153. int isValidLocalWhiteCard()
  3154. {
  3155. uint8_t result = FAIL;
  3156. for(uint8_t idx=0;idx<ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.LocalWhiteCard);idx++)
  3157. {
  3158. if(strcmp((char*)ShmSysConfigAndInfo->SysConfig.UserId, (char*)ShmSysConfigAndInfo->SysConfig.LocalWhiteCard[idx]) == 0)
  3159. {
  3160. result = PASS;
  3161. }
  3162. }
  3163. return result;
  3164. }
  3165. //==========================================
  3166. // Check routine
  3167. //==========================================
  3168. void checkTask()
  3169. {
  3170. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  3171. {
  3172. if(system("pidof -s Module_4g > /dev/null") != 0)
  3173. {
  3174. DEBUG_INFO("Module_4g not running, restart it.\n");
  3175. system("/root/Module_4g &");
  3176. }
  3177. }
  3178. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  3179. {
  3180. if(system("pidof -s Module_Wifi > /dev/null") != 0)
  3181. {
  3182. DEBUG_INFO("Module_Wifi not running, restart it.\n");
  3183. system("/root/Module_Wifi &");
  3184. }
  3185. }
  3186. if(system("pidof -s Module_EventLogging > /dev/null") != 0)
  3187. {
  3188. DEBUG_INFO("Module_EventLogging not running, restart it.\n");
  3189. system("/root/Module_EventLogging &");
  3190. }
  3191. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") != 0)
  3192. {
  3193. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3194. {
  3195. if((time((time_t*)NULL) - ShmOCPP16Data->procDogTime) > 180)
  3196. {
  3197. DEBUG_WARN("OcppBackend watch dog timeout task restart.\n");
  3198. ShmOCPP16Data->procDogTime = time((time_t*)NULL);
  3199. system("pkill OcppBackend");
  3200. sleep(3);
  3201. ocpp_process_start();
  3202. }
  3203. if(system("pidof -s OcppBackend > /dev/null") != 0)
  3204. {
  3205. DEBUG_INFO("OcppBackend not running, restart it.\n");
  3206. ocpp_process_start();
  3207. }
  3208. }
  3209. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3210. {
  3211. if((time((time_t*)NULL) - ShmOCPP20Data->procDogTime) > 180)
  3212. {
  3213. DEBUG_WARN("OcppBackend20 watch dog timeout task restart.\n");
  3214. ShmOCPP20Data->procDogTime = time((time_t*)NULL);
  3215. system("pkill OcppBackend20");
  3216. sleep(3);
  3217. ocpp_process_start();
  3218. }
  3219. if(system("pidof -s OcppBackend20 > /dev/null") != 0)
  3220. {
  3221. DEBUG_INFO("OcppBackend20 not running, restart it.\n");
  3222. ocpp_process_start();
  3223. }
  3224. }
  3225. }
  3226. if(system("pidof -s Module_AlarmDetect > /dev/null") != 0)
  3227. {
  3228. DEBUG_INFO("Module_AlarmDetect not running, restart it.\n");
  3229. system("/root/Module_AlarmDetect &");
  3230. }
  3231. if(system("pidof -s Module_InternalComm > /dev/null") != 0)
  3232. {
  3233. DEBUG_INFO("Module_InternalComm not running, restart it.\n");
  3234. system("/root/Module_InternalComm &");
  3235. }
  3236. if(system("pidof -s Module_Speaker > /dev/null") != 0)
  3237. {
  3238. DEBUG_INFO("Module_Speaker not running, restart it.\n");
  3239. system("/root/Module_Speaker &");
  3240. }
  3241. if(system("pidof -s Module_ProduceUtils > /dev/null") != 0)
  3242. {
  3243. DEBUG_INFO("Module_ProduceUtils not running, restart it.\n");
  3244. system ("/root/Module_ProduceUtils &");
  3245. }
  3246. if(system("pidof -s Module_LcmControl > /dev/null") != 0)
  3247. {
  3248. DEBUG_INFO("Module_LcmControl not running, restart it.\n");
  3249. system ("/root/Module_LcmControl &");
  3250. }
  3251. if((system("pidof -s Module_PowerSharing > /dev/null") != 0) &&
  3252. ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharging)
  3253. {
  3254. DEBUG_INFO("Module_PowerSharing not running, restart it.\n");
  3255. system ("/root/Module_PowerSharing &");
  3256. }
  3257. if((system("pidof -s Module_InitUpgrade > /dev/null") != 0) &&
  3258. ShmSysConfigAndInfo->SysConfig.isReqFirstUpgrade)
  3259. {
  3260. DEBUG_INFO("Module_InitUpgrade not running, restart it.\n");
  3261. system ("/root/Module_InitUpgrade &");
  3262. }
  3263. }
  3264. void checkConnectionTimeout()
  3265. {
  3266. if((system("pidof -s OcppBackend > /dev/null") != 0) && (system("pidof -s OcppBackend20 > /dev/null") != 0))
  3267. {
  3268. ShmCharger->timeoutSpec.Present_Timeout_Spec = TIMEOUT_SPEC_HANDSHAKING;
  3269. //DEBUG_INFO("Handshaking timeout specification follow by initial setting : %d s \n", TIMEOUT_SPEC_HANDSHAKING/1000);
  3270. }
  3271. else
  3272. {
  3273. ShmCharger->timeoutSpec.Setting_Timeout_Spec = ocpp_get_connection_timeout();
  3274. if((ShmCharger->timeoutSpec.Setting_Timeout_Spec*1000) < TIMEOUT_SPEC_BS_HLC_HANDSHAKE)
  3275. {
  3276. ShmCharger->timeoutSpec.Present_Timeout_Spec = (TIMEOUT_SPEC_BS_HLC_HANDSHAKE+10000);
  3277. //DEBUG_INFO("Handshaking timeout specification follow by OCPP Configuration : Fail. Value can't be zero or less than zero.\n.");
  3278. }
  3279. else
  3280. {
  3281. ShmCharger->timeoutSpec.Present_Timeout_Spec = (ShmCharger->timeoutSpec.Setting_Timeout_Spec*1000);
  3282. //DEBUG_INFO("Handshaking timeout specification follow by OCPP Configuration : Pass...\n.");
  3283. }
  3284. //DEBUG_INFO("Handshaking timeout specification follow by OCPP Configuration : %s s \n.",ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData);
  3285. }
  3286. }
  3287. void checkReset()
  3288. {
  3289. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3290. {
  3291. if(ShmOCPP16Data->MsMsg.bits.ResetReq)
  3292. {
  3293. if((!isMode(0, SYS_MODE_CHARGING) && !isMode(0, SYS_MODE_TERMINATING) && !isMode(0, SYS_MODE_COMPLETE)) &&
  3294. (AC_QUANTITY>1?(!isMode(1, SYS_MODE_CHARGING) && !isMode(1, SYS_MODE_TERMINATING) && !isMode(0, SYS_MODE_COMPLETE)):TRUE))
  3295. {
  3296. ShmOCPP16Data->MsMsg.bits.ResetReq = OFF;
  3297. sprintf((char*)ShmOCPP16Data->Reset.ResponseStatus, "Accepted");
  3298. ShmOCPP16Data->MsMsg.bits.ResetConf = ON;
  3299. DEBUG_INFO("%s reset request by OCPP.\n", ShmOCPP16Data->Reset.Type);
  3300. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  3301. setChargerMode(gun_index, SYS_MODE_BOOTING);
  3302. if(strcmp((char*)ShmOCPP16Data->Reset.Type, "Hard") == 0)
  3303. {
  3304. system("sync");
  3305. sleep(5);
  3306. system("reboot -f");
  3307. sleep(5);
  3308. system("reboot -f");
  3309. }
  3310. else
  3311. {
  3312. sleep(5);
  3313. close(wtdFd);
  3314. system("/usr/bin/run_evse_restart.sh");
  3315. }
  3316. }
  3317. }
  3318. }
  3319. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3320. {
  3321. if(ShmOCPP20Data->MsMsg.bits.ResetReq)
  3322. {
  3323. if((!isMode(0, SYS_MODE_CHARGING) && !isMode(0, SYS_MODE_TERMINATING) && !isMode(0, SYS_MODE_COMPLETE)) &&
  3324. (AC_QUANTITY>1?(!isMode(1, SYS_MODE_CHARGING) && !isMode(1, SYS_MODE_TERMINATING) && !isMode(0, SYS_MODE_COMPLETE)):TRUE))
  3325. {
  3326. ShmOCPP20Data->MsMsg.bits.ResetReq = OFF;
  3327. sprintf((char*)ShmOCPP20Data->Reset.Response_status, "Accepted");
  3328. ShmOCPP20Data->MsMsg.bits.ResetConf = ON;
  3329. DEBUG_INFO("%s reset request by OCPP.\n", ShmOCPP20Data->Reset.type);
  3330. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  3331. setChargerMode(gun_index, SYS_MODE_BOOTING);
  3332. if(strcmp((char*)ShmOCPP20Data->Reset.type, "Immediate") == 0)
  3333. {
  3334. system("sync");
  3335. sleep(5);
  3336. system("reboot -f");
  3337. sleep(5);
  3338. system("reboot -f");
  3339. }
  3340. else
  3341. {
  3342. sleep(5);
  3343. close(wtdFd);
  3344. system("/usr/bin/run_evse_restart.sh");
  3345. }
  3346. }
  3347. }
  3348. }
  3349. }
  3350. void checkReservation(uint8_t gun_index)
  3351. {
  3352. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3353. {
  3354. if(ShmOCPP16Data->CsMsg.bits[gun_index].ReserveNowReq)
  3355. {
  3356. ShmOCPP16Data->CsMsg.bits[gun_index].ReserveNowReq = OFF;
  3357. if(isMode(gun_index, SYS_MODE_IDLE) && !isReservationExpired(gun_index))
  3358. {
  3359. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId = ShmOCPP16Data->ReserveNow[gun_index].ReservationId;
  3360. setChargerMode(gun_index, SYS_MODE_RESERVATION);
  3361. }
  3362. DEBUG_INFO("Reservation request on connector-%d.\n", gun_index);
  3363. ShmOCPP16Data->CsMsg.bits[gun_index].ReserveNowConf = ON;
  3364. }
  3365. }
  3366. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3367. {
  3368. if(ShmOCPP20Data->CsMsg.bits[gun_index].ReserveNowReq)
  3369. {
  3370. ShmOCPP20Data->CsMsg.bits[gun_index].ReserveNowReq = OFF;
  3371. if(isMode(gun_index, SYS_MODE_IDLE) && !isReservationExpired(gun_index))
  3372. {
  3373. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId = ShmOCPP20Data->ReserveNow[gun_index].id;
  3374. setChargerMode(gun_index, SYS_MODE_RESERVATION);
  3375. }
  3376. DEBUG_INFO("Reservation request on connector-%d.\n", gun_index);
  3377. ShmOCPP20Data->CsMsg.bits[gun_index].ReserveNowConf = ON;
  3378. }
  3379. }
  3380. }
  3381. void checkUnlocker(uint8_t gun_index)
  3382. {
  3383. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3384. {
  3385. if(ShmOCPP16Data->CsMsg.bits[gun_index].UnlockConnectorReq == ON)
  3386. {
  3387. ShmOCPP16Data->CsMsg.bits[gun_index].UnlockConnectorReq = OFF;
  3388. sprintf((char*)ShmOCPP16Data->UnlockConnector[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].ResponseStatus, "NotSupported");
  3389. ShmOCPP16Data->CsMsg.bits[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].UnlockConnectorConf = ON;
  3390. ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor = ON;
  3391. }
  3392. }
  3393. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3394. {
  3395. if(ShmOCPP20Data->CsMsg.bits[gun_index].UnlockConnectorReq == ON)
  3396. {
  3397. ShmOCPP20Data->CsMsg.bits[gun_index].UnlockConnectorReq = OFF;
  3398. sprintf((char*)ShmOCPP20Data->UnlockConnector[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].Response_status, "NotSupported");
  3399. ShmOCPP20Data->CsMsg.bits[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].UnlockConnectorConf = ON;
  3400. ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor = ON;
  3401. }
  3402. }
  3403. }
  3404. void checkAvailability(uint8_t gun_index)
  3405. {
  3406. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3407. {
  3408. if(ShmOCPP16Data->CsMsg.bits[gun_index].ChangeAvailabilityReq)
  3409. {
  3410. if(strcmp((char*)ShmOCPP16Data->ChangeAvailability[gun_index].Type, "Operative") == 0)
  3411. {
  3412. DB_Update_Operactive(localDb, gun_index, true);
  3413. ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
  3414. }
  3415. else
  3416. {
  3417. DB_Update_Operactive(localDb, gun_index, false);
  3418. ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
  3419. }
  3420. ShmOCPP16Data->CsMsg.bits[gun_index].ChangeAvailabilityReq = OFF;
  3421. }
  3422. }
  3423. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3424. {
  3425. if(ShmOCPP20Data->CsMsg.bits[gun_index].ChangeAvailabilityReq)
  3426. {
  3427. if(strcmp((char*)ShmOCPP20Data->ChangeAvailability[gun_index].operationalStatus, "Operative") == 0)
  3428. {
  3429. DB_Update_Operactive(localDb, gun_index, true);
  3430. ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
  3431. }
  3432. else
  3433. {
  3434. DB_Update_Operactive(localDb, gun_index, false);
  3435. ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
  3436. }
  3437. ShmOCPP20Data->CsMsg.bits[gun_index].ChangeAvailabilityReq = OFF;
  3438. }
  3439. }
  3440. }
  3441. void checkChargingProfileLimit(uint8_t gun_index)
  3442. {
  3443. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3444. {
  3445. if((ocpp_get_smartcharging_profileId(gun_index) > 0) &&
  3446. (ocpp_get_profile_req(gun_index) != ON) &&
  3447. (((strlen((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ValidFrom)>0) && (strlen((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ValidTo)>0)) ? isProfileValid(gun_index) : ON))
  3448. {
  3449. // Debug information
  3450. if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_LOGPPRINTOUT]) > TIMEOUT_SPEC_LOGPPRINTOUT)
  3451. {
  3452. DEBUG_INFO("Profile ID found: %d\n", ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfileId);
  3453. DEBUG_INFO("Valid from: %s\n", ShmOCPP16Data->SmartChargingProfile[gun_index].ValidFrom);
  3454. DEBUG_INFO("Valid to: %s\n", ShmOCPP16Data->SmartChargingProfile[gun_index].ValidTo);
  3455. DEBUG_INFO("Start schedule: %s\n", ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.StartSchedule);
  3456. DEBUG_INFO("Profile kind: %s\n", ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfileKind);
  3457. DEBUG_INFO("RecurrencyKind: %s\n", ShmOCPP16Data->SmartChargingProfile[gun_index].RecurrencyKind);
  3458. DEBUG_INFO("Profile purpose: %s\n", ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfilePurpose);
  3459. DEBUG_INFO("Transaction ID: %d\n", ShmOCPP16Data->SmartChargingProfile[gun_index].TransactionId);
  3460. DEBUG_INFO("ChargingRateUnit: %s\n", ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingRateUnit);
  3461. DEBUG_INFO("===============================================================\n");
  3462. }
  3463. // Checking profile kind
  3464. if((mystrcmp((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfileKind, "Absolute") == PASS))
  3465. {
  3466. // Absolute profile
  3467. if(((mystrcmp((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfilePurpose, "TxProfile") == PASS) && (ShmOCPP16Data->SmartChargingProfile[gun_index].TransactionId == ShmOCPP16Data->StartTransaction[gun_index].ResponseTransactionId)) ||
  3468. (mystrcmp((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfilePurpose, "TxProfile") == FAIL))
  3469. {
  3470. // Checking limitation
  3471. for(uint8_t idx_period=0;idx_period<ARRAY_SIZE(ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod);idx_period++)
  3472. {
  3473. if((getScheduleStart(gun_index) > ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod[idx_period].StartPeriod) &&
  3474. ((idx_period == 0) || (ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod[idx_period].StartPeriod > 0))
  3475. )
  3476. {
  3477. 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);
  3478. //DEBUG_INFO("ShmCharger->gun_info[%d].targetCurrent on period[%d]: %d\n", gun_index, idx_period, ShmCharger->gun_info[gun_index].targetCurrent);
  3479. }
  3480. else
  3481. break;
  3482. }
  3483. }
  3484. }
  3485. }
  3486. else if((ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfileId == 0) && (ShmOCPP16Data->CSUMsg.bits[gun_index].ChargingProfileReq != ON))
  3487. {
  3488. ShmCharger->gun_info[gun_index].targetCurrent = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
  3489. }
  3490. }
  3491. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3492. {
  3493. if((ocpp_get_smartcharging_profileId(gun_index) > 0) &&
  3494. (ocpp_get_profile_req(gun_index) != ON) &&
  3495. (((strlen((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].validFrom)>0) && (strlen((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].validTo)>0)) ? isProfileValid(gun_index) : ON))
  3496. {
  3497. // Debug information
  3498. if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_LOGPPRINTOUT]) > TIMEOUT_SPEC_LOGPPRINTOUT)
  3499. {
  3500. DEBUG_INFO("Profile ID found: %d\n", ShmOCPP20Data->SmartChargingProfile[gun_index].id);
  3501. DEBUG_INFO("Valid from: %s\n", ShmOCPP20Data->SmartChargingProfile[gun_index].validFrom);
  3502. DEBUG_INFO("Valid to: %s\n", ShmOCPP20Data->SmartChargingProfile[gun_index].validTo);
  3503. DEBUG_INFO("Start schedule: %s\n", ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].startSchedule);
  3504. DEBUG_INFO("Profile kind: %s\n", ShmOCPP20Data->SmartChargingProfile[gun_index].chargingProfileKind);
  3505. DEBUG_INFO("RecurrencyKind: %s\n", ShmOCPP20Data->SmartChargingProfile[gun_index].recurrencyKind);
  3506. DEBUG_INFO("Profile purpose: %s\n", ShmOCPP20Data->SmartChargingProfile[gun_index].chargingProfilePurpose);
  3507. DEBUG_INFO("Transaction ID: %d\n", ShmOCPP20Data->SmartChargingProfile[gun_index].transactionId);
  3508. DEBUG_INFO("ChargingRateUnit: %s\n", ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingRateUnit);
  3509. DEBUG_INFO("===============================================================\n");
  3510. }
  3511. // Checking profile kind
  3512. if((mystrcmp((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].chargingProfileKind, "Absolute") == PASS))
  3513. {
  3514. // Absolute profile
  3515. if(((mystrcmp((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].chargingProfilePurpose, "TxProfile") == PASS) && (ShmOCPP20Data->SmartChargingProfile[gun_index].transactionId == ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.transactionId)) ||
  3516. (mystrcmp((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].chargingProfilePurpose, "TxProfile") == FAIL))
  3517. {
  3518. // Checking limitation
  3519. for(uint8_t idx_period=0;idx_period<ARRAY_SIZE(ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod);idx_period++)
  3520. {
  3521. if((getScheduleStart(gun_index) > ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod[idx_period].startPeriod) &&
  3522. ((idx_period == 0) || (ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod[idx_period].startPeriod > 0))
  3523. )
  3524. {
  3525. 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);
  3526. DEBUG_INFO("ShmCharger->gun_info[%d].targetCurrent on period[%d]: %d\n", gun_index, idx_period, ShmCharger->gun_info[gun_index].targetCurrent);
  3527. }
  3528. else
  3529. break;
  3530. }
  3531. }
  3532. }
  3533. }
  3534. else if((ShmOCPP20Data->SmartChargingProfile[gun_index].id == 0) && (ShmOCPP20Data->CSUMsg.bits[gun_index].ChargingProfileReq != ON))
  3535. {
  3536. ShmCharger->gun_info[gun_index].targetCurrent = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
  3537. }
  3538. }
  3539. }
  3540. void checkStopReason(uint8_t gun_index)
  3541. {
  3542. sleep(2);
  3543. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3544. {
  3545. memset(ShmOCPP16Data->StopTransaction[gun_index].IdTag, 0x00, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  3546. if(!ocpp_get_starttransaction_result(gun_index))
  3547. {
  3548. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "DeAuthorized");
  3549. }
  3550. else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_EMERGENCY_STOP)
  3551. {
  3552. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EmergencyStop");
  3553. }
  3554. else if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)
  3555. {
  3556. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EVDisconnected");
  3557. }
  3558. else if(ShmOCPP16Data->MsMsg.bits.ResetReq)
  3559. {
  3560. if(strcmp((char*)ShmOCPP16Data->Reset.Type, "Hard")==0)
  3561. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "HardReset");
  3562. else
  3563. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "SoftReset");
  3564. }
  3565. else if(ShmCharger->gun_info[gun_index].rfidReq || ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop)
  3566. {
  3567. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
  3568. if(!isMatchStartUser(gun_index))
  3569. {
  3570. memcpy((char*)ShmOCPP16Data->StopTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  3571. }
  3572. else
  3573. {
  3574. memcpy((char*)ShmOCPP16Data->StopTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  3575. }
  3576. DEBUG_INFO("Gun-%d [ IdTag ] : %s \n", gun_index, ShmOCPP16Data->StopTransaction[gun_index].IdTag);
  3577. }
  3578. else if(ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStopTransactionReq)
  3579. {
  3580. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Remote");
  3581. }
  3582. else if(ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor == ON)
  3583. {
  3584. sprintf((char*)ShmOCPP16Data->StopTransaction[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].StopReason, "UnlockCommand");
  3585. }
  3586. else
  3587. {
  3588. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Other");
  3589. }
  3590. DEBUG_INFO("Gun-%d : StopReason [ %s ]...\n.",gun_index,ShmOCPP16Data->StopTransaction[gun_index].StopReason);
  3591. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  3592. presentChargedEnergyUpdate(gun_index);
  3593. DEBUG_INFO("PresentChargedEnergy Gun-[%d] : %.4f \n",gun_index ,ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy);
  3594. ShmOCPP16Data->CpMsg.bits[gun_index].StopTransactionReq = ON;
  3595. }
  3596. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3597. {
  3598. memset(ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, 0x00, ARRAY_SIZE(ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken));
  3599. if(!ocpp_get_starttransaction_result(gun_index))
  3600. {
  3601. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "DeAuthorized");
  3602. }
  3603. else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_EMERGENCY_STOP)
  3604. {
  3605. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "EmergencyStop");
  3606. }
  3607. else if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)
  3608. {
  3609. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "EVDisconnected");
  3610. }
  3611. else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_GROUND_FAIL)
  3612. {
  3613. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "GroundFault");
  3614. }
  3615. else if(ShmOCPP20Data->MsMsg.bits.ResetReq)
  3616. {
  3617. if(strcmp((char*)ShmOCPP20Data->Reset.type, "Immediate")==0)
  3618. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "ImmediateReset");
  3619. else
  3620. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "OnIdle");
  3621. }
  3622. else if(ShmCharger->gun_info[gun_index].rfidReq || ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop)
  3623. {
  3624. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Local");
  3625. if(!isMatchStartUser(gun_index))
  3626. {
  3627. memcpy((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, (char*)ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken));
  3628. }
  3629. else
  3630. {
  3631. memcpy((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId));
  3632. }
  3633. DEBUG_INFO("Gun-%d [ idToken ] : %s \n", gun_index, ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken);
  3634. }
  3635. else if((ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_L1_OVER_CURRENT) ||
  3636. (ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_L2_OVER_CURRENT) ||
  3637. (ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_L3_OVER_CURRENT))
  3638. {
  3639. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "OvercurrentFault");
  3640. }
  3641. else if(ShmOCPP20Data->CsMsg.bits[gun_index].RequestStopTransactionReq)
  3642. {
  3643. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Remote");
  3644. }
  3645. else if(ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor == ON)
  3646. {
  3647. sprintf((char*)ShmOCPP20Data->TransactionEvent[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].transactionInfo.stoppedReason, "UnlockCommand");
  3648. }
  3649. else
  3650. {
  3651. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Other");
  3652. }
  3653. DEBUG_INFO("Gun-%d : StopReason [ %s ]...\n.", gun_index, ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason);
  3654. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  3655. presentChargedEnergyUpdate(gun_index);
  3656. DEBUG_INFO("PresentChargedEnergy Gun-[%d] : %.4f \n",gun_index ,ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy);
  3657. ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventReq = ON;
  3658. }
  3659. }
  3660. void checkRemoteUpgradeStatus()
  3661. {
  3662. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3663. {
  3664. if(strcmp((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "DownloadFailed")==0)
  3665. {
  3666. DEBUG_INFO("Firmware remote upgraded fail...\n");
  3667. ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq = OFF;
  3668. ShmCharger->isUpdateSuccess = NO;
  3669. }
  3670. else if(strcmp((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Downloaded")==0)
  3671. {
  3672. DEBUG_INFO("Firmware remote upgrading...\n");
  3673. sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installing");
  3674. ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  3675. ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq = OFF;
  3676. int result = upgrade_check();
  3677. DEBUG_INFO("Remote update Result: %s... \n",((result == PASS)?"Pass": "Fail"));
  3678. if(result == PASS)
  3679. {
  3680. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == ON)
  3681. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = OFF;
  3682. ShmCharger->isUpdateSuccess = YES;
  3683. DEBUG_INFO("Remote update success...\n");
  3684. }
  3685. else
  3686. {
  3687. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == OFF)
  3688. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = ON;
  3689. ShmCharger->isUpdateSuccess = NO;
  3690. DEBUG_INFO("Remote update unsuccess...\n");
  3691. }
  3692. }
  3693. else
  3694. {}
  3695. }
  3696. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3697. {
  3698. if(strcmp((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "DownloadFailed")==0)
  3699. {
  3700. DEBUG_INFO("Firmware remote upgraded fail...\n");
  3701. ShmOCPP20Data->MsMsg.bits.UpdateFirmwareReq = OFF;
  3702. ShmCharger->isUpdateSuccess = NO;
  3703. }
  3704. else if(strcmp((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "Downloaded")==0)
  3705. {
  3706. DEBUG_INFO("Firmware remote upgrading...\n");
  3707. sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installing");
  3708. ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  3709. ShmOCPP20Data->MsMsg.bits.UpdateFirmwareReq = OFF;
  3710. int result = upgrade_check();
  3711. DEBUG_INFO("Remote update Result: %s... \n",((result == PASS)?"Pass": "Fail"));
  3712. if(result == PASS)
  3713. {
  3714. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == ON)
  3715. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = OFF;
  3716. ShmCharger->isUpdateSuccess = YES;
  3717. DEBUG_INFO("Remote update success...\n");
  3718. }
  3719. else
  3720. {
  3721. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == OFF)
  3722. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = ON;
  3723. ShmCharger->isUpdateSuccess = NO;
  3724. DEBUG_INFO("Remote update unsuccess...\n");
  3725. }
  3726. }
  3727. else
  3728. {}
  3729. }
  3730. }
  3731. void checkRfidAuthrize()
  3732. {
  3733. static uint8_t isCheckdResult = FALSE;
  3734. if(!ShmCharger->isAuthrizing)
  3735. {
  3736. // Read RFID
  3737. if(GetCardSerialNumber() != FAIL)
  3738. {
  3739. uint8_t isSnStart = FALSE;
  3740. uint8_t bufferRFID[ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId)];
  3741. if(ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian)
  3742. {
  3743. // Big endian
  3744. switch(rfid.snType)
  3745. {
  3746. case RFID_SN_TYPE_6BYTE:
  3747. 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]);
  3748. break;
  3749. case RFID_SN_TYPE_7BYTE:
  3750. 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]);
  3751. break;
  3752. case RFID_SN_TYPE_10BYTE:
  3753. 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]);
  3754. break;
  3755. case RFID_SN_TYPE_4BYTE:
  3756. default:
  3757. sprintf((char*)bufferRFID, "%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3]);
  3758. break;
  3759. }
  3760. }
  3761. else
  3762. {
  3763. // Little endian
  3764. switch(rfid.snType)
  3765. {
  3766. case RFID_SN_TYPE_6BYTE:
  3767. 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]);
  3768. break;
  3769. case RFID_SN_TYPE_7BYTE:
  3770. 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]);
  3771. break;
  3772. case RFID_SN_TYPE_10BYTE:
  3773. 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]);
  3774. break;
  3775. case RFID_SN_TYPE_4BYTE:
  3776. default:
  3777. sprintf((char*)bufferRFID, "%02X%02X%02X%02X", rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  3778. break;
  3779. }
  3780. }
  3781. DEBUG_INFO("Authorize request User Id : %s\n", ShmSysConfigAndInfo->SysConfig.UserId);
  3782. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  3783. ShmCharger->gun_info[gun_index].resultAuthorization = UNKNOW_RFID;
  3784. // Check SN already start
  3785. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  3786. {
  3787. if(isMatchStartUser(gun_index) || (isMatchPresentUser(gun_index) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_PREPARING)))
  3788. {
  3789. DEBUG_INFO("%s running on connector-%02d.\n", ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, gun_index);
  3790. isSnStart = TRUE;
  3791. ShmCharger->gun_info[gun_index].rfidReq = ON;
  3792. ocpp_set_auth_conf(ON);
  3793. setLedMotion(gun_index,LED_ACTION_RFID_PASS);
  3794. setSpeaker(ON, SPEAKER_SHORT);
  3795. sleep(3);
  3796. break;
  3797. }
  3798. }
  3799. // Request authorize if isSnStart is false
  3800. if(!isSnStart)
  3801. {
  3802. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, bufferRFID, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  3803. ftime(&startTime[0][TMR_IDX_AUTH]);
  3804. ocpp_set_auth_conf(OFF);
  3805. ocpp_set_auth_req(ON, "ISO14443");
  3806. setLedMotion(0,LED_ACTION_AUTHED);
  3807. ShmCharger->isAuthrizing = TRUE;
  3808. ShmCharger->isGetAuthResult = FALSE;
  3809. isCheckdResult = FALSE;
  3810. sleep(1);
  3811. }
  3812. }
  3813. }
  3814. else
  3815. {
  3816. // Wait authorize result
  3817. if(!ocpp_get_auth_conf() && (DiffTimebWithNow(startTime[0][TMR_IDX_AUTH]) > TIMEOUT_SPEC_AUTH))
  3818. {
  3819. // Authorization timeout process.
  3820. DEBUG_WARN("Authorize timeout !!!\n");
  3821. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  3822. {
  3823. ShmCharger->gun_info[gun_index].resultAuthorization = UNVALIDATED_RFID;
  3824. setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
  3825. }
  3826. setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
  3827. sleep(3);
  3828. ShmCharger->isAuthrizing = FALSE;
  3829. }
  3830. else
  3831. {
  3832. if(ocpp_get_auth_conf() ||
  3833. (!ocpp_get_connection_status() && ((ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE) || (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_NOCHARGE))) ||
  3834. (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST) && (DiffTimebWithNow(startTime[0][TMR_IDX_AUTH]) > 2000))
  3835. )
  3836. {
  3837. if(ocpp_get_auth_result(NO) ||
  3838. (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE)) ||
  3839. (!ocpp_get_connection_status() && (isValidLocalWhiteCard() == PASS) && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST)))
  3840. {
  3841. if(!isCheckdResult)
  3842. {
  3843. DEBUG_INFO("Authorize pass.\n");
  3844. setSpeaker(ON, SPEAKER_SHORT);
  3845. ftime(&startTime[0][TMR_IDX_GUN_DETECT]);
  3846. ShmCharger->isGetAuthResult = TRUE;
  3847. isCheckdResult = TRUE;
  3848. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0)
  3849. {
  3850. ocpp_set_auth_conf(ON);
  3851. }
  3852. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  3853. ShmCharger->gun_info[gun_index].resultAuthorization = VALIDATED_RFID;
  3854. }
  3855. if(DiffTimebWithNow(startTime[0][TMR_IDX_GUN_DETECT]) < (ocpp_get_connection_timeout()*1000))
  3856. {
  3857. if(GetCardSerialNumber() != FAIL)
  3858. {
  3859. if(isMatchPresentUser())
  3860. {
  3861. DEBUG_INFO("Cancel present user.\n");
  3862. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  3863. setLedMotion(gun_index,LED_ACTION_IDLE);
  3864. ShmCharger->isAuthrizing = FALSE;
  3865. }
  3866. }
  3867. else
  3868. {
  3869. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  3870. {
  3871. if(DiffTimebWithNow(startTime[0][TMR_IDX_GUN_DETECT]) < 3000)
  3872. setLedMotion(gun_index,LED_ACTION_RFID_PASS);
  3873. else
  3874. setLedMotion(gun_index,LED_ACTION_AUTHED);
  3875. 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))) ||
  3876. ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_PREPARING) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B) && (ShmCharger->gun_selectd == gun_index)) ||
  3877. (((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_CHARGING) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_TERMINATING)) && (ShmCharger->gun_selectd == gun_index))
  3878. )
  3879. {
  3880. DEBUG_INFO("Connector-%02d action detect.\n", gun_index);
  3881. ShmCharger->isAuthrizing = FALSE;
  3882. ShmCharger->gun_info[gun_index].rfidReq = ON;
  3883. break;
  3884. }
  3885. }
  3886. }
  3887. }
  3888. else
  3889. {
  3890. DEBUG_INFO("Connector action detect timeout.\n");
  3891. ShmCharger->isAuthrizing = FALSE;
  3892. ShmCharger->isGetAuthResult = TRUE;
  3893. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  3894. setLedMotion(gun_index,LED_ACTION_IDLE);
  3895. }
  3896. }
  3897. else
  3898. {
  3899. DEBUG_INFO("Authorize fail.\n");
  3900. ShmCharger->isAuthrizing = FALSE;
  3901. ShmCharger->isGetAuthResult = TRUE;
  3902. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  3903. {
  3904. ShmCharger->gun_info[gun_index].resultAuthorization = UNVALIDATED_RFID;
  3905. setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
  3906. }
  3907. setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
  3908. sleep(3);
  3909. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  3910. {
  3911. setLedMotion(gun_index,LED_ACTION_IDLE);
  3912. }
  3913. }
  3914. }
  3915. }
  3916. }
  3917. }
  3918. //======================================================
  3919. // Main process
  3920. //======================================================
  3921. int main(void)
  3922. {
  3923. //==================================================
  3924. // Create all share memory
  3925. //==================================================
  3926. if(CreatShareMemory()==0)
  3927. {
  3928. DEBUG_ERROR("CreatShareMemory NG\n");
  3929. if(ShmStatusCodeData!=NULL)
  3930. {
  3931. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=1;
  3932. }
  3933. sleep(5);
  3934. system("reboot -f");
  3935. sleep(5);
  3936. system("reboot -f");
  3937. }
  3938. else
  3939. {
  3940. DEBUG_INFO("CreatShareMemory OK\n");
  3941. }
  3942. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  3943. {
  3944. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus = 0xff;
  3945. ShmCharger->gun_info[gun_index].primaryMcuState.rotatory_switch = 0xff;
  3946. ShmCharger->gun_info[gun_index].mcuResetRequest.isMcuResetRequest = ON;
  3947. ShmCharger->gun_info[gun_index].isSetBreatheLedTiming = OFF;
  3948. ShmCharger->gun_info[gun_index].isSetLedBrightness = OFF;
  3949. }
  3950. //==================================================
  3951. // Main loop
  3952. //==================================================
  3953. for(;;)
  3954. {
  3955. //==============================================
  3956. // Synchronize share memory from OCPP struct
  3957. //==============================================
  3958. ShmSysConfigAndInfo->SysInfo.OcppConnStatus = ocpp_get_connection_status();
  3959. //==============================================
  3960. // Period check for 10 seconds
  3961. //==============================================
  3962. if(DiffTimebWithNow(startTime[0][TMR_IDX_CHECK_TASK]) > 10000)
  3963. {
  3964. //==============================================
  3965. // Check task processing
  3966. //==============================================
  3967. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[0].SystemStatus != SYS_MODE_BOOTING)
  3968. checkTask();
  3969. //==============================================
  3970. // Check connection timeout specification
  3971. //==============================================
  3972. checkConnectionTimeout();
  3973. ftime(&startTime[0][TMR_IDX_CHECK_TASK]);
  3974. }
  3975. //==============================================
  3976. // Something need run in Idle mode
  3977. //==============================================
  3978. 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)) &&
  3979. (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))
  3980. {
  3981. // Check restore factory setting request
  3982. if(ShmSysConfigAndInfo->SysInfo.FactoryConfiguration)
  3983. {
  3984. // Set led to initial
  3985. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  3986. {
  3987. setLedMotion(gun_index,LED_ACTION_INIT);
  3988. }
  3989. sleep(5);
  3990. system("cd /root;./Module_FactoryConfig -m");
  3991. system("rm -f /Storage/OCPP/OCPPConfiguration");
  3992. system("sync");
  3993. sleep(5);
  3994. system("reboot -f");
  3995. sleep(5);
  3996. system("reboot -f");
  3997. }
  3998. // Check upgrade firmware request
  3999. if(ShmSysConfigAndInfo->SysInfo.FirmwareUpdate ||
  4000. ocpp_get_update_firmware_req())
  4001. {
  4002. // If available memory too small, free memory cache first
  4003. if(getAvailableMemory() < (200*1024*1024))
  4004. {
  4005. DEBUG_INFO("Available memory (%.2f Bytes) less than 200 MBytes, free cache first.\n", getAvailableMemory()/(1024*1024.0));
  4006. system("echo 3 > /proc/sys/vm/drop_caches");
  4007. }
  4008. ShmCharger->isUpdateSuccess = NO;
  4009. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  4010. {
  4011. setLedMotion(gun_index,LED_ACTION_MAINTAIN);
  4012. setChargerMode(gun_index, SYS_MODE_UPDATE);
  4013. }
  4014. }
  4015. }
  4016. //==============================================
  4017. // Check remote reset request
  4018. //==============================================
  4019. checkReset();
  4020. //==============================================
  4021. // Check RFID authorization
  4022. //==============================================
  4023. checkRfidAuthrize();
  4024. //==============================================
  4025. // Connector loop
  4026. //==============================================
  4027. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  4028. {
  4029. //==========================================
  4030. // Power saving logic
  4031. //==========================================
  4032. /*
  4033. * TODO:
  4034. * 1. Power saving logic
  4035. */
  4036. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)
  4037. {
  4038. ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_STATE_B]);
  4039. }
  4040. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_CHARGING) ||
  4041. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_TERMINATING))
  4042. {
  4043. ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
  4044. ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_RFID]);
  4045. ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_METER]);
  4046. }
  4047. else
  4048. {
  4049. if((ShmCharger->gun_info[gun_index].GPIO_Input.Button_Mode_Switch == ON) ||
  4050. (gpio_get_value(GPIO_IN_WAKEUP) == ON) ||
  4051. (((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_IDLE) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_PREPARING)) &&
  4052. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B) &&
  4053. (DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_STATE_B]) < 10000)))
  4054. {
  4055. ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
  4056. ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_RFID]);
  4057. ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_METER]);
  4058. }
  4059. }
  4060. if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD]) > TIMEOUT_SPEC_POWERSAVING_LCD)
  4061. {
  4062. if(ShmCharger->isLcdOn == ON)
  4063. {
  4064. //if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD]) < (TIMEOUT_SPEC_POWERSAVING_LCD+600))
  4065. DEBUG_INFO("LCD into power saving...%d\n", DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD]));
  4066. ShmCharger->isLcdOn = OFF;
  4067. }
  4068. }
  4069. else
  4070. {
  4071. if(ShmCharger->isLcdOn == OFF)
  4072. {
  4073. //if((0 < DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD])) && (DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD]) < 600))
  4074. DEBUG_INFO("LCD exit power saving...%d\n", DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD]));
  4075. ShmCharger->isLcdOn = ON;
  4076. }
  4077. }
  4078. if(DiffTimebWithNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_RFID]) > TIMEOUT_SPEC_POWERSAVING_RFID)
  4079. {
  4080. if(gpio_get_value(GPIO_OUT_RST_RFID) == ON)
  4081. {
  4082. DEBUG_INFO("RFID into power saving...%d\n", DiffTimebWithNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_RFID]));
  4083. gpio_set_value(GPIO_OUT_RST_RFID, OFF);
  4084. }
  4085. }
  4086. else
  4087. {
  4088. if(gpio_get_value(GPIO_OUT_RST_RFID) == OFF)
  4089. {
  4090. DEBUG_INFO("RFID exit power saving...%d\n", DiffTimebWithNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_RFID]));
  4091. gpio_set_value(GPIO_OUT_RST_RFID, ON);
  4092. }
  4093. }
  4094. if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_METER]) > TIMEOUT_SPEC_POWERSAVING_METER)
  4095. {
  4096. if(ShmCharger->gun_info[gun_index].isMeterOn )
  4097. {
  4098. DEBUG_INFO("Meter into power saving...%d\n", DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_METER]));
  4099. ShmCharger->gun_info[gun_index].isMeterOn = OFF;
  4100. }
  4101. }
  4102. else
  4103. {
  4104. if(!ShmCharger->gun_info[gun_index].isMeterOn )
  4105. {
  4106. DEBUG_INFO("Meter exit power saving...%d\n", DiffTimebWithNow(startTime[gun_index][TMR_IDX_POWERSAVING_METER]));
  4107. ShmCharger->gun_info[gun_index].isMeterOn = ON;
  4108. }
  4109. }
  4110. //==========================================
  4111. // Synchronize current rating value from MCU
  4112. //==========================================
  4113. ShmSysConfigAndInfo->SysConfig.RatingCurrent = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
  4114. //==========================================
  4115. // Assign connector location index for OCPP
  4116. //==========================================
  4117. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].Index = gun_index;
  4118. //==========================================
  4119. // Synchronize present charging power
  4120. //==========================================
  4121. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount == 1)
  4122. {
  4123. if(ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON)
  4124. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingVoltage*ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrent)/1000;
  4125. else
  4126. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = 0;
  4127. }
  4128. else
  4129. {
  4130. if(ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON)
  4131. {
  4132. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = (((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingVoltage*ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrent)/1000) +
  4133. ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingVoltageL2*ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrentL2)/1000) +
  4134. ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingVoltageL3*ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrentL3)/1000));
  4135. }
  4136. else
  4137. {
  4138. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = 0;
  4139. }
  4140. }
  4141. //==========================================
  4142. // Check initialization "PASS" or "FAIL"
  4143. //==========================================
  4144. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[0].SystemStatus != SYS_MODE_BOOTING)
  4145. {
  4146. // Alarm event check
  4147. if((ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode>0))
  4148. {
  4149. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_ALARM)
  4150. {
  4151. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_UPDATE)
  4152. {
  4153. setChargerMode(gun_index, SYS_MODE_ALARM);
  4154. }
  4155. }
  4156. }
  4157. }
  4158. //==========================================
  4159. // Reservation request check
  4160. //==========================================
  4161. checkReservation(gun_index);
  4162. //==========================================
  4163. // Change availability check
  4164. //==========================================
  4165. checkAvailability(gun_index);
  4166. if(ShmCharger->gun_info[gun_index].isOperactive)
  4167. {
  4168. if(isMode(gun_index, SYS_MODE_MAINTAIN))
  4169. {
  4170. setChargerMode(gun_index, SYS_MODE_IDLE);
  4171. }
  4172. }
  4173. else
  4174. {
  4175. if(isMode(gun_index, SYS_MODE_IDLE))
  4176. {
  4177. setChargerMode(gun_index, SYS_MODE_MAINTAIN);
  4178. }
  4179. }
  4180. //==========================================
  4181. // Unlock Connector signal check
  4182. //==========================================
  4183. checkUnlocker(gun_index);
  4184. //==========================================
  4185. // Connector process
  4186. //==========================================
  4187. switch(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus)
  4188. {
  4189. case SYS_MODE_BOOTING:
  4190. if(isModeChange(gun_index))
  4191. {
  4192. setLedMotion(gun_index,LED_ACTION_INIT);
  4193. //CSU Initialization & task spawn
  4194. if((Initialization(gun_index) != PASS) ||
  4195. (SpawnTask(gun_index) != PASS))
  4196. {
  4197. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = ON;
  4198. }
  4199. ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
  4200. ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_RFID]);
  4201. ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_METER]);
  4202. ftime(&startTime[gun_index][TMR_IDX_POWERSAVING_STATE_B]);
  4203. }
  4204. if(ShmCharger->gun_info[gun_index].mcuFlag.isReadFwVerPass &&
  4205. ShmCharger->gun_info[gun_index].mcuFlag.isSetModelNamePass &&
  4206. ShmCharger->gun_info[gun_index].mcuFlag.isSetSerialNumberPass)
  4207. {
  4208. ShmCharger->gun_selectd = 0;
  4209. // Firmware version
  4210. get_firmware_version(gun_index);
  4211. // OCPP BootNotification info set
  4212. DEBUG_INFO("==========================================\n");
  4213. DEBUG_INFO("System ID: %s\n",ShmSysConfigAndInfo->SysConfig.SystemId);
  4214. DEBUG_INFO("==========================================\n");
  4215. DEBUG_INFO("=== OCPP BootNotification information ====\n");
  4216. ocpp_boot_info_sync();
  4217. DEBUG_INFO("OcppServerURL: %s\n",ShmSysConfigAndInfo->SysConfig.OcppServerURL);
  4218. DEBUG_INFO("ChargeBoxId: %s\n",ShmSysConfigAndInfo->SysConfig.ChargeBoxId);
  4219. DEBUG_INFO("ChargePointVendor: %s\n",ShmSysConfigAndInfo->SysConfig.chargePointVendor);
  4220. DEBUG_INFO("==========================================\n");
  4221. DEBUG_INFO("========== Set Wifi information ==========\n");
  4222. DEBUG_INFO("Wifi mode: %d\n", ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode);
  4223. DEBUG_INFO("Wifi SSID: %s\n", ShmSysConfigAndInfo->SysConfig.AthInterface.WifiSsid);
  4224. DEBUG_INFO("Wifi password: %s\n", ShmSysConfigAndInfo->SysConfig.AthInterface.WifiPassword);
  4225. DEBUG_INFO("==========================================\n");
  4226. // Set max current to rating current
  4227. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
  4228. // Default Ethernet / Wifi / 4G to 1:disconnected
  4229. switch(ShmSysConfigAndInfo->SysConfig.ModelName[10])
  4230. {
  4231. case 'E':
  4232. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
  4233. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = OFF;
  4234. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = OFF;
  4235. break;
  4236. case 'W':
  4237. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
  4238. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = ON;
  4239. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = OFF;
  4240. break;
  4241. case 'T':
  4242. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
  4243. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = OFF;
  4244. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = ON;
  4245. break;
  4246. case 'D':
  4247. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
  4248. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = ON;
  4249. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = ON;
  4250. break;
  4251. }
  4252. // Default LCM brightness to 100
  4253. ShmCharger->isLcdOn = ON;
  4254. // If Web Server OPCC URL is empty kill Module_OcppBackend
  4255. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0)
  4256. {
  4257. DEBUG_INFO("URL is empty kill Module_OcppBackend...\n");
  4258. system ("pkill OcppBackend");
  4259. }
  4260. // If rotate switch equal zero, the system needs to change Debug mode
  4261. if(ShmCharger->gun_info[gun_index].primaryMcuState.rotatory_switch == 0)
  4262. setChargerMode(gun_index, SYS_MODE_DEBUG);
  4263. else
  4264. setChargerMode(gun_index, SYS_MODE_IDLE);
  4265. ShmSysConfigAndInfo->SysConfig.AcPhaseCount = ((ShmSysConfigAndInfo->SysConfig.ModelName[2]=='Y') ||
  4266. (ShmSysConfigAndInfo->SysConfig.ModelName[2]=='D') ||
  4267. (ShmSysConfigAndInfo->SysConfig.ModelName[2]=='W')
  4268. ?3:1);
  4269. }
  4270. break;
  4271. case SYS_MODE_IDLE:
  4272. if(isModeChange(gun_index))
  4273. {
  4274. setLedMotion(gun_index,LED_ACTION_IDLE);
  4275. setRelay(gun_index, OFF);
  4276. setRequest(gun_index,OFF);
  4277. ShmCharger->gun_info[gun_index].isGunPlugged = NO;
  4278. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  4279. ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart = OFF;
  4280. ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop = OFF;
  4281. ocpp_set_remotestart(gun_index, OFF);
  4282. ocpp_set_remotestop(gun_index, OFF);
  4283. ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode = 0x00;
  4284. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = 0;
  4285. presentChargedEnergyClear(gun_index);
  4286. ShmCharger->gun_info[gun_index].targetCurrent = 0xFF;
  4287. ocpp_set_unlocker_req(gun_index, OFF);
  4288. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId = -1;
  4289. // Response StopTransactionConf
  4290. ocpp_set_stoptransaction_conf(gun_index, OFF);
  4291. memset(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId));
  4292. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_IDLE;
  4293. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_BS;
  4294. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  4295. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  4296. ShmCharger->gun_info[gun_index].isDoEvReadyOnce = OFF;
  4297. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  4298. if(ShmCharger->isCcsEnable)system("pkill Module_CCS");
  4299. DB_Check_Record_Buf(localDb, gun_index);
  4300. }
  4301. if(((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B)) ||
  4302. ((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)) ||
  4303. (ShmCharger->gun_info[gun_index].rfidReq == ON) ||
  4304. (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart == ON) ||
  4305. (ocpp_get_remotestart(gun_index) == ON) ||
  4306. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStart == ON))
  4307. {
  4308. if((ShmCharger->gun_info[gun_index].rfidReq == ON))
  4309. {
  4310. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_RFID;
  4311. DEBUG_INFO("Start Method : RFID...\n");
  4312. }
  4313. else if(ocpp_get_remotestart(gun_index))
  4314. {
  4315. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_BACKEND;
  4316. ocpp_copy_userid_from_remotestart(gun_index);
  4317. setSpeaker(ON, SPEAKER_SHORT);
  4318. DEBUG_INFO("Start Method : BACKEND...\n");
  4319. }
  4320. else if(ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart == ON)
  4321. {
  4322. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_BLE;
  4323. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmCharger->gun_info[gun_index].bleLoginCentralId.id, ARRAY_SIZE(ShmCharger->gun_info[gun_index].bleLoginCentralId.id));
  4324. setSpeaker(ON, SPEAKER_SHORT);
  4325. DEBUG_INFO("Start Method : BLE...\n");
  4326. }
  4327. else
  4328. {
  4329. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_FREE;
  4330. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmSysConfigAndInfo->SysConfig.SerialNumber, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SerialNumber));
  4331. setSpeaker(ON, SPEAKER_SHORT);
  4332. DEBUG_INFO("Start Method : FREE...\n");
  4333. }
  4334. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  4335. ocpp_set_remotestart(gun_index, OFF);
  4336. ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart = OFF;
  4337. ShmCharger->gun_info[gun_index].isGunPlugged = NO;
  4338. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStart = OFF;
  4339. setChargerMode(gun_index, SYS_MODE_AUTHORIZING);
  4340. }
  4341. else
  4342. {}
  4343. break;
  4344. case SYS_MODE_AUTHORIZING:
  4345. if(isModeChange(gun_index))
  4346. {
  4347. ftime(&startTime[gun_index][TMR_IDX_AUTH]);
  4348. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = YES;
  4349. if(ShmCharger->isCcsEnable)system("/root/Module_CCS &");
  4350. }
  4351. setChargerMode(gun_index, SYS_MODE_PREPARING);
  4352. break;
  4353. case SYS_MODE_PREPARING:
  4354. if(isModeChange(gun_index))
  4355. {
  4356. ftime(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  4357. setLedMotion(gun_index,LED_ACTION_AUTHED);
  4358. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  4359. if(ShmCharger->isCcsEnable)
  4360. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_DUTY_5;
  4361. else
  4362. {
  4363. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_CP_STATE_E;
  4364. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_BS;
  4365. setRequest(gun_index, ON);
  4366. }
  4367. }
  4368. // If control pilot detect Bx, skip watch dog time out.
  4369. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B) ||
  4370. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C))
  4371. {
  4372. ShmCharger->gun_info[gun_index].isGunPlugged = YES;
  4373. switch(ShmCharger->gun_info[gun_index].ccsHandshakeState)
  4374. {
  4375. case HANDSHAKE_DUTY_5:
  4376. if(!getRequest(gun_index))
  4377. {
  4378. setRequest(gun_index, ON);
  4379. setLedMotion(gun_index,LED_ACTION_CONNECTED);
  4380. ftime(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  4381. DEBUG_INFO("Set Request On.\n");
  4382. //Let CCS task start to negotiate
  4383. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = ON;
  4384. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_NONE;
  4385. }
  4386. // Set CCS 5% PWM duty
  4387. if(ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty == CCS_PWM_DUTY_5)
  4388. {
  4389. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_5;
  4390. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_DUTY_5_CHECK;
  4391. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  4392. }
  4393. break;
  4394. case HANDSHAKE_DUTY_5_CHECK:
  4395. if((ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF))
  4396. {
  4397. //2 secs timeout
  4398. ftime(&startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]);
  4399. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_CCS;
  4400. }
  4401. break;
  4402. case HANDSHAKE_CCS:
  4403. //CCS handshake timeout
  4404. if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]) > TIMEOUT_SPEC_BS_HLC_HANDSHAKE)
  4405. {
  4406. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  4407. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  4408. DEBUG_INFO("BS/HLC %d secs handshake timeout.\n", (TIMEOUT_SPEC_BS_HLC_HANDSHAKE/1000));
  4409. }
  4410. if((ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission == OFF) && (ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty != CCS_PWM_DUTY_5))
  4411. {
  4412. DEBUG_INFO("Wait CCS give up negotiagting.\n");
  4413. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_CP_STATE_F;
  4414. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  4415. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_CP_STATE_E;
  4416. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_BS;
  4417. }
  4418. //CCS status check
  4419. if((16 < ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus) && (ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus < 254))
  4420. {
  4421. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_HLC;
  4422. DEBUG_INFO("Enter HLC Mode charging.\n");
  4423. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_HLC_MODE;
  4424. ftime(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  4425. }
  4426. break;
  4427. case HANDSHAKE_CP_STATE_E:
  4428. if(ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)
  4429. {
  4430. if(ShmCharger->isCcsEnable)
  4431. {
  4432. DEBUG_INFO("Change to CP STATE E for 4 secs.\n");
  4433. //CP STATE E for 4 secs
  4434. sleep(4);
  4435. }
  4436. //restore normal CP PWM duty
  4437. // Determine max charging current to MCU
  4438. DEBUG_INFO("Determine max charging current to MCU.\n");
  4439. if(ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent == 0)
  4440. {
  4441. 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);
  4442. if(ShmCharger->gun_info[gun_index].targetCurrent != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current)
  4443. {
  4444. 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);
  4445. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  4446. }
  4447. }
  4448. else
  4449. {
  4450. ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent)?ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent:ShmCharger->gun_info[gun_index].targetCurrent);
  4451. if(ShmCharger->gun_info[gun_index].targetCurrent != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current)
  4452. {
  4453. 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);
  4454. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  4455. }
  4456. }
  4457. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  4458. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_SET_MAX_CURRENT;
  4459. ftime(&startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]);
  4460. }
  4461. break;
  4462. case HANDSHAKE_SET_MAX_CURRENT:
  4463. if(ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)
  4464. {
  4465. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_BS_MODE;
  4466. DEBUG_INFO("Enter BS Mode charging.\n");
  4467. //for EV READY 30 secs didn't start charging to STATE E
  4468. ftime(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  4469. }
  4470. break;
  4471. case HANDSHAKE_BS_MODE:
  4472. ftime(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  4473. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)
  4474. setRelay(gun_index,ON);
  4475. if((ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON))
  4476. {
  4477. ocpp_set_unlocker_req(gun_index, OFF);
  4478. presentChargedEnergyClear(gun_index);
  4479. getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime);
  4480. ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption;
  4481. ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption;
  4482. ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption;
  4483. ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption;
  4484. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==1)
  4485. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  4486. else
  4487. {
  4488. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[0] = (ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption/10000.0);
  4489. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[1] = (ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption/10000.0);
  4490. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[2] = (ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption/10000.0);
  4491. }
  4492. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  4493. ocpp_copy_userid_to_starttransaction(gun_index);
  4494. ocpp_set_starttransaction_req(gun_index, ON);
  4495. ftime(&startChargingTime[gun_index]);
  4496. setChargerMode(gun_index, SYS_MODE_CHARGING);
  4497. }
  4498. //EV READY CHECK
  4499. /*
  4500. if((DiffTimebWithNow(startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]) > TIMEOUT_SPEC_EV_READY) && (ShmCharger->gun_info[gun_index].isEvReady2StateE == OFF))
  4501. {
  4502. if(ShmCharger->gun_info[gun_index].isDoEvReadyOnce == OFF)
  4503. {
  4504. DEBUG_INFO("EV READY STATE E 4sec.\n");
  4505. ShmCharger->gun_info[gun_index].isEvReady2StateE = ON;
  4506. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_CP_STATE_E;
  4507. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  4508. ShmCharger->gun_info[gun_index].evReadyState = EV_READY_STAT_E;
  4509. }
  4510. }
  4511. if(ShmCharger->gun_info[gun_index].isEvReady2StateE == ON)
  4512. {
  4513. switch(ShmCharger->gun_info[gun_index].evReadyState)
  4514. {
  4515. case EV_READY_STAT_E:
  4516. if(ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)
  4517. {
  4518. sleep(4);
  4519. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  4520. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  4521. ShmCharger->gun_info[gun_index].evReadyState = EV_READY_STAT_C;
  4522. }
  4523. break;
  4524. case EV_READY_STAT_C:
  4525. if(ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)
  4526. {
  4527. usleep(500000);
  4528. DEBUG_INFO("EV READY Determine max charging current to MCU.\n");
  4529. if(ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent == 0)
  4530. {
  4531. 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);
  4532. if(ShmCharger->gun_info[gun_index].targetCurrent != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current)
  4533. {
  4534. 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);
  4535. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  4536. }
  4537. }
  4538. else
  4539. {
  4540. ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent)?ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent:ShmCharger->gun_info[gun_index].targetCurrent);
  4541. if(ShmCharger->gun_info[gun_index].targetCurrent != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current)
  4542. {
  4543. 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);
  4544. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  4545. }
  4546. }
  4547. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  4548. ShmCharger->gun_info[gun_index].evReadyState = EV_READY_SET_MAX_CURRENT;
  4549. }
  4550. break;
  4551. case EV_READY_SET_MAX_CURRENT:
  4552. if(ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)
  4553. {
  4554. ShmCharger->gun_info[gun_index].isEvReady2StateE = OFF;
  4555. ShmCharger->gun_info[gun_index].isDoEvReadyOnce = ON;
  4556. }
  4557. break;
  4558. default:
  4559. break;
  4560. }
  4561. }*/
  4562. break;
  4563. case HANDSHAKE_HLC_MODE:
  4564. if(ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_START_MODE)
  4565. {
  4566. setRelay(gun_index,ON);
  4567. ShmCharger->gun_info[gun_index].isCCSStartTransation = ON;
  4568. }
  4569. if((ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON) &&
  4570. (ShmCharger->gun_info[gun_index].isCCSStartTransation == ON))
  4571. {
  4572. ocpp_set_unlocker_req(gun_index, OFF);
  4573. presentChargedEnergyClear(gun_index);
  4574. getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime);
  4575. ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption;
  4576. ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption;
  4577. ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption;
  4578. ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption;
  4579. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==1)
  4580. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  4581. else
  4582. {
  4583. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[0] = (ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption/10000.0);
  4584. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[1] = (ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption/10000.0);
  4585. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[2] = (ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption/10000.0);
  4586. }
  4587. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  4588. ocpp_copy_userid_to_starttransaction(gun_index);
  4589. ocpp_set_starttransaction_req(gun_index, ON);
  4590. ShmCharger->gun_info[gun_index].isCCSStartTransation = OFF;
  4591. setChargerMode(gun_index, SYS_MODE_CHARGING);
  4592. ftime(&startChargingTime[gun_index]);
  4593. ftime(&startTime[gun_index][TMR_IDX_CCS_HEARTBEAT_COUNT_RESET]);
  4594. }
  4595. //120 sec timeout
  4596. if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_HANDSHAKING]) > TIMEOUT_SPEC_CCS_HANDSHAKE)
  4597. {
  4598. setLedMotion(gun_index, LED_ACTION_HANDSHAKE_FAIL);
  4599. if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_HANDSHAKING]) > TIMEOUT_SPEC_CCS_HANDSHAKE+5000)
  4600. {
  4601. DEBUG_INFO("CCS 120 secs handshake timeout.\n");
  4602. //Cancel CCS task negotiating
  4603. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  4604. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  4605. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = ON;
  4606. }
  4607. }
  4608. if((ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty == ON) && ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty == CCS_PWM_DUTY_100)
  4609. {
  4610. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  4611. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  4612. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = OFF;
  4613. setChargerMode(gun_index, SYS_MODE_IDLE);
  4614. }
  4615. break;
  4616. default:
  4617. break;
  4618. }
  4619. }
  4620. else if(ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEMode)
  4621. {
  4622. DEBUG_INFO("Enter Socket-E Mode charging.\n");
  4623. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_SOCKETE;
  4624. if(ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn == ON)
  4625. setRelay(gun_index,ON);
  4626. ocpp_copy_userid_to_starttransaction(gun_index);
  4627. ocpp_set_starttransaction_req(gun_index, ON);
  4628. ftime(&startChargingTime[gun_index]);
  4629. setChargerMode(gun_index, SYS_MODE_CHARGING);
  4630. }
  4631. // Unplug charging gun to Idle mode
  4632. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A) && (ShmCharger->gun_info[gun_index].isGunPlugged == YES))
  4633. {
  4634. DEBUG_INFO("Charging gun is plugged before.\n");
  4635. //setChargerMode(gun_index, SYS_MODE_IDLE);
  4636. //Cancel CCS task negotiating
  4637. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  4638. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  4639. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = ON;
  4640. }
  4641. // Use RFID card to stop handshaking
  4642. if((ShmCharger->gun_info[gun_index].rfidReq == ON) && isMatchPresentUser(gun_index))
  4643. {
  4644. DEBUG_INFO("Use RFID card to stop handshaking.\n");
  4645. setSpeaker(ON,SPEAKER_SHORT);
  4646. //setChargerMode(gun_index, SYS_MODE_IDLE);
  4647. //Cancel CCS task negotiating
  4648. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  4649. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  4650. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = ON;
  4651. }
  4652. else
  4653. {
  4654. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  4655. }
  4656. if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_HANDSHAKING]) > ShmCharger->timeoutSpec.Present_Timeout_Spec)
  4657. {
  4658. setLedMotion(gun_index, LED_ACTION_HANDSHAKE_FAIL);
  4659. if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_HANDSHAKING]) > (ShmCharger->timeoutSpec.Present_Timeout_Spec+5000))
  4660. {
  4661. DEBUG_INFO("Handshaking timeout...\n");
  4662. //Cancel CCS task negotiating
  4663. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  4664. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  4665. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = ON;
  4666. }
  4667. }
  4668. if((ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty == ON) && ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty != CCS_PWM_DUTY_5)
  4669. {
  4670. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  4671. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  4672. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = OFF;
  4673. setChargerMode(gun_index, SYS_MODE_IDLE);
  4674. }
  4675. break;
  4676. case SYS_MODE_CHARGING:
  4677. if(isModeChange(gun_index))
  4678. {
  4679. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  4680. //ftime(&startChargingTime[gun_index]);
  4681. ftime(&startTime[gun_index][TMR_IDX_LOGPPRINTOUT]);
  4682. ftime(&startTime[gun_index][TMR_IDX_PROFILE_PREPARE]);
  4683. ftime(&startTime[gun_index][TMR_IDX_PWN_CHANGE]);
  4684. ocpp_set_auth_req(OFF);
  4685. ocpp_reset_smartcharging_profileId(gun_index);
  4686. ocpp_set_profile_req(gun_index, ON);
  4687. ShmCharger->gun_info[gun_index].isChargerStopByCondition = NO;
  4688. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  4689. }
  4690. //if time up, clear CCS MSG count
  4691. if((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) &&
  4692. (DiffTimebWithNow(startTime[gun_index][TMR_IDX_CCS_HEARTBEAT_COUNT_RESET]) > TIMEOUT_SPEC_CCS_HEARTBEAT_COUNT_RESET))
  4693. {
  4694. ftime(&startTime[gun_index][TMR_IDX_CCS_HEARTBEAT_COUNT_RESET]);
  4695. if(ShmCharger->gun_info[gun_index].acCcsInfo.CcsHeartBeat > 0)
  4696. {
  4697. ShmCharger->gun_info[gun_index].acCcsInfo.CcsHeartBeat = 0;
  4698. }
  4699. else
  4700. {
  4701. DEBUG_INFO("CCS could not get MSG from car.\n");
  4702. //setChargerMode(gun_index, SYS_MODE_TERMINATING);
  4703. //setRelay(gun_index, OFF);
  4704. }
  4705. }
  4706. if((ShmCharger->gun_info[gun_index].rfidReq == ON) ||
  4707. (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop == ON) ||
  4708. ocpp_get_remotestop(gun_index) ||
  4709. (ocpp_get_connection_status() && !ocpp_get_starttransaction_result(gun_index)) ||
  4710. ((ShmCharger->gun_info[gun_index].chargingMode != CHARGING_MODE_SOCKETE) && ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState != CP_STATE_C) ||
  4711. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE) && !ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn) ||
  4712. ocpp_get_reset_req() ||
  4713. ocpp_get_unlocker_req(gun_index) ||
  4714. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop == ON) ||
  4715. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && (ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_STOP_MODE)) ||
  4716. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_RENEGOTIATE_MODE) ||
  4717. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_STANDBY_MODE))
  4718. {
  4719. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  4720. setRelay(gun_index, OFF);
  4721. }
  4722. else
  4723. {
  4724. // Charging session info calculation
  4725. setLedMotion(gun_index,LED_ACTION_CHARGING);
  4726. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==1)
  4727. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  4728. else
  4729. {
  4730. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[0] = (ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption/10000.0);
  4731. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[1] = (ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption/10000.0);
  4732. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[2] = (ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption/10000.0);
  4733. }
  4734. ftime(&endChargingTime[gun_index]);
  4735. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = DiffTimeb(startChargingTime[gun_index], endChargingTime[gun_index])/1000;
  4736. presentChargedEnergyUpdate(gun_index);
  4737. // Response StartTransactionConf
  4738. ocpp_set_starttransaction_conf(gun_index, OFF);
  4739. // Charging profile preparation
  4740. if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_PROFILE_PREPARE]) > TIMEOUT_SPEC_PROFILE_PREPARE)
  4741. {
  4742. if(!ocpp_get_profile_conf(gun_index))
  4743. {
  4744. ocpp_set_profile_req(gun_index, ON);
  4745. ftime(&startTime[gun_index][TMR_IDX_PROFILE_PREPARE]);
  4746. }
  4747. else
  4748. {
  4749. ocpp_set_profile_conf(gun_index, OFF);
  4750. }
  4751. }
  4752. // Checking profile id > 0 and current time is between charging profile validFrom & validTo
  4753. checkChargingProfileLimit(gun_index);
  4754. // Charging session target current check if OCPP disconnect and power sharing server connected
  4755. if(!ocpp_get_connection_status() && ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer)
  4756. {
  4757. ShmCharger->gun_info[gun_index].targetCurrent = ShmSysConfigAndInfo->SysInfo.localSharingInfo.AvailableShargingCurrent;
  4758. }
  4759. // Determine max charging current to MCU
  4760. if(ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent == 0)
  4761. {
  4762. ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmCharger->gun_info[gun_index].primaryMcuState.rating_current)?ShmCharger->gun_info[gun_index].primaryMcuState.rating_current:ShmCharger->gun_info[gun_index].targetCurrent);
  4763. if((ShmCharger->gun_info[gun_index].targetCurrent != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current) ||
  4764. (ShmCharger->gun_info[gun_index].primaryMcuState.current_limit != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current))
  4765. {
  4766. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  4767. {
  4768. if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_PWN_CHANGE]) > TIMEOUT_SPEC_PWN_CHANGE)
  4769. {
  4770. if(ShmCharger->gun_info[gun_index].targetCurrent>0)
  4771. {
  4772. 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);
  4773. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = YES;
  4774. }
  4775. ftime(&startTime[gun_index][TMR_IDX_PWN_CHANGE]);
  4776. }
  4777. }
  4778. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  4779. {
  4780. 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);
  4781. }
  4782. }
  4783. }
  4784. else
  4785. {
  4786. ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent)?ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent:ShmCharger->gun_info[gun_index].targetCurrent);
  4787. if((ShmCharger->gun_info[gun_index].targetCurrent != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current) ||
  4788. (ShmCharger->gun_info[gun_index].primaryMcuState.current_limit != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current))
  4789. {
  4790. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  4791. {
  4792. if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_PWN_CHANGE]) > TIMEOUT_SPEC_PWN_CHANGE)
  4793. {
  4794. if(ShmCharger->gun_info[gun_index].targetCurrent>0)
  4795. {
  4796. 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);
  4797. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = YES;
  4798. }
  4799. ftime(&startTime[gun_index][TMR_IDX_PWN_CHANGE]);
  4800. }
  4801. }
  4802. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  4803. {
  4804. 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);
  4805. }
  4806. }
  4807. }
  4808. // Charging session local limit condition check
  4809. if(ocpp_get_connection_status())
  4810. {
  4811. // On-line max condition check
  4812. if((ShmSysConfigAndInfo->SysConfig.MaxChargingDuration > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60)))
  4813. {
  4814. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  4815. {
  4816. setRelay(gun_index, OFF);
  4817. ShmCharger->gun_info[gun_index].isChargerStopByCondition = YES;
  4818. }
  4819. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  4820. {
  4821. setRelay(gun_index, OFF);
  4822. }
  4823. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  4824. 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));
  4825. }
  4826. else if((ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy)))
  4827. {
  4828. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  4829. {
  4830. setRelay(gun_index, OFF);
  4831. ShmCharger->gun_info[gun_index].isChargerStopByCondition = YES;
  4832. }
  4833. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  4834. {
  4835. setRelay(gun_index, OFF);
  4836. }
  4837. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  4838. 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));
  4839. }
  4840. else
  4841. {
  4842. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  4843. {
  4844. ShmCharger->gun_info[gun_index].isChargerStopByCondition = NO;
  4845. if(ShmCharger->gun_info[gun_index].targetCurrent>0)
  4846. setRelay(gun_index, ON);
  4847. else
  4848. setRelay(gun_index, OFF);
  4849. }
  4850. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  4851. {
  4852. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)
  4853. setRelay(gun_index, ON);
  4854. }
  4855. }
  4856. }
  4857. else
  4858. {
  4859. // Off-line max condition check
  4860. if((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) ||
  4861. ((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_ENABLE) && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy != OFF_POLICY_NOCHARGE)))
  4862. {
  4863. 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))))
  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 off-line max duration(%d) in second.\n", gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration, (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60));
  4876. }
  4877. 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))))
  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 off-line max energy(%.2f) in KWH.\n", gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy, ((float)ShmSysConfigAndInfo->SysConfig.OfflineMaxChargeEnergy));
  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. if(ShmCharger->gun_info[gun_index].primaryMcuState.relay_state > 0)
  4911. DEBUG_INFO("Connector-%d can not charging in off line\n", gun_index);
  4912. setRelay(gun_index, OFF);
  4913. }
  4914. }
  4915. // Debug information
  4916. if(DiffTimebWithNow(startTime[gun_index][TMR_IDX_LOGPPRINTOUT]) > TIMEOUT_SPEC_LOGPPRINTOUT)
  4917. {
  4918. DEBUG_INFO("==============================================================\n");
  4919. DEBUG_INFO("ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent: %d \n", ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent);
  4920. 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);
  4921. DEBUG_INFO("ShmCharger->gun_info[%d].targetCurrent: %d\n", gun_index, ShmCharger->gun_info[gun_index].targetCurrent);
  4922. DEBUG_INFO("==============================================================\n");
  4923. ftime(&startTime[gun_index][TMR_IDX_LOGPPRINTOUT]);
  4924. getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime);
  4925. DB_Update_Record_Buf(localDb, gun_index);
  4926. }
  4927. }
  4928. break;
  4929. case SYS_MODE_TERMINATING:
  4930. if(isModeChange(gun_index))
  4931. {
  4932. if(!ShmCharger->gun_info[gun_index].primaryMcuState.relay_state)
  4933. {
  4934. setLedMotion(gun_index, LED_ACTION_STOP);
  4935. }
  4936. else
  4937. {}
  4938. getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime);
  4939. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  4940. }
  4941. ftime(&endChargingTime[gun_index]);
  4942. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration != 0)
  4943. {
  4944. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = DiffTimeb(startChargingTime[gun_index], endChargingTime[gun_index])/1000;
  4945. }
  4946. // End authorize pass
  4947. if(((ShmCharger->gun_info[gun_index].rfidReq == ON) &&isMatchStartUser(gun_index)) ||
  4948. ((ShmCharger->gun_info[gun_index].rfidReq == ON) && ocpp_get_auth_result(YES, gun_index)) ||
  4949. (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE) && (ShmCharger->gun_info[gun_index].rfidReq == ON)) ||
  4950. (!ocpp_get_connection_status() && (isValidLocalWhiteCard() == PASS) && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST) && (ShmCharger->gun_info[gun_index].rfidReq == ON)) ||
  4951. (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop == ON) ||
  4952. ocpp_get_remotestop(gun_index) ||
  4953. (ocpp_get_connection_status() && !ocpp_get_starttransaction_result(gun_index)) ||
  4954. ((ShmCharger->gun_info[gun_index].chargingMode != CHARGING_MODE_SOCKETE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A) && ocpp_get_StopTransactionOnEVSideDisconnect()) ||
  4955. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE) && !ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn) ||
  4956. ocpp_get_reset_req() ||
  4957. ocpp_get_unlocker_req(gun_index) ||
  4958. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop == ON) ||
  4959. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && (ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_STOP_MODE)))
  4960. {
  4961. setRelay(gun_index, OFF);
  4962. setLedMotion(gun_index, LED_ACTION_STOP);
  4963. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  4964. {
  4965. checkStopReason(gun_index);
  4966. setChargerMode(gun_index, SYS_MODE_COMPLETE);
  4967. }
  4968. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  4969. {
  4970. //setChargerMode(gun_index, SYS_MODE_COMPLETE);
  4971. //Cancel CCS task negotiating
  4972. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  4973. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  4974. setRelay(gun_index,OFF);
  4975. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = ON;
  4976. }
  4977. else
  4978. {
  4979. setChargerMode(gun_index, SYS_MODE_COMPLETE);
  4980. }
  4981. }
  4982. else
  4983. {
  4984. // If the charger stops charging, the led should be stoped blink
  4985. if(!ShmCharger->gun_info[gun_index].primaryMcuState.relay_state)
  4986. {
  4987. setLedMotion(gun_index, LED_ACTION_STOP);
  4988. }
  4989. if(!ocpp_get_auth_result(YES, gun_index))
  4990. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  4991. 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)) &&
  4992. (ShmCharger->gun_info[gun_index].rfidReq != ON) &&
  4993. (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop != ON) &&
  4994. !ocpp_get_remotestop(gun_index) &&
  4995. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop != ON) &&
  4996. !ocpp_get_reset_req() &&
  4997. ocpp_get_starttransaction_result(gun_index) &&
  4998. !(ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60))) &&
  4999. !(ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy))) &&
  5000. !(!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)))) &&
  5001. !(!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)))) &&
  5002. (((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))
  5003. )
  5004. {
  5005. setChargerMode(gun_index, SYS_MODE_CHARGING);
  5006. }
  5007. }
  5008. if((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) &&
  5009. (ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty == ON) &&
  5010. (ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty == CCS_PWM_DUTY_100))
  5011. {
  5012. DEBUG_INFO("Set PWM duty 100% go to SYS_MODE_TERMINATING.\n");
  5013. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  5014. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  5015. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = OFF;
  5016. checkStopReason(gun_index);
  5017. setChargerMode(gun_index, SYS_MODE_COMPLETE);
  5018. }
  5019. break;
  5020. case SYS_MODE_COMPLETE:
  5021. if(isModeChange(gun_index))
  5022. {
  5023. setLedMotion(gun_index, LED_ACTION_STOP);
  5024. setRelay(gun_index, OFF);
  5025. setRequest(gun_index, OFF);
  5026. sleep(15);
  5027. }
  5028. if(((ShmCharger->gun_info[gun_index].chargingMode != CHARGING_MODE_SOCKETE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)) ||
  5029. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE) && (!ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn)) ||
  5030. ocpp_get_reset_req())
  5031. {
  5032. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  5033. ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop = OFF;
  5034. ocpp_set_remotestop(gun_index, OFF);
  5035. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop = OFF;
  5036. DB_Insert_Record(localDb, gun_index);
  5037. setChargerMode(gun_index, SYS_MODE_IDLE);
  5038. }
  5039. break;
  5040. case SYS_MODE_ALARM:
  5041. setLedMotion(gun_index,LED_ACTION_ALARM);
  5042. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus == SYS_MODE_CHARGING) ||
  5043. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus == SYS_MODE_TERMINATING))
  5044. {}
  5045. else
  5046. {
  5047. setRelay(gun_index, OFF);
  5048. }
  5049. if((ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode == 0))
  5050. {
  5051. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus == SYS_MODE_CHARGING) ||
  5052. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus == SYS_MODE_TERMINATING))
  5053. {
  5054. setChargerMode(gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus);
  5055. }
  5056. else
  5057. {
  5058. setChargerMode(gun_index, SYS_MODE_IDLE);
  5059. }
  5060. }
  5061. break;
  5062. case SYS_MODE_FAULT:
  5063. if(isModeChange(gun_index))
  5064. {}
  5065. break;
  5066. case SYS_MODE_MAINTAIN:
  5067. if(isModeChange(gun_index))
  5068. {
  5069. setLedMotion(gun_index,LED_ACTION_MAINTAIN);
  5070. }
  5071. break;
  5072. case SYS_MODE_UPDATE:
  5073. if(isModeChange(gun_index))
  5074. {
  5075. setLedMotion(gun_index,LED_ACTION_MAINTAIN);
  5076. }
  5077. //======================================
  5078. // Check local upgrade firmware request
  5079. //======================================
  5080. if(ShmSysConfigAndInfo->SysInfo.FirmwareUpdate)
  5081. {
  5082. DEBUG_INFO("Firmware local upgrading...\n");
  5083. ShmSysConfigAndInfo->SysInfo.FirmwareUpdate = OFF;
  5084. int value = upgrade_check();
  5085. DEBUG_INFO("Local update Value: %s... \n",((value == PASS)?"Pass": "Fail"));
  5086. if(value == PASS)
  5087. {
  5088. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == ON)
  5089. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = OFF;
  5090. ShmCharger->isUpdateSuccess = YES;
  5091. DEBUG_INFO("Local update success...\n");
  5092. }
  5093. else
  5094. {
  5095. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == OFF)
  5096. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = ON;
  5097. ShmCharger->isUpdateSuccess = NO;
  5098. DEBUG_INFO("Local update unsuccess...\n");
  5099. }
  5100. }
  5101. else if(ocpp_get_update_firmware_req())
  5102. {
  5103. //======================================
  5104. // Check remote upgrade firmware request
  5105. //======================================
  5106. checkRemoteUpgradeStatus();
  5107. }
  5108. else
  5109. {
  5110. //======================================
  5111. // Upgrade complete reboot system
  5112. //======================================
  5113. if(!ShmCharger->gun_info[gun_index].mcuFlag.isMcuUpgradeReq && ((AC_QUANTITY>1)?!ShmCharger->gun_info[gun_index^1].mcuFlag.isMcuUpgradeReq:YES))
  5114. {
  5115. if(ShmCharger->isUpdateSuccess == YES)
  5116. {
  5117. sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installed");
  5118. ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  5119. sprintf((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "Installed");
  5120. ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  5121. DEBUG_WARN("Firmware upgrade success.\n");
  5122. sleep(5);
  5123. DEBUG_INFO("Firmware upgraded, reboot...\n");
  5124. system("reboot -f");
  5125. sleep(5);
  5126. system("reboot -f");
  5127. }
  5128. else
  5129. {
  5130. sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "InstallationFailed");
  5131. ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  5132. sprintf((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "InstallationFailed");
  5133. ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  5134. DEBUG_WARN("Firmware upgrade fail.\n");
  5135. sleep(5);
  5136. system("rm -rvf /mnt/* ");
  5137. close(wtdFd);
  5138. system("/usr/bin/run_evse_restart.sh");
  5139. }
  5140. }
  5141. }
  5142. break;
  5143. case SYS_MODE_RESERVATION:
  5144. if(isModeChange(gun_index))
  5145. {}
  5146. setLedMotion(gun_index,LED_ACTION_MAINTAIN);
  5147. if(isReservationExpired(gun_index))
  5148. {
  5149. DEBUG_INFO("Reservation: Time's up...\n");
  5150. setChargerMode(gun_index, SYS_MODE_IDLE);
  5151. }
  5152. else if(ocpp_get_cancelreservation_req(gun_index))
  5153. {
  5154. DEBUG_INFO("Reservation: Cancel reservation...\n");
  5155. setChargerMode(gun_index, SYS_MODE_IDLE);
  5156. ocpp_set_cancelreservation_req(gun_index, OFF);
  5157. }
  5158. else
  5159. {
  5160. // Check is there RFID or back end request start
  5161. if((ShmCharger->gun_info[gun_index].rfidReq == ON) ||
  5162. ocpp_get_remotestart(gun_index))
  5163. {
  5164. if((ShmCharger->gun_info[gun_index].rfidReq == ON))
  5165. {
  5166. if(ocpp_compare_reserve_id_with_user(gun_index))
  5167. {
  5168. DEBUG_INFO("Start Method in reservation : RFID...\n");
  5169. DEBUG_INFO("Start request User Id : %s\n", ShmSysConfigAndInfo->SysConfig.UserId);
  5170. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_RFID;
  5171. setChargerMode(gun_index, SYS_MODE_AUTHORIZING);
  5172. }
  5173. else
  5174. DEBUG_INFO("It's not reserve user id.\n");
  5175. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  5176. }
  5177. else if(ocpp_get_remotestart(gun_index))
  5178. {
  5179. if(ocpp_compare_reserve_id_with_remote_user(gun_index))
  5180. {
  5181. DEBUG_INFO("Start Method in reservation: BACKEND...\n");
  5182. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_BACKEND;
  5183. setChargerMode(gun_index, SYS_MODE_AUTHORIZING);
  5184. }
  5185. ocpp_set_remotestop(gun_index, OFF);
  5186. }
  5187. }
  5188. }
  5189. break;
  5190. case SYS_MODE_BOOKING:
  5191. if(isModeChange(gun_index))
  5192. {}
  5193. break;
  5194. case SYS_MODE_DEBUG:
  5195. if(isModeChange(gun_index))
  5196. {
  5197. setLedMotion(gun_index,LED_ACTION_DEBUG);
  5198. }
  5199. break;
  5200. }
  5201. }
  5202. // System watch dog reset
  5203. write(wtdFd, "a", 1);
  5204. usleep(50000);
  5205. }
  5206. return FAIL;
  5207. }