main.c 239 KB

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