main.c 234 KB

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