main.c 221 KB

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