main.c 207 KB

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