main.c 216 KB

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