main.c 239 KB

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