main.c 217 KB

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