main.c 234 KB

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