main.c 303 KB

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