main.c 245 KB

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