main.c 303 KB

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