main.c 208 KB

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