main.c 216 KB

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