main.c 224 KB

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