main.c 306 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993
  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. // Check is ccs Enable/Disable to open ccs power.
  2755. if(ShmCharger->isCcsEnable == ON)
  2756. {
  2757. system("echo 1 > /sys/class/gpio/gpio115/value");
  2758. DEBUG_INFO("QCA7000: Power on. \n");
  2759. }
  2760. else
  2761. {
  2762. system("echo 0 > /sys/class/gpio/gpio115/value");
  2763. DEBUG_INFO("QCA7000: Power off. \n");
  2764. }
  2765. return result;
  2766. }
  2767. //=====================================================
  2768. // Common routine
  2769. //=====================================================
  2770. char* getSystemModeName(unsigned char mode)
  2771. {
  2772. char* result;
  2773. switch(mode)
  2774. {
  2775. case SYS_MODE_BOOTING:
  2776. result = "booting";
  2777. break;
  2778. case SYS_MODE_IDLE:
  2779. result = "idle";
  2780. break;
  2781. case SYS_MODE_AUTHORIZING:
  2782. result = "authorizing";
  2783. break;
  2784. case SYS_MODE_PREPARING:
  2785. result = "preparing";
  2786. break;
  2787. case SYS_MODE_CHARGING:
  2788. result = "charging";
  2789. break;
  2790. case SYS_MODE_TERMINATING:
  2791. result = "terminating";
  2792. break;
  2793. case SYS_MODE_COMPLETE:
  2794. result = "complete";
  2795. break;
  2796. case SYS_MODE_ALARM:
  2797. result = "alarm";
  2798. break;
  2799. case SYS_MODE_FAULT:
  2800. result = "fault";
  2801. break;
  2802. case SYS_MODE_MAINTAIN:
  2803. result = "maintain";
  2804. break;
  2805. case SYS_MODE_RESERVATION:
  2806. result = "reservation";
  2807. break;
  2808. case SYS_MODE_BOOKING:
  2809. result = "booking";
  2810. break;
  2811. case SYS_MODE_DEBUG:
  2812. result = "debug";
  2813. break;
  2814. case SYS_MODE_UPDATE:
  2815. result = "upgrade";
  2816. break;
  2817. default:
  2818. result = "unknown";
  2819. break;
  2820. }
  2821. return result;
  2822. }
  2823. void setChargerMode(unsigned char gun_index, unsigned char mode)
  2824. {
  2825. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus = ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus;
  2826. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus = mode;
  2827. 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));
  2828. }
  2829. unsigned char isMode(unsigned char gun_index, unsigned char mode)
  2830. {
  2831. return ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == mode)?YES:NO);
  2832. }
  2833. unsigned char isModeChange(unsigned char gun_index)
  2834. {
  2835. unsigned char result = NO;
  2836. if(!isMode(gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus))
  2837. {
  2838. result = YES;
  2839. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus = ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus;
  2840. }
  2841. return result;
  2842. }
  2843. void gpio_set_value(unsigned int gpio, unsigned int value)
  2844. {
  2845. int fd;
  2846. char buf[256];
  2847. sprintf(buf, "/sys/class/gpio/gpio%d/value", gpio);
  2848. fd = open(buf, O_WRONLY);
  2849. if (fd < 0)
  2850. {
  2851. DEBUG_ERROR("GPIO-%d set %d fail.\n", gpio, value);
  2852. return;
  2853. }
  2854. if (value)
  2855. write(fd, "1", 2);
  2856. else
  2857. write(fd, "0", 2);
  2858. close(fd);
  2859. }
  2860. int gpio_get_value(unsigned int gpio)
  2861. {
  2862. int fd;
  2863. char buf[256];
  2864. char ch;
  2865. int8_t result = FAIL;
  2866. sprintf(buf, "/sys/class/gpio/gpio%d/value", gpio);
  2867. fd = open(buf, O_RDONLY);
  2868. if (fd < 0)
  2869. {
  2870. DEBUG_ERROR("GPIO-%d get fail\n", gpio);
  2871. return result;
  2872. }
  2873. read(fd, &ch, 1);
  2874. if (ch != '0')
  2875. result = 1;
  2876. else
  2877. result = 0;
  2878. close(fd);
  2879. return result;
  2880. }
  2881. int presentChargedEnergyClear(unsigned char gun_index)
  2882. {
  2883. int result = FAIL;
  2884. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy = 0;
  2885. memset(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].presentChargedEnergyPeriod, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].presentChargedEnergyPeriod)*sizeof(float));
  2886. result = PASS;
  2887. return result;
  2888. }
  2889. float presentChargedEnergyTotal(unsigned char gun_index)
  2890. {
  2891. float result = 0.0f;
  2892. for(int idx=0;idx<ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].presentChargedEnergyPeriod);idx++)
  2893. {
  2894. //result += ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].presentChargedEnergyPeriod[idx];
  2895. result += (((int)(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].presentChargedEnergyPeriod[idx]*10000))/(float)10000);
  2896. }
  2897. return result;
  2898. }
  2899. int presentChargedEnergyUpdate(unsigned char gun_index)
  2900. {
  2901. int result = FAIL;
  2902. time_t CurrentTime;
  2903. struct tm *tm;
  2904. CurrentTime = time(NULL);
  2905. tm=localtime(&CurrentTime);
  2906. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==1)
  2907. {
  2908. // Resolution: 0.0001 kwh
  2909. 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);
  2910. }
  2911. else
  2912. {
  2913. // Resolution: 0.0001 kwh
  2914. 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) +
  2915. (((float)(ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption - ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption_at_start))/10000.0) +
  2916. (((float)(ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption - ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption_at_start))/10000.0))
  2917. - presentChargedEnergyTotal(gun_index);
  2918. }
  2919. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy = presentChargedEnergyTotal(gun_index);
  2920. return result;
  2921. }
  2922. //===============================================
  2923. // Get firmware version
  2924. //===============================================
  2925. void get_firmware_version(unsigned char gun_index)
  2926. {
  2927. FILE *fp;
  2928. char cmd[512];
  2929. char buf[512];
  2930. // Get CSU hardware version
  2931. sprintf((char*)ShmSysConfigAndInfo->SysInfo.CsuHwRev, "REV.XXXXXXX");
  2932. // Get CSU boot loader version
  2933. memcpy(ShmSysConfigAndInfo->SysInfo.CsuBootLoadFwRev, ShmSysConfigAndInfo->SysConfig.CsuBootLoadFwRev, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.CsuBootLoadFwRev));
  2934. // Get CSU kernel version
  2935. sprintf(cmd, "/bin/uname -r");
  2936. fp = popen(cmd, "r");
  2937. if(fp == NULL)
  2938. sprintf((char*)ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev, "Unknown version");
  2939. else
  2940. {
  2941. while(fgets(buf, sizeof(buf), fp) != NULL)
  2942. {
  2943. memcpy(ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev, buf, strlen(buf)-1);
  2944. }
  2945. }
  2946. // Get MCU firmware version
  2947. strcpy((char*)ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev, ShmCharger->gun_info[gun_index].ver.Version_FW);
  2948. // Get CSU root file system version
  2949. sprintf((char*)ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev, "B0.63.00.0000.00");
  2950. // Get AC connector type from model name
  2951. for(uint8_t idx=0;idx<3;idx++)
  2952. {
  2953. switch(ShmSysConfigAndInfo->SysConfig.ModelName[7+idx])
  2954. {
  2955. case '1':
  2956. // J1772 Plug
  2957. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '4';
  2958. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '4';
  2959. break;
  2960. case '2':
  2961. // J1772 Socket
  2962. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '1';
  2963. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '1';
  2964. break;
  2965. case '3':
  2966. // CE Plug
  2967. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '5';
  2968. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '5';
  2969. break;
  2970. case '4':
  2971. // CE Socket
  2972. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '2';
  2973. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '2';
  2974. break;
  2975. case '5':
  2976. // GB Plug
  2977. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '6';
  2978. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '6';
  2979. break;
  2980. case '6':
  2981. // GB Socket
  2982. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[6] = '3';
  2983. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[6] = '3';
  2984. break;
  2985. }
  2986. }
  2987. // Get network option from model name
  2988. switch(ShmSysConfigAndInfo->SysConfig.ModelName[10])
  2989. {
  2990. case 'B':
  2991. case 'U':
  2992. //Blue tooth
  2993. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '3';
  2994. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[9] = '3';
  2995. break;
  2996. case 'W':
  2997. // WIFI
  2998. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '1';
  2999. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[9] = '1';
  3000. break;
  3001. case 'T':
  3002. // 3G/4G
  3003. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '2';
  3004. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[9] = '2';
  3005. break;
  3006. case 'D':
  3007. // WIFI + 4G
  3008. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '5';
  3009. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[9] = '5';
  3010. break;
  3011. default:
  3012. // LAN
  3013. ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[9] = '0';
  3014. ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[9] = '0';
  3015. break;
  3016. }
  3017. // Get rating power from model name
  3018. memcpy(&ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[10], &ShmSysConfigAndInfo->SysConfig.ModelName[4], 0x03);
  3019. memcpy(&ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[10], &ShmSysConfigAndInfo->SysConfig.ModelName[4], 0x03);
  3020. // Get vender code from model name
  3021. memcpy(&ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev[14], &ShmSysConfigAndInfo->SysConfig.ModelName[12], 0x02);
  3022. memcpy(&ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev[14], &ShmSysConfigAndInfo->SysConfig.ModelName[12], 0x02);
  3023. DEBUG_INFO("========================================\n");
  3024. DEBUG_INFO("Model: %s\n", ShmSysConfigAndInfo->SysConfig.ModelName);
  3025. DEBUG_INFO("CSU hardware version: %s\n", ShmSysConfigAndInfo->SysInfo.CsuHwRev);
  3026. DEBUG_INFO("CSU boot loader version: %s\n", ShmSysConfigAndInfo->SysInfo.CsuBootLoadFwRev);
  3027. DEBUG_INFO("CSU kernel version: %s\n", ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev);
  3028. DEBUG_INFO("CSU root file system version: %s\n", ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev);
  3029. DEBUG_INFO("CSU MCU-%2d firmware version: %s\n", gun_index, ShmCharger->gun_info[gun_index].ver.Version_FW);
  3030. DEBUG_INFO("========================================\n");
  3031. }
  3032. //===============================================
  3033. // Upgrade firmware
  3034. //===============================================
  3035. int upgrade_check()
  3036. {
  3037. int result = PASS;
  3038. int fd;
  3039. DIR *dir;
  3040. struct dirent *file;
  3041. char cmd[512];
  3042. long int MaxLen=48*1024*1024, ImageLen=0, wrd;
  3043. if ((dir = opendir ("/mnt")) != NULL)
  3044. {
  3045. /* print all the files and directories within directory */
  3046. while ((file = readdir (dir)) != NULL)
  3047. {
  3048. if((strlen(file->d_name)>2))
  3049. {
  3050. // Wait for MCU upgrade finish.
  3051. while(ShmCharger->gun_info[0].mcuFlag.isMcuUpgradeReq || (AC_QUANTITY>1?ShmCharger->gun_info[1].mcuFlag.isMcuUpgradeReq:FALSE))sleep(1);
  3052. // Wait for LCM upgrade finish.
  3053. while(ShmCharger->isUpgradeLcmReq)sleep(1);
  3054. memset(&ShmCharger->fwUpgradeInfo, 0xFF, sizeof(Fw_Upgrade_Info));
  3055. DEBUG_INFO("New firmware file: %s\n", file->d_name);
  3056. sprintf(ShmCharger->fwUpgradeInfo.location, "/mnt/%s", file->d_name);
  3057. if((fd=open(ShmCharger->fwUpgradeInfo.location, O_RDONLY)) >= 0)
  3058. {
  3059. unsigned char *ptr = malloc(MaxLen); //-48 is take out the header
  3060. memset(ptr, 0xFF, MaxLen); //-48 is take out the header
  3061. ImageLen = read(fd, ptr, MaxLen);
  3062. close(fd);
  3063. ShmCharger->fwUpgradeInfo.fwType = ((ptr[0x13]<<0) | (ptr[0x12]<<8) | (ptr[0x11]<<16) | (ptr[0x10]<<24));
  3064. substr(ShmCharger->fwUpgradeInfo.modelName, (char *)ptr, 0, 0x10);
  3065. DEBUG_INFO("New firmware type: %X\n", ShmCharger->fwUpgradeInfo.fwType);
  3066. DEBUG_INFO("New firmware model name: %s, %s\n", ShmCharger->fwUpgradeInfo.modelName, ShmSysConfigAndInfo->SysConfig.ModelName);
  3067. if((ShmCharger->fwUpgradeInfo.modelName[0] == ShmSysConfigAndInfo->SysConfig.ModelName[0]) &&
  3068. (ShmCharger->fwUpgradeInfo.modelName[1] == ShmSysConfigAndInfo->SysConfig.ModelName[1]) &&
  3069. (ShmCharger->fwUpgradeInfo.modelName[7] == ShmSysConfigAndInfo->SysConfig.ModelName[7]) &&
  3070. (ShmCharger->fwUpgradeInfo.modelName[8] == ShmSysConfigAndInfo->SysConfig.ModelName[8]) &&
  3071. (ShmCharger->fwUpgradeInfo.modelName[9] == ShmSysConfigAndInfo->SysConfig.ModelName[9]) &&
  3072. (ShmCharger->fwUpgradeInfo.modelName[11] == ShmSysConfigAndInfo->SysConfig.ModelName[11]) &&
  3073. (ShmCharger->fwUpgradeInfo.modelName[12] == ShmSysConfigAndInfo->SysConfig.ModelName[12]) &&
  3074. (ShmCharger->fwUpgradeInfo.modelName[13] == ShmSysConfigAndInfo->SysConfig.ModelName[13]) &&
  3075. (ShmCharger->fwUpgradeInfo.fwType>0))
  3076. {
  3077. switch(ShmCharger->fwUpgradeInfo.fwType)
  3078. {
  3079. case CSU_MLO:
  3080. case CSU_BOOTLOADER:
  3081. case CSU_KERNEL_CONFIGURATION:
  3082. case CSU_KERNEL_IMAGE:
  3083. case CSU_ROOT_FILE_SYSTEM:
  3084. case CSU_USER_CONFIGURATION:
  3085. case CSU_PRIMARY_CONTROLLER:
  3086. if(Upgrade_Flash(ShmCharger->fwUpgradeInfo.fwType, ShmCharger->fwUpgradeInfo.location, ShmCharger->fwUpgradeInfo.modelName) != PASS)
  3087. {
  3088. result = FAIL;
  3089. }
  3090. else
  3091. {
  3092. if(ShmCharger->fwUpgradeInfo.fwType == CSU_USER_CONFIGURATION)
  3093. {
  3094. DEBUG_INFO("Restore model name & serial number.\n");
  3095. memcpy(&SysConfigOrg, &ShmSysConfigAndInfo->SysConfig, sizeof(struct SysConfigData));
  3096. if(LoadSysConfigAndInfo(&ShmSysConfigAndInfo->SysConfig) != PASS)
  3097. {
  3098. DEBUG_INFO("Re-load configuration fail.\n");
  3099. result = FAIL;
  3100. }
  3101. else
  3102. {
  3103. memcpy(&ShmSysConfigAndInfo->SysConfig.ModelName, &SysConfigOrg.ModelName, ARRAY_SIZE(SysConfigOrg.ModelName));
  3104. memcpy(&ShmSysConfigAndInfo->SysConfig.SerialNumber, &SysConfigOrg.SerialNumber, ARRAY_SIZE(SysConfigOrg.SerialNumber));
  3105. memcpy(&ShmSysConfigAndInfo->SysConfig.SystemId, &SysConfigOrg.SystemId, ARRAY_SIZE(SysConfigOrg.SystemId));
  3106. if(StoreUsrConfigData(&ShmSysConfigAndInfo->SysConfig) != PASS)
  3107. {
  3108. DEBUG_INFO("Re-write configuration fail.\n");
  3109. result = FAIL;
  3110. }
  3111. else
  3112. DEBUG_INFO("Re-write configuration OK.\n");
  3113. }
  3114. }
  3115. }
  3116. sprintf(cmd, "yes|rm %s", ShmCharger->fwUpgradeInfo.location);
  3117. system(cmd);
  3118. break;
  3119. case AC_WALLMOUNT_CONTROLLER:
  3120. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  3121. ShmCharger->gun_info[gun_index].mcuFlag.isMcuUpgradeReq = ON;
  3122. sleep(10);
  3123. break;
  3124. case LCM:
  3125. fd = open("/mnt/lcm.zip", O_RDWR | O_CREAT | O_EXCL);
  3126. if (fd < 0)
  3127. {
  3128. DEBUG_ERROR("Can not create lcm.zip file.\n");
  3129. result = FAIL;
  3130. }
  3131. else
  3132. {
  3133. // Write image to flash
  3134. DEBUG_INFO("Writing data to lcm.zip file...\n");
  3135. wrd=write(fd, ptr+48, ImageLen-48);
  3136. close(fd);
  3137. DEBUG_INFO(">> lcm.zip Written length: 0x%x\n", wrd);
  3138. if(wrd != (ImageLen-48))
  3139. {
  3140. result = FAIL;
  3141. }
  3142. else
  3143. {
  3144. runShellCmd("mkdir -p /mnt/lcd");
  3145. runShellCmd("unzip /mnt/lcm.zip -d /mnt/lcd");
  3146. sprintf(cmd, "yes|rm %s", ShmCharger->fwUpgradeInfo.location);
  3147. system(cmd);
  3148. system("rm -f /mnt/lcm.zip");
  3149. result = PASS;
  3150. }
  3151. }
  3152. ShmCharger->isUpgradeLcmReq = ON;
  3153. sleep(10);
  3154. break;
  3155. default:
  3156. result = FAIL;
  3157. DEBUG_WARN("Image file is unknown type.\n");
  3158. sprintf(cmd, "yes|rm %s", ShmCharger->fwUpgradeInfo.location);
  3159. system(cmd);
  3160. break;
  3161. }
  3162. }
  3163. else
  3164. {
  3165. result = FAIL;
  3166. DEBUG_ERROR("Model name and Firmware type error.\n");
  3167. sprintf(cmd, "yes|rm %s", ShmCharger->fwUpgradeInfo.location);
  3168. system(cmd);
  3169. }
  3170. free(ptr);
  3171. }
  3172. else
  3173. {
  3174. result = FAIL;
  3175. DEBUG_ERROR("New firmware open error.\n");
  3176. }
  3177. }
  3178. else
  3179. {
  3180. if(strlen(file->d_name) >= 3)
  3181. {
  3182. result = FAIL;
  3183. DEBUG_ERROR("File name error.\n");
  3184. }
  3185. else
  3186. {
  3187. DEBUG_ERROR("Searching file.\n");
  3188. }
  3189. }
  3190. }
  3191. closedir (dir);
  3192. }
  3193. else
  3194. {
  3195. result = FAIL;
  3196. DEBUG_ERROR("/mnt does not valid.\n");
  3197. }
  3198. return result;
  3199. }
  3200. //===============================================
  3201. // Check RFID is match with start user
  3202. //===============================================
  3203. int isMatchStartUser(unsigned char gun_index)
  3204. {
  3205. uint8_t tmpUser[32];
  3206. if(ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian)
  3207. {
  3208. // Big endian
  3209. switch(rfid.snType)
  3210. {
  3211. case RFID_SN_TYPE_8BYTE:
  3212. 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]);
  3213. break;
  3214. case RFID_SN_TYPE_7BYTE:
  3215. 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]);
  3216. break;
  3217. case RFID_SN_TYPE_10BYTE:
  3218. 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]);
  3219. break;
  3220. case RFID_SN_TYPE_4BYTE:
  3221. default:
  3222. sprintf((char*)tmpUser, "%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3]);
  3223. break;
  3224. }
  3225. }
  3226. else
  3227. {
  3228. // Little endian
  3229. switch(rfid.snType)
  3230. {
  3231. case RFID_SN_TYPE_8BYTE:
  3232. 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]);
  3233. break;
  3234. case RFID_SN_TYPE_7BYTE:
  3235. 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]);
  3236. break;
  3237. case RFID_SN_TYPE_10BYTE:
  3238. 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]);
  3239. break;
  3240. case RFID_SN_TYPE_4BYTE:
  3241. default:
  3242. sprintf((char*)tmpUser, "%02X%02X%02X%02X", rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  3243. break;
  3244. }
  3245. }
  3246. //DEBUG_INFO("==== isMatchStartUser ==== \n");
  3247. //DEBUG_INFO("tmpUser : %s \n", tmpUser);
  3248. //DEBUG_INFO("StartUserId : %s \n", ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId);
  3249. //DEBUG_INFO("========================== \n");
  3250. return ((strcmp((char*)tmpUser, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId)==0)?YES:NO);
  3251. }
  3252. int isMatchPresentUser()
  3253. {
  3254. uint8_t tmpUser[32];
  3255. if(ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian)
  3256. {
  3257. // Big endian
  3258. switch(rfid.snType)
  3259. {
  3260. case RFID_SN_TYPE_8BYTE:
  3261. 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]);
  3262. break;
  3263. case RFID_SN_TYPE_7BYTE:
  3264. 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]);
  3265. break;
  3266. case RFID_SN_TYPE_10BYTE:
  3267. 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]);
  3268. break;
  3269. case RFID_SN_TYPE_4BYTE:
  3270. default:
  3271. sprintf((char*)tmpUser, "%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3]);
  3272. break;
  3273. }
  3274. }
  3275. else
  3276. {
  3277. // Little endian
  3278. switch(rfid.snType)
  3279. {
  3280. case RFID_SN_TYPE_8BYTE:
  3281. 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]);
  3282. break;
  3283. case RFID_SN_TYPE_7BYTE:
  3284. 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]);
  3285. break;
  3286. case RFID_SN_TYPE_10BYTE:
  3287. 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]);
  3288. break;
  3289. case RFID_SN_TYPE_4BYTE:
  3290. default:
  3291. sprintf((char*)tmpUser, "%02X%02X%02X%02X", rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  3292. break;
  3293. }
  3294. }
  3295. //DEBUG_INFO("==== isMatchPresentUser ==== \n");
  3296. //DEBUG_INFO("tmpUser : %s \n", tmpUser);
  3297. //DEBUG_INFO("UserId : %s \n", ShmSysConfigAndInfo->SysConfig.UserId);
  3298. //DEBUG_INFO("============================ \n");
  3299. return ((strcmp((char*)tmpUser, (char*)ShmSysConfigAndInfo->SysConfig.UserId)==0)?YES:NO);
  3300. }
  3301. //===============================================
  3302. // Read RFID Serial Number
  3303. //===============================================
  3304. int GetCardSerialNumber()
  3305. {
  3306. int isSuccess = FAIL;
  3307. int module_type = MODULE_EWT;
  3308. if(getRequestCardSN(rfidFd,module_type,&rfid))
  3309. {
  3310. if(rfid.cardType == ISO14443A)
  3311. {
  3312. if(rfid.snType == RFID_SN_TYPE_4BYTE)
  3313. {
  3314. isSuccess = PASS;
  3315. }
  3316. else if (rfid.snType == RFID_SN_TYPE_7BYTE)
  3317. {
  3318. isSuccess = PASS;
  3319. }
  3320. sethaltCard(rfidFd,module_type);
  3321. }
  3322. else if(rfid.cardType == IS014443B)
  3323. {
  3324. isSuccess = PASS;
  3325. }
  3326. else if(rfid.cardType == FELICA)
  3327. {
  3328. isSuccess = PASS;
  3329. }
  3330. else
  3331. {}
  3332. }
  3333. else
  3334. {}
  3335. return isSuccess;
  3336. }
  3337. //===============================================
  3338. // Set led motion
  3339. //===============================================
  3340. void setLedMotion(unsigned char gun_index,unsigned char led_mode)
  3341. {
  3342. switch(led_mode)
  3343. {
  3344. case LED_ACTION_INIT:
  3345. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_INIT;
  3346. break;
  3347. case LED_ACTION_IDLE:
  3348. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_IDLE;
  3349. break;
  3350. case LED_ACTION_AUTHED:
  3351. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_AUTHED;
  3352. break;
  3353. case LED_ACTION_CONNECTED:
  3354. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_CONNECTED;
  3355. break;
  3356. case LED_ACTION_CHARGING:
  3357. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_CHARGING;
  3358. break;
  3359. case LED_ACTION_STOP:
  3360. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_STOP;
  3361. break;
  3362. case LED_ACTION_ALARM:
  3363. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_ALARM;
  3364. break;
  3365. case LED_ACTION_MAINTAIN:
  3366. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_MAINTAIN;
  3367. break;
  3368. case LED_ACTION_RFID_PASS:
  3369. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_RFID_PASS;
  3370. break;
  3371. case LED_ACTION_RFID_FAIL:
  3372. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_RFID_FAIL;
  3373. break;
  3374. case LED_ACTION_BLE_CONNECT:
  3375. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_BLE_CONNECT;
  3376. break;
  3377. case LED_ACTION_BLE_DISABLE:
  3378. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_BLE_DISABLE;
  3379. break;
  3380. case LED_ACTION_DEBUG:
  3381. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_DEBUG;
  3382. break;
  3383. case LED_ACTION_ALL_OFF:
  3384. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_ALL_OFF;
  3385. break;
  3386. case LED_RELAY_ON:
  3387. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_RELAY_ON;
  3388. break;
  3389. case LED_RELAY_OFF:
  3390. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_RELAY_OFF;
  3391. break;
  3392. case LED_ACTION_HANDSHAKE_FAIL:
  3393. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_HANDSHAKE_FAIL;
  3394. break;
  3395. case LED_ACTION_INTERNET_DISCONNECT:
  3396. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_INTERNET_DISCONNECT;
  3397. break;
  3398. case LED_ACTION_RESTORE_SETTING:
  3399. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_RESTORE_SETTING;
  3400. break;
  3401. case LED_ACTION_IDLE_BACKEND_CONNECTED:
  3402. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_IDLE_BACKEND_CONNECTED;
  3403. break;
  3404. case LED_ACTION_IDLE_BACKEND_CONNECTED_SLEEP:
  3405. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_IDLE_BACKEND_CONNECTED_SLEEP;
  3406. break;
  3407. case LED_ACTION_IDLE_BACKEND_DISCONNECTED:
  3408. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_IDLE_BACKEND_DISCONNECTED;
  3409. break;
  3410. case LED_ACTION_IDLE_BACKEND_DISCONNECTED_SLEEP:
  3411. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_IDLE_BACKEND_DISCONNECTED_SLEEP;
  3412. break;
  3413. case LED_ACTION_RESERVATION_MODE:
  3414. ShmCharger->gun_info[gun_index].primaryMcuLed.mode = LED_ACTION_RESERVATION_MODE;
  3415. break;
  3416. }
  3417. }
  3418. //===============================================
  3419. // Request on/off set
  3420. //===============================================
  3421. void setRequest(unsigned char gun_index,unsigned char isOn)
  3422. {
  3423. if(isOn == ON)
  3424. {
  3425. if(ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest == OFF)
  3426. {
  3427. ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest = ON;
  3428. DEBUG_INFO("Gun-[%d] permission request: ON \n",gun_index);
  3429. }
  3430. }
  3431. else
  3432. {
  3433. if(ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest == ON)
  3434. {
  3435. ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest = OFF;
  3436. DEBUG_INFO("Gun-[%d] permission request: OFF \n",gun_index);
  3437. }
  3438. }
  3439. }
  3440. //===============================================
  3441. // Request on/off get
  3442. //===============================================
  3443. int getRequest(unsigned char gun_index)
  3444. {
  3445. return ShmCharger->gun_info[gun_index].legacyRequest.isLegacyRequest;
  3446. }
  3447. //===============================================
  3448. // Relay on/off set
  3449. //===============================================
  3450. void setRelay(unsigned char gun_index,unsigned char isOn)
  3451. {
  3452. if(isOn == ON)
  3453. {
  3454. if(ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn == OFF)
  3455. {
  3456. switch(ShmCharger->gun_info[gun_index].chargingMode)
  3457. {
  3458. case CHARGING_MODE_BS:
  3459. case CHARGING_MODE_HLC:
  3460. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = ON;
  3461. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][0] = 0x01;
  3462. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][1] = 0x01;
  3463. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][2] = 0x01;
  3464. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  3465. DEBUG_INFO("Gun-[%d] Output relay status: ON. [CHARGING_MODE_BS] \n",gun_index);
  3466. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  3467. DEBUG_INFO("Gun-[%d] Output relay status: ON. [CHARGING_MODE_HLC] \n",gun_index);
  3468. break;
  3469. case CHARGING_MODE_SOCKETE:
  3470. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = ON;
  3471. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][3] = 0x01;
  3472. DEBUG_INFO("Gun-[%d] Output relay status: ON. [CHARGING_MODE_SOCKETE] \n",gun_index);
  3473. break;
  3474. default:
  3475. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = ON;
  3476. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][0] = 0x01;
  3477. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][1] = 0x01;
  3478. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][2] = 0x01;
  3479. DEBUG_INFO("Gun-[%d] Output relay status: ON. [DEFFAULT] \n",gun_index);
  3480. break;
  3481. }
  3482. }
  3483. }
  3484. else
  3485. {
  3486. if(ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn == ON)
  3487. {
  3488. switch(ShmCharger->gun_info[gun_index].chargingMode)
  3489. {
  3490. case CHARGING_MODE_BS:
  3491. case CHARGING_MODE_HLC:
  3492. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = OFF;
  3493. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][0] = 0;
  3494. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][1] = 0;
  3495. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][2] = 0;
  3496. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  3497. DEBUG_INFO("Gun-[%d] Output relay status: OFF. [CHARGING_MODE_BS] \n",gun_index);
  3498. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  3499. DEBUG_INFO("Gun-[%d] Output relay status: OFF. [CHARGING_MODE_HLC] \n",gun_index);
  3500. break;
  3501. case CHARGING_MODE_SOCKETE:
  3502. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = OFF;
  3503. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][3] = 0;
  3504. DEBUG_INFO("Gun-[%d] Output relay status: OFF. [CHARGING_MODE_SOCKETE] \n",gun_index);
  3505. break;
  3506. default:
  3507. ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn = OFF;
  3508. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][0] = 0;
  3509. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][1] = 0;
  3510. ShmCharger->gun_info[gun_index].primaryMcuState.relayState.relay_status[0][2] = 0;
  3511. DEBUG_INFO("Gun-[%d] Output relay status: OFF. [DEFFAULT] \n",gun_index);
  3512. break;
  3513. }
  3514. }
  3515. }
  3516. }
  3517. //===============================================
  3518. // Relay on/off get
  3519. //===============================================
  3520. int getRelay(unsigned char gun_index)
  3521. {
  3522. return ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn;
  3523. }
  3524. //===============================================
  3525. // Set speaker on/off request
  3526. //===============================================
  3527. void setSpeaker(unsigned char isOn, unsigned char speaker_mode)
  3528. {
  3529. if(isOn == ON)
  3530. {
  3531. ShmCharger->isSpeakerOn = ON;
  3532. ShmCharger->speaker_type = speaker_mode;
  3533. }
  3534. }
  3535. //===============================================
  3536. // Initialization RFID communication port
  3537. //===============================================
  3538. int InitRfidPort()
  3539. {
  3540. int uartO2 = open(rfidPortName, O_RDWR);
  3541. struct termios tios;
  3542. if (uartO2 != FAIL)
  3543. {
  3544. ioctl (uartO2, TCGETS, &tios);
  3545. tios.c_cflag = B19200 | CS8 | CLOCAL | CREAD;
  3546. tios.c_lflag = 0;
  3547. tios.c_iflag = 0;
  3548. tios.c_oflag = 0;
  3549. tios.c_cc[VMIN] = 0;
  3550. tios.c_cc[VTIME] = (unsigned char) 1;
  3551. tios.c_lflag = 0;
  3552. tcflush(uartO2, TCIFLUSH);
  3553. ioctl(uartO2, TCSETS, &tios);
  3554. }
  3555. if (uartO2 < 0)
  3556. {
  3557. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.RfidModuleCommFail = 1;
  3558. }
  3559. return uartO2;
  3560. }
  3561. //===============================================
  3562. // Check internet access status
  3563. //===============================================
  3564. int isReachableInternet()
  3565. {
  3566. int result = FAIL;
  3567. FILE *fp;
  3568. char cmd[256];
  3569. char buf[512];
  3570. char tmp[512];
  3571. // Get ip address & net mask
  3572. strcpy(cmd, "ifconfig eth0");
  3573. fp = popen(cmd, "r");
  3574. if (fp != NULL)
  3575. {
  3576. while(fgets(buf, sizeof(buf), fp) != NULL)
  3577. {
  3578. if (strstr(buf, "inet addr:") > 0)
  3579. {
  3580. sscanf(buf, "%*s%s", tmp);
  3581. substr((char*)ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthIpAddress, tmp, strspn(tmp, "addr:"), strlen(tmp)-strspn(tmp, "addr:"));
  3582. sscanf(buf, "%*s%*s%*s%s", tmp);
  3583. substr((char*)ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthSubmaskAddress, tmp, strspn(tmp, "Mask:"), strlen(tmp)-strspn(tmp, "Mask:"));
  3584. }
  3585. }
  3586. }
  3587. pclose(fp);
  3588. memset(buf, 0x00, sizeof(buf));
  3589. // Get gateway
  3590. fp = popen("ip route", "r");
  3591. if(fp == NULL)
  3592. result = FAIL;
  3593. else
  3594. {
  3595. while(fgets(buf, sizeof(buf), fp) != NULL)
  3596. {
  3597. if((strstr(buf, "default") != NULL) && (strstr(buf, "eth0") != NULL))
  3598. break;
  3599. }
  3600. if(strstr(buf, "default") != NULL)
  3601. {
  3602. sscanf(buf, "%*s%*s%s", tmp);
  3603. substr((char*)ShmSysConfigAndInfo->SysConfig.Eth0Interface.EthGatewayAddress, tmp, 0, strlen(tmp));
  3604. }
  3605. }
  3606. pclose(fp);
  3607. memset(buf, 0x00, sizeof(buf));
  3608. for(int idx=0;idx<ARRAY_SIZE(valid_Internet);idx++)
  3609. {
  3610. sprintf(cmd, "ping -c 1 -w 3 -I eth0 %s", valid_Internet[idx]);
  3611. fp = popen(cmd, "r");
  3612. if(fp != NULL)
  3613. {
  3614. while(fgets(buf, sizeof(buf), fp) != NULL)
  3615. {
  3616. if(strstr(buf, "transmitted") > 0)
  3617. {
  3618. //sscanf(buf, "%*s%*s%*s%*s%*s%*s%s", tmp);
  3619. if(strstr(buf,"100%") != NULL)
  3620. {
  3621. }
  3622. else
  3623. {
  3624. result = PASS;
  3625. }
  3626. //DEBUG_INFO("%s",buf);
  3627. //DEBUG_INFO("%s\n",tmp);
  3628. }
  3629. }
  3630. }
  3631. pclose(fp);
  3632. }
  3633. return result;
  3634. }
  3635. int isRouteFail()
  3636. {
  3637. int result = YES;
  3638. FILE *fp;
  3639. char buf[512];
  3640. fp = popen("route -n", "r");
  3641. if(fp != NULL)
  3642. {
  3643. while(fgets(buf, sizeof(buf), fp) != NULL)
  3644. {
  3645. if(strstr(buf, "eth0") != NULL)
  3646. result = NO;
  3647. }
  3648. }
  3649. pclose(fp);
  3650. return result;
  3651. }
  3652. //===============================================
  3653. // Check reservation date is expired
  3654. //===============================================
  3655. int isReservationExpired(unsigned char gun_index)
  3656. {
  3657. int result = NO;
  3658. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3659. {
  3660. if(isOvertNow(ShmOCPP16Data->ReserveNow[gun_index].ExpiryDate))
  3661. result = YES;
  3662. }
  3663. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3664. {
  3665. if(isOvertNow(ShmOCPP20Data->ReserveNow[gun_index].expiryDateTime))
  3666. result = YES;
  3667. }
  3668. return result;
  3669. }
  3670. //===============================================
  3671. // Check charging profile related date routine
  3672. //===============================================
  3673. int isProfileValid(uint8_t gun_index)
  3674. {
  3675. int result = NO;
  3676. struct tm tmFrom, tmTo;
  3677. struct timeb tbFrom, tbTo;
  3678. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3679. {
  3680. 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) &&
  3681. (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))
  3682. {
  3683. tmFrom.tm_year -= 1900;
  3684. tmFrom.tm_mon -= 1;
  3685. tbFrom.time = mktime(&tmFrom);
  3686. tmTo.tm_year -= 1900;
  3687. tmTo.tm_mon -= 1;
  3688. tbTo.time = mktime(&tmTo);
  3689. DEBUG_INFO("Valid from compare Now: %d\n", DiffTimebWithNow(tbFrom));
  3690. DEBUG_INFO("Valid to compare Now: %d\n", DiffTimebWithNow(tbTo));
  3691. if((DiffTimebWithNow(tbFrom)>=0) && (DiffTimebWithNow(tbTo)<=0))
  3692. {
  3693. result = YES;
  3694. }
  3695. }
  3696. else
  3697. {
  3698. DEBUG_WARN("ValidFrom or ValidTo date parsing error.\n");
  3699. }
  3700. }
  3701. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3702. {
  3703. 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) &&
  3704. (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))
  3705. {
  3706. tmFrom.tm_year -= 1900;
  3707. tmFrom.tm_mon -= 1;
  3708. tbFrom.time = mktime(&tmFrom);
  3709. tmTo.tm_year -= 1900;
  3710. tmTo.tm_mon -= 1;
  3711. tbTo.time = mktime(&tmTo);
  3712. DEBUG_INFO("Valid from compare Now: %d\n", DiffTimebWithNow(tbFrom));
  3713. DEBUG_INFO("Valid to compare Now: %d\n", DiffTimebWithNow(tbTo));
  3714. if((DiffTimebWithNow(tbFrom)>=0) && (DiffTimebWithNow(tbTo)<=0))
  3715. {
  3716. result = YES;
  3717. }
  3718. }
  3719. else
  3720. {
  3721. DEBUG_WARN("ValidFrom or ValidTo date parsing error.\n");
  3722. }
  3723. }
  3724. return result;
  3725. }
  3726. int getMaxScheduleStart()
  3727. {
  3728. int result = -1;
  3729. struct tm tmScheduleStart;;
  3730. struct timeb tbScheduleStart;
  3731. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3732. {
  3733. 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))
  3734. {
  3735. tmScheduleStart.tm_year -= 1900;
  3736. tmScheduleStart.tm_mon -= 1;
  3737. tbScheduleStart.time = mktime(&tmScheduleStart);
  3738. tbScheduleStart.millitm = 0;
  3739. result = DiffTimebWithNow(tbScheduleStart)/1000;
  3740. //DEBUG_INFO("Max schedule start compare Now(seconds): %d\n", result);
  3741. }
  3742. else
  3743. {
  3744. DEBUG_WARN("Max schedule start date parsing error.\n");
  3745. }
  3746. }
  3747. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3748. {
  3749. 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))
  3750. {
  3751. tmScheduleStart.tm_year -= 1900;
  3752. tmScheduleStart.tm_mon -= 1;
  3753. tbScheduleStart.time = mktime(&tmScheduleStart);
  3754. tbScheduleStart.millitm = 0;
  3755. result = DiffTimebWithNow(tbScheduleStart)/1000;
  3756. //DEBUG_INFO("Max schedule start compare Now(seconds): %d\n", result);
  3757. }
  3758. else
  3759. {
  3760. DEBUG_WARN("Max schedule start date parsing error.\n");
  3761. }
  3762. }
  3763. return result;
  3764. }
  3765. int getScheduleStart(int gun_index)
  3766. {
  3767. int result = -1;
  3768. struct tm tmScheduleStart;;
  3769. struct timeb tbScheduleStart;
  3770. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3771. {
  3772. 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))
  3773. {
  3774. tmScheduleStart.tm_year -= 1900;
  3775. tmScheduleStart.tm_mon -= 1;
  3776. tbScheduleStart.time = mktime(&tmScheduleStart);
  3777. tbScheduleStart.millitm = 0;
  3778. result = DiffTimebWithNow(tbScheduleStart)/1000;
  3779. //DEBUG_INFO("Schedule start compare Now(seconds): %d\n", result);
  3780. }
  3781. else
  3782. {
  3783. DEBUG_WARN("Schedule start date parsing error.\n");
  3784. }
  3785. }
  3786. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3787. {
  3788. 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))
  3789. {
  3790. tmScheduleStart.tm_year -= 1900;
  3791. tmScheduleStart.tm_mon -= 1;
  3792. tbScheduleStart.time = mktime(&tmScheduleStart);
  3793. tbScheduleStart.millitm = 0;
  3794. result = DiffTimebWithNow(tbScheduleStart)/1000;
  3795. //DEBUG_INFO("Schedule start compare Now(seconds): %d\n", result);
  3796. }
  3797. else
  3798. {
  3799. DEBUG_WARN("Schedule start date parsing error.\n");
  3800. }
  3801. }
  3802. return result;
  3803. }
  3804. int getStartSinceToday()
  3805. {
  3806. int result = -1;
  3807. time_t t;
  3808. struct tm *tmStartToday;
  3809. struct timeb tbStartToday;
  3810. t=time(NULL);
  3811. tmStartToday=localtime(&t);
  3812. tmStartToday->tm_hour = 0;
  3813. tmStartToday->tm_min = 0;
  3814. tmStartToday->tm_sec = 0;
  3815. tbStartToday.time = mktime(tmStartToday);
  3816. result = DiffTimebWithNow(tbStartToday)/1000;
  3817. //DEBUG_INFO("Start today compare Now(seconds): %d\n", result);
  3818. return result;
  3819. }
  3820. int getStartSinceWeek()
  3821. {
  3822. int result = -1;
  3823. time_t t;
  3824. struct tm *tmStartWeek;
  3825. struct timeb tbStartWeek;
  3826. t=time(NULL);
  3827. tmStartWeek=localtime(&t);
  3828. t-=86400*tmStartWeek->tm_wday;
  3829. tmStartWeek=localtime(&t);
  3830. tmStartWeek->tm_hour = 0;
  3831. tmStartWeek->tm_min = 0;
  3832. tmStartWeek->tm_sec = 0;
  3833. tbStartWeek.time = mktime(tmStartWeek);
  3834. result = DiffTimebWithNow(tbStartWeek)/1000;
  3835. //DEBUG_INFO("Start week compare Now(seconds): %d\n", result);
  3836. return result;
  3837. }
  3838. //===============================================
  3839. // Valid from local white list
  3840. //===============================================
  3841. int isValidLocalWhiteCard()
  3842. {
  3843. uint8_t result = FAIL;
  3844. for(uint8_t idx=0;idx<ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.LocalWhiteCard);idx++)
  3845. {
  3846. if(strcmp((char*)ShmSysConfigAndInfo->SysConfig.UserId, (char*)ShmSysConfigAndInfo->SysConfig.LocalWhiteCard[idx]) == 0)
  3847. {
  3848. result = PASS;
  3849. }
  3850. }
  3851. return result;
  3852. }
  3853. //==========================================
  3854. // Check routine
  3855. //==========================================
  3856. void checkTask()
  3857. {
  3858. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'T') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  3859. {
  3860. if(system("pidof -s Module_4g > /dev/null") != 0)
  3861. {
  3862. DEBUG_INFO("Module_4g not running, restart it.\n");
  3863. system("/root/Module_4g &");
  3864. }
  3865. }
  3866. if((ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'W') || (ShmSysConfigAndInfo->SysConfig.ModelName[10] == 'D'))
  3867. {
  3868. if(system("pidof -s Module_Wifi > /dev/null") != 0)
  3869. {
  3870. DEBUG_INFO("Module_Wifi not running, restart it.\n");
  3871. system("/root/Module_Wifi &");
  3872. }
  3873. }
  3874. if(system("pidof -s Module_EventLogging > /dev/null") != 0)
  3875. {
  3876. DEBUG_INFO("Module_EventLogging not running, restart it.\n");
  3877. system("/root/Module_EventLogging &");
  3878. }
  3879. if((strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") != 0))
  3880. {
  3881. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3882. {
  3883. if((time((time_t*)NULL) - ShmOCPP16Data->procDogTime) > 180)
  3884. {
  3885. DEBUG_WARN("OcppBackend watch dog timeout task restart.\n");
  3886. ShmOCPP16Data->procDogTime = time((time_t*)NULL);
  3887. system("pkill OcppBackend");
  3888. sleep(3);
  3889. ocpp_process_start();
  3890. }
  3891. if(system("pidof -s OcppBackend > /dev/null") != 0)
  3892. {
  3893. DEBUG_INFO("OcppBackend not running, restart it.\n");
  3894. ocpp_process_start();
  3895. }
  3896. }
  3897. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  3898. {
  3899. if((time((time_t*)NULL) - ShmOCPP20Data->procDogTime) > 180)
  3900. {
  3901. DEBUG_WARN("OcppBackend20 watch dog timeout task restart.\n");
  3902. ShmOCPP20Data->procDogTime = time((time_t*)NULL);
  3903. system("pkill OcppBackend20");
  3904. sleep(3);
  3905. ocpp_process_start();
  3906. }
  3907. if(system("pidof -s OcppBackend20 > /dev/null") != 0)
  3908. {
  3909. DEBUG_INFO("OcppBackend20 not running, restart it.\n");
  3910. ocpp_process_start();
  3911. }
  3912. }
  3913. }
  3914. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.MaintainServerURL,"") != 0)
  3915. {
  3916. if(system("pidof -s OcppBackendPH > /dev/null") != 0)
  3917. {
  3918. DEBUG_INFO("OcppBackendPH not running, restart it.\n");
  3919. system("/root/OcppBackendPH &");
  3920. }
  3921. }
  3922. if(system("pidof -s Module_AlarmDetect > /dev/null") != 0)
  3923. {
  3924. DEBUG_INFO("Module_AlarmDetect not running, restart it.\n");
  3925. system("/root/Module_AlarmDetect &");
  3926. }
  3927. if(system("pidof -s Module_InternalComm > /dev/null") != 0)
  3928. {
  3929. DEBUG_INFO("Module_InternalComm not running, restart it.\n");
  3930. system("/root/Module_InternalComm &");
  3931. }
  3932. if(system("pidof -s Module_Speaker > /dev/null") != 0)
  3933. {
  3934. DEBUG_INFO("Module_Speaker not running, restart it.\n");
  3935. system("/root/Module_Speaker &");
  3936. }
  3937. if(system("pidof -s Module_ProduceUtils > /dev/null") != 0)
  3938. {
  3939. DEBUG_INFO("Module_ProduceUtils not running, restart it.\n");
  3940. system ("/root/Module_ProduceUtils &");
  3941. }
  3942. if(system("pidof -s Module_LcmControl > /dev/null") != 0)
  3943. {
  3944. DEBUG_INFO("Module_LcmControl not running, restart it.\n");
  3945. system ("/root/Module_LcmControl &");
  3946. }
  3947. if((system("pidof -s Module_PowerSharing > /dev/null") != 0) &&
  3948. ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharing)
  3949. {
  3950. DEBUG_INFO("Module_PowerSharing not running, restart it.\n");
  3951. system ("/root/Module_PowerSharing &");
  3952. }
  3953. if(ShmCharger->isCcsEnable == ON)
  3954. {
  3955. if((system("pidof -s CsuComm > /dev/null") != 0))
  3956. {
  3957. DEBUG_INFO("CsuComm not running, restart it.\n");
  3958. system ("/root/CsuComm &");
  3959. }
  3960. if((system("pidof -s SeccComm > /dev/null") != 0))
  3961. {
  3962. sleep(3);
  3963. DEBUG_INFO("SeccComm not running, restart it.\n");
  3964. system ("/root/SeccComm &");
  3965. }
  3966. }
  3967. }
  3968. void checkConnectionTimeout()
  3969. {
  3970. if((system("pidof -s OcppBackend > /dev/null") != 0) && (system("pidof -s OcppBackend20 > /dev/null") != 0))
  3971. {
  3972. ShmCharger->timeoutSpec.Present_Timeout_Spec = TIMEOUT_SPEC_HANDSHAKING;
  3973. //DEBUG_INFO("Handshaking timeout specification follow by initial setting : %d s \n", TIMEOUT_SPEC_HANDSHAKING);
  3974. }
  3975. else
  3976. {
  3977. ShmCharger->timeoutSpec.Setting_Timeout_Spec = ocpp_get_connection_timeout();
  3978. if((ShmCharger->timeoutSpec.Setting_Timeout_Spec) < TIMEOUT_SPEC_BS_HLC_HANDSHAKE)
  3979. {
  3980. ShmCharger->timeoutSpec.Present_Timeout_Spec = (TIMEOUT_SPEC_BS_HLC_HANDSHAKE+10);
  3981. //DEBUG_INFO("Handshaking timeout specification follow by OCPP Configuration : Fail. Value can't be zero or less than zero.\n.");
  3982. }
  3983. else
  3984. {
  3985. ShmCharger->timeoutSpec.Present_Timeout_Spec = ShmCharger->timeoutSpec.Setting_Timeout_Spec;
  3986. //DEBUG_INFO("Handshaking timeout specification follow by OCPP Configuration : Pass...\n.");
  3987. }
  3988. //DEBUG_INFO("Handshaking timeout specification follow by OCPP Configuration : %s s \n.",ShmOCPP16Data->ConfigurationTable.CoreProfile[ConnectionTimeOut].ItemData);
  3989. }
  3990. }
  3991. void checkReset()
  3992. {
  3993. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  3994. {
  3995. if(ShmOCPP16Data->MsMsg.bits.ResetReq)
  3996. {
  3997. if((!isMode(0, SYS_MODE_CHARGING) && !isMode(0, SYS_MODE_TERMINATING) && !isMode(0, SYS_MODE_COMPLETE)) &&
  3998. (AC_QUANTITY>1?(!isMode(1, SYS_MODE_CHARGING) && !isMode(1, SYS_MODE_TERMINATING) && !isMode(1, SYS_MODE_COMPLETE)):TRUE))
  3999. {
  4000. ShmOCPP16Data->MsMsg.bits.ResetReq = OFF;
  4001. sprintf((char*)ShmOCPP16Data->Reset.ResponseStatus, "Accepted");
  4002. ShmOCPP16Data->MsMsg.bits.ResetConf = ON;
  4003. DEBUG_INFO("%s reset request by OCPP.\n", ShmOCPP16Data->Reset.Type);
  4004. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  4005. setChargerMode(gun_index, SYS_MODE_BOOTING);
  4006. if(strcmp((char*)ShmOCPP16Data->Reset.Type, "Hard") == 0)
  4007. {
  4008. system("sync");
  4009. sleep(10);
  4010. system("reboot -f");
  4011. sleep(10);
  4012. system("reboot -f");
  4013. }
  4014. else
  4015. {
  4016. sleep(10);
  4017. close(wtdFd);
  4018. system("/usr/bin/run_evse_restart.sh");
  4019. }
  4020. }
  4021. }
  4022. }
  4023. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  4024. {
  4025. if(ShmOCPP20Data->MsMsg.bits.ResetReq)
  4026. {
  4027. if((!isMode(0, SYS_MODE_CHARGING) && !isMode(0, SYS_MODE_TERMINATING) && !isMode(0, SYS_MODE_COMPLETE)) &&
  4028. (AC_QUANTITY>1?(!isMode(1, SYS_MODE_CHARGING) && !isMode(1, SYS_MODE_TERMINATING) && !isMode(1, SYS_MODE_COMPLETE)):TRUE))
  4029. {
  4030. ShmOCPP20Data->MsMsg.bits.ResetReq = OFF;
  4031. sprintf((char*)ShmOCPP20Data->Reset.Response_status, "Accepted");
  4032. ShmOCPP20Data->MsMsg.bits.ResetConf = ON;
  4033. DEBUG_INFO("%s reset request by OCPP.\n", ShmOCPP20Data->Reset.type);
  4034. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  4035. setChargerMode(gun_index, SYS_MODE_BOOTING);
  4036. if(strcmp((char*)ShmOCPP20Data->Reset.type, "Immediate") == 0)
  4037. {
  4038. system("sync");
  4039. sleep(10);
  4040. system("reboot -f");
  4041. sleep(10);
  4042. system("reboot -f");
  4043. }
  4044. else
  4045. {
  4046. sleep(10);
  4047. close(wtdFd);
  4048. system("/usr/bin/run_evse_restart.sh");
  4049. }
  4050. }
  4051. }
  4052. }
  4053. }
  4054. void checkReservation(uint8_t gun_index)
  4055. {
  4056. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  4057. {
  4058. if(ShmOCPP16Data->CsMsg.bits[gun_index].ReserveNowReq)
  4059. {
  4060. ShmOCPP16Data->CsMsg.bits[gun_index].ReserveNowReq = OFF;
  4061. ShmOCPP16Data->CsMsg.bits[gun_index].ReserveNowConf = ON;
  4062. if(isMode(gun_index, SYS_MODE_IDLE) && !isReservationExpired(gun_index))
  4063. {
  4064. sleep(5);
  4065. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId = ShmOCPP16Data->ReserveNow[gun_index].ReservationId;
  4066. setChargerMode(gun_index, SYS_MODE_RESERVATION);
  4067. }
  4068. DEBUG_INFO("Reservation request on gun-%d.\n", gun_index);
  4069. }
  4070. }
  4071. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  4072. {
  4073. if(ShmOCPP20Data->CsMsg.bits[gun_index].ReserveNowReq)
  4074. {
  4075. ShmOCPP20Data->CsMsg.bits[gun_index].ReserveNowReq = OFF;
  4076. ShmOCPP20Data->CsMsg.bits[gun_index].ReserveNowConf = ON;
  4077. if(isMode(gun_index, SYS_MODE_IDLE) && !isReservationExpired(gun_index))
  4078. {
  4079. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId = ShmOCPP20Data->ReserveNow[gun_index].id;
  4080. setChargerMode(gun_index, SYS_MODE_RESERVATION);
  4081. }
  4082. DEBUG_INFO("Reservation request on gun-%d.\n", gun_index);
  4083. }
  4084. }
  4085. }
  4086. void checkUnlocker(uint8_t gun_index)
  4087. {
  4088. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  4089. {
  4090. if(ShmOCPP16Data->CsMsg.bits[gun_index].UnlockConnectorReq == ON)
  4091. {
  4092. ShmOCPP16Data->CsMsg.bits[gun_index].UnlockConnectorReq = OFF;
  4093. if(ShmSysConfigAndInfo->SysConfig.ModelName[9-gun_index] == '4')
  4094. {
  4095. sprintf((char*)ShmOCPP16Data->UnlockConnector[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].ResponseStatus, "Unlocked");
  4096. ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor = ON;
  4097. }
  4098. else
  4099. {
  4100. sprintf((char*)ShmOCPP16Data->UnlockConnector[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].ResponseStatus, "NotSupported");
  4101. ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor = OFF;
  4102. }
  4103. ShmOCPP16Data->CsMsg.bits[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].UnlockConnectorConf = ON;
  4104. }
  4105. }
  4106. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  4107. {
  4108. if(ShmOCPP20Data->CsMsg.bits[gun_index].UnlockConnectorReq == ON)
  4109. {
  4110. ShmOCPP20Data->CsMsg.bits[gun_index].UnlockConnectorReq = OFF;
  4111. if(ShmSysConfigAndInfo->SysConfig.ModelName[9-gun_index] == '4')
  4112. {
  4113. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_CHARGING)
  4114. {
  4115. sprintf((char*)ShmOCPP20Data->UnlockConnector[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].Response_status, "OngoingAuthorizedTransaction");
  4116. ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor = OFF;
  4117. }
  4118. else
  4119. {
  4120. sprintf((char*)ShmOCPP20Data->UnlockConnector[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].Response_status, "Unlocked");
  4121. ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor = ON;
  4122. }
  4123. }
  4124. else
  4125. {
  4126. sprintf((char*)ShmOCPP20Data->UnlockConnector[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].Response_status, "UnlockFailed");
  4127. ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor = OFF;
  4128. }
  4129. ShmOCPP20Data->CsMsg.bits[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].UnlockConnectorConf = ON;
  4130. }
  4131. }
  4132. }
  4133. void checkAvailability(uint8_t gun_index)
  4134. {
  4135. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  4136. {
  4137. if(ShmOCPP16Data->CsMsg.bits[gun_index].ChangeAvailabilityReq)
  4138. {
  4139. if(strcmp((char*)ShmOCPP16Data->ChangeAvailability[gun_index].Type, "Operative") == 0)
  4140. {
  4141. DB_Update_Operactive(localDb, gun_index, true);
  4142. ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
  4143. }
  4144. else
  4145. {
  4146. DB_Update_Operactive(localDb, gun_index, false);
  4147. ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
  4148. }
  4149. ShmOCPP16Data->CsMsg.bits[gun_index].ChangeAvailabilityReq = OFF;
  4150. }
  4151. }
  4152. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  4153. {
  4154. if(ShmOCPP20Data->CsMsg.bits[gun_index].ChangeAvailabilityReq)
  4155. {
  4156. if(strcmp((char*)ShmOCPP20Data->ChangeAvailability[gun_index].operationalStatus, "Operative") == 0)
  4157. {
  4158. DB_Update_Operactive(localDb, gun_index, true);
  4159. ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
  4160. }
  4161. else
  4162. {
  4163. DB_Update_Operactive(localDb, gun_index, false);
  4164. ShmCharger->gun_info[gun_index].isOperactive = DB_Get_Operactive(localDb, gun_index);
  4165. }
  4166. ShmOCPP20Data->CsMsg.bits[gun_index].ChangeAvailabilityReq = OFF;
  4167. }
  4168. }
  4169. }
  4170. void checkChargingProfileLimit(uint8_t gun_index, uint8_t system_mode)
  4171. {
  4172. uint16_t MaxChargingProfileChargingCurrent = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
  4173. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  4174. {
  4175. // Get profile charging profile limit
  4176. if((ocpp_get_smartcharging_profileId(gun_index) > 0))
  4177. {
  4178. // Checking profile kind
  4179. if((mystrcmp((char*)ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingProfileKind, "Absolute") == PASS))
  4180. {
  4181. // Checking limitation
  4182. for(uint8_t idx_period=0;idx_period<ARRAY_SIZE(ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod);idx_period++)
  4183. {
  4184. if((getScheduleStart(gun_index) >= ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod[idx_period].StartPeriod) &&
  4185. ((idx_period == 0) || (ShmOCPP16Data->SmartChargingProfile[gun_index].ChargingSchedule.ChargingSchedulePeriod[idx_period].StartPeriod > 0))
  4186. )
  4187. {
  4188. 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);
  4189. //DEBUG_INFO("ShmCharger->gun_info[%d].targetCurrent on period[%d]: %d\n", gun_index, idx_period, ShmCharger->gun_info[gun_index].targetCurrent);
  4190. }
  4191. else
  4192. break;
  4193. }
  4194. }
  4195. }
  4196. else
  4197. {
  4198. ShmCharger->gun_info[gun_index].targetCurrent = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
  4199. }
  4200. // Get max charging profile limit
  4201. if((ocpp_get_maxcharging_profileId() > 0))
  4202. {
  4203. // Absolute profile
  4204. if((mystrcmp((char*)ShmOCPP16Data->MaxChargingProfile.ChargingProfileKind, "Absolute") == PASS))
  4205. {
  4206. for(uint8_t idx_period=0;idx_period<ARRAY_SIZE(ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod);idx_period++)
  4207. {
  4208. if((getMaxScheduleStart() >= ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[idx_period].StartPeriod) &&
  4209. ((idx_period == 0) || (ShmOCPP16Data->MaxChargingProfile.ChargingSchedule.ChargingSchedulePeriod[idx_period].StartPeriod > 0))
  4210. )
  4211. {
  4212. 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);
  4213. //DEBUG_INFO("ShmCharger->gun_info[%d].targetCurrent on period[%d]: %d\n", gun_index, idx_period, ShmCharger->gun_info[gun_index].targetCurrent);
  4214. }
  4215. else
  4216. break;
  4217. }
  4218. }
  4219. }
  4220. // Compare target current is over max current for EVSE limit
  4221. if(gun_index == 0)
  4222. {
  4223. if(ShmCharger->gun_info[gun_index].targetCurrent > MaxChargingProfileChargingCurrent)
  4224. {
  4225. ShmCharger->gun_info[gun_index].targetCurrent = MaxChargingProfileChargingCurrent;
  4226. }
  4227. }
  4228. else
  4229. {
  4230. if((ShmCharger->gun_info[gun_index-1].targetCurrent + ShmCharger->gun_info[gun_index].targetCurrent) > MaxChargingProfileChargingCurrent)
  4231. {
  4232. ShmCharger->gun_info[gun_index].targetCurrent = (MaxChargingProfileChargingCurrent - ShmCharger->gun_info[gun_index-1].targetCurrent);
  4233. }
  4234. }
  4235. }
  4236. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  4237. {
  4238. // Get profile charging profile limit
  4239. if((ocpp_get_smartcharging_profileId(gun_index) > 0))
  4240. {
  4241. // Checking profile kind
  4242. if((mystrcmp((char*)ShmOCPP20Data->SmartChargingProfile[gun_index].chargingProfileKind, "Absolute") == PASS))
  4243. {
  4244. // Checking limitation
  4245. for(uint8_t idx_period=0;idx_period<ARRAY_SIZE(ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod);idx_period++)
  4246. {
  4247. if((getScheduleStart(gun_index) >= ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod[idx_period].startPeriod) &&
  4248. ((idx_period == 0) || (ShmOCPP20Data->SmartChargingProfile[gun_index].chargingSchedule[0].chargingSchedulePeriod[idx_period].startPeriod > 0))
  4249. )
  4250. {
  4251. 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);
  4252. //DEBUG_INFO("ShmCharger->gun_info[%d].targetCurrent on period[%d]: %d\n", gun_index, idx_period, ShmCharger->gun_info[gun_index].targetCurrent);
  4253. }
  4254. else
  4255. break;
  4256. }
  4257. }
  4258. }
  4259. else
  4260. {
  4261. ShmCharger->gun_info[gun_index].targetCurrent = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
  4262. }
  4263. // Get max charging profile limit
  4264. if((ocpp_get_maxcharging_profileId() > 0))
  4265. {
  4266. // Absolute profile
  4267. if((mystrcmp((char*)ShmOCPP20Data->MaxChargingProfile.chargingProfileKind, "Absolute") == PASS))
  4268. {
  4269. // Checking limitation
  4270. for(uint8_t idx_period=0;idx_period<ARRAY_SIZE(ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingSchedulePeriod);idx_period++)
  4271. {
  4272. if((getMaxScheduleStart() >= ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingSchedulePeriod[idx_period].startPeriod) &&
  4273. ((idx_period == 0) || (ShmOCPP20Data->MaxChargingProfile.chargingSchedule[0].chargingSchedulePeriod[idx_period].startPeriod > 0))
  4274. )
  4275. {
  4276. 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);
  4277. //DEBUG_INFO("ShmCharger->gun_info[%d].targetCurrent on period[%d]: %d\n", gun_index, idx_period, ShmCharger->gun_info[gun_index].targetCurrent);
  4278. }
  4279. else
  4280. break;
  4281. }
  4282. }
  4283. }
  4284. // Compare target current is over max current for EVSE limit
  4285. if(gun_index == 0)
  4286. {
  4287. if(ShmCharger->gun_info[gun_index].targetCurrent > MaxChargingProfileChargingCurrent)
  4288. {
  4289. ShmCharger->gun_info[gun_index].targetCurrent = MaxChargingProfileChargingCurrent;
  4290. }
  4291. }
  4292. else
  4293. {
  4294. if((ShmCharger->gun_info[gun_index-1].targetCurrent + ShmCharger->gun_info[gun_index].targetCurrent) > MaxChargingProfileChargingCurrent)
  4295. {
  4296. ShmCharger->gun_info[gun_index].targetCurrent = (MaxChargingProfileChargingCurrent - ShmCharger->gun_info[gun_index-1].targetCurrent);
  4297. }
  4298. }
  4299. }
  4300. // Charging session target current check if OCPP disconnect and power sharing server connected
  4301. if(ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharing > 0)
  4302. {
  4303. if(ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer)
  4304. 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];
  4305. else
  4306. {
  4307. if(ShmCharger->gun_info[gun_index].targetCurrent != 0)
  4308. DEBUG_WARN("Disconnect from power sharing server, target current set to 0.\n");
  4309. ShmCharger->gun_info[gun_index].targetCurrent = 0;
  4310. }
  4311. }
  4312. switch(system_mode)
  4313. {
  4314. case SYS_MODE_IDLE:
  4315. if(ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent == 0)
  4316. {
  4317. 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);
  4318. if(ShmCharger->isCcsEnable)
  4319. {
  4320. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_5;
  4321. }
  4322. else
  4323. {
  4324. 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);
  4325. 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));
  4326. }
  4327. }
  4328. else
  4329. {
  4330. ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent)?ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent:ShmCharger->gun_info[gun_index].targetCurrent);
  4331. if(ShmCharger->isCcsEnable)
  4332. {
  4333. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_5;
  4334. }
  4335. else
  4336. {
  4337. 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);
  4338. 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));
  4339. }
  4340. }
  4341. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = YES;
  4342. break;
  4343. case SYS_MODE_PREPARING:
  4344. if(ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent == 0)
  4345. {
  4346. 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);
  4347. 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);
  4348. 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));
  4349. }
  4350. else
  4351. {
  4352. ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent)?ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent:ShmCharger->gun_info[gun_index].targetCurrent);
  4353. 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);
  4354. 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));
  4355. }
  4356. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = YES;
  4357. break;
  4358. case SYS_MODE_CHARGING:
  4359. case SYS_MODE_TERMINATING:
  4360. if(ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent == 0)
  4361. {
  4362. 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);
  4363. if((ShmCharger->gun_info[gun_index].targetCurrent != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current) ||
  4364. (ShmCharger->gun_info[gun_index].primaryMcuState.current_limit != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current))
  4365. {
  4366. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  4367. {
  4368. if(getDiffSecNow(startTime[gun_index][TMR_IDX_PWN_CHANGE]) > TIMEOUT_SPEC_PWN_CHANGE)
  4369. {
  4370. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmCharger->gun_info[gun_index].primaryMcuState.rating_current)?ShmCharger->gun_info[gun_index].primaryMcuState.rating_current:ShmCharger->gun_info[gun_index].targetCurrent);
  4371. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = ((1 <= ShmCharger->gun_info[gun_index].targetCurrent) && (ShmCharger->gun_info[gun_index].targetCurrent <= 5)? 6:((ShmCharger->gun_info[gun_index].targetCurrent == 0)? 100:ShmCharger->gun_info[gun_index].targetCurrent));
  4372. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = YES;
  4373. refreshStartTimer(&startTime[gun_index][TMR_IDX_PWN_CHANGE]);
  4374. }
  4375. }
  4376. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  4377. {
  4378. ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmCharger->gun_info[gun_index].primaryMcuState.rating_current)?ShmCharger->gun_info[gun_index].primaryMcuState.rating_current:ShmCharger->gun_info[gun_index].targetCurrent);
  4379. ShmCharger->gun_info[gun_index].targetCurrent = ((1 <= ShmCharger->gun_info[gun_index].targetCurrent) && (ShmCharger->gun_info[gun_index].targetCurrent <= 5)?6:ShmCharger->gun_info[gun_index].targetCurrent);
  4380. ShmCharger->gun_info[gun_index].acCcsInfo.EVSEMaxCurrent = (float)ShmCharger->gun_info[gun_index].targetCurrent;
  4381. //ShmCharger->gun_info[gun_index].acCcsInfo.EVSEMaxCurrent = (float)((ShmCharger->gun_info[gun_index].targetCurrent > ShmCharger->gun_info[gun_index].primaryMcuState.rating_current)?ShmCharger->gun_info[gun_index].primaryMcuState.rating_current:ShmCharger->gun_info[gun_index].targetCurrent);
  4382. }
  4383. }
  4384. }
  4385. else
  4386. {
  4387. ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent)?ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent:ShmCharger->gun_info[gun_index].targetCurrent);
  4388. if((ShmCharger->gun_info[gun_index].targetCurrent != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current) ||
  4389. (ShmCharger->gun_info[gun_index].primaryMcuState.current_limit != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current))
  4390. {
  4391. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  4392. {
  4393. if(getDiffSecNow(startTime[gun_index][TMR_IDX_PWN_CHANGE]) > TIMEOUT_SPEC_PWN_CHANGE)
  4394. {
  4395. 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);
  4396. 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));
  4397. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = YES;
  4398. refreshStartTimer(&startTime[gun_index][TMR_IDX_PWN_CHANGE]);
  4399. }
  4400. }
  4401. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  4402. {
  4403. ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent)?ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent:ShmCharger->gun_info[gun_index].targetCurrent);
  4404. 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);
  4405. ShmCharger->gun_info[gun_index].acCcsInfo.EVSEMaxCurrent = (float)ShmCharger->gun_info[gun_index].targetCurrent;
  4406. //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);
  4407. }
  4408. }
  4409. }
  4410. if(previousData[gun_index].primaryMcuCp_Pwn_Duty != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current)
  4411. {
  4412. DEBUG_INFO("==================================================\n");
  4413. DEBUG_INFO("gun-[%d] primaryMcuCp_Pwn_Duty: %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current);
  4414. DEBUG_INFO("==================================================\n");
  4415. previousData[gun_index].primaryMcuCp_Pwn_Duty = ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current;
  4416. }
  4417. if(ShmCharger->gun_info[gun_index].targetCurrent != previousData[gun_index].targetCurrent)
  4418. {
  4419. DEBUG_INFO("==================================================\n");
  4420. DEBUG_INFO("gun-[%d] targetCurrent: %d\n", gun_index, ShmCharger->gun_info[gun_index].targetCurrent);
  4421. DEBUG_INFO("MaxChargingCurrent: %d \n", ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent);
  4422. DEBUG_INFO("==================================================\n");
  4423. previousData[gun_index].targetCurrent = ShmCharger->gun_info[gun_index].targetCurrent;
  4424. }
  4425. if(ShmCharger->gun_info[gun_index].primaryMcuState.current_limit != previousData[gun_index].current_limit)
  4426. {
  4427. DEBUG_INFO("==================================================\n");
  4428. DEBUG_INFO("gun-[%d] mcu current_limit: %d\n", gun_index, ShmCharger->gun_info[gun_index].primaryMcuState.current_limit);
  4429. DEBUG_INFO("==================================================\n");
  4430. previousData[gun_index].current_limit = ShmCharger->gun_info[gun_index].primaryMcuState.current_limit;
  4431. }
  4432. break;
  4433. }
  4434. }
  4435. void checkStopReason(uint8_t gun_index)
  4436. {
  4437. sleep(2);
  4438. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  4439. {
  4440. memset(ShmOCPP16Data->StopTransaction[gun_index].IdTag, 0x00, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  4441. if(!ocpp_get_starttransaction_result(gun_index))
  4442. {
  4443. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "DeAuthorized");
  4444. }
  4445. else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_EMERGENCY_STOP)
  4446. {
  4447. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EmergencyStop");
  4448. memcpy((char*)ShmOCPP16Data->StopTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  4449. }
  4450. 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))
  4451. {
  4452. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "EVDisconnected");
  4453. memcpy((char*)ShmOCPP16Data->StopTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  4454. //memcpy((char*)ShmOCPP16Data->StopTransaction[gun_index].IdTag, (char*)ShmOCPP16Data->StartTransaction[gun_index].IdTag, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  4455. }
  4456. else if(ShmOCPP16Data->MsMsg.bits.ResetReq)
  4457. {
  4458. if(strcmp((char*)ShmOCPP16Data->Reset.Type, "Hard")==0)
  4459. {
  4460. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "HardReset");
  4461. memcpy((char*)ShmOCPP16Data->StopTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  4462. }
  4463. else
  4464. {
  4465. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "SoftReset");
  4466. memcpy((char*)ShmOCPP16Data->StopTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  4467. }
  4468. }
  4469. else if(ShmCharger->gun_info[gun_index].rfidReq || ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop)
  4470. {
  4471. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
  4472. if(!isMatchStartUser(gun_index))
  4473. {
  4474. memcpy((char*)ShmOCPP16Data->StopTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  4475. }
  4476. else
  4477. {
  4478. memcpy((char*)ShmOCPP16Data->StopTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  4479. }
  4480. DEBUG_INFO("Gun-[%d] : IdTag [ %s ].\n", gun_index, ShmOCPP16Data->StopTransaction[gun_index].IdTag);
  4481. }
  4482. else if(ShmOCPP16Data->CsMsg.bits[gun_index].RemoteStopTransactionReq)
  4483. {
  4484. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Remote");
  4485. memcpy((char*)ShmOCPP16Data->StopTransaction[gun_index].IdTag, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  4486. }
  4487. else if(ShmCharger->gun_info[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].isUnlockerConnetor == ON)
  4488. {
  4489. sprintf((char*)ShmOCPP16Data->StopTransaction[ShmOCPP16Data->UnlockConnector[gun_index].ConnectorId-1].StopReason, "UnlockCommand");
  4490. }
  4491. else
  4492. {
  4493. sprintf((char*)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Other");
  4494. }
  4495. DEBUG_INFO("Gun-[%d] : StopReason [ %s ].\n",gun_index,ShmOCPP16Data->StopTransaction[gun_index].StopReason);
  4496. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  4497. presentChargedEnergyUpdate(gun_index);
  4498. DEBUG_INFO("Gun-[%d] : PresentChargedEnergy [ %.4f ].\n",gun_index ,ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy);
  4499. ShmOCPP16Data->CpMsg.bits[gun_index].StopTransactionReq = ON;
  4500. }
  4501. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  4502. {
  4503. memset(ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, 0x00, ARRAY_SIZE(ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken));
  4504. if(!ocpp_get_starttransaction_result(gun_index))
  4505. {
  4506. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "DeAuthorized");
  4507. }
  4508. else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_EMERGENCY_STOP)
  4509. {
  4510. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "EmergencyStop");
  4511. memcpy((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId));
  4512. }
  4513. else if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A) || (ShmCharger->gun_info[gun_index].isGunUnpluggedBefore == YES))
  4514. {
  4515. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "EVDisconnected");
  4516. memcpy((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId));
  4517. }
  4518. else if(ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_GROUND_FAIL)
  4519. {
  4520. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "GroundFault");
  4521. }
  4522. else if((ShmOCPP20Data->MsMsg.bits.ResetReq) && (strcmp((char*)ShmOCPP20Data->Reset.type, "Immediate")==0))
  4523. {
  4524. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "ImmediateReset");
  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. else if(ShmCharger->gun_info[gun_index].rfidReq || ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop)
  4528. {
  4529. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Local");
  4530. if(!isMatchStartUser(gun_index))
  4531. {
  4532. memcpy((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, (char*)ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken));
  4533. }
  4534. else
  4535. {
  4536. memcpy((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId));
  4537. }
  4538. DEBUG_INFO("Gun-[%d] : idToken [ %s ].\n", gun_index, ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken);
  4539. }
  4540. else if((ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_L1_OVER_CURRENT) ||
  4541. (ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_L2_OVER_CURRENT) ||
  4542. (ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode & ALARM_L3_OVER_CURRENT))
  4543. {
  4544. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "OvercurrentFault");
  4545. }
  4546. else if(ShmOCPP20Data->CsMsg.bits[gun_index].RequestStopTransactionReq)
  4547. {
  4548. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Remote");
  4549. memcpy((char*)ShmOCPP20Data->TransactionEvent[gun_index].idToken.idToken, (char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId));
  4550. }
  4551. else if(ShmCharger->gun_info[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].isUnlockerConnetor == ON)
  4552. {
  4553. sprintf((char*)ShmOCPP20Data->TransactionEvent[ShmOCPP20Data->UnlockConnector[gun_index].connectorId-1].transactionInfo.stoppedReason, "UnlockCommand");
  4554. }
  4555. else
  4556. {
  4557. sprintf((char*)ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason, "Other");
  4558. }
  4559. DEBUG_INFO("Gun-[%d] : StopReason [ %s ].\n", gun_index, ShmOCPP20Data->TransactionEvent[gun_index].transactionInfo.stoppedReason);
  4560. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  4561. presentChargedEnergyUpdate(gun_index);
  4562. DEBUG_INFO("Gun-[%d] : PresentChargedEnergy [ %.4f ].\n",gun_index ,ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy);
  4563. ShmOCPP20Data->CpMsg.bits[gun_index].TransactionEventReq = ON;
  4564. }
  4565. // Maintain server
  4566. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.MaintainServerURL,"") != 0)
  4567. {
  4568. memcpy(ShmOCPP16DataPH->StopTransaction[gun_index].StopReason, ShmOCPP16Data->StopTransaction[gun_index].StopReason, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].StopReason));
  4569. memcpy(ShmOCPP16DataPH->StopTransaction[gun_index].IdTag, ShmOCPP16Data->StopTransaction[gun_index].IdTag, ARRAY_SIZE(ShmOCPP16Data->StopTransaction[gun_index].IdTag));
  4570. ShmOCPP16DataPH->CpMsg.bits[gun_index].StopTransactionReq = ON;
  4571. }
  4572. }
  4573. void checkRemoteUpgradeStatus()
  4574. {
  4575. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  4576. {
  4577. if(strcmp((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "DownloadFailed")==0)
  4578. {
  4579. DEBUG_INFO("Firmware remote upgraded fail...\n");
  4580. ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq = OFF;
  4581. ShmCharger->isUpdateSuccess = NO;
  4582. }
  4583. else if((strcmp((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Downloaded")==0))
  4584. {
  4585. DEBUG_INFO("Firmware remote upgrading...\n");
  4586. sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installing");
  4587. sleep(1);
  4588. ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  4589. ShmOCPP16Data->MsMsg.bits.UpdateFirmwareReq = OFF;
  4590. int result = upgrade_check();
  4591. DEBUG_INFO("Remote update Result: %s... \n",((result == PASS)?"Pass": "Fail"));
  4592. if(result == PASS)
  4593. {
  4594. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == ON)
  4595. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = OFF;
  4596. ShmCharger->isUpdateSuccess = YES;
  4597. DEBUG_INFO("Remote update success...\n");
  4598. }
  4599. else
  4600. {
  4601. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == OFF)
  4602. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = ON;
  4603. ShmCharger->isUpdateSuccess = NO;
  4604. DEBUG_INFO("Remote update unsuccess...\n");
  4605. }
  4606. }
  4607. else if((strcmp((char*)ShmOCPP16Data->SignedFirmwareStatusNotification.status, "SignatureVerified")==0))
  4608. {
  4609. DEBUG_INFO("Signature firmware remote upgrading...\n");
  4610. ShmOCPP16Data->SignedFirmwareStatusNotification.requestId = ShmOCPP16Data->SignedUpdateFirmware.requestId;
  4611. sprintf((char*)ShmOCPP16Data->SignedFirmwareStatusNotification.status, "Installing");
  4612. sleep(1);
  4613. ShmOCPP16Data->SpMsg.bits.SignedFirmwareStatusNotificationReq = ON;
  4614. ShmOCPP16Data->MsMsg.bits.SignedUpdateFirmwareReq = OFF;
  4615. if(upgrade_check() == PASS)
  4616. {
  4617. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == ON)
  4618. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = OFF;
  4619. ShmCharger->isUpdateSuccess = YES;
  4620. DEBUG_INFO("Remote update success.\n");
  4621. }
  4622. else
  4623. {
  4624. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == OFF)
  4625. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = ON;
  4626. ShmCharger->isUpdateSuccess = NO;
  4627. DEBUG_INFO("Remote update fail.\n");
  4628. }
  4629. }
  4630. else
  4631. {}
  4632. }
  4633. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  4634. {
  4635. if(strcmp((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "DownloadFailed")==0)
  4636. {
  4637. DEBUG_INFO("Firmware remote upgraded fail...\n");
  4638. ShmOCPP20Data->MsMsg.bits.UpdateFirmwareReq = OFF;
  4639. ShmCharger->isUpdateSuccess = NO;
  4640. }
  4641. else if((strcmp((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "Downloaded")==0))
  4642. {
  4643. DEBUG_INFO("Firmware remote upgrading...\n");
  4644. sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installing");
  4645. ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  4646. ShmOCPP20Data->MsMsg.bits.UpdateFirmwareReq = OFF;
  4647. int result = upgrade_check();
  4648. DEBUG_INFO("Remote update Result: %s... \n",((result == PASS)?"Pass": "Fail"));
  4649. if(result == PASS)
  4650. {
  4651. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == ON)
  4652. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = OFF;
  4653. ShmCharger->isUpdateSuccess = YES;
  4654. DEBUG_INFO("Remote update success...\n");
  4655. }
  4656. else
  4657. {
  4658. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == OFF)
  4659. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = ON;
  4660. ShmCharger->isUpdateSuccess = NO;
  4661. DEBUG_INFO("Remote update unsuccess...\n");
  4662. }
  4663. }
  4664. else
  4665. {}
  4666. }
  4667. }
  4668. void checkHandshakeCountdown(uint8_t gun_index)
  4669. {
  4670. switch(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus)
  4671. {
  4672. case SYS_MODE_IDLE:
  4673. if(ShmCharger->gun_info[ShmCharger->gun_selectd].isHandshakeTimerRefresh == YES)
  4674. refreshStartTimer(&startTime[0][TMR_IDX_GUN_DETECT]);
  4675. else
  4676. ShmCharger->timeoutSpec.Handshake_Timeout = ((ocpp_get_connection_timeout()) - (getDiffSecNow(startTime[0][TMR_IDX_GUN_DETECT])));
  4677. if(!ShmCharger->isAuthrizing)
  4678. {
  4679. if(ocpp_get_isRemoteStartWait())
  4680. ShmCharger->timeoutSpec.Handshake_Timeout = ((ocpp_get_connection_timeout()) - (getDiffSecNow(startTime[0][TMR_IDX_GUN_DETECT])));
  4681. else
  4682. refreshStartTimer(&startTime[0][TMR_IDX_GUN_DETECT]);
  4683. }
  4684. break;
  4685. case SYS_MODE_PREPARING:
  4686. if(ShmCharger->gun_info[ShmCharger->gun_selectd].isHandshakeTimerRefresh == YES)
  4687. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  4688. else
  4689. ShmCharger->timeoutSpec.Handshake_Timeout = ((ocpp_get_connection_timeout()) - getDiffSecNow(startTime[gun_index][TMR_IDX_HANDSHAKING]));
  4690. break;
  4691. case SYS_MODE_RESERVATION:
  4692. if(ShmCharger->gun_info[ShmCharger->gun_selectd].isHandshakeTimerRefresh == YES)
  4693. refreshStartTimer(&startTime[0][TMR_IDX_GUN_DETECT]);
  4694. else
  4695. ShmCharger->timeoutSpec.Handshake_Timeout = ((ocpp_get_connection_timeout()) - (getDiffSecNow(startTime[0][TMR_IDX_GUN_DETECT])));
  4696. break;
  4697. }
  4698. }
  4699. void checkRfidAuthrize()
  4700. {
  4701. static uint8_t isCheckdResult = FALSE;
  4702. static uint8_t isReadable = TRUE;
  4703. static uint8_t lastIdtag[ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId)];
  4704. uint8_t isStartByWrongReservation = NO;
  4705. if(!ShmCharger->isAuthrizing)
  4706. {
  4707. // Read RFID
  4708. if(GetCardSerialNumber() != FAIL)
  4709. {
  4710. if(isReadable == TRUE)
  4711. {
  4712. uint8_t isSnStart = FALSE;
  4713. uint8_t bufferRFID[ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId)];
  4714. if(ShmSysConfigAndInfo->SysConfig.RfidCardNumEndian)
  4715. {
  4716. // Big endian
  4717. switch(rfid.snType)
  4718. {
  4719. case RFID_SN_TYPE_8BYTE:
  4720. 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]);
  4721. break;
  4722. case RFID_SN_TYPE_7BYTE:
  4723. 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]);
  4724. break;
  4725. case RFID_SN_TYPE_10BYTE:
  4726. 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]);
  4727. break;
  4728. case RFID_SN_TYPE_4BYTE:
  4729. default:
  4730. sprintf((char*)bufferRFID, "%02X%02X%02X%02X", rfid.currentCard[0], rfid.currentCard[1], rfid.currentCard[2], rfid.currentCard[3]);
  4731. break;
  4732. }
  4733. }
  4734. else
  4735. {
  4736. // Little endian
  4737. switch(rfid.snType)
  4738. {
  4739. case RFID_SN_TYPE_8BYTE:
  4740. 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]);
  4741. break;
  4742. case RFID_SN_TYPE_7BYTE:
  4743. 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]);
  4744. break;
  4745. case RFID_SN_TYPE_10BYTE:
  4746. 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]);
  4747. break;
  4748. case RFID_SN_TYPE_4BYTE:
  4749. default:
  4750. sprintf((char*)bufferRFID, "%02X%02X%02X%02X", rfid.currentCard[3], rfid.currentCard[2], rfid.currentCard[1], rfid.currentCard[0]);
  4751. break;
  4752. }
  4753. }
  4754. DEBUG_INFO("Authorize request User Id : %s\n", bufferRFID);
  4755. //DEBUG_INFO("Authorize request User Id : %s\n", ShmSysConfigAndInfo->SysConfig.UserId);
  4756. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4757. ShmCharger->gun_info[gun_index].resultAuthorization = UNKNOW_RFID;
  4758. // Check SN already start
  4759. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4760. {
  4761. if(isMatchStartUser(gun_index) || (isMatchPresentUser(gun_index) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_PREPARING)))
  4762. {
  4763. DEBUG_INFO("%s running on connector-%02d.\n", ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, gun_index);
  4764. isSnStart = TRUE;
  4765. ShmCharger->gun_info[gun_index].rfidReq = ON;
  4766. ocpp_set_auth_conf(ON);
  4767. setLedMotion(gun_index,LED_ACTION_RFID_PASS);
  4768. setSpeaker(ON, SPEAKER_SHORT);
  4769. sleep(3);
  4770. break;
  4771. }
  4772. }
  4773. // Request authorize if isSnStart is false
  4774. if(!isSnStart)
  4775. {
  4776. memcpy(lastIdtag, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  4777. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, bufferRFID, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  4778. refreshStartTimer(&startTime[0][TMR_IDX_AUTH]);
  4779. ocpp_set_auth_req(ON, "ISO14443");
  4780. setLedMotion(0,LED_ACTION_AUTHED);
  4781. ShmCharger->isAuthrizing = TRUE;
  4782. ShmCharger->isGetAuthResult = FALSE;
  4783. isCheckdResult = FALSE;
  4784. }
  4785. isReadable = FALSE;
  4786. }
  4787. }
  4788. else
  4789. {
  4790. isReadable = TRUE;
  4791. }
  4792. }
  4793. else
  4794. {
  4795. // Wait authorize result
  4796. if(!ocpp_get_auth_conf() && (getDiffSecNow(startTime[0][TMR_IDX_AUTH]) > TIMEOUT_SPEC_AUTH))
  4797. {
  4798. // Authorization timeout process.
  4799. DEBUG_WARN("Authorize timeout !!!\n");
  4800. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4801. {
  4802. ShmCharger->gun_info[gun_index].resultAuthorization = UNVALIDATED_RFID;
  4803. setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
  4804. }
  4805. setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
  4806. sleep(3);
  4807. ShmCharger->isAuthrizing = FALSE;
  4808. }
  4809. else
  4810. {
  4811. if(ocpp_get_auth_conf() ||
  4812. (!ocpp_get_connection_status() && ((ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE) || (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_NOCHARGE))) ||
  4813. (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST) && (getDiffSecNow(startTime[0][TMR_IDX_AUTH]) > 2))
  4814. )
  4815. {
  4816. if(ocpp_get_auth_result(NO) ||
  4817. (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE)) ||
  4818. (!ocpp_get_connection_status() && (isValidLocalWhiteCard() == PASS) && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST)))
  4819. {
  4820. if(!isCheckdResult)
  4821. {
  4822. refreshStartTimer(&startTime[0][TMR_IDX_GUN_DETECT]);
  4823. ShmCharger->isGetAuthResult = TRUE;
  4824. isCheckdResult = TRUE;
  4825. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0)
  4826. {
  4827. ocpp_set_auth_conf(ON);
  4828. }
  4829. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4830. {
  4831. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_RESERVATION) &&
  4832. (ocpp_compare_reserve_id_with_user(gun_index) != YES) &&
  4833. (ocpp_get_auth_result(YES, gun_index) != PASS))
  4834. {
  4835. isStartByWrongReservation = YES;
  4836. ShmCharger->gun_info[gun_index].resultAuthorization = UNVALIDATED_RFID;
  4837. DEBUG_INFO("================================================== \n");
  4838. DEBUG_INFO("UserId: [ %s ]\n", ShmSysConfigAndInfo->SysConfig.UserId);
  4839. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  4840. {
  4841. DEBUG_INFO("Gun-%d IdTag: [ %s ]\n", gun_index, ShmOCPP16Data->ReserveNow[gun_index].IdTag);
  4842. DEBUG_INFO("Authorize response ParentIdTag: [ %s ]. \n", ShmOCPP16Data->Authorize.ResponseIdTagInfo.ParentIdTag);
  4843. DEBUG_INFO("Gun-%d Reserve ParentIdTag: [ %s ]. \n", gun_index, ShmOCPP16Data->ReserveNow[gun_index].ParentIdTag);
  4844. }
  4845. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  4846. {
  4847. DEBUG_INFO("Gun-%d idToken: [ %s ]\n", gun_index, ShmOCPP20Data->ReserveNow[gun_index].idToken.idToken);
  4848. DEBUG_INFO("Authorize response groupIdToken idToken: [ %s ]\n", ShmOCPP20Data->Authorize.Response_idTokenInfo.groupIdToken.idToken);
  4849. DEBUG_INFO("Gun-%d Reserve groupIdToken idToken: [ %s]\n", ShmOCPP20Data->ReserveNow[gun_index].groupIdToken.idToken);
  4850. }
  4851. DEBUG_INFO("================================================== \n");
  4852. DEBUG_INFO("Authorize fail.\n");
  4853. setSpeaker(ON, SPEAKER_INTERVAL_3COUNT);
  4854. }
  4855. else
  4856. {
  4857. ShmCharger->gun_info[gun_index].resultAuthorization = VALIDATED_RFID;
  4858. DEBUG_INFO("Authorize pass.\n");
  4859. setSpeaker(ON, SPEAKER_SHORT);
  4860. }
  4861. }
  4862. }
  4863. // Check handshake timeout
  4864. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4865. checkHandshakeCountdown(gun_index);
  4866. if((getDiffSecNow(startTime[0][TMR_IDX_GUN_DETECT]) < (ocpp_get_connection_timeout())) && (isStartByWrongReservation != YES))
  4867. {
  4868. if(GetCardSerialNumber() != FAIL)
  4869. {
  4870. if(isReadable == TRUE)
  4871. {
  4872. if(isMatchPresentUser())
  4873. {
  4874. DEBUG_INFO("Cancel present user.\n");
  4875. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4876. {
  4877. setLedMotion(gun_index,LED_ACTION_IDLE);
  4878. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  4879. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_PREPARING)
  4880. ShmCharger->gun_info[gun_index].rfidReq = ON;
  4881. }
  4882. setSpeaker(ON, SPEAKER_SHORT);
  4883. ShmCharger->isAuthrizing = FALSE;
  4884. }
  4885. isReadable = FALSE;
  4886. }
  4887. }
  4888. else
  4889. {
  4890. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4891. {
  4892. if(getDiffSecNow(startTime[0][TMR_IDX_GUN_DETECT]) < 3)
  4893. setLedMotion(gun_index,LED_ACTION_RFID_PASS);
  4894. else
  4895. setLedMotion(gun_index,LED_ACTION_AUTHED);
  4896. 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))) ||
  4897. ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_PREPARING) && (ShmCharger->gun_selectd == gun_index)) ||
  4898. (((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_CHARGING) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_TERMINATING)) && (ShmCharger->gun_selectd == gun_index))
  4899. )
  4900. {
  4901. DEBUG_INFO("Connector-%02d action detect.\n", gun_index);
  4902. ShmCharger->isAuthrizing = FALSE;
  4903. ShmCharger->gun_info[gun_index].rfidReq = ON;
  4904. break;
  4905. }
  4906. }
  4907. isReadable = TRUE;
  4908. }
  4909. }
  4910. else
  4911. {
  4912. if(isStartByWrongReservation != YES)
  4913. DEBUG_INFO("Connector action detect timeout.\n");
  4914. else
  4915. DEBUG_INFO("Start by wrong reservation user. \n");
  4916. ShmCharger->isAuthrizing = FALSE;
  4917. ShmCharger->isGetAuthResult = TRUE;
  4918. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4919. {
  4920. if(isStartByWrongReservation != YES)
  4921. {
  4922. setLedMotion(gun_index,LED_ACTION_HANDSHAKE_FAIL);
  4923. sleep(6);
  4924. }
  4925. else
  4926. {
  4927. setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
  4928. sleep(3);
  4929. }
  4930. setLedMotion(gun_index,LED_ACTION_IDLE);
  4931. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  4932. }
  4933. }
  4934. }
  4935. else
  4936. {
  4937. DEBUG_INFO("Authorize fail.\n");
  4938. ShmCharger->isAuthrizing = FALSE;
  4939. ShmCharger->isGetAuthResult = TRUE;
  4940. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4941. {
  4942. ShmCharger->gun_info[gun_index].resultAuthorization = UNVALIDATED_RFID;
  4943. setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
  4944. }
  4945. setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
  4946. sleep(3);
  4947. for(int gun_index = 0;gun_index<modelnameInfo.GetGunCount;gun_index++)
  4948. {
  4949. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_PREPARING))
  4950. setLedMotion(gun_index,LED_ACTION_AUTHED);
  4951. else
  4952. setLedMotion(gun_index,LED_ACTION_IDLE);
  4953. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_PREPARING) && (ShmCharger->gun_selectd == gun_index))
  4954. {
  4955. switch(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod)
  4956. {
  4957. case START_METHOD_BACKEND:
  4958. ocpp_copy_userid_from_remotestart(gun_index);
  4959. break;
  4960. default:
  4961. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, lastIdtag, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  4962. DEBUG_INFO("==========================================\n");
  4963. DEBUG_INFO("Copy lastIdtag into UserId. \n");
  4964. DEBUG_INFO("lastIdtag : [%s] ---> UserId : [%s] . \n", lastIdtag, ShmSysConfigAndInfo->SysConfig.UserId);
  4965. DEBUG_INFO("==========================================\n");
  4966. break;
  4967. }
  4968. }
  4969. }
  4970. }
  4971. }
  4972. }
  4973. }
  4974. }
  4975. void setPtbMeterPermission(uint8_t gun_index, uint8_t permission)
  4976. {
  4977. switch(permission)
  4978. {
  4979. case PREMISSION_DEFAULT:
  4980. // Changed permission to [Default]
  4981. ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.PtbMeterPermissionStatus = PREMISSION_DEFAULT;
  4982. DEBUG_INFO("Set PTB meter permission to [ PREMISSION_DEFAULT ] \n");
  4983. break;
  4984. case PERMISSION_START_CHARGING:
  4985. // Changed permission to [Start Charging]
  4986. if((ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.PtbMeterPermissionStatus != PERMISSION_START_CHARGING) &&
  4987. (ShmCharger->gun_info[gun_index].isSetPtbMeterPermisson != ON))
  4988. {
  4989. ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.PtbMeterPermissionStatus = PERMISSION_START_CHARGING;
  4990. ShmCharger->gun_info[gun_index].isSetPtbMeterPermisson = ON;
  4991. DEBUG_INFO("Set PTB meter permission to [ PERMISSION_START_CHARGING ] \n");
  4992. DB_Update_Meter_Permission(localDb, gun_index, PERMISSION_START_CHARGING);
  4993. }
  4994. break;
  4995. case PERMISSION_END_CHARGING:
  4996. // Changed permission to [End Charging]
  4997. if((ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.PtbMeterPermissionStatus != PERMISSION_END_CHARGING) &&
  4998. (ShmCharger->gun_info[gun_index].isSetPtbMeterPermisson != ON))
  4999. {
  5000. ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.PtbMeterPermissionStatus = PERMISSION_END_CHARGING;
  5001. ShmCharger->gun_info[gun_index].isSetPtbMeterPermisson = ON;
  5002. DEBUG_INFO("Set PTB meter permission to [ PERMISSION_END_CHARGING ] \n");
  5003. DB_Update_Meter_Permission(localDb, gun_index, PERMISSION_END_CHARGING);
  5004. }
  5005. break;
  5006. }
  5007. }
  5008. void processEndOfChargingForPtbMeter(uint8_t gun_index)
  5009. {
  5010. if(getDiffSecNow(startTime[gun_index][TMR_IDX_PTB_METER_MESSAGE]) >= 12)
  5011. {
  5012. if((ocpp_set_ocmf_data_transfer(gun_index) == YES))
  5013. {
  5014. checkStopReason(gun_index);
  5015. if(ShmOCPP16Data->OcmfData[gun_index].SendOcmfDataReq != ON)
  5016. ShmOCPP16Data->OcmfData[gun_index].SendOcmfDataReq = ON;
  5017. ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.isUpLoad = YES;
  5018. setChargerMode(gun_index, SYS_MODE_COMPLETE);
  5019. }
  5020. else
  5021. {
  5022. checkStopReason(gun_index);
  5023. ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.isUpLoad = NO;
  5024. setChargerMode(gun_index, SYS_MODE_COMPLETE);
  5025. }
  5026. }
  5027. else
  5028. {
  5029. setPtbMeterPermission(gun_index, PERMISSION_END_CHARGING);
  5030. if((getDiffSecNow(startTime[gun_index][TMR_IDX_PTB_METER_MESSAGE]) >= 6) && (getDiffSecNow(startTime[gun_index][TMR_IDX_PTB_METER_MESSAGE]) <= 9))
  5031. {
  5032. ShmCharger->gun_info[gun_index].isGetPtbMeterMessage = ON;
  5033. // After 6 seconds Relay off & PWM off (specifcation)
  5034. setRelay(gun_index, OFF);
  5035. setRequest(gun_index, OFF);
  5036. }
  5037. }
  5038. }
  5039. void checkMissingPtbMeterMessage(uint8_t gun_index)
  5040. {
  5041. if((ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.PtbMeterPermissionStatus == PERMISSION_START_CHARGING))
  5042. {
  5043. // Trigger get PTB meter message
  5044. if((getDiffSecNow(startTime[gun_index][TMR_IDX_PTB_METER_SEND]) > 0) && (getDiffSecNow(startTime[gun_index][TMR_IDX_PTB_METER_SEND]) <= 5))
  5045. {
  5046. ShmCharger->gun_info[gun_index].isGetPtbMeterMessage = ON;
  5047. }
  5048. // 5 seconds for MCU & PTB communcation + 5 seconds for CSU & MCU get PTB messages.
  5049. if((getDiffSecNow(startTime[gun_index][TMR_IDX_PTB_METER_SEND]) >= 12))
  5050. {
  5051. if((ShmCharger->gun_info[gun_index].isGetPtbMeterMessage != ON))
  5052. {
  5053. if((ocpp_set_ocmf_data_transfer(gun_index) == YES))
  5054. {
  5055. if(ShmOCPP16Data->OcmfData[gun_index].SendOcmfDataReq != ON)
  5056. ShmOCPP16Data->OcmfData[gun_index].SendOcmfDataReq = ON;
  5057. ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.isUpLoad = YES;
  5058. ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.PtbMeterPermissionStatus = PERMISSION_END_CHARGING;
  5059. DB_Update_Meter_Permission(localDb, gun_index, PERMISSION_END_CHARGING);
  5060. DB_Insert_Record(localDb, gun_index);
  5061. DEBUG_INFO("Meter data send to the backend system. \n");
  5062. }
  5063. else
  5064. {
  5065. ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.isUpLoad = NO;
  5066. ShmCharger->gun_info[gun_index].Ptb_Meter_Parameters.PtbMeterPermissionStatus = PERMISSION_END_CHARGING;
  5067. DB_Update_Meter_Permission(localDb, gun_index, PERMISSION_END_CHARGING);
  5068. DEBUG_INFO("No data to send. \n");
  5069. }
  5070. }
  5071. else
  5072. {}
  5073. }
  5074. else
  5075. {}
  5076. }
  5077. else
  5078. {
  5079. refreshStartTimer(&startTime[gun_index][TMR_IDX_PTB_METER_SEND]);
  5080. }
  5081. }
  5082. void checkConnectorStatus(uint8_t gun_index)
  5083. {
  5084. if((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS) || (ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC))
  5085. {
  5086. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A))
  5087. {
  5088. if(ShmCharger->gun_info[gun_index].isGunUnpluggedBefore != YES)
  5089. {
  5090. ShmCharger->gun_info[gun_index].isGunUnpluggedBefore = YES;
  5091. switch(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus)
  5092. {
  5093. case SYS_MODE_CHARGING:
  5094. DEBUG_INFO("Gun-[%d] is unplugged under: [CHARGING].\n", gun_index);
  5095. break;
  5096. case SYS_MODE_TERMINATING:
  5097. DEBUG_INFO("Gun-[%d] is unplugged under: [TERMINATING].\n", gun_index);
  5098. break;
  5099. case SYS_MODE_COMPLETE:
  5100. DEBUG_INFO("Gun-[%d] is unplugged under: [COMPLETE].\n", gun_index);
  5101. break;
  5102. case SYS_MODE_ALARM:
  5103. DEBUG_INFO("Gun-[%d] is unplugged under: [ALARM].\n", gun_index);
  5104. break;
  5105. }
  5106. }
  5107. }
  5108. }
  5109. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE)
  5110. {
  5111. if(ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn != ON)
  5112. {
  5113. if(ShmCharger->gun_info[gun_index].isGunUnpluggedBefore != YES)
  5114. {
  5115. ShmCharger->gun_info[gun_index].isGunUnpluggedBefore = YES;
  5116. switch(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus)
  5117. {
  5118. case SYS_MODE_CHARGING:
  5119. DEBUG_INFO("Socket_e-[%d] is unplugged under: [CHARGING].\n", gun_index);
  5120. break;
  5121. case SYS_MODE_TERMINATING:
  5122. DEBUG_INFO("Socket_e-[%d] is unplugged under: [TERMINATING].\n", gun_index);
  5123. break;
  5124. case SYS_MODE_COMPLETE:
  5125. DEBUG_INFO("Socket_e-[%d] is unplugged under: [COMPLETE].\n", gun_index);
  5126. break;
  5127. case SYS_MODE_ALARM:
  5128. DEBUG_INFO("Socket_e-[%d] is unplugged under: [ALARM].\n", gun_index);
  5129. break;
  5130. }
  5131. }
  5132. }
  5133. }
  5134. else
  5135. {}
  5136. }
  5137. //======================================================
  5138. // Main process
  5139. //======================================================
  5140. int main(void)
  5141. {
  5142. //==================================================
  5143. // Create all share memory
  5144. //==================================================
  5145. if(CreatShareMemory()==0)
  5146. {
  5147. DEBUG_ERROR("CreatShareMemory NG\n");
  5148. if(ShmStatusCodeData!=NULL)
  5149. {
  5150. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=1;
  5151. }
  5152. sleep(5);
  5153. system("reboot -f");
  5154. sleep(5);
  5155. system("reboot -f");
  5156. }
  5157. else
  5158. {
  5159. DEBUG_INFO("CreatShareMemory OK\n");
  5160. }
  5161. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  5162. {
  5163. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus = 0xff;
  5164. ShmCharger->gun_info[gun_index].primaryMcuState.rotatory_switch = 0xff;
  5165. ShmCharger->gun_info[gun_index].mcuResetRequest.isMcuResetRequest = ON;
  5166. ShmCharger->gun_info[gun_index].isSetBreatheLedTiming = OFF;
  5167. ShmCharger->gun_info[gun_index].isSetLedBrightness = OFF;
  5168. }
  5169. //==================================================
  5170. // Main loop
  5171. //==================================================
  5172. for(;;)
  5173. {
  5174. //==============================================
  5175. // Synchronize share memory from OCPP struct
  5176. //==============================================
  5177. ShmSysConfigAndInfo->SysInfo.OcppConnStatus = ocpp_get_connection_status();
  5178. //==============================================
  5179. // Period check for 10 seconds
  5180. //==============================================
  5181. if((getDiffSecNow(startTime[0][TMR_IDX_CHECK_TASK]) > 10) || (getDiffSecNow(startTime[0][TMR_IDX_CHECK_TASK]) < 0))
  5182. {
  5183. //==============================================
  5184. // Check task processing
  5185. //==============================================
  5186. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[0].SystemStatus != SYS_MODE_BOOTING)
  5187. checkTask();
  5188. //==============================================
  5189. // Check connection timeout specification
  5190. //==============================================
  5191. checkConnectionTimeout();
  5192. refreshStartTimer(&startTime[0][TMR_IDX_CHECK_TASK]);
  5193. }
  5194. //==============================================
  5195. // Something need run in Idle mode
  5196. //==============================================
  5197. 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)) &&
  5198. (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))
  5199. {
  5200. // Check restore factory setting request
  5201. if(ShmSysConfigAndInfo->SysInfo.FactoryConfiguration)
  5202. {
  5203. // Set led to initial
  5204. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  5205. {
  5206. setLedMotion(gun_index,LED_ACTION_INIT);
  5207. }
  5208. sleep(5);
  5209. system("cd /root;./Module_FactoryConfig -m");
  5210. // OCPP 1.6 Configuration key
  5211. system("rm -f /Storage/OCPP/OCPPConfiguration");
  5212. // OCPP 2.O Configuration variable
  5213. DB_variableClear(ocppDb);
  5214. DEBUG_INFO("Default configuration to factory setting. \n");
  5215. system("sync");
  5216. sleep(5);
  5217. system("reboot -f");
  5218. sleep(5);
  5219. system("reboot -f");
  5220. }
  5221. // Check upgrade firmware request
  5222. if(ShmSysConfigAndInfo->SysInfo.FirmwareUpdate ||
  5223. ocpp_get_update_firmware_req())
  5224. {
  5225. // If available memory too small, free memory cache first
  5226. if(getAvailableMemory() < (200*1024*1024))
  5227. {
  5228. DEBUG_INFO("Available memory (%.2f Bytes) less than 200 MBytes, free cache first.\n", getAvailableMemory()/(1024*1024.0));
  5229. system("echo 3 > /proc/sys/vm/drop_caches");
  5230. }
  5231. ShmCharger->isUpdateSuccess = NO;
  5232. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  5233. {
  5234. setLedMotion(gun_index,LED_ACTION_MAINTAIN);
  5235. setChargerMode(gun_index, SYS_MODE_UPDATE);
  5236. }
  5237. }
  5238. }
  5239. //==============================================
  5240. // Check remote reset request
  5241. //==============================================
  5242. checkReset();
  5243. //==============================================
  5244. // Check RFID authorization
  5245. //==============================================
  5246. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  5247. {
  5248. // The user is not allowed to use RFID when the system change to under those modes.
  5249. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_ALARM) ||
  5250. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_FAULT) ||
  5251. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_DEBUG) ||
  5252. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_UPDATE) ||
  5253. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_BOOTING) ||
  5254. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_COMPLETE) ||
  5255. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_MAINTAIN) ||
  5256. (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE))
  5257. {
  5258. }
  5259. else
  5260. {
  5261. checkRfidAuthrize();
  5262. }
  5263. }
  5264. //==============================================
  5265. // Check Local Power Sharing Communication
  5266. //==============================================
  5267. if(ShmSysConfigAndInfo->SysConfig.isEnableLocalPowerSharing > 0)
  5268. {
  5269. if(ShmSysConfigAndInfo->SysInfo.localSharingInfo.isConnectedSharingServer)
  5270. {
  5271. if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LocalPowerSharingCommunicationError == ON)
  5272. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LocalPowerSharingCommunicationError = OFF;
  5273. }
  5274. else
  5275. {
  5276. if(ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LocalPowerSharingCommunicationError == OFF)
  5277. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.LocalPowerSharingCommunicationError = ON;
  5278. }
  5279. }
  5280. //==============================================
  5281. // Connector loop
  5282. //==============================================
  5283. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  5284. {
  5285. //==========================================
  5286. // Power saving logic
  5287. //==========================================
  5288. /*
  5289. * TODO:
  5290. * 1. Power saving logic
  5291. */
  5292. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A) && (ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn == OFF))
  5293. {
  5294. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_STATE_B]);
  5295. }
  5296. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_ALARM) ||
  5297. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_FAULT) ||
  5298. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_UPDATE) ||
  5299. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_MAINTAIN) ||
  5300. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_CHARGING) ||
  5301. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_TERMINATING) ||
  5302. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_COMPLETE) ||
  5303. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_RESERVATION))
  5304. {
  5305. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
  5306. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_RFID]);
  5307. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_METER]);
  5308. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]);
  5309. }
  5310. else
  5311. {
  5312. if((ShmCharger->gun_info[ShmCharger->gun_selectd].isHandshakeTimerRefresh == YES) ||
  5313. (gpio_get_value(GPIO_IN_WAKEUP) == OFF) ||
  5314. (ShmCharger->gun_info[gun_index].GPIO_Input.Button_Mode_Switch == ON) ||
  5315. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus != ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus) ||
  5316. (((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)) &&
  5317. ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B) || (ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn == ON)) &&
  5318. (getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_STATE_B]) < 10)))
  5319. {
  5320. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
  5321. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_RFID]);
  5322. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_METER]);
  5323. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]);
  5324. if(((gpio_get_value(GPIO_IN_WAKEUP) == OFF) || (ShmCharger->gun_info[gun_index].GPIO_Input.Button_Mode_Switch == ON)) &&
  5325. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_IDLE) &&
  5326. (getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_CHECK_POWER_CONSUMPTION]) > TIMEOUT_SPEC_CEHCK_POWER_CONSUMPTION))
  5327. {
  5328. ShmCharger->gun_info[gun_index].isCheckPowerConsumption = YES;
  5329. refreshStartTimer(&startTime[gun_index][TMR_IDX_LCM_POWER_CONSUMPTION]);
  5330. }
  5331. }
  5332. else
  5333. {
  5334. refreshStartTimer(&startTime[gun_index][TMR_IDX_CHECK_POWER_CONSUMPTION]);
  5335. if((getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_LCM_POWER_CONSUMPTION]) > TIMEOUT_SPEC_CEHCK_POWER_CONSUMPTION))
  5336. {
  5337. ShmCharger->gun_info[gun_index].isCheckPowerConsumption = NO;
  5338. }
  5339. }
  5340. }
  5341. if(getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD]) > TIMEOUT_SPEC_POWERSAVING_LCD)
  5342. {
  5343. if(ShmCharger->isLcdOn == ON)
  5344. {
  5345. DEBUG_INFO("LCD into power saving...%d\n", getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD]));
  5346. ShmCharger->isLcdOn = OFF;
  5347. }
  5348. }
  5349. else
  5350. {
  5351. if(ShmCharger->isLcdOn == OFF)
  5352. {
  5353. DEBUG_INFO("LCD exit power saving...%d\n", getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_LCD]));
  5354. ShmCharger->isLcdOn = ON;
  5355. }
  5356. }
  5357. if(getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_RFID]) > TIMEOUT_SPEC_POWERSAVING_RFID)
  5358. {
  5359. if(gpio_get_value(GPIO_OUT_RST_RFID) == ON)
  5360. {
  5361. DEBUG_INFO("RFID into power saving...%d\n", getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_RFID]));
  5362. gpio_set_value(GPIO_OUT_RST_RFID, OFF);
  5363. }
  5364. }
  5365. else
  5366. {
  5367. if(gpio_get_value(GPIO_OUT_RST_RFID) == OFF)
  5368. {
  5369. DEBUG_INFO("RFID exit power saving...%d\n", getDiffSecNow(startTime[ShmCharger->gun_selectd][TMR_IDX_POWERSAVING_RFID]));
  5370. gpio_set_value(GPIO_OUT_RST_RFID, ON);
  5371. }
  5372. }
  5373. if(getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_METER]) > TIMEOUT_SPEC_POWERSAVING_METER)
  5374. {
  5375. if(ShmCharger->gun_info[gun_index].isMeterOn)
  5376. {
  5377. DEBUG_INFO("Meter into power saving...%d\n", getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_METER]));
  5378. ShmCharger->gun_info[gun_index].isMeterOn = OFF;
  5379. }
  5380. }
  5381. else
  5382. {
  5383. if(!ShmCharger->gun_info[gun_index].isMeterOn)
  5384. {
  5385. DEBUG_INFO("Meter exit power saving...%d\n", getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_METER]));
  5386. ShmCharger->gun_info[gun_index].isMeterOn = ON;
  5387. }
  5388. }
  5389. if(getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]) > TIMEOUT_SPEC_POWERSAVING_LED_STATUS)
  5390. {
  5391. if(ShmCharger->gun_info[gun_index].isSleepOn == NO)
  5392. {
  5393. DEBUG_INFO("LED status into power saving...%d\n", getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]));
  5394. ShmCharger->gun_info[gun_index].isSleepOn = YES;
  5395. }
  5396. }
  5397. else
  5398. {
  5399. if(ShmCharger->gun_info[gun_index].isSleepOn == YES)
  5400. {
  5401. DEBUG_INFO("LED status exit power saving...%d\n", getDiffSecNow(startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]));
  5402. ShmCharger->gun_info[gun_index].isSleepOn = NO;
  5403. }
  5404. }
  5405. //==========================================
  5406. // Synchronize current rating value from MCU
  5407. //==========================================
  5408. ShmSysConfigAndInfo->SysConfig.RatingCurrent = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
  5409. //==========================================
  5410. // Assign connector location index for OCPP
  5411. //==========================================
  5412. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].Index = gun_index;
  5413. //==========================================
  5414. // Synchronize present charging power
  5415. //==========================================
  5416. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount == 1)
  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. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower <= 1.0)
  5422. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = 0;
  5423. }
  5424. else
  5425. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = 0;
  5426. }
  5427. else
  5428. {
  5429. if(ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON)
  5430. {
  5431. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = (((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingVoltage*ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrent)/1000) +
  5432. ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingVoltageL2*ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrentL2)/1000) +
  5433. ((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingVoltageL3*ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingCurrentL3)/1000));
  5434. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower <= 1.0)
  5435. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = 0;
  5436. }
  5437. else
  5438. {
  5439. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargingPower = 0;
  5440. }
  5441. }
  5442. //==========================================
  5443. // Check initialization "PASS" or "FAIL"
  5444. //==========================================
  5445. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[0].SystemStatus != SYS_MODE_BOOTING)
  5446. {
  5447. // Alarm event check
  5448. if((ShmCharger->gun_info[gun_index].primaryMcuAlarm.InputAlarmCode>0) || (ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode>0) || ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CCSboardStestFail)
  5449. {
  5450. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_ALARM)
  5451. {
  5452. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus != SYS_MODE_UPDATE)
  5453. {
  5454. setChargerMode(gun_index, SYS_MODE_ALARM);
  5455. }
  5456. }
  5457. }
  5458. }
  5459. //==========================================
  5460. // Reservation request check
  5461. //==========================================
  5462. checkReservation(gun_index);
  5463. //==========================================
  5464. // Change availability check
  5465. //==========================================
  5466. checkAvailability(gun_index);
  5467. if(ShmCharger->gun_info[gun_index].isOperactive)
  5468. {
  5469. if(isMode(gun_index, SYS_MODE_MAINTAIN))
  5470. {
  5471. setChargerMode(gun_index, SYS_MODE_IDLE);
  5472. }
  5473. }
  5474. else
  5475. {
  5476. if(isMode(gun_index, SYS_MODE_IDLE))
  5477. {
  5478. setChargerMode(gun_index, SYS_MODE_MAINTAIN);
  5479. }
  5480. }
  5481. //==========================================
  5482. // Unlock Connector signal check
  5483. //==========================================
  5484. checkUnlocker(gun_index);
  5485. //==========================================
  5486. // Clean EVCCID timeout flag
  5487. //==========================================
  5488. if((ShmSysConfigAndInfo->SysConfig.isAuthrizeByEVCCID && (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_ENABLE)) &&
  5489. (ShmCharger->isCcsEnable) &&
  5490. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A))
  5491. {
  5492. for(int gun_index = 0;gun_index<AC_QUANTITY;gun_index++)
  5493. {
  5494. ShmCharger->gun_info[gun_index].isGetEvCCIDTimeout = OFF;
  5495. ShmCharger->gun_info[gun_index].isEvCCIDAuthorizeFail = NO;
  5496. }
  5497. }
  5498. //==========================================
  5499. // Check EVCCID communcation error
  5500. //==========================================
  5501. if(ShmCharger->gun_info[gun_index].isGetEvCCIDTimeout == ON)
  5502. {
  5503. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEvCommFail == OFF)
  5504. ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEvCommFail = ON;
  5505. }
  5506. else
  5507. {
  5508. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEvCommFail == ON)
  5509. ShmStatusCodeData->InfoCode.InfoEvents.bits.CcsEvCommFail = OFF;
  5510. }
  5511. //==========================================
  5512. // Clean isRemoteStartWait flag
  5513. //==========================================
  5514. if(ocpp_get_isRemoteStartWait())
  5515. {
  5516. if(ShmCharger->gun_info[gun_index].isRemoteStartWait == OFF)
  5517. {
  5518. ShmCharger->gun_info[gun_index].isRemoteStartWait = ON;
  5519. DEBUG_INFO("Remote start without connector id... \n");
  5520. }
  5521. refreshStartTimer(&startTime[gun_index][TMR_IDX_CLEAN_REMOTE_START_WAIT]);
  5522. }
  5523. else
  5524. {
  5525. if((getDiffSecNow(startTime[gun_index][TMR_IDX_CLEAN_REMOTE_START_WAIT]) > 5))
  5526. {
  5527. if(ShmCharger->gun_info[gun_index].isRemoteStartWait == ON)
  5528. {
  5529. ShmCharger->gun_info[gun_index].isRemoteStartWait = OFF;
  5530. DEBUG_INFO("Clean isRemoteStartWait flag... \n");
  5531. }
  5532. }
  5533. if((getDiffSecNow(startTime[gun_index][TMR_IDX_CLEAN_REMOTE_START_WAIT]) > 10))
  5534. {
  5535. refreshStartTimer(&startTime[gun_index][TMR_IDX_CLEAN_REMOTE_START_WAIT]);
  5536. }
  5537. }
  5538. //==========================================
  5539. // QCA7000 close and open timing
  5540. //==========================================
  5541. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus > SYS_MODE_BOOTING)
  5542. {
  5543. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A) ||
  5544. (((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_CHARGING) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_TERMINATING) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus == SYS_MODE_COMPLETE)) && (ShmCharger->gun_info[gun_index].chargingMode != CHARGING_MODE_HLC)))
  5545. {
  5546. if((gpio_get_value(GPIO_OUT_RST_QCA) == ON) && (ShmCharger->isCcsEnable))
  5547. {
  5548. gpio_set_value(GPIO_OUT_RST_QCA, OFF);
  5549. }
  5550. }
  5551. else
  5552. {
  5553. if((gpio_get_value(GPIO_OUT_RST_QCA) == OFF) && (ShmCharger->isCcsEnable))
  5554. {
  5555. gpio_set_value(GPIO_OUT_RST_QCA, ON);
  5556. //sleep(3);
  5557. }
  5558. }
  5559. }
  5560. //==========================================
  5561. // Synchronized total power consumption
  5562. //==========================================
  5563. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==1)
  5564. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  5565. else
  5566. {
  5567. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  5568. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[0] = (ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption/10000.0);
  5569. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[1] = (ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption/10000.0);
  5570. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[2] = (ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption/10000.0);
  5571. }
  5572. //==========================================
  5573. // Connector process
  5574. //==========================================
  5575. switch(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus)
  5576. {
  5577. case SYS_MODE_BOOTING:
  5578. if(isModeChange(gun_index))
  5579. {
  5580. setLedMotion(gun_index,LED_ACTION_INIT);
  5581. //CSU Initialization & task spawn
  5582. if((Initialization(gun_index) != PASS) ||
  5583. (SpawnTask(gun_index) != PASS))
  5584. {
  5585. ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = ON;
  5586. }
  5587. // Firmware version
  5588. get_firmware_version(gun_index);
  5589. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
  5590. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_RFID]);
  5591. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_METER]);
  5592. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_STATE_B]);
  5593. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LED_STATUS]);
  5594. refreshStartTimer(&startTime[gun_index][TMR_IDX_LCM_POWER_CONSUMPTION]);
  5595. }
  5596. if(ShmCharger->gun_info[gun_index].mcuFlag.isReadFwVerPass &&
  5597. ShmCharger->gun_info[gun_index].mcuFlag.isSetModelNamePass &&
  5598. ShmCharger->gun_info[gun_index].mcuFlag.isSetSerialNumberPass)
  5599. {
  5600. ShmCharger->gun_selectd = 0;
  5601. // Firmware version
  5602. get_firmware_version(gun_index);
  5603. // Change availability check
  5604. checkAvailability(gun_index);
  5605. // OCPP BootNotification info set
  5606. DEBUG_INFO("==========================================\n");
  5607. DEBUG_INFO("System ID: %s\n",ShmSysConfigAndInfo->SysConfig.SystemId);
  5608. DEBUG_INFO("==========================================\n");
  5609. DEBUG_INFO("=== OCPP BootNotification information ====\n");
  5610. ocpp_boot_info_sync();
  5611. DEBUG_INFO("OcppServerURL: %s\n",ShmSysConfigAndInfo->SysConfig.OcppServerURL);
  5612. DEBUG_INFO("ChargeBoxId: %s\n",ShmSysConfigAndInfo->SysConfig.ChargeBoxId);
  5613. DEBUG_INFO("ChargePointVendor: %s\n",ShmSysConfigAndInfo->SysConfig.chargePointVendor);
  5614. DEBUG_INFO("==========================================\n");
  5615. DEBUG_INFO("========== Set Wifi information ==========\n");
  5616. DEBUG_INFO("Wifi mode: %d\n", ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode);
  5617. DEBUG_INFO("Wifi SSID: %s\n", ShmSysConfigAndInfo->SysConfig.AthInterface.WifiSsid);
  5618. DEBUG_INFO("Wifi password: %s\n", ShmSysConfigAndInfo->SysConfig.AthInterface.WifiPassword);
  5619. DEBUG_INFO("==========================================\n");
  5620. // Set max current to rating current
  5621. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = ShmCharger->gun_info[gun_index].primaryMcuState.rating_current;
  5622. // Default Ethernet / Wifi / 4G to 1:disconnected
  5623. switch(ShmSysConfigAndInfo->SysConfig.ModelName[10])
  5624. {
  5625. case 'E':
  5626. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
  5627. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = OFF;
  5628. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = OFF;
  5629. break;
  5630. case 'W':
  5631. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
  5632. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = ON;
  5633. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = OFF;
  5634. break;
  5635. case 'T':
  5636. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
  5637. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = OFF;
  5638. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = ON;
  5639. break;
  5640. case 'D':
  5641. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaEthernet = ON;
  5642. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi = ON;
  5643. ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectVia4Gi = ON;
  5644. break;
  5645. }
  5646. // Default LCM brightness to 100
  5647. ShmCharger->isLcdOn = ON;
  5648. // Defaule led status to not sleep mode
  5649. ShmCharger->gun_info[gun_index].isSleepOn = NO;
  5650. // If Web Server OPCC URL is empty kill Module_OcppBackend
  5651. if((strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0))
  5652. {
  5653. if(strcmp((char *)&ShmSysConfigAndInfo->SysConfig.OcppServerURL,"") == 0)
  5654. DEBUG_INFO("URL is empty kill Module_OcppBackend...\n");
  5655. system ("pkill OcppBackend");
  5656. }
  5657. else
  5658. {
  5659. system ("pkill OcppBackend");
  5660. DEBUG_INFO("Initialization: Kill OcppBackend task. \n");
  5661. }
  5662. // If rotate switch equal zero, the system needs to change Debug mode
  5663. if(ShmCharger->gun_info[gun_index].primaryMcuState.rotatory_switch == 0)
  5664. {
  5665. setChargerMode(gun_index, SYS_MODE_DEBUG);
  5666. }
  5667. else
  5668. {
  5669. // Check is operactive
  5670. if(ShmCharger->gun_info[gun_index].isOperactive)
  5671. {
  5672. setChargerMode(gun_index, SYS_MODE_IDLE);
  5673. }
  5674. else
  5675. {
  5676. setChargerMode(gun_index, SYS_MODE_MAINTAIN);
  5677. }
  5678. }
  5679. // The system identifies 1 phase or 3 phases depending on the model name
  5680. ShmSysConfigAndInfo->SysConfig.AcPhaseCount = ((ShmSysConfigAndInfo->SysConfig.ModelName[2]=='Y') ||
  5681. (ShmSysConfigAndInfo->SysConfig.ModelName[2]=='D') ||
  5682. (ShmSysConfigAndInfo->SysConfig.ModelName[2]=='W')
  5683. ?3:1);
  5684. /*
  5685. if((ShmSysConfigAndInfo->SysConfig.ModelName[2]=='Y') || (ShmSysConfigAndInfo->SysConfig.ModelName[2]=='D') || (ShmSysConfigAndInfo->SysConfig.ModelName[2]=='W'))
  5686. {
  5687. // The dip switch 1: one phase 0: three phases
  5688. if(ShmCharger->gun_info[gun_index].primaryMcuState.dip_switch == ON)
  5689. ShmSysConfigAndInfo->SysConfig.AcPhaseCount = 1;
  5690. else
  5691. ShmSysConfigAndInfo->SysConfig.AcPhaseCount = 3;
  5692. DEBUG_INFO("Dip switch: %s \n", (ShmCharger->gun_info[gun_index].primaryMcuState.dip_switch == ON? "ON":"OFF"));
  5693. }
  5694. else
  5695. {
  5696. ShmSysConfigAndInfo->SysConfig.AcPhaseCount = 1;
  5697. }
  5698. DEBUG_INFO("AcPhaseCount: %d \n", ShmSysConfigAndInfo->SysConfig.AcPhaseCount);
  5699. */
  5700. // Refresh PTB resend timer
  5701. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  5702. refreshStartTimer(&startTime[gun_index][TMR_IDX_PTB_METER_SEND]);
  5703. DEBUG_INFO("System memory power consumption: %.4f \n",(ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0));
  5704. DEBUG_INFO("Share memory power consumption: %.4f \n",ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption);
  5705. }
  5706. break;
  5707. case SYS_MODE_IDLE:
  5708. if(isModeChange(gun_index))
  5709. {
  5710. setLedMotion(gun_index,LED_ACTION_IDLE);
  5711. setRelay(gun_index, OFF);
  5712. setRequest(gun_index,OFF);
  5713. ShmCharger->gun_info[gun_index].isGunPlugged = NO;
  5714. ShmCharger->gun_info[gun_index].isGunUnpluggedBefore = NO;
  5715. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  5716. ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart = OFF;
  5717. ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop = OFF;
  5718. ShmCharger->gun_info[gun_index].isGetEvCCID = OFF;
  5719. ocpp_set_remotestart(gun_index, OFF);
  5720. ocpp_set_remotestop(gun_index, OFF);
  5721. ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode = 0x00;
  5722. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = 0;
  5723. presentChargedEnergyClear(gun_index);
  5724. ShmCharger->gun_info[gun_index].targetCurrent = 0xFF;
  5725. ocpp_set_unlocker_req(gun_index, OFF);
  5726. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId = -1;
  5727. // Response StopTransactionConf
  5728. ocpp_set_stoptransaction_conf(gun_index, OFF);
  5729. memset(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId));
  5730. memset(ShmSysConfigAndInfo->SysConfig.UserId, 0x00, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  5731. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_IDLE;
  5732. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_BS;
  5733. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  5734. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  5735. ShmCharger->gun_info[gun_index].isDoEvReadyOnce = OFF;
  5736. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  5737. //if(ShmCharger->isCcsEnable)system("pkill Module_CCS");
  5738. DB_Check_Record_Buf(localDb, gun_index);
  5739. ShmCharger->gun_info[gun_index].isEmergencyStopReport = OFF;
  5740. // Default previousData every time
  5741. previousData[gun_index].primaryMcuCp_Pwn_Duty = 0;
  5742. previousData[gun_index].targetCurrent = 0;
  5743. previousData[gun_index].current_limit = 0;
  5744. // Refresh PTB resend timer
  5745. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  5746. refreshStartTimer(&startTime[gun_index][TMR_IDX_PTB_METER_SEND]);
  5747. }
  5748. // Check missing PTB meter messages
  5749. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  5750. checkMissingPtbMeterMessage(gun_index);
  5751. // Check handshake timeout
  5752. checkHandshakeCountdown(gun_index);
  5753. // LED status in Idle mode
  5754. if(!ShmCharger->isAuthrizing)
  5755. {
  5756. if(ocpp_get_isRemoteStartWait())
  5757. {
  5758. ShmCharger->gun_info[gun_index].isSleepOn = OFF;
  5759. setLedMotion(gun_index, LED_ACTION_AUTHED);
  5760. refreshStartTimer(&startTime[gun_index][TMR_IDX_POWERSAVING_LCD]);
  5761. //DEBUG_INFO("Remote Start Transaction without connector Id.\n");
  5762. }
  5763. else
  5764. {
  5765. if(ShmSysConfigAndInfo->SysInfo.OcppConnStatus == ON)
  5766. {
  5767. if(ShmCharger->gun_info[gun_index].rfidReq == OFF)
  5768. {
  5769. if(ShmCharger->gun_info[gun_index].isSleepOn == NO)
  5770. setLedMotion(gun_index,LED_ACTION_IDLE_BACKEND_CONNECTED);
  5771. else
  5772. setLedMotion(gun_index,LED_ACTION_IDLE_BACKEND_CONNECTED_SLEEP);
  5773. }
  5774. }
  5775. else
  5776. {
  5777. if(ShmCharger->gun_info[gun_index].rfidReq == OFF)
  5778. {
  5779. if(ShmCharger->gun_info[gun_index].isSleepOn == NO)
  5780. setLedMotion(gun_index,LED_ACTION_IDLE_BACKEND_DISCONNECTED);
  5781. else
  5782. setLedMotion(gun_index,LED_ACTION_IDLE_BACKEND_DISCONNECTED_SLEEP);
  5783. }
  5784. }
  5785. }
  5786. }
  5787. /*
  5788. * TODO:
  5789. * 1. Try to get EVCCID if plug first
  5790. */
  5791. if((ShmSysConfigAndInfo->SysConfig.isAuthrizeByEVCCID && (ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_ENABLE)) &&
  5792. (ShmCharger->isCcsEnable) &&
  5793. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B) &&
  5794. (ShmCharger->gun_info[gun_index].isGetEvCCIDTimeout == OFF) &&
  5795. (ShmCharger->gun_info[gun_index].isRemoteStartWait != ON) &&
  5796. (ShmCharger->gun_info[gun_index].isEvCCIDAuthorizeFail != YES))
  5797. {
  5798. switch(ShmCharger->gun_info[gun_index].ccsHandshakeState)
  5799. {
  5800. case HANDSHAKE_DUTY_5:
  5801. if(!getRequest(gun_index))
  5802. {
  5803. setRequest(gun_index, ON);
  5804. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  5805. DEBUG_INFO("Try to get EVCCID, Set Request On.\n");
  5806. //Let CCS task start to negotiate
  5807. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = ON;
  5808. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_NONE;
  5809. }
  5810. // Set CCS 5% PWM duty
  5811. if(ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty == CCS_PWM_DUTY_5) //set 5% by SeccComm.c
  5812. {
  5813. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_5;
  5814. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_DUTY_5_CHECK;
  5815. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  5816. DEBUG_INFO("ccsHandshakeState = HANDSHAKE_DUTY_5_CHECK\n");
  5817. }
  5818. break;
  5819. case HANDSHAKE_DUTY_5_CHECK:
  5820. if((ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF))
  5821. {
  5822. //2 secs timeout
  5823. refreshStartTimer(&startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]);
  5824. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_CCS;
  5825. DEBUG_INFO("ccsHandshakeState = HANDSHAKE_CCS\n");
  5826. }
  5827. break;
  5828. case HANDSHAKE_CCS:
  5829. if(getDiffSecNow(startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]) > TIMEOUT_SPEC_BS_HLC_HANDSHAKE)
  5830. {
  5831. ShmCharger->gun_info[gun_index].isGetEvCCIDTimeout = ON;
  5832. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  5833. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  5834. setLedMotion(gun_index, LED_ACTION_HANDSHAKE_FAIL);
  5835. setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
  5836. DEBUG_INFO("Get EVCCID timeout.\n");
  5837. sleep(3);
  5838. }
  5839. if((19 <= ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus) && (ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus < 253))
  5840. {
  5841. if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_16)
  5842. {
  5843. sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%s%02X%02X%02X%02X%02X%02X", ShmOCPP16Data->ConfigurationTable.CoreProfile[EVCCID_PREFIX].ItemData,
  5844. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[0],
  5845. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[1],
  5846. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[2],
  5847. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[3],
  5848. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[4],
  5849. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[5]);
  5850. }
  5851. else if(ShmSysConfigAndInfo->SysInfo.OcppRunningVer == OCPP_RUNNING_VERSION_20)
  5852. {
  5853. sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "%02X%02X%02X%02X%02X%02X", ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[0],
  5854. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[1],
  5855. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[2],
  5856. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[3],
  5857. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[4],
  5858. ShmCharger->gun_info[gun_index].acCcsInfo.EVCCID[5]);
  5859. }
  5860. //sprintf((char*)ShmSysConfigAndInfo->SysConfig.UserId, "F5902677");
  5861. ShmCharger->gun_info[gun_index].isGetEvCCID = ON;
  5862. DEBUG_INFO("Got EVCCID: %s\n", ShmSysConfigAndInfo->SysConfig.UserId);
  5863. }
  5864. break;
  5865. default:
  5866. break;
  5867. }
  5868. }
  5869. else
  5870. {
  5871. if(getRequest(gun_index))
  5872. {
  5873. setRequest(gun_index, OFF);
  5874. }
  5875. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_DUTY_5;
  5876. }
  5877. if(((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B)) ||
  5878. ((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)) ||
  5879. ((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) && (ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn == ON)) ||
  5880. (ShmCharger->gun_info[gun_index].rfidReq == ON) ||
  5881. (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart == ON) ||
  5882. (ocpp_get_remotestart(gun_index) == ON) ||
  5883. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStart == ON) ||
  5884. (ShmCharger->gun_info[gun_index].isGetEvCCID == ON))
  5885. {
  5886. if((ShmCharger->gun_info[gun_index].rfidReq == ON))
  5887. {
  5888. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_RFID;
  5889. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_ISO14443;
  5890. DEBUG_INFO("Start Method : RFID...\n");
  5891. }
  5892. else if(ocpp_get_remotestart(gun_index))
  5893. {
  5894. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_BACKEND;
  5895. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_Central;
  5896. ocpp_copy_userid_from_remotestart(gun_index);
  5897. setSpeaker(ON, SPEAKER_SHORT);
  5898. DEBUG_INFO("Start Method : BACKEND...\n");
  5899. }
  5900. else if(ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart == ON)
  5901. {
  5902. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_BLE;
  5903. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_Local;
  5904. memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmCharger->gun_info[gun_index].bleLoginCentralId.id, ARRAY_SIZE(ShmCharger->gun_info[gun_index].bleLoginCentralId.id));
  5905. setSpeaker(ON, SPEAKER_SHORT);
  5906. DEBUG_INFO("Start Method : BLE...\n");
  5907. }
  5908. else if(ShmCharger->gun_info[gun_index].isGetEvCCID == ON)
  5909. {
  5910. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_EVCCID;
  5911. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_MacAddress;
  5912. setSpeaker(ON, SPEAKER_SHORT);
  5913. DEBUG_INFO("Start Method : EVCCID...\n");
  5914. }
  5915. else
  5916. {
  5917. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_FREE;
  5918. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_NoAuthorization;
  5919. //memcpy(ShmSysConfigAndInfo->SysConfig.UserId, ShmSysConfigAndInfo->SysConfig.SerialNumber, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.SerialNumber));
  5920. ocpp_get_freevend_idtag(ShmSysConfigAndInfo->SysConfig.UserId);
  5921. setSpeaker(ON, SPEAKER_SHORT);
  5922. DEBUG_INFO("Start Method : FREE...\n");
  5923. }
  5924. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  5925. ocpp_set_remotestart(gun_index, OFF);
  5926. ShmCharger->gun_info[gun_index].bleConfigData.isRequestStart = OFF;
  5927. ShmCharger->gun_info[gun_index].isGunPlugged = NO;
  5928. ShmCharger->gun_info[gun_index].isGunUnpluggedBefore = NO;
  5929. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStart = OFF;
  5930. ShmCharger->gun_info[gun_index].isGetEvCCID = OFF;
  5931. // Get target current
  5932. ocpp_set_profile_req(gun_index, ON);
  5933. sleep(1);
  5934. checkChargingProfileLimit(gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus);
  5935. setChargerMode(gun_index, SYS_MODE_AUTHORIZING);
  5936. }
  5937. else
  5938. {}
  5939. break;
  5940. case SYS_MODE_AUTHORIZING:
  5941. if(isModeChange(gun_index))
  5942. {
  5943. refreshStartTimer(&startTime[gun_index][TMR_IDX_AUTH]);
  5944. if(ocpp_isAuthorizeRemoteStart() && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod == START_METHOD_BACKEND))
  5945. {
  5946. DEBUG_INFO("Remote start request authorize.\n");
  5947. ocpp_set_auth_req(ON, "ISO14443");
  5948. }
  5949. else if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod == START_METHOD_EVCCID))
  5950. {
  5951. DEBUG_INFO("EVCCID request authorize.\n");
  5952. ocpp_set_auth_req(ON, "MacAddress");
  5953. }
  5954. }
  5955. if(getDiffSecNow(startTime[gun_index][TMR_IDX_AUTH]) > TIMEOUT_SPEC_AUTH)
  5956. {
  5957. // Authorization timeout process.
  5958. setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
  5959. setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
  5960. sleep(3);
  5961. setChargerMode(gun_index, SYS_MODE_IDLE);
  5962. DEBUG_WARN("Authorize timeout !!!\n");
  5963. }
  5964. else
  5965. {
  5966. switch(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod)
  5967. {
  5968. case START_METHOD_BACKEND:
  5969. if(ocpp_isAuthorizeRemoteStart())
  5970. {
  5971. if(ocpp_get_auth_conf())
  5972. {
  5973. if(ocpp_get_auth_result(YES, gun_index))
  5974. {
  5975. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  5976. DEBUG_INFO("[START_METHOD_BACKEND] StartUserId : %s \n",ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId);
  5977. DEBUG_INFO("Authorize pass.\n");
  5978. setSpeaker(ON,SPEAKER_SHORT);
  5979. setLedMotion(gun_index,LED_ACTION_RFID_PASS);
  5980. #if 0
  5981. if(ShmCharger->isCcsEnable)
  5982. {
  5983. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_CP_STATE_F;
  5984. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  5985. sleep(4);
  5986. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  5987. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  5988. //system("/root/Module_CCS &");
  5989. }
  5990. else
  5991. #endif
  5992. sleep(4);
  5993. setChargerMode(gun_index, SYS_MODE_PREPARING);
  5994. }
  5995. else
  5996. {
  5997. DEBUG_INFO("Authorize fail.\n");
  5998. setSpeaker(ON,SPEAKER_INTERVAL_3COUNT);
  5999. setLedMotion(gun_index,LED_ACTION_RFID_FAIL);
  6000. sleep(3);
  6001. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].ReservationId == -1)
  6002. setChargerMode(gun_index, SYS_MODE_IDLE);
  6003. else
  6004. setChargerMode(gun_index, SYS_MODE_RESERVATION);
  6005. }
  6006. ocpp_set_auth_conf(OFF);
  6007. }
  6008. }
  6009. else
  6010. {
  6011. if(ShmCharger->isCcsEnable)
  6012. {
  6013. //ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_CP_STATE_F;
  6014. //ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6015. //sleep(4);
  6016. //ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  6017. //ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6018. //system("/root/Module_CCS &");
  6019. }
  6020. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  6021. DEBUG_INFO("[START_METHOD_BACKEND] StartUserId : %s \n",ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId);
  6022. setChargerMode(gun_index, SYS_MODE_PREPARING);
  6023. }
  6024. break;
  6025. case START_METHOD_EVCCID:
  6026. ShmCharger->gun_info[gun_index].resultAuthorization = UNKNOW_RFID;
  6027. if(ocpp_get_auth_conf() ||
  6028. (!ocpp_get_connection_status() && ((ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE) || (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_NOCHARGE))) ||
  6029. (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST) && (getDiffSecNow(startTime[0][TMR_IDX_AUTH]) > 2)))
  6030. {
  6031. if(ocpp_get_auth_result(YES, gun_index) ||
  6032. (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE)) ||
  6033. (!ocpp_get_connection_status() && (isValidLocalWhiteCard() == PASS) && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST)))
  6034. {
  6035. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  6036. DEBUG_INFO("[START_METHOD_EVCCID] StartUserId : %s \n",ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId);
  6037. ShmCharger->gun_info[gun_index].resultAuthorization = VALIDATED_RFID;
  6038. DEBUG_INFO("Authorize pass [EVCCID].\n");
  6039. setSpeaker(ON, SPEAKER_SHORT);
  6040. setLedMotion(gun_index, LED_ACTION_RFID_PASS);
  6041. sleep(1);
  6042. setChargerMode(gun_index, SYS_MODE_PREPARING);
  6043. ShmCharger->gun_info[gun_index].isEvCCIDAuthorizeFail = NO;
  6044. }
  6045. else
  6046. {
  6047. ShmCharger->gun_info[gun_index].resultAuthorization = UNVALIDATED_RFID;
  6048. DEBUG_INFO("Authorize fail [EVCCID].\n");
  6049. setSpeaker(ON, SPEAKER_INTERVAL_3COUNT);
  6050. setLedMotion(gun_index, LED_ACTION_RFID_FAIL);
  6051. sleep(3);
  6052. setChargerMode(gun_index, SYS_MODE_IDLE);
  6053. ShmCharger->gun_info[gun_index].isEvCCIDAuthorizeFail = YES;
  6054. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  6055. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  6056. }
  6057. ocpp_set_auth_conf(OFF);
  6058. }
  6059. break;
  6060. case START_METHOD_RFID:
  6061. case START_METHOD_BLE:
  6062. case START_METHOD_FREE:
  6063. default:
  6064. if(ShmCharger->isCcsEnable)
  6065. {
  6066. //ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_CP_STATE_F;
  6067. //ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6068. //sleep(4);
  6069. //ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  6070. //ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6071. //system("/root/Module_CCS &");
  6072. }
  6073. setChargerMode(gun_index, SYS_MODE_PREPARING);
  6074. break;
  6075. }
  6076. }
  6077. break;
  6078. case SYS_MODE_PREPARING:
  6079. if(isModeChange(gun_index))
  6080. {
  6081. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  6082. setLedMotion(gun_index,LED_ACTION_AUTHED);
  6083. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  6084. if(ShmCharger->isCcsEnable)
  6085. {
  6086. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod != START_METHOD_EVCCID)
  6087. {
  6088. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_DUTY_5;
  6089. DEBUG_INFO("ccsHandshakeState = HANDSHAKE_DUTY_5\n");
  6090. }
  6091. }
  6092. else
  6093. {
  6094. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_CP_STATE_E;
  6095. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_BS;
  6096. setRequest(gun_index, ON);
  6097. }
  6098. }
  6099. // If control pilot detect Bx, skip watch dog time out.
  6100. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_B) ||
  6101. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C) ||
  6102. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_E) ||
  6103. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_F))
  6104. {
  6105. ShmCharger->gun_info[gun_index].isGunPlugged = YES;
  6106. ShmCharger->gun_info[gun_index].isGunUnpluggedBefore = NO;
  6107. switch(ShmCharger->gun_info[gun_index].ccsHandshakeState)
  6108. {
  6109. case HANDSHAKE_DUTY_5:
  6110. if(!getRequest(gun_index))
  6111. {
  6112. setRequest(gun_index, ON);
  6113. setLedMotion(gun_index,LED_ACTION_CONNECTED);
  6114. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  6115. DEBUG_INFO("Set Request On.\n");
  6116. //Let CCS task start to negotiate
  6117. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = ON;
  6118. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_NONE;
  6119. }
  6120. // Set CCS 5% PWM duty
  6121. if(ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty == CCS_PWM_DUTY_5)//set 5% by SeccComm.c
  6122. {
  6123. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_5;
  6124. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_DUTY_5_CHECK;
  6125. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6126. DEBUG_INFO("ccsHandshakeState = HANDSHAKE_DUTY_5_CHECK\n");
  6127. }
  6128. break;
  6129. case HANDSHAKE_DUTY_5_CHECK:
  6130. if((ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF))
  6131. {
  6132. //2 secs timeout
  6133. refreshStartTimer(&startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]);
  6134. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_CCS;
  6135. DEBUG_INFO("ccsHandshakeState = HANDSHAKE_CCS\n");
  6136. }
  6137. break;
  6138. case HANDSHAKE_CCS:
  6139. //CCS handshake timeout
  6140. if(getDiffSecNow(startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]) > TIMEOUT_SPEC_BS_HLC_HANDSHAKE)
  6141. {
  6142. if(ShmCharger->isCcsEnable)
  6143. {
  6144. DEBUG_INFO("TIMEOUT_SPEC_BS_HLC_HANDSHAKE.\n");
  6145. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  6146. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_CP_STATE_F;
  6147. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6148. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_CP_STATE_E;
  6149. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_BS;
  6150. break;
  6151. }
  6152. else
  6153. {
  6154. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  6155. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  6156. DEBUG_INFO("BS/HLC %d secs handshake timeout.\n", TIMEOUT_SPEC_BS_HLC_HANDSHAKE);
  6157. }
  6158. }
  6159. if((ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission == OFF) && (ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty != CCS_PWM_DUTY_5))
  6160. {
  6161. DEBUG_INFO("Wait CCS give up negotiagting.\n");
  6162. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_CP_STATE_F;
  6163. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6164. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_CP_STATE_E;
  6165. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_BS;
  6166. }
  6167. //CCS status check
  6168. #if 0
  6169. if((16 < ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus) && (ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus < 254))
  6170. {
  6171. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_HLC;
  6172. DEBUG_INFO("Enter HLC Mode charging.\n");
  6173. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_HLC_MODE;
  6174. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  6175. }
  6176. #else
  6177. if((16 <= ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus) && (ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus < 253))
  6178. {
  6179. //chang PWM duty to BS
  6180. if((ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)&&(ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current!=CCS_PWM_DUTY_5))
  6181. {
  6182. 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);
  6183. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6184. DEBUG_INFO("ccsHandshakeState = HANDSHAKE_CCS (set 5% duty)\n");
  6185. }
  6186. //ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_HLC;
  6187. //ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_HLC_MODE;
  6188. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  6189. }
  6190. if((37 <= ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus) && (ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus < 49))
  6191. {
  6192. //chang PWM duty to BS
  6193. if((ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)&&(ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current!=CCS_PWM_DUTY_5))
  6194. {
  6195. 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);
  6196. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6197. }
  6198. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_HLC;
  6199. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_HLC_MODE;
  6200. //refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  6201. DEBUG_INFO("ccsHandshakeState = HANDSHAKE_HLC_MODE\n");
  6202. }
  6203. else if((54 < ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus) && (ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus <= 255))
  6204. {
  6205. DEBUG_INFO("ccsHandshakeState = CHARGING_MODE_BS, CCS terminated\n");
  6206. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  6207. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_CP_STATE_F;
  6208. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6209. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_CP_STATE_E;
  6210. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_BS;
  6211. }
  6212. #endif
  6213. break;
  6214. case HANDSHAKE_CP_STATE_E:
  6215. if(ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)
  6216. {
  6217. if(ShmCharger->isCcsEnable)
  6218. {
  6219. DEBUG_INFO("Change to CP STATE E for 4 secs.\n");
  6220. //CP STATE E for 4 secs
  6221. sleep(4);
  6222. }
  6223. //restore normal CP PWM duty
  6224. // Determine max charging current to MCU
  6225. DEBUG_INFO("Determine max charging current to MCU.\n");
  6226. ocpp_set_profile_req(gun_index, ON);
  6227. sleep(1);
  6228. checkChargingProfileLimit(gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus);
  6229. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_SET_MAX_CURRENT;
  6230. refreshStartTimer(&startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]);
  6231. }
  6232. break;
  6233. case HANDSHAKE_SET_MAX_CURRENT:
  6234. if(ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)
  6235. {
  6236. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_BS_MODE;
  6237. DEBUG_INFO("Enter BS Mode charging.\n");
  6238. //for EV READY 30 secs didn't start charging to STATE E
  6239. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  6240. }
  6241. break;
  6242. case HANDSHAKE_BS_MODE:
  6243. refreshStartTimer(&startTime[gun_index][TMR_IDX_HANDSHAKING]);
  6244. checkChargingProfileLimit(gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus);
  6245. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C) && ((ShmCharger->gun_info[gun_index].targetCurrent != 0)))
  6246. {
  6247. setRelay(gun_index,ON);
  6248. }
  6249. if((ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON) || (ShmCharger->gun_info[gun_index].targetCurrent == 0))
  6250. {
  6251. ocpp_set_unlocker_req(gun_index, OFF);
  6252. presentChargedEnergyClear(gun_index);
  6253. getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime);
  6254. ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption;
  6255. ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption;
  6256. ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption;
  6257. ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption;
  6258. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==1)
  6259. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  6260. else
  6261. {
  6262. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  6263. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[0] = (ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption/10000.0);
  6264. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[1] = (ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption/10000.0);
  6265. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[2] = (ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption/10000.0);
  6266. }
  6267. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  6268. ocpp_copy_userid_to_starttransaction(gun_index);
  6269. ocpp_set_starttransaction_req(gun_index, ON);
  6270. refreshStartTimer(&startChargingTime[gun_index]);
  6271. // PTB Permission
  6272. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  6273. setPtbMeterPermission(gun_index, PERMISSION_START_CHARGING);
  6274. setChargerMode(gun_index, SYS_MODE_CHARGING);
  6275. }
  6276. //EV READY CHECK
  6277. /*
  6278. if((DiffTimebWithNow(startTime[gun_index][TMR_IDX_BS_HLC_HANDSHAKE]) > TIMEOUT_SPEC_EV_READY) && (ShmCharger->gun_info[gun_index].isEvReady2StateE == OFF))
  6279. {
  6280. if(ShmCharger->gun_info[gun_index].isDoEvReadyOnce == OFF)
  6281. {
  6282. DEBUG_INFO("EV READY STATE E 4sec.\n");
  6283. ShmCharger->gun_info[gun_index].isEvReady2StateE = ON;
  6284. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_CP_STATE_E;
  6285. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6286. ShmCharger->gun_info[gun_index].evReadyState = EV_READY_STAT_E;
  6287. }
  6288. }
  6289. if(ShmCharger->gun_info[gun_index].isEvReady2StateE == ON)
  6290. {
  6291. switch(ShmCharger->gun_info[gun_index].evReadyState)
  6292. {
  6293. case EV_READY_STAT_E:
  6294. if(ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)
  6295. {
  6296. sleep(4);
  6297. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  6298. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6299. ShmCharger->gun_info[gun_index].evReadyState = EV_READY_STAT_C;
  6300. }
  6301. break;
  6302. case EV_READY_STAT_C:
  6303. if(ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)
  6304. {
  6305. usleep(500000);
  6306. DEBUG_INFO("EV READY Determine max charging current to MCU.\n");
  6307. if(ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent == 0)
  6308. {
  6309. 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);
  6310. if(ShmCharger->gun_info[gun_index].targetCurrent != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current)
  6311. {
  6312. 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);
  6313. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6314. }
  6315. }
  6316. else
  6317. {
  6318. ShmCharger->gun_info[gun_index].targetCurrent = ((ShmCharger->gun_info[gun_index].targetCurrent > ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent)?ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent:ShmCharger->gun_info[gun_index].targetCurrent);
  6319. if(ShmCharger->gun_info[gun_index].targetCurrent != ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current)
  6320. {
  6321. 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);
  6322. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6323. }
  6324. }
  6325. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6326. ShmCharger->gun_info[gun_index].evReadyState = EV_READY_SET_MAX_CURRENT;
  6327. }
  6328. break;
  6329. case EV_READY_SET_MAX_CURRENT:
  6330. if(ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty == OFF)
  6331. {
  6332. ShmCharger->gun_info[gun_index].isEvReady2StateE = OFF;
  6333. ShmCharger->gun_info[gun_index].isDoEvReadyOnce = ON;
  6334. }
  6335. break;
  6336. default:
  6337. break;
  6338. }
  6339. }*/
  6340. break;
  6341. case HANDSHAKE_HLC_MODE:
  6342. if(ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_START_MODE)//powerDelivery
  6343. {
  6344. if(ShmCharger->gun_info[gun_index].legacyRequest.isRelayOn == OFF)
  6345. {
  6346. setRelay(gun_index,ON);
  6347. ShmCharger->gun_info[gun_index].isCCSStartTransation = ON;
  6348. DEBUG_INFO("HANDSHAKE_HLC_MODE:setRelay ON\n");
  6349. }
  6350. }
  6351. if((ShmCharger->gun_info[gun_index].primaryMcuState.relay_state == ON) &&
  6352. (ShmCharger->gun_info[gun_index].isCCSStartTransation == ON))
  6353. {
  6354. DEBUG_INFO("HANDSHAKE_HLC_MODE:Relay ON done\n");
  6355. ocpp_set_unlocker_req(gun_index, OFF);
  6356. presentChargedEnergyClear(gun_index);
  6357. getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartDateTime);
  6358. ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption;
  6359. ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption;
  6360. ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption;
  6361. ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption_at_start = ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption;
  6362. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==1)
  6363. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  6364. else
  6365. {
  6366. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  6367. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[0] = (ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption/10000.0);
  6368. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[1] = (ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption/10000.0);
  6369. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[2] = (ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption/10000.0);
  6370. }
  6371. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  6372. ocpp_copy_userid_to_starttransaction(gun_index);
  6373. ocpp_set_starttransaction_req(gun_index, ON);
  6374. ShmCharger->gun_info[gun_index].isCCSStartTransation = OFF;
  6375. // PTB Permission
  6376. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  6377. setPtbMeterPermission(gun_index, PERMISSION_START_CHARGING);
  6378. setChargerMode(gun_index, SYS_MODE_CHARGING);
  6379. DEBUG_INFO("set SYS_MODE_CHARGING\n");
  6380. refreshStartTimer(&startChargingTime[gun_index]);
  6381. refreshStartTimer(&startTime[gun_index][TMR_IDX_CCS_HEARTBEAT_COUNT_RESET]);
  6382. }
  6383. //120 sec timeout
  6384. if(getDiffSecNow(startTime[gun_index][TMR_IDX_HANDSHAKING]) > TIMEOUT_SPEC_CCS_HANDSHAKE)
  6385. {
  6386. setLedMotion(gun_index, LED_ACTION_HANDSHAKE_FAIL);
  6387. if(getDiffSecNow(startTime[gun_index][TMR_IDX_HANDSHAKING]) > TIMEOUT_SPEC_CCS_HANDSHAKE+5)
  6388. {
  6389. DEBUG_INFO("CCS 120 secs handshake timeout, change to BS Mode...\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. if((ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission == OFF) && (ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty != CCS_PWM_DUTY_5))
  6395. {
  6396. DEBUG_INFO("Wait CCS give up negotiagting.\n");
  6397. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_CP_STATE_F;
  6398. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6399. ShmCharger->gun_info[gun_index].ccsHandshakeState = HANDSHAKE_CP_STATE_E;
  6400. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_BS;
  6401. }
  6402. }
  6403. }
  6404. break;
  6405. default:
  6406. break;
  6407. }
  6408. }
  6409. else if(ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEMode)
  6410. {
  6411. DEBUG_INFO("Enter Socket-E Mode charging.\n");
  6412. ShmCharger->gun_info[gun_index].chargingMode = CHARGING_MODE_SOCKETE;
  6413. if(ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn == ON)
  6414. setRelay(gun_index,ON);
  6415. memcpy((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartUserId, ShmSysConfigAndInfo->SysConfig.UserId, ARRAY_SIZE(ShmSysConfigAndInfo->SysConfig.UserId));
  6416. ocpp_copy_userid_to_starttransaction(gun_index);
  6417. ocpp_set_starttransaction_req(gun_index, ON);
  6418. refreshStartTimer(&startChargingTime[gun_index]);
  6419. // PTB Permission
  6420. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  6421. setPtbMeterPermission(gun_index, PERMISSION_START_CHARGING);
  6422. setChargerMode(gun_index, SYS_MODE_CHARGING);
  6423. }
  6424. else if(ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn == ON)
  6425. {
  6426. setRequest(gun_index, ON);
  6427. ShmCharger->gun_info[gun_index].isGunUnpluggedBefore = NO;
  6428. }
  6429. // Unplug charging gun to Idle mode
  6430. if((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A) && (ShmCharger->gun_info[gun_index].isGunPlugged == YES))
  6431. {
  6432. DEBUG_INFO("Unplug the connector.\n");
  6433. //Cancel CCS task negotiating
  6434. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  6435. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  6436. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = ON;
  6437. }
  6438. // Use RFID card to stop handshaking
  6439. if((ShmCharger->gun_info[gun_index].rfidReq == ON))
  6440. {
  6441. DEBUG_INFO("Use RFID card to stop handshaking.\n");
  6442. //Cancel CCS task negotiating
  6443. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  6444. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  6445. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = ON;
  6446. }
  6447. else
  6448. {
  6449. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  6450. }
  6451. // Check handshake timeout
  6452. checkHandshakeCountdown(gun_index);
  6453. if(getDiffSecNow(startTime[gun_index][TMR_IDX_HANDSHAKING]) > ShmCharger->timeoutSpec.Present_Timeout_Spec)
  6454. {
  6455. setLedMotion(gun_index, LED_ACTION_HANDSHAKE_FAIL);
  6456. if(getDiffSecNow(startTime[gun_index][TMR_IDX_HANDSHAKING]) > (ShmCharger->timeoutSpec.Present_Timeout_Spec+5))
  6457. {
  6458. DEBUG_INFO("Handshaking timeout...\n");
  6459. //Cancel CCS task negotiating
  6460. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  6461. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  6462. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = ON;
  6463. }
  6464. }
  6465. if((ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty == ON) && ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty != CCS_PWM_DUTY_5)
  6466. {
  6467. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  6468. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6469. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = OFF;
  6470. setChargerMode(gun_index, SYS_MODE_IDLE);
  6471. }
  6472. break;
  6473. case SYS_MODE_CHARGING:
  6474. if(isModeChange(gun_index))
  6475. {
  6476. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  6477. //ftime(&startChargingTime[gun_index]);
  6478. refreshStartTimer(&startTime[gun_index][TMR_IDX_REFRESH_CHARGING_INFO]);
  6479. refreshStartTimer(&startTime[gun_index][TMR_IDX_PROFILE_PREPARE]);
  6480. refreshStartTimer(&startTime[gun_index][TMR_IDX_PWN_CHANGE]);
  6481. ocpp_reset_smartcharging_profileId(gun_index);
  6482. ocpp_set_profile_req(gun_index, ON);
  6483. ShmCharger->gun_info[gun_index].isChargerStopByCondition = NO;
  6484. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  6485. // Refresh timer for getting PTB meter message
  6486. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  6487. refreshStartTimer(&startTime[gun_index][TMR_IDX_PTB_METER_MESSAGE]);
  6488. }
  6489. //if time up, clear CCS MSG count
  6490. if((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) &&
  6491. (getDiffSecNow(startTime[gun_index][TMR_IDX_CCS_HEARTBEAT_COUNT_RESET]) > TIMEOUT_SPEC_CCS_HEARTBEAT_COUNT_RESET))
  6492. {
  6493. refreshStartTimer(&startTime[gun_index][TMR_IDX_CCS_HEARTBEAT_COUNT_RESET]);
  6494. /*if(ShmCharger->gun_info[gun_index].acCcsInfo.CcsHeartBeat > 0)
  6495. {
  6496. ShmCharger->gun_info[gun_index].acCcsInfo.CcsHeartBeat = 0;
  6497. }
  6498. else
  6499. {
  6500. DEBUG_INFO("CCS could not get MSG from car.\n");
  6501. //setChargerMode(gun_index, SYS_MODE_TERMINATING);
  6502. //setRelay(gun_index, OFF);
  6503. }*/
  6504. }
  6505. // If unplug the connector during a session, the system must stop charging and stop session.
  6506. checkConnectorStatus(gun_index);
  6507. if((ShmCharger->gun_info[gun_index].isGunUnpluggedBefore == YES) ||
  6508. (ShmCharger->gun_info[gun_index].rfidReq == ON) ||
  6509. (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop == ON) ||
  6510. ocpp_get_remotestop(gun_index) ||
  6511. (ocpp_get_connection_status() && !ocpp_get_starttransaction_result(gun_index)) ||
  6512. ((ShmCharger->gun_info[gun_index].chargingMode != CHARGING_MODE_SOCKETE) && ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState != CP_STATE_C) ||
  6513. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE) && !ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn) ||
  6514. ocpp_get_reset_req() ||
  6515. ocpp_get_unlocker_req(gun_index) ||
  6516. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop == ON) ||
  6517. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && (ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_STOP_MODE)) ||
  6518. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && (ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_RENEGOTIATE_MODE)) ||
  6519. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && (ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_STANDBY_MODE)) ||
  6520. ((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)))
  6521. )
  6522. {
  6523. //printf("EVChargeProgress=0x%x, PresentMsgFlowStatus=0x%x\n",ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress,ShmCharger->gun_info[gun_index].acCcsInfo.PresentMsgFlowStatus);
  6524. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  6525. }
  6526. else
  6527. {
  6528. // Charging session info calculation
  6529. setLedMotion(gun_index,LED_ACTION_CHARGING);
  6530. if(ShmSysConfigAndInfo->SysConfig.AcPhaseCount==1)
  6531. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  6532. else
  6533. {
  6534. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption = (ShmCharger->gun_info[gun_index].powerConsumptionTotal.power_consumption/10000.0);
  6535. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[0] = (ShmCharger->gun_info[gun_index].powerConsumption[0].power_consumption/10000.0);
  6536. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[1] = (ShmCharger->gun_info[gun_index].powerConsumption[1].power_consumption/10000.0);
  6537. //ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PowerConsumption[2] = (ShmCharger->gun_info[gun_index].powerConsumption[2].power_consumption/10000.0);
  6538. }
  6539. refreshStartTimer(&endChargingTime[gun_index]);
  6540. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = getDiffSecBetween(startChargingTime[gun_index], endChargingTime[gun_index]);
  6541. presentChargedEnergyUpdate(gun_index);
  6542. // Response StartTransactionConf
  6543. ocpp_set_starttransaction_conf(gun_index, OFF);
  6544. // Charging profile preparation
  6545. if((getDiffSecNow(startTime[gun_index][TMR_IDX_PROFILE_PREPARE]) > TIMEOUT_SPEC_PROFILE_PREPARE) || (getDiffSecNow(startTime[gun_index][TMR_IDX_PROFILE_PREPARE]) < 0))
  6546. {
  6547. if(!ocpp_get_profile_conf(gun_index))
  6548. {
  6549. ocpp_set_profile_req(gun_index, ON);
  6550. refreshStartTimer(&startTime[gun_index][TMR_IDX_PROFILE_PREPARE]);
  6551. }
  6552. else
  6553. {
  6554. ocpp_set_profile_conf(gun_index, OFF);
  6555. }
  6556. }
  6557. // Checking profile id > 0 and current time is between charging profile validFrom & validTo
  6558. checkChargingProfileLimit(gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus);
  6559. // Charging session local limit condition check
  6560. if(ocpp_get_connection_status())
  6561. {
  6562. // On-line max condition check
  6563. if((ShmSysConfigAndInfo->SysConfig.MaxChargingDuration > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60)))
  6564. {
  6565. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  6566. {
  6567. setRelay(gun_index, OFF);
  6568. ShmCharger->gun_info[gun_index].isChargerStopByCondition = YES;
  6569. }
  6570. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  6571. {
  6572. setRelay(gun_index, OFF);
  6573. }
  6574. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE)
  6575. {
  6576. setRelay(gun_index, OFF);
  6577. }
  6578. else
  6579. {}
  6580. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  6581. 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));
  6582. }
  6583. else if((ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy)))
  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 energy(%.2f) already over max energy(%.2f) in KWH.\n", gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy, ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy));
  6602. }
  6603. else
  6604. {
  6605. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  6606. {
  6607. ShmCharger->gun_info[gun_index].isChargerStopByCondition = NO;
  6608. if(ShmCharger->gun_info[gun_index].targetCurrent>0)
  6609. setRelay(gun_index, ON);
  6610. else
  6611. setRelay(gun_index, OFF);
  6612. }
  6613. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  6614. {
  6615. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)
  6616. setRelay(gun_index, ON);
  6617. }
  6618. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE)
  6619. {
  6620. if(ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn == ON)
  6621. setRelay(gun_index, ON);
  6622. else
  6623. setRelay(gun_index, OFF);
  6624. }
  6625. else
  6626. {}
  6627. }
  6628. }
  6629. else
  6630. {
  6631. // Off-line max condition check
  6632. if((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_DISABLE) ||
  6633. ((ShmSysConfigAndInfo->SysConfig.AuthorisationMode == AUTH_MODE_ENABLE) && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy != OFF_POLICY_NOCHARGE)))
  6634. {
  6635. 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))))
  6636. {
  6637. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  6638. {
  6639. setRelay(gun_index, OFF);
  6640. ShmCharger->gun_info[gun_index].isChargerStopByCondition = YES;
  6641. }
  6642. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  6643. {
  6644. setRelay(gun_index, OFF);
  6645. }
  6646. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE)
  6647. {
  6648. setRelay(gun_index, OFF);
  6649. }
  6650. else
  6651. {}
  6652. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  6653. 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));
  6654. }
  6655. 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))))
  6656. {
  6657. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  6658. {
  6659. setRelay(gun_index, OFF);
  6660. ShmCharger->gun_info[gun_index].isChargerStopByCondition = YES;
  6661. }
  6662. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  6663. {
  6664. setRelay(gun_index, OFF);
  6665. }
  6666. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE)
  6667. {
  6668. setRelay(gun_index, OFF);
  6669. }
  6670. else
  6671. {}
  6672. setChargerMode(gun_index, SYS_MODE_TERMINATING);
  6673. 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));
  6674. }
  6675. else
  6676. {
  6677. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  6678. {
  6679. ShmCharger->gun_info[gun_index].isChargerStopByCondition = NO;
  6680. if(ShmCharger->gun_info[gun_index].targetCurrent>0)
  6681. setRelay(gun_index, ON);
  6682. else
  6683. setRelay(gun_index, OFF);
  6684. }
  6685. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  6686. {
  6687. if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_C)
  6688. setRelay(gun_index, ON);
  6689. }
  6690. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE)
  6691. {
  6692. if(ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn == ON)
  6693. setRelay(gun_index, ON);
  6694. else
  6695. setRelay(gun_index, OFF);
  6696. }
  6697. else
  6698. {}
  6699. }
  6700. }
  6701. else
  6702. {
  6703. if(ShmCharger->gun_info[gun_index].primaryMcuState.relay_state > 0)
  6704. DEBUG_INFO("Connector-%d can not charging in off line\n", gun_index);
  6705. setRelay(gun_index, OFF);
  6706. }
  6707. }
  6708. // Debug information
  6709. if((getDiffSecNow(startTime[gun_index][TMR_IDX_REFRESH_CHARGING_INFO]) > TIMEOUT_SPEC_LOGPPRINTOUT) || (getDiffSecNow(startTime[gun_index][TMR_IDX_REFRESH_CHARGING_INFO]) < 0))
  6710. {
  6711. refreshStartTimer(&startTime[gun_index][TMR_IDX_REFRESH_CHARGING_INFO]);
  6712. getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime);
  6713. DB_Update_Record_Buf(localDb, gun_index);
  6714. }
  6715. }
  6716. break;
  6717. case SYS_MODE_TERMINATING:
  6718. if(isModeChange(gun_index))
  6719. {
  6720. if(!ShmCharger->gun_info[gun_index].primaryMcuState.relay_state)
  6721. {
  6722. setLedMotion(gun_index, LED_ACTION_STOP);
  6723. }
  6724. else
  6725. {}
  6726. getDateTimeString((char*)ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StopDateTime);
  6727. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  6728. if(ShmCharger->gun_info[gun_index].isGunUnpluggedBefore == YES)
  6729. setRelay(gun_index, OFF);
  6730. // Refresh timer for getting PTB meter message
  6731. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  6732. refreshStartTimer(&startTime[gun_index][TMR_IDX_PTB_METER_MESSAGE]);
  6733. }
  6734. refreshStartTimer(&endChargingTime[gun_index]);
  6735. //if(ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration != 0)
  6736. //{
  6737. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration = getDiffSecBetween(startChargingTime[gun_index], endChargingTime[gun_index]);
  6738. //}
  6739. // If unplug the connector during a session, the system must stop charging and stop session.
  6740. checkConnectorStatus(gun_index);
  6741. // End authorize pass
  6742. if(((ShmCharger->gun_info[gun_index].rfidReq == ON) && isMatchStartUser(gun_index)) ||
  6743. ((ShmCharger->gun_info[gun_index].rfidReq == ON) && ocpp_get_auth_result(YES, gun_index)) ||
  6744. (!ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_FREE) && (ShmCharger->gun_info[gun_index].rfidReq == ON)) ||
  6745. (!ocpp_get_connection_status() && (isValidLocalWhiteCard() == PASS) && (ShmSysConfigAndInfo->SysConfig.OfflinePolicy == OFF_POLICY_LOCALLIST) && (ShmCharger->gun_info[gun_index].rfidReq == ON)) ||
  6746. (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop == ON) ||
  6747. ocpp_get_remotestop(gun_index) ||
  6748. (ocpp_get_connection_status() && !ocpp_get_starttransaction_result(gun_index)) ||
  6749. ((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()) ||
  6750. ((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))) ||
  6751. ocpp_get_reset_req() ||
  6752. ocpp_get_unlocker_req(gun_index) ||
  6753. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop == ON) ||
  6754. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) && (ShmCharger->gun_info[gun_index].acCcsInfo.EVChargeProgress == HLC_STOP_MODE)))
  6755. {
  6756. setLedMotion(gun_index, LED_ACTION_STOP);
  6757. if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_BS)
  6758. {
  6759. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  6760. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6761. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  6762. {
  6763. processEndOfChargingForPtbMeter(gun_index);
  6764. }
  6765. else
  6766. {
  6767. sleep(1);
  6768. checkStopReason(gun_index);
  6769. setChargerMode(gun_index, SYS_MODE_COMPLETE);
  6770. }
  6771. }
  6772. else if(ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC)
  6773. {
  6774. //setChargerMode(gun_index, SYS_MODE_COMPLETE);
  6775. //Cancel CCS task negotiating
  6776. ShmCharger->gun_info[gun_index].acCcsInfo.ChargingPermission = OFF;
  6777. ShmCharger->gun_info[gun_index].acCcsInfo.EVSENotification = NOTIFICATION_STOP;
  6778. setRelay(gun_index,OFF);
  6779. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = ON;
  6780. }
  6781. else
  6782. {
  6783. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  6784. {
  6785. processEndOfChargingForPtbMeter(gun_index);
  6786. }
  6787. else
  6788. {
  6789. checkStopReason(gun_index);
  6790. setChargerMode(gun_index, SYS_MODE_COMPLETE);
  6791. }
  6792. }
  6793. }
  6794. else
  6795. {
  6796. // Refresh timer for getting PTB meter message
  6797. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  6798. refreshStartTimer(&startTime[gun_index][TMR_IDX_PTB_METER_MESSAGE]);
  6799. // If the charger stops charging, the led should be stoped blink
  6800. if(!ShmCharger->gun_info[gun_index].primaryMcuState.relay_state)
  6801. {
  6802. setLedMotion(gun_index, LED_ACTION_STOP);
  6803. }
  6804. // Charging profile preparation
  6805. if((getDiffSecNow(startTime[gun_index][TMR_IDX_PROFILE_PREPARE]) > TIMEOUT_SPEC_PROFILE_PREPARE) || (getDiffSecNow(startTime[gun_index][TMR_IDX_PROFILE_PREPARE]) < 0))
  6806. {
  6807. if(!ocpp_get_profile_conf(gun_index))
  6808. {
  6809. ocpp_set_profile_req(gun_index, ON);
  6810. refreshStartTimer(&startTime[gun_index][TMR_IDX_PROFILE_PREPARE]);
  6811. }
  6812. else
  6813. {
  6814. ocpp_set_profile_conf(gun_index, OFF);
  6815. }
  6816. }
  6817. // Checking profile id > 0 and current time is between charging profile validFrom & validTo
  6818. checkChargingProfileLimit(gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].SystemStatus);
  6819. setRelay(gun_index, OFF);
  6820. // Debug information
  6821. if((getDiffSecNow(startTime[gun_index][TMR_IDX_REFRESH_CHARGING_INFO]) > TIMEOUT_SPEC_LOGPPRINTOUT) || (getDiffSecNow(startTime[gun_index][TMR_IDX_REFRESH_CHARGING_INFO]) < 0))
  6822. {
  6823. refreshStartTimer(&startTime[gun_index][TMR_IDX_REFRESH_CHARGING_INFO]);
  6824. }
  6825. if(!ocpp_get_auth_result(YES, gun_index))
  6826. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  6827. if((ShmCharger->gun_info[gun_index].isGunUnpluggedBefore != YES) &&
  6828. (((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)) &&
  6829. (ShmCharger->gun_info[gun_index].rfidReq != ON) &&
  6830. (ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop != ON) &&
  6831. !ocpp_get_remotestop(gun_index) &&
  6832. (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop != ON) &&
  6833. !ocpp_get_reset_req() &&
  6834. ocpp_get_starttransaction_result(gun_index) &&
  6835. !(ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedDuration >= (ShmSysConfigAndInfo->SysConfig.MaxChargingDuration*60))) &&
  6836. !(ocpp_get_connection_status() && (ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy > 0) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PresentChargedEnergy >= ((float)ShmSysConfigAndInfo->SysConfig.MaxChargingEnergy))) &&
  6837. !(!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)))) &&
  6838. !(!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)))) &&
  6839. (((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))
  6840. )
  6841. {
  6842. sleep(1);
  6843. setChargerMode(gun_index, SYS_MODE_CHARGING);
  6844. }
  6845. }
  6846. if((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_HLC) &&
  6847. (ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty == ON) &&
  6848. (ShmCharger->gun_info[gun_index].acCcsInfo.CpSetPWMDuty == CCS_PWM_DUTY_100))
  6849. {
  6850. DEBUG_INFO("Set PWM duty 100%% go to SYS_MODE_TERMINATING.\n");
  6851. ShmCharger->gun_info[gun_index].primaryMcuCp_Pwn_Duty.max_current = CCS_PWM_DUTY_100;
  6852. ShmCharger->gun_info[gun_index].mcuFlag.isSetCpPwmDuty = ON;
  6853. ShmCharger->gun_info[gun_index].isCCSWaitChangeDuty = OFF;
  6854. if(ShmSysConfigAndInfo->SysConfig.ModelName[3] == 'P')
  6855. {
  6856. processEndOfChargingForPtbMeter(gun_index);
  6857. }
  6858. else
  6859. {
  6860. sleep(1);
  6861. checkStopReason(gun_index);
  6862. setChargerMode(gun_index, SYS_MODE_COMPLETE);
  6863. }
  6864. }
  6865. break;
  6866. case SYS_MODE_COMPLETE:
  6867. if(isModeChange(gun_index))
  6868. {
  6869. setLedMotion(gun_index, LED_ACTION_STOP);
  6870. refreshStartTimer(&startTime[gun_index][TMR_IDX_RECEIPT_INFORMATION]);
  6871. }
  6872. // Check the connector status
  6873. checkConnectorStatus(gun_index);
  6874. // Dispay receipt information for 15 seconds
  6875. if((getDiffSecNow(startTime[gun_index][TMR_IDX_RECEIPT_INFORMATION]) >= 15))
  6876. {
  6877. if(((ShmCharger->gun_info[gun_index].chargingMode != CHARGING_MODE_SOCKETE) && (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PilotState == CP_STATE_A)) ||
  6878. ((ShmCharger->gun_info[gun_index].chargingMode == CHARGING_MODE_SOCKETE) && (!ShmCharger->gun_info[gun_index].primaryMcuState.socket_e.isSocketEPinOn)) ||
  6879. ocpp_get_reset_req() ||
  6880. (ShmCharger->gun_info[gun_index].isGunUnpluggedBefore == YES))
  6881. {
  6882. sleep(2);
  6883. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  6884. ShmCharger->gun_info[gun_index].bleConfigData.isRequestStop = OFF;
  6885. ocpp_set_remotestop(gun_index, OFF);
  6886. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].schedule.isTriggerStop = OFF;
  6887. ShmCharger->gun_info[gun_index].isGunUnpluggedBefore = NO;
  6888. DB_Insert_Record(localDb, gun_index);
  6889. setChargerMode(gun_index, SYS_MODE_IDLE);
  6890. }
  6891. }
  6892. else
  6893. {
  6894. // After 6 seconds Relay off & PWM off (specifcation)
  6895. if((getDiffSecNow(startTime[gun_index][TMR_IDX_RECEIPT_INFORMATION]) >= 6))
  6896. {
  6897. setRelay(gun_index, OFF);
  6898. setRequest(gun_index, OFF);
  6899. }
  6900. }
  6901. break;
  6902. case SYS_MODE_ALARM:
  6903. setLedMotion(gun_index,LED_ACTION_ALARM);
  6904. setRelay(gun_index, OFF);
  6905. // Check the connector status
  6906. checkConnectorStatus(gun_index);
  6907. /*
  6908. * TODO:
  6909. * 1. Customize emergency stop and report stop transaction then return to idle mode if error recover.
  6910. * 2. Customer: Bambang
  6911. */
  6912. if(((ShmSysConfigAndInfo->SysConfig.ModelName[12] == 'B') && (ShmSysConfigAndInfo->SysConfig.ModelName[13] == 'B')) &&
  6913. (ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode == ALARM_EMERGENCY_STOP))
  6914. {
  6915. if(((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus == SYS_MODE_CHARGING) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus == SYS_MODE_TERMINATING)) &&
  6916. !ShmCharger->gun_info[gun_index].isEmergencyStopReport)
  6917. {
  6918. checkStopReason(gun_index);
  6919. ShmCharger->gun_info[gun_index].isEmergencyStopReport = ON;
  6920. }
  6921. }
  6922. if((ShmCharger->gun_info[gun_index].systemAlarmCode.SystemAlarmCode == 0) && !ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CCSboardStestFail)
  6923. {
  6924. if(((ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus == SYS_MODE_CHARGING) || (ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus == SYS_MODE_TERMINATING)) &&
  6925. (!ShmCharger->gun_info[gun_index].isEmergencyStopReport))
  6926. {
  6927. setChargerMode(gun_index, ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].PreviousSystemStatus);
  6928. }
  6929. else
  6930. {
  6931. setChargerMode(gun_index, SYS_MODE_IDLE);
  6932. }
  6933. }
  6934. break;
  6935. case SYS_MODE_FAULT:
  6936. if(isModeChange(gun_index))
  6937. {}
  6938. break;
  6939. case SYS_MODE_MAINTAIN:
  6940. if(isModeChange(gun_index))
  6941. {
  6942. setLedMotion(gun_index,LED_ACTION_MAINTAIN);
  6943. }
  6944. break;
  6945. case SYS_MODE_UPDATE:
  6946. if(isModeChange(gun_index))
  6947. {
  6948. setLedMotion(gun_index,LED_ACTION_MAINTAIN);
  6949. }
  6950. //======================================
  6951. // Check local upgrade firmware request
  6952. //======================================
  6953. if(ShmSysConfigAndInfo->SysInfo.FirmwareUpdate)
  6954. {
  6955. DEBUG_INFO("Firmware local upgrading...\n");
  6956. ShmSysConfigAndInfo->SysInfo.FirmwareUpdate = OFF;
  6957. int value = upgrade_check();
  6958. DEBUG_INFO("Local update Value: %s... \n",((value == PASS)?"Pass": "Fail"));
  6959. if(value == PASS)
  6960. {
  6961. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == ON)
  6962. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = OFF;
  6963. ShmCharger->isUpdateSuccess = YES;
  6964. DEBUG_INFO("Local update success...\n");
  6965. }
  6966. else
  6967. {
  6968. if(ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail == OFF)
  6969. ShmStatusCodeData->InfoCode.InfoEvents.bits.CsuFimrwareUpdateFail = ON;
  6970. ShmCharger->isUpdateSuccess = NO;
  6971. DEBUG_INFO("Local update unsuccess...\n");
  6972. }
  6973. }
  6974. else if(ocpp_get_update_firmware_req())
  6975. {
  6976. //======================================
  6977. // Check remote upgrade firmware request
  6978. //======================================
  6979. checkRemoteUpgradeStatus();
  6980. }
  6981. else
  6982. {
  6983. //======================================
  6984. // Upgrade complete reboot system
  6985. //======================================
  6986. if(!ShmCharger->gun_info[gun_index].mcuFlag.isMcuUpgradeReq && ((AC_QUANTITY>1)?!ShmCharger->gun_info[gun_index^1].mcuFlag.isMcuUpgradeReq:YES) && !ShmCharger->isUpgradeLcmReq)
  6987. {
  6988. if(ShmCharger->isUpdateSuccess == YES)
  6989. {
  6990. if((strcmp((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installing")==0))
  6991. {
  6992. sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "Installed");
  6993. ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  6994. }
  6995. else if((strcmp((char*)ShmOCPP16Data->SignedFirmwareStatusNotification.status, "Installing")==0))
  6996. {
  6997. ShmOCPP16Data->SignedFirmwareStatusNotification.requestId = ShmOCPP16Data->SignedUpdateFirmware.requestId;
  6998. sprintf((char*)ShmOCPP16Data->SignedFirmwareStatusNotification.status, "Installed");
  6999. ShmOCPP16Data->SpMsg.bits.SignedFirmwareStatusNotificationReq = ON;
  7000. }
  7001. sprintf((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "Installed");
  7002. ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  7003. DEBUG_WARN("Firmware upgrade success.\n");
  7004. sleep(5);
  7005. DEBUG_INFO("Firmware upgraded, reboot...\n");
  7006. system("reboot -f");
  7007. sleep(5);
  7008. system("reboot -f");
  7009. }
  7010. else
  7011. {
  7012. sprintf((char*)ShmOCPP16Data->FirmwareStatusNotification.Status, "InstallationFailed");
  7013. ShmOCPP16Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  7014. sprintf((char*)ShmOCPP20Data->FirmwareStatusNotification.status, "InstallationFailed");
  7015. ShmOCPP20Data->SpMsg.bits.FirmwareStatusNotificationReq = ON;
  7016. DEBUG_WARN("Firmware upgrade fail.\n");
  7017. sleep(5);
  7018. system("rm -rvf /mnt/* ");
  7019. close(wtdFd);
  7020. system("/usr/bin/run_evse_restart.sh");
  7021. }
  7022. }
  7023. }
  7024. break;
  7025. case SYS_MODE_RESERVATION:
  7026. if(isModeChange(gun_index))
  7027. {}
  7028. setLedMotion(gun_index,LED_ACTION_RESERVATION_MODE);
  7029. if(isReservationExpired(gun_index))
  7030. {
  7031. DEBUG_INFO("Reservation: Time's up...\n");
  7032. setChargerMode(gun_index, SYS_MODE_IDLE);
  7033. }
  7034. else if(ocpp_get_cancelreservation_req(gun_index))
  7035. {
  7036. DEBUG_INFO("Reservation: Cancel reservation...\n");
  7037. setChargerMode(gun_index, SYS_MODE_IDLE);
  7038. ocpp_set_cancelreservation_req(gun_index, OFF);
  7039. }
  7040. else
  7041. {
  7042. // Check is there RFID or back end request start
  7043. if((ShmCharger->gun_info[gun_index].rfidReq == ON) ||
  7044. ocpp_get_remotestart(gun_index))
  7045. {
  7046. if((ShmCharger->gun_info[gun_index].rfidReq == ON))
  7047. {
  7048. if(ocpp_compare_reserve_id_with_user(gun_index) ||
  7049. ocpp_get_auth_result(YES, gun_index))
  7050. {
  7051. DEBUG_INFO("Start Method in reservation : RFID...\n");
  7052. DEBUG_INFO("Start request User Id : %s\n", ShmSysConfigAndInfo->SysConfig.UserId);
  7053. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_RFID;
  7054. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_ISO14443;
  7055. setChargerMode(gun_index, SYS_MODE_AUTHORIZING);
  7056. }
  7057. else
  7058. {
  7059. setLedMotion(gun_index,LED_ACTION_RESERVATION_MODE);
  7060. ShmCharger->gun_info[gun_index].resultAuthorization = DEFAULT_RFID;
  7061. DEBUG_INFO("It's not reserve user id.\n");
  7062. }
  7063. ShmCharger->gun_info[gun_index].rfidReq = OFF;
  7064. }
  7065. else if(ocpp_get_remotestart(gun_index))
  7066. {
  7067. if(ocpp_compare_reserve_id_with_remote_user(gun_index) ||
  7068. ocpp_isAuthorizeRemoteStart())
  7069. {
  7070. DEBUG_INFO("Start Method in reservation: BACKEND...\n");
  7071. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartMethod = START_METHOD_BACKEND;
  7072. ShmSysConfigAndInfo->SysInfo.AcChargingData[gun_index].StartIdType = IdTokenType_Central;
  7073. if(ocpp_isAuthorizeRemoteStart())
  7074. ocpp_copy_userid_from_remotestart(gun_index);
  7075. setChargerMode(gun_index, SYS_MODE_AUTHORIZING);
  7076. }
  7077. ocpp_set_remotestart(gun_index, OFF);
  7078. }
  7079. }
  7080. }
  7081. break;
  7082. case SYS_MODE_BOOKING:
  7083. if(isModeChange(gun_index))
  7084. {}
  7085. break;
  7086. case SYS_MODE_DEBUG:
  7087. if(isModeChange(gun_index))
  7088. {
  7089. setLedMotion(gun_index,LED_ACTION_DEBUG);
  7090. }
  7091. break;
  7092. }
  7093. }
  7094. // System watch dog reset
  7095. write(wtdFd, "a", 1);
  7096. usleep(50000);
  7097. }
  7098. return FAIL;
  7099. }