88_HMCCU.pm 246 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663
  1. ##############################################################################
  2. #
  3. # 88_HMCCU.pm
  4. #
  5. # $Id: 88_HMCCU.pm 17338 2018-09-13 17:20:18Z zap $
  6. #
  7. # Version 4.3.001
  8. #
  9. # Module for communication between FHEM and Homematic CCU2.
  10. #
  11. # Supports BidCos-RF, BidCos-Wired, HmIP-RF, virtual CCU channels,
  12. # CCU group devices, HomeGear, CUxD, Osram Lightify, Homematic Virtual Layer
  13. # and Philips Hue (not tested)
  14. #
  15. # (c) 2018 by zap (zap01 <at> t-online <dot> de)
  16. #
  17. ##############################################################################
  18. #
  19. # define <name> HMCCU <hostname_or_ip_of_ccu> [ccunumber] [waitforccu=<seconds>]
  20. #
  21. # set <name> ackmessages
  22. # set <name> cleardefaults
  23. # set <name> defaults
  24. # set <name> delete <name> [{ OT_VARDP | OT_DEVICE }]
  25. # set <name> execute <ccu_program>
  26. # set <name> importdefaults <filename>
  27. # set <name> hmscript {<scriptfile>|!<function>|'['<code>']'} [dump] [<parname>=<value> [...]]
  28. # set <name> rpcserver {on|off|restart}
  29. # set <name> var [<type>] <name> <value> [<parameter>=<value> [...]]
  30. #
  31. # get <name> aggregation {<rule>|all}
  32. # get <name> configdesc {<device>|<channel>}
  33. # get <name> defaults
  34. # get <name> deviceinfo <device>
  35. # get <name> devicelist [dump]
  36. # get <name> devicelist create <devexp> [t={chn|dev|all}] [s=<suffix>] [p=<prefix>] [f=<format>]
  37. # [defattr] [duplicates] [save] [<attr>=<val> [...]]}]
  38. # get <name> dump {devtypes|datapoints} [<filter>]
  39. # get <name> dutycycle
  40. # get <name> exportdefaults {filename}
  41. # get <name> firmware [{type-expr}|full]
  42. # get <name> parfile [<parfile>]
  43. # get <name> rpcevents
  44. # get <name> rpcstate
  45. # get <name> update [<fhemdevexp> [{ State | Value }]]
  46. # get <name> updateccu [<devexp> [{ State | Value }]]
  47. # get <name> vars <regexp>
  48. #
  49. # attr <name> ccuaggregate <rules>
  50. # attr <name> ccudef-hmstatevals <subst_rules>
  51. # attr <name> ccudef-readingfilter <filter_rule>
  52. # attr <name> ccudef-readingname <rules>
  53. # attr <name> ccudef-substitute <subst_rule>
  54. # attr <name> ccudefaults <filename>
  55. # attr <name> ccuflags { intrpc,extrpc,procrpc,dptnocheck,noagg,logEvents,noReadings,nonBlocking }
  56. # attr <name> ccuget { State | Value }
  57. # attr <name> ccuReqTimeout <seconds>
  58. # attr <name> ccuGetVars <seconds>[:<pattern>]
  59. # attr <name> parfile <parfile>
  60. # attr <name> rpcevtimeout <seconds>
  61. # attr <name> rpcinterfaces { BidCos-Wired, BidCos-RF, HmIP-RF, VirtualDevices, Homegear, HVL }
  62. # attr <name> rpcinterval <seconds>
  63. # attr <name> rpcport <ccu_rpc_port>
  64. # attr <name> rpcqueue <file>
  65. # attr <name> rpcserver { on | off }
  66. # attr <name> rpcserveraddr <ip-or-name>
  67. # attr <name> rpcserverport <base_port>
  68. # attr <name> rpctimeout <read>[,<write>]
  69. # attr <name> stripchar <character>
  70. # attr <name> stripnumber [<datapoint-expr!]{-<digits>|0|1|2}[;...]
  71. # attr <name> substitute <subst_rule>
  72. #
  73. # filter_rule := channel-regexp!datapoint-regexp[;...]
  74. # subst_rule := [[channel.]datapoint[,...]!]<regexp>:<subtext>[,...][;...]
  75. ##############################################################################
  76. # Verbose levels:
  77. #
  78. # 0 = Log start/stop and initialization messages
  79. # 1 = Log errors
  80. # 2 = Log counters and warnings
  81. # 3 = Log events and runtime information
  82. ##############################################################################
  83. package main;
  84. no if $] >= 5.017011, warnings => 'experimental::smartmatch';
  85. use strict;
  86. use warnings;
  87. # use Data::Dumper;
  88. # use Time::HiRes qw(usleep);
  89. use IO::File;
  90. use Fcntl 'SEEK_END', 'SEEK_SET', 'O_CREAT', 'O_RDWR';
  91. use RPC::XML::Client;
  92. use RPC::XML::Server;
  93. use SetExtensions;
  94. use SubProcess;
  95. use HMCCUConf;
  96. # Import configuration data
  97. my $HMCCU_CHN_DEFAULTS = \%HMCCUConf::HMCCU_CHN_DEFAULTS;
  98. my $HMCCU_DEV_DEFAULTS = \%HMCCUConf::HMCCU_DEV_DEFAULTS;
  99. my $HMCCU_SCRIPTS = \%HMCCUConf::HMCCU_SCRIPTS;
  100. # Custom configuration data
  101. my %HMCCU_CUST_CHN_DEFAULTS;
  102. my %HMCCU_CUST_DEV_DEFAULTS;
  103. # HMCCU version
  104. my $HMCCU_VERSION = '4.3.001';
  105. # Default RPC port (BidCos-RF)
  106. my $HMCCU_RPC_PORT_DEFAULT = 2001;
  107. my $HMCCU_RPC_INTERFACE_DEFAULT = 'BidCos-RF';
  108. # Constants and default values
  109. my $HMCCU_MAX_IOERRORS = 100;
  110. my $HMCCU_MAX_QUEUESIZE = 500;
  111. my $HMCCU_TIME_WAIT = 100000;
  112. my $HMCCU_TIME_TRIGGER = 10;
  113. my $HMCCU_TIMEOUT_CONNECTION = 10;
  114. my $HMCCU_TIMEOUT_WRITE = 0.001;
  115. my $HMCCU_TIMEOUT_ACCEPT = 1;
  116. my $HMCCU_TIMEOUT_EVENT = 600;
  117. my $HMCCU_STATISTICS = 500;
  118. my $HMCCU_TIMEOUT_REQUEST = 4;
  119. # RPC port name by port number
  120. my %HMCCU_RPC_NUMPORT = (
  121. 2000 => 'BidCos-Wired', 2001 => 'BidCos-RF', 2010 => 'HmIP-RF', 9292 => 'VirtualDevices',
  122. 2003 => 'Homegear', 8701 => 'CUxD', 7000 => 'HVL'
  123. );
  124. # RPC port number by port name
  125. my %HMCCU_RPC_PORT = (
  126. 'BidCos-Wired', 2000, 'BidCos-RF', 2001, 'HmIP-RF', 2010, 'VirtualDevices', 9292,
  127. 'Homegear', 2003, 'CUxD', 8701, 'HVL', 7000
  128. );
  129. # RPC flags
  130. my %HMCCU_RPC_FLAG = (
  131. 2000 => 'forceASCII', 2001 => 'forceASCII', 2003 => '_', 2010 => '_',
  132. 7000 => 'forceInit', 8701 => 'forceInit', 9292 => '_'
  133. );
  134. # Initial intervals for registration of RPC callbacks and reading RPC queue
  135. #
  136. # X = Start RPC server
  137. # X+HMCCU_INIT_INTERVAL1 = Register RPC callback
  138. # X+HMCCU_INIT_INTERVAL2 = Read RPC Queue
  139. #
  140. my $HMCCU_INIT_INTERVAL0 = 12;
  141. my $HMCCU_INIT_INTERVAL1 = 7;
  142. my $HMCCU_INIT_INTERVAL2 = 5;
  143. # Default values for delayed initialization during FHEM startup
  144. my $HMCCU_CCU_PING_TIMEOUT = 1;
  145. my $HMCCU_CCU_BOOT_DELAY = 180;
  146. my $HMCCU_CCU_DELAYED_INIT = 59;
  147. my $HMCCU_CCU_RPC_OFFSET = 20;
  148. # Number of arguments in RPC events
  149. my %rpceventargs = (
  150. "EV", 3, # Datapoint value updated
  151. "ND", 6, # New device created
  152. "DD", 1, # Device deleted
  153. "RD", 2, # Device renamed
  154. "RA", 1, # Device readded
  155. "UD", 2, # Device updated
  156. "IN", 3, # RPC init
  157. "EX", 3, # Exit RPC server
  158. "SL", 2, # RPC server loop
  159. "ST", 10 # Status
  160. );
  161. # Datapoint operations
  162. my $HMCCU_OPER_READ = 1;
  163. my $HMCCU_OPER_WRITE = 2;
  164. my $HMCCU_OPER_EVENT = 4;
  165. # Datapoint types
  166. my $HMCCU_TYPE_BINARY = 2;
  167. my $HMCCU_TYPE_FLOAT = 4;
  168. my $HMCCU_TYPE_INTEGER = 16;
  169. my $HMCCU_TYPE_STRING = 20;
  170. # Flags for CCU object specification
  171. my $HMCCU_FLAG_NAME = 1;
  172. my $HMCCU_FLAG_CHANNEL = 2;
  173. my $HMCCU_FLAG_DATAPOINT = 4;
  174. my $HMCCU_FLAG_ADDRESS = 8;
  175. my $HMCCU_FLAG_INTERFACE = 16;
  176. my $HMCCU_FLAG_FULLADDR = 32;
  177. # Valid flag combinations
  178. my $HMCCU_FLAGS_IACD = $HMCCU_FLAG_INTERFACE | $HMCCU_FLAG_ADDRESS |
  179. $HMCCU_FLAG_CHANNEL | $HMCCU_FLAG_DATAPOINT;
  180. my $HMCCU_FLAGS_IAC = $HMCCU_FLAG_INTERFACE | $HMCCU_FLAG_ADDRESS | $HMCCU_FLAG_CHANNEL;
  181. my $HMCCU_FLAGS_ACD = $HMCCU_FLAG_ADDRESS | $HMCCU_FLAG_CHANNEL | $HMCCU_FLAG_DATAPOINT;
  182. my $HMCCU_FLAGS_AC = $HMCCU_FLAG_ADDRESS | $HMCCU_FLAG_CHANNEL;
  183. my $HMCCU_FLAGS_ND = $HMCCU_FLAG_NAME | $HMCCU_FLAG_DATAPOINT;
  184. my $HMCCU_FLAGS_NC = $HMCCU_FLAG_NAME | $HMCCU_FLAG_CHANNEL;
  185. my $HMCCU_FLAGS_NCD = $HMCCU_FLAG_NAME | $HMCCU_FLAG_CHANNEL | $HMCCU_FLAG_DATAPOINT;
  186. # Flags for address/name checks
  187. my $HMCCU_FL_STADDRESS = 1;
  188. my $HMCCU_FL_NAME = 2;
  189. my $HMCCU_FL_EXADDRESS = 4;
  190. my $HMCCU_FL_ADDRESS = 5;
  191. my $HMCCU_FL_ALL = 7;
  192. # Default values
  193. my $HMCCU_DEF_HMSTATE = '^0\.UNREACH!(1|true):unreachable;^[0-9]\.LOW_?BAT!(1|true):warn_battery';
  194. # Placeholder for external addresses (i.e. HVL)
  195. my $HMCCU_EXT_ADDR = 'ZZZ0000000';
  196. # Binary RPC data types
  197. my $BINRPC_INTEGER = 1;
  198. my $BINRPC_BOOL = 2;
  199. my $BINRPC_STRING = 3;
  200. my $BINRPC_DOUBLE = 4;
  201. my $BINRPC_BASE64 = 17;
  202. my $BINRPC_ARRAY = 256;
  203. my $BINRPC_STRUCT = 257;
  204. # Declare functions
  205. # FHEM standard functions
  206. sub HMCCU_Initialize ($);
  207. sub HMCCU_Define ($$);
  208. sub HMCCU_InitDevice ($);
  209. sub HMCCU_Undef ($$);
  210. sub HMCCU_Shutdown ($);
  211. sub HMCCU_Set ($@);
  212. sub HMCCU_Get ($@);
  213. sub HMCCU_Attr ($@);
  214. sub HMCCU_AttrInterfacesPorts ($$$);
  215. sub HMCCU_Notify ($$);
  216. sub HMCCU_Detail ($$$$);
  217. # Aggregation
  218. sub HMCCU_AggregateReadings ($$);
  219. sub HMCCU_AggregationRules ($$);
  220. # Handling of default attributes
  221. sub HMCCU_ExportDefaults ($);
  222. sub HMCCU_ImportDefaults ($);
  223. sub HMCCU_FindDefaults ($$);
  224. sub HMCCU_SetDefaults ($);
  225. sub HMCCU_GetDefaults ($$);
  226. # Status and logging functions
  227. sub HMCCU_Trace ($$$$);
  228. sub HMCCU_Log ($$$$);
  229. sub HMCCU_SetError ($@);
  230. sub HMCCU_SetState ($@);
  231. sub HMCCU_SetRPCState ($@);
  232. # Filter and modify readings
  233. sub HMCCU_FilterReading ($$$);
  234. sub HMCCU_FormatReadingValue ($$$);
  235. sub HMCCU_GetReadingName ($$$$$$$);
  236. sub HMCCU_ScaleValue ($$$$$);
  237. sub HMCCU_Substitute ($$$$$);
  238. sub HMCCU_SubstRule ($$$);
  239. sub HMCCU_SubstVariables ($$$);
  240. # Update client device readings
  241. sub HMCCU_BulkUpdate ($$$$);
  242. sub HMCCU_GetUpdate ($$$);
  243. sub HMCCU_UpdateClients ($$$$$);
  244. sub HMCCU_UpdateMultipleDevices ($$);
  245. sub HMCCU_UpdatePeers ($$$$);
  246. sub HMCCU_UpdateSingleDatapoint ($$$$);
  247. sub HMCCU_UpdateSingleDevice ($$$);
  248. # RPC functions
  249. sub HMCCU_GetRPCCallbackURL ($$$$$);
  250. sub HMCCU_GetRPCDevice ($$$);
  251. sub HMCCU_GetRPCInterfaceList ($);
  252. sub HMCCU_GetRPCPortList ($);
  253. sub HMCCU_GetRPCServerInfo ($$$);
  254. sub HMCCU_IsRPCServerRunning ($$$);
  255. sub HMCCU_IsRPCType ($$$);
  256. sub HMCCU_IsRPCStateBlocking ($);
  257. sub HMCCU_ResetCounters ($);
  258. sub HMCCU_RPCDeRegisterCallback ($);
  259. sub HMCCU_RPCRegisterCallback ($);
  260. sub HMCCU_RPCGetConfig ($$$$);
  261. sub HMCCU_RPCSetConfig ($$$);
  262. sub HMCCU_StartExtRPCServer ($);
  263. sub HMCCU_StartIntRPCServer ($);
  264. sub HMCCU_StopExtRPCServer ($);
  265. sub HMCCU_StopRPCServer ($);
  266. # Parse and validate names and addresses
  267. sub HMCCU_ParseObject ($$$);
  268. sub HMCCU_IsDevAddr ($$);
  269. sub HMCCU_IsChnAddr ($$);
  270. sub HMCCU_SplitChnAddr ($);
  271. # FHEM device handling functions
  272. sub HMCCU_AssignIODevice ($$$);
  273. sub HMCCU_FindClientDevices ($$$$);
  274. sub HMCCU_FindIODevice ($);
  275. sub HMCCU_GetHash ($@);
  276. sub HMCCU_GetAttribute ($$$$);
  277. sub HMCCU_GetFlags ($);
  278. sub HMCCU_GetAttrReadingFormat ($$);
  279. sub HMCCU_GetAttrSubstitute ($$);
  280. sub HMCCU_IODeviceStates ();
  281. sub HMCCU_IsFlag ($$);
  282. # Handle interfaces, devices and channels
  283. sub HMCCU_FormatDeviceInfo ($);
  284. sub HMCCU_GetAddress ($$$$);
  285. sub HMCCU_GetCCUDeviceParam ($$);
  286. sub HMCCU_GetChannelName ($$$);
  287. sub HMCCU_GetDeviceChannels ($$$);
  288. sub HMCCU_GetDeviceInfo ($$$);
  289. sub HMCCU_GetDeviceInterface ($$$);
  290. sub HMCCU_GetDeviceList ($);
  291. sub HMCCU_GetDeviceName ($$$);
  292. sub HMCCU_GetDeviceType ($$$);
  293. sub HMCCU_GetFirmwareVersions ($$);
  294. sub HMCCU_GetGroupMembers ($$);
  295. sub HMCCU_GetMatchingDevices ($$$$);
  296. sub HMCCU_IsValidChannel ($$$);
  297. sub HMCCU_IsValidDevice ($$$);
  298. sub HMCCU_IsValidDeviceOrChannel ($$$);
  299. sub HMCCU_UpdateDeviceTable ($$);
  300. # Handle datapoints
  301. sub HMCCU_FindDatapoint ($$$$$);
  302. sub HMCCU_GetChannel ($$);
  303. sub HMCCU_GetDatapoint ($@);
  304. sub HMCCU_GetDatapointAttr ($$$$$);
  305. sub HMCCU_GetDatapointCount ($$$);
  306. sub HMCCU_GetDatapointList ($$$);
  307. sub HMCCU_GetSpecialDatapoints ($$$$$);
  308. sub HMCCU_GetSwitchDatapoint ($$$);
  309. sub HMCCU_GetValidDatapoints ($$$$$);
  310. sub HMCCU_IsValidDatapoint ($$$$$);
  311. sub HMCCU_SetDatapoint ($$$);
  312. # Internal RPC server functions
  313. sub HMCCU_ResetRPCQueue ($$);
  314. sub HMCCU_ReadRPCQueue ($);
  315. sub HMCCU_ProcessEvent ($$);
  316. # Homematic script and variable functions
  317. sub HMCCU_GetVariables ($$);
  318. sub HMCCU_HMCommand ($$$);
  319. sub HMCCU_HMCommandCB ($$$);
  320. sub HMCCU_HMCommandNB ($$$);
  321. sub HMCCU_HMScriptExt ($$$);
  322. sub HMCCU_SetVariable ($$$$$);
  323. sub HMCCU_UpdateVariables ($);
  324. # File queue functions
  325. sub HMCCU_QueueOpen ($$);
  326. sub HMCCU_QueueClose ($);
  327. sub HMCCU_QueueReset ($);
  328. sub HMCCU_QueueEnq ($$);
  329. sub HMCCU_QueueDeq ($);
  330. # Helper functions
  331. sub HMCCU_CalculateReading ($$$);
  332. sub HMCCU_EncodeEPDisplay ($);
  333. sub HMCCU_ExprMatch ($$$);
  334. sub HMCCU_ExprNotMatch ($$$);
  335. sub HMCCU_GetDutyCycle ($);
  336. sub HMCCU_GetHMState ($$$);
  337. sub HMCCU_GetTimeSpec ($);
  338. sub HMCCU_CorrectName ($);
  339. sub HMCCU_RefToString ($);
  340. sub HMCCU_ResolveName ($$);
  341. sub HMCCU_TCPConnect ($$);
  342. sub HMCCU_TCPPing ($$$);
  343. # Subprocess functions of internal RPC server
  344. sub HMCCU_CCURPC_Write ($$);
  345. sub HMCCU_CCURPC_OnRun ($);
  346. sub HMCCU_CCURPC_OnExit ();
  347. sub HMCCU_CCURPC_NewDevicesCB ($$$);
  348. sub HMCCU_CCURPC_DeleteDevicesCB ($$$);
  349. sub HMCCU_CCURPC_UpdateDeviceCB ($$$$);
  350. sub HMCCU_CCURPC_ReplaceDeviceCB ($$$$);
  351. sub HMCCU_CCURPC_ReaddDevicesCB ($$$);
  352. sub HMCCU_CCURPC_EventCB ($$$$$);
  353. sub HMCCU_CCURPC_ListDevicesCB ($$);
  354. ##################################################
  355. # Initialize module
  356. ##################################################
  357. sub HMCCU_Initialize ($)
  358. {
  359. my ($hash) = @_;
  360. $hash->{DefFn} = "HMCCU_Define";
  361. $hash->{UndefFn} = "HMCCU_Undef";
  362. $hash->{SetFn} = "HMCCU_Set";
  363. $hash->{GetFn} = "HMCCU_Get";
  364. $hash->{ReadFn} = "HMCCU_Read";
  365. $hash->{AttrFn} = "HMCCU_Attr";
  366. $hash->{NotifyFn} = "HMCCU_Notify";
  367. $hash->{ShutdownFn} = "HMCCU_Shutdown";
  368. $hash->{FW_detailFn} = "HMCCU_Detail";
  369. $hash->{parseParams} = 1;
  370. $hash->{AttrList} = "stripchar stripnumber ccuaggregate:textField-long".
  371. " ccudefaults rpcinterfaces:multiple-strict,".join(',',sort keys %HMCCU_RPC_PORT).
  372. " ccudef-hmstatevals:textField-long ccudef-substitute:textField-long".
  373. " ccudef-readingname:textField-long ccudef-readingfilter:textField-long".
  374. " ccudef-readingformat:name,namelc,address,addresslc,datapoint,datapointlc".
  375. " ccuflags:multiple-strict,extrpc,intrpc,procrpc,dptnocheck,noagg,nohmstate,logEvents,noReadings,nonBlocking".
  376. " ccuReqTimeout ccuGetVars rpcinterval:2,3,5,7,10 rpcqueue".
  377. " rpcport:multiple-strict,".join(',',sort keys %HMCCU_RPC_NUMPORT).
  378. " rpcserver:on,off rpcserveraddr rpcserverport rpctimeout rpcevtimeout parfile substitute".
  379. " ccuget:Value,State ".
  380. $readingFnAttributes;
  381. }
  382. ######################################################################
  383. # Define device
  384. ######################################################################
  385. sub HMCCU_Define ($$)
  386. {
  387. my ($hash, $a, $h) = @_;
  388. my $name = $hash->{NAME};
  389. return "Specify CCU hostname or IP address as a parameter" if (scalar (@$a) < 3);
  390. $hash->{host} = $$a[2];
  391. $hash->{Clients} = ':HMCCUDEV:HMCCUCHN:HMCCURPC:HMCCURPCPROC:';
  392. $hash->{hmccu}{ccu}{delay} = exists ($h->{ccudelay}) ? $h->{ccudelay} : $HMCCU_CCU_BOOT_DELAY;
  393. $hash->{hmccu}{ccu}{timeout} = exists ($h->{waitforccu}) ? $h->{waitforccu} : $HMCCU_CCU_PING_TIMEOUT;
  394. $hash->{hmccu}{ccu}{delayed} = 0;
  395. # Check if TCL-Rega process is running on CCU (CCU reachable)
  396. if (exists ($h->{delayedinit}) && $h->{delayedinit} > 0) {
  397. return "Value for delayed initialization must be greater than $HMCCU_CCU_DELAYED_INIT"
  398. if ($h->{delayedinit} <= $HMCCU_CCU_DELAYED_INIT);
  399. $hash->{hmccu}{ccu}{delay} = $h->{delayedinit};
  400. $hash->{ccustate} = 'unreachable';
  401. HMCCU_Log ($hash, 1, "Forced delayed initialization", 0);
  402. }
  403. else {
  404. if (HMCCU_TCPPing ($hash->{host}, 8181, $hash->{hmccu}{ccu}{timeout})) {
  405. $hash->{ccustate} = 'active';
  406. }
  407. else {
  408. $hash->{ccustate} = 'unreachable';
  409. HMCCU_Log ($hash, 1, "CCU port 8181 is not reachable", 0);
  410. }
  411. }
  412. # Get CCU IP address
  413. $hash->{ccuip} = HMCCU_ResolveName ($hash->{host}, 'N/A');
  414. # Get CCU number (if more than one)
  415. if (scalar (@$a) >= 4) {
  416. return "CCU number must be in range 1-9" if ($$a[3] < 1 || $$a[3] > 9);
  417. $hash->{CCUNum} = $$a[3];
  418. }
  419. else {
  420. # Count CCU devices
  421. my $ccucount = 0;
  422. foreach my $d (keys %defs) {
  423. my $ch = $defs{$d};
  424. next if (!exists ($ch->{TYPE}));
  425. $ccucount++ if ($ch->{TYPE} eq 'HMCCU' && $ch != $hash);
  426. }
  427. $hash->{CCUNum} = $ccucount+1;
  428. }
  429. $hash->{version} = $HMCCU_VERSION;
  430. $hash->{ccutype} = 'CCU2/3';
  431. $hash->{RPCState} = "inactive";
  432. $hash->{NOTIFYDEV} = "global,TYPE=(HMCCU|HMCCUDEV|HMCCUCHN)";
  433. HMCCU_Log ($hash, 1, "Initialized version $HMCCU_VERSION", 0);
  434. my $rc = 0;
  435. if ($hash->{ccustate} eq 'active') {
  436. # If CCU is alive read devices, channels, interfaces and groups
  437. HMCCU_Log ($hash, 1, "HMCCU: Initializing device", 0);
  438. HMCCU_InitDevice ($hash);
  439. }
  440. if ($hash->{ccustate} ne 'active' || $rc > 0) {
  441. # Schedule update of CCU assets if CCU is not active during FHEM startup
  442. if (!$init_done) {
  443. $hash->{hmccu}{ccu}{delayed} = 1;
  444. HMCCU_Log ($hash, 1, "Scheduling delayed initialization in ".$hash->{hmccu}{ccu}{delay}." seconds", 0);
  445. InternalTimer (gettimeofday()+$hash->{hmccu}{ccu}{delay}, "HMCCU_InitDevice", $hash);
  446. }
  447. }
  448. $hash->{hmccu}{evtime} = 0;
  449. $hash->{hmccu}{evtimeout} = 0;
  450. $hash->{hmccu}{updatetime} = 0;
  451. $hash->{hmccu}{rpccount} = 0;
  452. $hash->{hmccu}{rpcports} = $HMCCU_RPC_PORT_DEFAULT;
  453. readingsBeginUpdate ($hash);
  454. readingsBulkUpdate ($hash, "state", "Initialized");
  455. readingsBulkUpdate ($hash, "rpcstate", "inactive");
  456. readingsEndUpdate ($hash, 1);
  457. $attr{$name}{stateFormat} = "rpcstate/state";
  458. return undef;
  459. }
  460. ######################################################################
  461. # Initialization of FHEM device.
  462. # Called during Define() or by HMCCU after CCU ready.
  463. # Return 0 on successful initialization or >0 on error:
  464. # 1 = CCU port 8181 is not reachable.
  465. # 2 = Error while reading device list from CCU.
  466. ######################################################################
  467. sub HMCCU_InitDevice ($)
  468. {
  469. my ($hash) = @_;
  470. my $name = $hash->{NAME};
  471. if ($hash->{hmccu}{ccu}{delayed} == 1) {
  472. HMCCU_Log ($hash, 1, "HMCCU: Initializing devices", 0);
  473. if (!HMCCU_TCPPing ($hash->{host}, 8181, $hash->{hmccu}{ccu}{timeout})) {
  474. $hash->{ccustate} = 'unreachable';
  475. HMCCU_Log ($hash, 1, "HMCCU: CCU port 8181 is not reachable", 0);
  476. return 1;
  477. }
  478. }
  479. my ($devcnt, $chncnt, $ifcount, $prgcount, $gcount) = HMCCU_GetDeviceList ($hash);
  480. if ($devcnt >= 0) {
  481. HMCCU_Log ($hash, 1, "HMCCU: Read $devcnt devices with $chncnt channels from CCU ".$hash->{host}, 0);
  482. HMCCU_Log ($hash, 1, "HMCCU: Read $ifcount interfaces from CCU ".$hash->{host}, 0);
  483. HMCCU_Log ($hash, 1, "HMCCU: Read $prgcount programs from CCU ".$hash->{host}, 0);
  484. HMCCU_Log ($hash, 1, "HMCCU: Read $gcount virtual groups from CCU ".$hash->{host}, 0);
  485. return 0;
  486. }
  487. else {
  488. HMCCU_Log ($hash, 1, "HMCCU: Error while reading device list from CCU ".$hash->{host}, 0);
  489. return 2;
  490. }
  491. }
  492. ######################################################################
  493. # Set or delete attribute
  494. ######################################################################
  495. sub HMCCU_Attr ($@)
  496. {
  497. my ($cmd, $name, $attrname, $attrval) = @_;
  498. my $hash = $defs{$name};
  499. my $rc = 0;
  500. if ($cmd eq 'set') {
  501. if ($attrname eq 'ccudefaults') {
  502. $rc = HMCCU_ImportDefaults ($attrval);
  503. return HMCCU_SetError ($hash, -16) if ($rc == 0);
  504. if ($rc < 0) {
  505. $rc = -$rc;
  506. return HMCCU_SetError ($hash,
  507. "Syntax error in default attribute file $attrval line $rc");
  508. }
  509. }
  510. elsif ($attrname eq 'ccuaggregate') {
  511. $rc = HMCCU_AggregationRules ($hash, $attrval);
  512. return HMCCU_SetError ($hash, "Syntax error in attribute ccuaggregate") if ($rc == 0);
  513. }
  514. elsif ($attrname eq 'ccuackstate') {
  515. return "HMCCU: Attribute ccuackstate is depricated. Use ccuflags with 'ackState' instead";
  516. }
  517. elsif ($attrname eq 'ccureadings') {
  518. return "HMCCU: Attribute ccureadings is depricated. Use ccuflags with 'noReadings' instead";
  519. }
  520. elsif ($attrname eq 'ccuflags') {
  521. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  522. my @flags = ($attrval =~ /(intrpc|extrpc|procrpc)/g);
  523. return "Flags extrpc, procrpc and intrpc cannot be combined" if (scalar (@flags) > 1);
  524. if ($attrval =~ /(extrpc|intrpc|procrpc)/) {
  525. my $rpcmode = $1;
  526. if ($ccuflags !~ /$rpcmode/) {
  527. return "Stop RPC server before switching RPC server"
  528. if (HMCCU_IsRPCServerRunning ($hash, undef, undef));
  529. }
  530. }
  531. if ($attrval =~ /extrpc/) {
  532. HMCCU_Log ($hash, 1, "RPC server mode extrpc will be ignored. Using procrpc instead", 0);
  533. }
  534. elsif ($attrval =~ /intrpc/) {
  535. HMCCU_Log ($hash, 1, "RPC server mode intrpc is deprecated. Please use procrpc instead", 0);
  536. }
  537. }
  538. elsif ($attrname eq 'ccuGetVars') {
  539. my ($interval, $pattern) = split /:/, $attrval;
  540. $pattern = '.*' if (!defined ($pattern));
  541. $hash->{hmccu}{ccuvarspat} = $pattern;
  542. $hash->{hmccu}{ccuvarsint} = $interval;
  543. RemoveInternalTimer ($hash, "HMCCU_UpdateVariables");
  544. if ($interval > 0) {
  545. HMCCU_Log ($hash, 2, "Updating CCU system variables every $interval seconds", 0);
  546. InternalTimer (gettimeofday()+$interval, "HMCCU_UpdateVariables", $hash);
  547. }
  548. }
  549. elsif ($attrname eq 'rpcdevice') {
  550. return "HMCCU: Attribute rpcdevice is depricated. Please remove it";
  551. # return "HMCCU: Can't find HMCCURPC device $attrval"
  552. # if (!exists ($defs{$attrval}) || $defs{$attrval}->{TYPE} ne 'HMCCURPC');
  553. # if (exists ($defs{$attrval}->{IODev})) {
  554. # return "HMCCU: Device $attrval is not assigned to $name"
  555. # if ($defs{$attrval}->{IODev} != $hash);
  556. # }
  557. # else {
  558. # $defs{$attrval}->{IODev} = $hash;
  559. # }
  560. # $hash->{RPCDEV} = $attrval;
  561. }
  562. elsif ($attrname eq 'rpcinterfaces' || $attrname eq 'rpcport') {
  563. if ($hash->{hmccu}{ccu}{delayed} == 0) {
  564. my $msg = HMCCU_AttrInterfacesPorts ($hash, $attrname, $attrval);
  565. return $msg if ($msg ne '');
  566. }
  567. # my @ports = split (',', $attrval);
  568. # my @plist = ();
  569. # foreach my $p (@ports) {
  570. # my $pn = HMCCU_GetRPCServerInfo ($hash, $p, 'port');
  571. # return "HMCCU: Illegal RPC interface $p" if (!defined ($pn));
  572. # push (@plist, $pn);
  573. # }
  574. # return "No RPC interface specified" if (scalar (@plist) == 0);
  575. # $hash->{hmccu}{rpcports} = join (',', @plist);
  576. # $attr{$name}{"rpcport"} = $hash->{hmccu}{rpcports};
  577. }
  578. # elsif ($attrname eq 'rpcport') {
  579. # my @ports = split (',', $attrval);
  580. # my @ilist = ();
  581. # foreach my $p (@ports) {
  582. # my $pn = HMCCU_GetRPCServerInfo ($hash, $p, 'name');
  583. # return "HMCCU: Illegal RPC port $p" if (!defined ($pn));
  584. # push (@ilist, $pn);
  585. # }
  586. # return "No RPC port specified" if (scalar (@ilist) == 0);
  587. # $hash->{hmccu}{rpcports} = $attrval;
  588. # $attr{$name}{"rpcinterfaces"} = join (',', @ilist);
  589. # }
  590. }
  591. elsif ($cmd eq 'del') {
  592. if ($attrname eq 'ccuaggregate') {
  593. HMCCU_AggregationRules ($hash, '');
  594. }
  595. elsif ($attrname eq 'ccuGetVars') {
  596. RemoveInternalTimer ($hash, "HMCCU_UpdateVariables");
  597. }
  598. elsif ($attrname eq 'rpcdevice') {
  599. delete $hash->{RPCDEV} if (exists ($hash->{RPCDEV}));
  600. }
  601. elsif ($attrname eq 'rpcport' || $attrname eq 'rpcinterfaces') {
  602. $hash->{hmccu}{rpcports} = $HMCCU_RPC_PORT_DEFAULT;
  603. }
  604. }
  605. return undef;
  606. }
  607. ######################################################################
  608. # Set attributes rpcinterfaces and rpcport.
  609. # Return empty string or error message on error.
  610. ######################################################################
  611. sub HMCCU_AttrInterfacesPorts ($$$) {
  612. my ($hash, $attr, $attrval) = @_;
  613. my $name = $hash->{NAME};
  614. if ($attr eq 'rpcinterfaces') {
  615. my @ports = split (',', $attrval);
  616. my @plist = ();
  617. foreach my $p (@ports) {
  618. my $pn = HMCCU_GetRPCServerInfo ($hash, $p, 'port');
  619. return "HMCCU: Illegal RPC interface $p" if (!defined ($pn));
  620. push (@plist, $pn);
  621. }
  622. return "No RPC interface specified" if (scalar (@plist) == 0);
  623. $hash->{hmccu}{rpcports} = join (',', @plist);
  624. $attr{$name}{"rpcport"} = $hash->{hmccu}{rpcports};
  625. }
  626. elsif ($attr eq 'rpcport') {
  627. my @ports = split (',', $attrval);
  628. my @ilist = ();
  629. foreach my $p (@ports) {
  630. my $pn = HMCCU_GetRPCServerInfo ($hash, $p, 'name');
  631. return "HMCCU: Illegal RPC port $p" if (!defined ($pn));
  632. push (@ilist, $pn);
  633. }
  634. return "No RPC port specified" if (scalar (@ilist) == 0);
  635. $hash->{hmccu}{rpcports} = $attrval;
  636. $attr{$name}{"rpcinterfaces"} = join (',', @ilist);
  637. }
  638. return '';
  639. }
  640. ######################################################################
  641. # Parse aggregation rules for readings.
  642. # Syntax of aggregation rule is:
  643. # FilterSpec[;...]
  644. # FilterSpec := {Name|Filt|Read|Cond|Else|Pref|Coll|Html}[,...]
  645. # Name := name:Name
  646. # Filt := filter:{name|type|group|room|alias}=Regexp[!Regexp]
  647. # Read := read:Regexp
  648. # Cond := if:{any|all|min|max|sum|avg|gt|lt|ge|le}=Value
  649. # Else := else:Value
  650. # Pref := prefix:{RULE|Prefix}
  651. # Coll := coll:{NAME|Attribute}
  652. # Html := html:Template
  653. ######################################################################
  654. sub HMCCU_AggregationRules ($$)
  655. {
  656. my ($hash, $rulestr) = @_;
  657. my $name = $hash->{NAME};
  658. # Delete existing aggregation rules
  659. if (exists ($hash->{hmccu}{agg})) {
  660. delete $hash->{hmccu}{agg};
  661. }
  662. return if ($rulestr eq '');
  663. my @pars = ('name', 'filter', 'if', 'else');
  664. # Extract aggregation rules
  665. my $cnt = 0;
  666. my @rules = split (/[;\n]+/, $rulestr);
  667. foreach my $r (@rules) {
  668. $cnt++;
  669. # Set default rule parameters. Can be modified later
  670. my %opt = ( 'read' => 'state', 'prefix' => 'RULE', 'coll' => 'NAME' );
  671. # Parse aggregation rule
  672. my @specs = split (',', $r);
  673. foreach my $spec (@specs) {
  674. if ($spec =~ /^(name|filter|read|if|else|prefix|coll|html):(.+)$/) {
  675. $opt{$1} = $2;
  676. }
  677. }
  678. # Check if mandatory parameters are specified
  679. foreach my $p (@pars) {
  680. return HMCCU_Log ($hash, 1, "Parameter $p is missing in aggregation rule $cnt.", 0)
  681. if (!exists ($opt{$p}));
  682. }
  683. my $fname = $opt{name};
  684. my ($fincl, $fexcl) = split ('!', $opt{filter});
  685. my ($ftype, $fexpr) = split ('=', $fincl);
  686. return 0 if (!defined ($fexpr));
  687. my ($fcond, $fval) = split ('=', $opt{if});
  688. return 0 if (!defined ($fval));
  689. my ($fcoll, $fdflt) = split ('!', $opt{coll});
  690. $fdflt = 'no match' if (!defined ($fdflt));
  691. my $fhtml = exists ($opt{'html'}) ? $opt{'html'} : '';
  692. # Read HTML template (optional)
  693. if ($fhtml ne '') {
  694. my %tdef;
  695. my @html;
  696. # Read template file
  697. if (open (TEMPLATE, "<$fhtml")) {
  698. @html = <TEMPLATE>;
  699. close (TEMPLATE);
  700. }
  701. else {
  702. return HMCCU_Log ($hash, 1, "Can't open file $fhtml.", 0);
  703. }
  704. # Parse template
  705. foreach my $line (@html) {
  706. chomp $line;
  707. my ($key, $h) = split /:/, $line, 2;
  708. next if (!defined ($h) || $key =~ /^#/);
  709. $tdef{$key} = $h;
  710. }
  711. # Some syntax checks
  712. return HMCCU_Log ($hash, 1, "Missing definition row-odd in template file.", 0)
  713. if (!exists ($tdef{'row-odd'}));
  714. # Set default values
  715. $tdef{'begin-html'} = '' if (!exists ($tdef{'begin-html'}));
  716. $tdef{'end-html'} = '' if (!exists ($tdef{'end-html'}));
  717. $tdef{'begin-table'} = "<table>" if (!exists ($tdef{'begin-table'}));
  718. $tdef{'end-table'} = "</table>" if (!exists ($tdef{'end-table'}));
  719. $tdef{'default'} = 'no data' if (!exists ($tdef{'default'}));;
  720. $tdef{'row-even'} = $tdef{'row-odd'} if (!exists ($tdef{'row-even'}));
  721. foreach my $t (keys %tdef) {
  722. $hash->{hmccu}{agg}{$fname}{fhtml}{$t} = $tdef{$t};
  723. }
  724. }
  725. $hash->{hmccu}{agg}{$fname}{ftype} = $ftype;
  726. $hash->{hmccu}{agg}{$fname}{fexpr} = $fexpr;
  727. $hash->{hmccu}{agg}{$fname}{fexcl} = (defined ($fexcl) ? $fexcl : '');
  728. $hash->{hmccu}{agg}{$fname}{fread} = $opt{'read'};
  729. $hash->{hmccu}{agg}{$fname}{fcond} = $fcond;
  730. $hash->{hmccu}{agg}{$fname}{ftrue} = $fval;
  731. $hash->{hmccu}{agg}{$fname}{felse} = $opt{'else'};
  732. $hash->{hmccu}{agg}{$fname}{fpref} = $opt{prefix} eq 'RULE' ? $fname : $opt{prefix};
  733. $hash->{hmccu}{agg}{$fname}{fcoll} = $fcoll;
  734. $hash->{hmccu}{agg}{$fname}{fdflt} = $fdflt;
  735. }
  736. return 1;
  737. }
  738. ######################################################################
  739. # Export default attributes.
  740. ######################################################################
  741. sub HMCCU_ExportDefaults ($)
  742. {
  743. my ($filename) = @_;
  744. return 0 if (!open (DEFFILE, ">$filename"));
  745. print DEFFILE "# HMCCU default attributes for channels\n";
  746. foreach my $t (keys %{$HMCCU_CHN_DEFAULTS}) {
  747. print DEFFILE "\nchannel:$t\n";
  748. foreach my $a (sort keys %{$HMCCU_CHN_DEFAULTS->{$t}}) {
  749. print DEFFILE "$a=".$HMCCU_CHN_DEFAULTS->{$t}{$a}."\n";
  750. }
  751. }
  752. print DEFFILE "\n# HMCCU default attributes for devices\n";
  753. foreach my $t (keys %{$HMCCU_DEV_DEFAULTS}) {
  754. print DEFFILE "\ndevice:$t\n";
  755. foreach my $a (sort keys %{$HMCCU_DEV_DEFAULTS->{$t}}) {
  756. print DEFFILE "$a=".$HMCCU_DEV_DEFAULTS->{$t}{$a}."\n";
  757. }
  758. }
  759. close (DEFFILE);
  760. return 1;
  761. }
  762. ######################################################################
  763. # Import customer default attributes
  764. # Returns 1 on success. Returns negative line number on syntax errors.
  765. # Returns 0 on file open error.
  766. ######################################################################
  767. sub HMCCU_ImportDefaults ($)
  768. {
  769. my ($filename) = @_;
  770. my $modtype = '';
  771. my $ccutype = '';
  772. my $line = 0;
  773. return 0 if (!open (DEFFILE, "<$filename"));
  774. my @defaults = <DEFFILE>;
  775. close (DEFFILE);
  776. chomp (@defaults);
  777. %HMCCU_CUST_CHN_DEFAULTS = ();
  778. %HMCCU_CUST_DEV_DEFAULTS = ();
  779. foreach my $d (@defaults) {
  780. $line++;
  781. next if ($d eq '' || $d =~ /^#/);
  782. if ($d =~ /^(channel|device):/) {
  783. my @t = split (':', $d, 2);
  784. if (scalar (@t) != 2) {
  785. close (DEFFILE);
  786. return -$line;
  787. }
  788. $modtype = $t[0];
  789. $ccutype = $t[1];
  790. next;
  791. }
  792. if ($ccutype eq '' || $modtype eq '') {
  793. close (DEFFILE);
  794. return -$line;
  795. }
  796. my @av = split ('=', $d, 2);
  797. if (scalar (@av) != 2) {
  798. close (DEFFILE);
  799. return -$line;
  800. }
  801. if ($modtype eq 'channel') {
  802. $HMCCU_CUST_CHN_DEFAULTS{$ccutype}{$av[0]} = $av[1];
  803. }
  804. else {
  805. $HMCCU_CUST_DEV_DEFAULTS{$ccutype}{$av[0]} = $av[1];
  806. }
  807. }
  808. return 1;
  809. }
  810. ######################################################################
  811. # Find default attributes
  812. # Return template reference.
  813. ######################################################################
  814. sub HMCCU_FindDefaults ($$)
  815. {
  816. my ($hash, $common) = @_;
  817. my $type = $hash->{TYPE};
  818. my $ccutype = $hash->{ccutype};
  819. if ($type eq 'HMCCUCHN') {
  820. my ($adr, $chn) = split (':', $hash->{ccuaddr});
  821. foreach my $deftype (keys %HMCCU_CUST_CHN_DEFAULTS) {
  822. my @chnlst = split (',', $HMCCU_CUST_CHN_DEFAULTS{$deftype}{_channels});
  823. return \%{$HMCCU_CUST_CHN_DEFAULTS{$deftype}}
  824. if ($ccutype =~ /^($deftype)$/i && grep { $_ eq $chn} @chnlst);
  825. }
  826. foreach my $deftype (keys %{$HMCCU_CHN_DEFAULTS}) {
  827. my @chnlst = split (',', $HMCCU_CHN_DEFAULTS->{$deftype}{_channels});
  828. return \%{$HMCCU_CHN_DEFAULTS->{$deftype}}
  829. if ($ccutype =~ /^($deftype)$/i && grep { $_ eq $chn} @chnlst);
  830. }
  831. }
  832. elsif ($type eq 'HMCCUDEV' || $type eq 'HMCCU') {
  833. foreach my $deftype (keys %HMCCU_CUST_DEV_DEFAULTS) {
  834. return \%{$HMCCU_CUST_DEV_DEFAULTS{$deftype}} if ($ccutype =~ /^($deftype)$/i);
  835. }
  836. foreach my $deftype (keys %{$HMCCU_DEV_DEFAULTS}) {
  837. return \%{$HMCCU_DEV_DEFAULTS->{$deftype}} if ($ccutype =~ /^($deftype)$/i);
  838. }
  839. }
  840. return undef;
  841. }
  842. ######################################################################
  843. # Set default attributes from template
  844. ######################################################################
  845. sub HMCCU_SetDefaultsTemplate ($$)
  846. {
  847. my ($hash, $template) = @_;
  848. my $name = $hash->{NAME};
  849. foreach my $a (keys %{$template}) {
  850. next if ($a =~ /^_/);
  851. my $v = $template->{$a};
  852. CommandAttr (undef, "$name $a $v");
  853. }
  854. }
  855. ######################################################################
  856. # Set default attributes
  857. ######################################################################
  858. sub HMCCU_SetDefaults ($)
  859. {
  860. my ($hash) = @_;
  861. my $name = $hash->{NAME};
  862. # Set type specific attributes
  863. my $template = HMCCU_FindDefaults ($hash, 0);
  864. return 0 if (!defined ($template));
  865. HMCCU_SetDefaultsTemplate ($hash, $template);
  866. return 1;
  867. }
  868. ######################################################################
  869. # List default attributes for device type (mode = 0) or all
  870. # device types (mode = 1) with default attributes available.
  871. ######################################################################
  872. sub HMCCU_GetDefaults ($$)
  873. {
  874. my ($hash, $mode) = @_;
  875. my $name = $hash->{NAME};
  876. my $type = $hash->{TYPE};
  877. my $ccutype = $hash->{ccutype};
  878. my $result = '';
  879. my $deffile = '';
  880. if ($mode == 0) {
  881. my $template = HMCCU_FindDefaults ($hash, 0);
  882. return ($result eq '' ? "No default attributes defined" : $result) if (!defined ($template));
  883. foreach my $a (keys %{$template}) {
  884. next if ($a =~ /^_/);
  885. my $v = $template->{$a};
  886. $result .= $a." = ".$v."\n";
  887. }
  888. }
  889. else {
  890. $result = "HMCCU Channels:\n------------------------------\n";
  891. foreach my $deftype (sort keys %{$HMCCU_CHN_DEFAULTS}) {
  892. my $tlist = $deftype;
  893. $tlist =~ s/\|/,/g;
  894. $result .= $HMCCU_CHN_DEFAULTS->{$deftype}{_description}." ($tlist), channels ".
  895. $HMCCU_CHN_DEFAULTS->{$deftype}{_channels}."\n";
  896. }
  897. $result .= "\nHMCCU Devices:\n------------------------------\n";
  898. foreach my $deftype (sort keys %{$HMCCU_DEV_DEFAULTS}) {
  899. my $tlist = $deftype;
  900. $tlist =~ s/\|/,/g;
  901. $result .= $HMCCU_DEV_DEFAULTS->{$deftype}{_description}." ($tlist)\n";
  902. }
  903. $result .= "\nCustom Channels:\n-----------------------------\n";
  904. foreach my $deftype (sort keys %HMCCU_CUST_CHN_DEFAULTS) {
  905. my $tlist = $deftype;
  906. $tlist =~ s/\|/,/g;
  907. $result .= $HMCCU_CUST_CHN_DEFAULTS{$deftype}{_description}." ($tlist), channels ".
  908. $HMCCU_CUST_CHN_DEFAULTS{$deftype}{_channels}."\n";
  909. }
  910. $result .= "\nCustom Devices:\n-----------------------------\n";
  911. foreach my $deftype (sort keys %HMCCU_CUST_DEV_DEFAULTS) {
  912. my $tlist = $deftype;
  913. $tlist =~ s/\|/,/g;
  914. $result .= $HMCCU_CUST_DEV_DEFAULTS{$deftype}{_description}." ($tlist)\n";
  915. }
  916. }
  917. return $result;
  918. }
  919. ######################################################################
  920. # Handle FHEM events
  921. ######################################################################
  922. sub HMCCU_Notify ($$)
  923. {
  924. my ($hash, $devhash) = @_;
  925. my $name = $hash->{NAME};
  926. my $devname = $devhash->{NAME};
  927. my $devtype = $devhash->{TYPE};
  928. my $disable = AttrVal ($name, 'disable', 0);
  929. my $rpcserver = AttrVal ($name, 'rpcserver', 'off');
  930. my $ccuflags = HMCCU_GetFlags ($name);
  931. return if ($disable);
  932. my $events = deviceEvents ($devhash, 1);
  933. return if (! $events);
  934. # Process events
  935. foreach my $event (@{$events}) {
  936. if ($devname eq 'global') {
  937. if ($event eq 'INITIALIZED') {
  938. return if ($rpcserver eq 'off');
  939. my $delay = $hash->{ccustate} eq 'active' && $hash->{hmccu}{ccu}{delayed} == 0 ?
  940. $HMCCU_INIT_INTERVAL0 : $hash->{hmccu}{ccu}{delay}+$HMCCU_CCU_RPC_OFFSET;
  941. Log3 $name, 0, "HMCCU: Start of RPC server after FHEM initialization in $delay seconds";
  942. if ($ccuflags =~ /(extrpc|procrpc)/) {
  943. InternalTimer (gettimeofday()+$delay, "HMCCU_StartExtRPCServer", $hash, 0);
  944. }
  945. else {
  946. InternalTimer (gettimeofday()+$delay, "HMCCU_StartIntRPCServer", $hash, 0);
  947. }
  948. }
  949. }
  950. else {
  951. return if ($devtype ne 'HMCCUDEV' && $devtype ne 'HMCCUCHN');
  952. my ($r, $v) = split (": ", $event);
  953. return if (!defined ($v));
  954. return if ($ccuflags =~ /noagg/);
  955. foreach my $rule (keys %{$hash->{hmccu}{agg}}) {
  956. my $ftype = $hash->{hmccu}{agg}{$rule}{ftype};
  957. my $fexpr = $hash->{hmccu}{agg}{$rule}{fexpr};
  958. my $fread = $hash->{hmccu}{agg}{$rule}{fread};
  959. next if ($r !~ $fread);
  960. next if ($ftype eq 'name' && $devname !~ /$fexpr/);
  961. next if ($ftype eq 'type' && $devhash->{ccutype} !~ /$fexpr/);
  962. next if ($ftype eq 'group' && AttrVal ($devname, 'group', 'null') !~ /$fexpr/);
  963. next if ($ftype eq 'room' && AttrVal ($devname, 'room', 'null') !~ /$fexpr/);
  964. next if ($ftype eq 'alias' && AttrVal ($devname, 'alias', 'null') !~ /$fexpr/);
  965. HMCCU_AggregateReadings ($hash, $rule);
  966. }
  967. }
  968. }
  969. return;
  970. }
  971. ######################################################################
  972. # Enhance device details in FHEM WEB
  973. ######################################################################
  974. sub HMCCU_Detail ($$$$)
  975. {
  976. my ($FW_Name, $Device, $Room, $pageHash) = @_;
  977. my $hash = $defs{$Device};
  978. return defined ($hash->{host}) ? qq(
  979. <span class='mkTitle'>CCU Administration</span>
  980. <table class="block wide">
  981. <tr class="odd">
  982. <td><div class="col1">
  983. &gt; <a target="_blank" href="http://$hash->{host}">CCU WebUI</a>
  984. </div></td>
  985. </tr>
  986. <tr class="odd">
  987. <td><div class="col1">
  988. &gt; <a target="_blank" href="http://$hash->{host}/addons/cuxd/index.ccc">CUxD Config</a>
  989. </div></td>
  990. </tr>
  991. </table>
  992. ) : '';
  993. }
  994. ######################################################################
  995. # Calculate reading aggregations.
  996. # Called by Notify or via command get aggregation.
  997. ######################################################################
  998. sub HMCCU_AggregateReadings ($$)
  999. {
  1000. my ($hash, $rule) = @_;
  1001. my $dc = 0;
  1002. my $mc = 0;
  1003. my $result = '';
  1004. my $rl = '';
  1005. my $table = '';
  1006. # Get rule parameters
  1007. my $ftype = $hash->{hmccu}{agg}{$rule}{ftype};
  1008. my $fexpr = $hash->{hmccu}{agg}{$rule}{fexpr};
  1009. my $fexcl = $hash->{hmccu}{agg}{$rule}{fexcl};
  1010. my $fread = $hash->{hmccu}{agg}{$rule}{fread};
  1011. my $fcond = $hash->{hmccu}{agg}{$rule}{fcond};
  1012. my $ftrue = $hash->{hmccu}{agg}{$rule}{ftrue};
  1013. my $felse = $hash->{hmccu}{agg}{$rule}{felse};
  1014. my $fpref = $hash->{hmccu}{agg}{$rule}{fpref};
  1015. my $fhtml = exists ($hash->{hmccu}{agg}{$rule}{fhtml}) ? 1 : 0;
  1016. my $resval;
  1017. $resval = $ftrue if ($fcond =~ /^(max|min|sum|avg)$/);
  1018. my @devlist = HMCCU_FindClientDevices ($hash, "(HMCCUDEV|HMCCUCHN)", undef, undef);
  1019. foreach my $d (@devlist) {
  1020. my $ch = $defs{$d};
  1021. my $cn = $ch->{NAME};
  1022. my $ct = $ch->{TYPE};
  1023. my $fmatch = '';
  1024. $fmatch = $cn if ($ftype eq 'name');
  1025. $fmatch = $ch->{ccutype} if ($ftype eq 'type');
  1026. $fmatch = AttrVal ($cn, 'group', '') if ($ftype eq 'group');
  1027. $fmatch = AttrVal ($cn, 'room', '') if ($ftype eq 'room');
  1028. $fmatch = AttrVal ($cn, 'alias', '') if ($ftype eq 'alias');
  1029. next if ($fmatch eq '' || $fmatch !~ /$fexpr/ || ($fexcl ne '' && $fmatch =~ /$fexcl/));
  1030. my $fcoll = $hash->{hmccu}{agg}{$rule}{fcoll} eq 'NAME' ?
  1031. $cn : AttrVal ($cn, $hash->{hmccu}{agg}{$rule}{fcoll}, $cn);
  1032. # Compare readings
  1033. foreach my $r (keys %{$ch->{READINGS}}) {
  1034. next if ($r !~ /$fread/);
  1035. my $rv = $ch->{READINGS}{$r}{VAL};
  1036. my $f = 0;
  1037. if (($fcond eq 'any' || $fcond eq 'all') && $rv =~ /$ftrue/) {
  1038. $mc++;
  1039. $f = 1;
  1040. }
  1041. if ($fcond eq 'max' && $rv > $resval) {
  1042. $resval = $rv;
  1043. $mc = 1;
  1044. $f = 1;
  1045. }
  1046. if ($fcond eq 'min' && $rv < $resval) {
  1047. $resval = $rv;
  1048. $mc = 1;
  1049. $f = 1;
  1050. }
  1051. if ($fcond eq 'sum' || $fcond eq 'avg') {
  1052. $resval += $rv;
  1053. $mc++;
  1054. $f = 1;
  1055. }
  1056. if (($fcond eq 'gt' && $rv > $ftrue) ||
  1057. ($fcond eq 'lt' && $rv < $ftrue) ||
  1058. ($fcond eq 'ge' && $rv >= $ftrue) ||
  1059. ($fcond eq 'le' && $rv <= $ftrue)) {
  1060. $mc++;
  1061. $f = 1;
  1062. }
  1063. if ($f) {
  1064. $rl .= ($mc > 1 ? ",$fcoll" : $fcoll);
  1065. last;
  1066. }
  1067. }
  1068. $dc++;
  1069. }
  1070. $rl = $hash->{hmccu}{agg}{$rule}{fdflt} if ($rl eq '');
  1071. # HTML code generation
  1072. if ($fhtml) {
  1073. if ($rl ne '') {
  1074. $table = $hash->{hmccu}{agg}{$rule}{fhtml}{'begin-html'}.
  1075. $hash->{hmccu}{agg}{$rule}{fhtml}{'begin-table'};
  1076. $table .= $hash->{hmccu}{agg}{$rule}{fhtml}{'header'}
  1077. if (exists ($hash->{hmccu}{agg}{$rule}{fhtml}{'header'}));
  1078. my $row = 1;
  1079. foreach my $v (split (",", $rl)) {
  1080. my $t_row = ($row % 2) ? $hash->{hmccu}{agg}{$rule}{fhtml}{'row-odd'} :
  1081. $hash->{hmccu}{agg}{$rule}{fhtml}{'row-even'};
  1082. $t_row =~ s/\<reading\/\>/$v/;
  1083. $table .= $t_row;
  1084. $row++;
  1085. }
  1086. $table .= $hash->{hmccu}{agg}{$rule}{fhtml}{'end-table'}.
  1087. $hash->{hmccu}{agg}{$rule}{fhtml}{'end-html'};
  1088. }
  1089. else {
  1090. $table = $hash->{hmccu}{agg}{$rule}{fhtml}{'begin-html'}.
  1091. $hash->{hmccu}{agg}{$rule}{fhtml}{'default'}.
  1092. $hash->{hmccu}{agg}{$rule}{fhtml}{'end-html'};
  1093. }
  1094. }
  1095. if ($fcond eq 'any') {
  1096. $result = $mc > 0 ? $ftrue : $felse;
  1097. }
  1098. elsif ($fcond eq 'all') {
  1099. $result = $mc == $dc ? $ftrue : $felse;
  1100. }
  1101. elsif ($fcond eq 'min' || $fcond eq 'max' || $fcond eq 'sum') {
  1102. $result = $mc > 0 ? $resval : $felse;
  1103. }
  1104. elsif ($fcond eq 'avg') {
  1105. $result = $mc > 0 ? $resval/$mc : $felse;
  1106. }
  1107. elsif ($fcond =~ /^(gt|lt|ge|le)$/) {
  1108. $result = $mc;
  1109. }
  1110. # Set readings
  1111. readingsBeginUpdate ($hash);
  1112. readingsBulkUpdate ($hash, $fpref.'state', $result);
  1113. readingsBulkUpdate ($hash, $fpref.'match', $mc);
  1114. readingsBulkUpdate ($hash, $fpref.'count', $dc);
  1115. readingsBulkUpdate ($hash, $fpref.'list', $rl);
  1116. readingsBulkUpdate ($hash, $fpref.'table', $table) if ($fhtml);
  1117. readingsEndUpdate ($hash, 1);
  1118. return $result;
  1119. }
  1120. ######################################################################
  1121. # Delete device
  1122. ######################################################################
  1123. sub HMCCU_Undef ($$)
  1124. {
  1125. my ($hash, $arg) = @_;
  1126. # Shutdown RPC server
  1127. HMCCU_Shutdown ($hash);
  1128. # Delete reference to IO module in client devices
  1129. my @keylist = keys %defs;
  1130. foreach my $d (@keylist) {
  1131. if (exists ($defs{$d}) && exists($defs{$d}{IODev}) &&
  1132. $defs{$d}{IODev} == $hash) {
  1133. delete $defs{$d}{IODev};
  1134. }
  1135. }
  1136. return undef;
  1137. }
  1138. ######################################################################
  1139. # Shutdown FHEM
  1140. ######################################################################
  1141. sub HMCCU_Shutdown ($)
  1142. {
  1143. my ($hash) = @_;
  1144. my $name = $hash->{NAME};
  1145. # Shutdown RPC server
  1146. if (HMCCU_IsFlag ($name, "(extrpc|procrpc)")) {
  1147. HMCCU_StopExtRPCServer ($hash);
  1148. }
  1149. else {
  1150. HMCCU_StopRPCServer ($hash);
  1151. }
  1152. # Remove existing timer functions
  1153. RemoveInternalTimer ($hash);
  1154. return undef;
  1155. }
  1156. ######################################################################
  1157. # Set commands
  1158. ######################################################################
  1159. sub HMCCU_Set ($@)
  1160. {
  1161. my ($hash, $a, $h) = @_;
  1162. my $name = shift @$a;
  1163. my $opt = shift @$a;
  1164. my $options = "var delete execute hmscript cleardefaults:noArg defaults:noArg ".
  1165. "importdefaults rpcserver:on,off,restart datapoint ackmessages:noArg";
  1166. my $usage = "HMCCU: Unknown argument $opt, choose one of $options";
  1167. my $host = $hash->{host};
  1168. return "HMCCU: I/O device not initialized. Try again later." if ($hash->{hmccu}{ccu}{delayed});
  1169. return "HMCCU: CCU busy, choose one of rpcserver:off"
  1170. if ($opt ne 'rpcserver' && HMCCU_IsRPCStateBlocking ($hash));
  1171. my $ccuflags = HMCCU_GetFlags ($name);
  1172. my $stripchar = AttrVal ($name, "stripchar", '');
  1173. my $ccureadings = AttrVal ($name, "ccureadings", $ccuflags =~ /noReadings/ ? 0 : 1);
  1174. my $ccureqtimeout = AttrVal ($name, "ccuReqTimeout", $HMCCU_TIMEOUT_REQUEST);
  1175. my $readingformat = HMCCU_GetAttrReadingFormat ($hash, $hash);
  1176. my $substitute = HMCCU_GetAttrSubstitute ($hash, $hash);
  1177. # Add program names to command execute
  1178. if (exists ($hash->{hmccu}{prg})) {
  1179. my @progs = ();
  1180. foreach my $p (keys %{$hash->{hmccu}{prg}}) {
  1181. push (@progs, $p) if ($hash->{hmccu}{prg}{$p}{internal} eq 'false');
  1182. }
  1183. if (scalar (@progs) > 0) {
  1184. my $prgopt = "execute:".join(',', @progs);
  1185. $options =~ s/execute/$prgopt/;
  1186. $usage =~ s/execute/$prgopt/;
  1187. }
  1188. }
  1189. if ($opt eq 'var') {
  1190. my $vartype;
  1191. $vartype = shift @$a if (scalar (@$a) == 3);
  1192. my $objname = shift @$a;
  1193. my $objvalue = shift @$a;
  1194. $usage = "set $name $opt [{'bool'|'list'|'number'|'test'}] variable value [param=value [...]]";
  1195. my $result;
  1196. return HMCCU_SetError ($hash, $usage) if (!defined ($objvalue));
  1197. $objname =~ s/$stripchar$// if ($stripchar ne '');
  1198. $objvalue =~ s/\\_/%20/g;
  1199. $h->{name} = $objname if (!defined ($h) && defined ($vartype));
  1200. $result = HMCCU_SetVariable ($hash, $objname, $objvalue, $vartype, $h);
  1201. return HMCCU_SetError ($hash, $result) if ($result < 0);
  1202. return HMCCU_SetState ($hash, "OK");
  1203. }
  1204. elsif ($opt eq 'datapoint') {
  1205. my $objname = shift @$a;
  1206. my $objvalue = shift @$a;
  1207. $usage = "Usage: set $name $opt {ccuobject|'hmccu':fhemobject} value";
  1208. return HMCCU_SetError ($hash, $usage) if (!defined ($objvalue));
  1209. my $rc = HMCCU_SetDatapoint ($hash, $objname, $objvalue);
  1210. return HMCCU_SetError ($hash, $rc) if ($rc < 0);
  1211. return HMCCU_SetState ($hash, "OK");
  1212. }
  1213. elsif ($opt eq 'delete') {
  1214. my $objname = shift @$a;
  1215. my $objtype = shift @$a;
  1216. $objtype = "OT_VARDP" if (!defined ($objtype));
  1217. $usage = "Usage: set $name $opt ccuobject ['OT_VARDP'|'OT_DEVICE']";
  1218. return HMCCU_SetError ($hash, $usage)
  1219. if (!defined ($objname) || $objtype !~ /^(OT_VARDP|OT_DEVICE)$/);
  1220. my $result = HMCCU_HMScriptExt ($hash, "!DeleteObject", { name => $objname, type => $objtype });
  1221. return HMCCU_SetError ($hash, -2) if ($result =~ /^ERROR:.*/);
  1222. return HMCCU_SetState ($hash, "OK");
  1223. }
  1224. elsif ($opt eq 'execute') {
  1225. my $program = shift @$a;
  1226. my $response;
  1227. $usage = "Usage: set $name $opt program-name";
  1228. return HMCCU_SetError ($hash, $usage) if (!defined ($program));
  1229. my $cmd = qq(dom.GetObject("$program").ProgramExecute());
  1230. my $value = HMCCU_HMCommand ($hash, $cmd, 0);
  1231. return HMCCU_SetState ($hash, "OK") if (defined ($value));
  1232. return HMCCU_SetError ($hash, "Program execution error");
  1233. }
  1234. elsif ($opt eq 'hmscript') {
  1235. my $script = shift @$a;
  1236. my $dump = shift @$a;
  1237. my $response = '';
  1238. my %objects = ();
  1239. my $objcount = 0;
  1240. $usage = "Usage: set $name $opt {file|!function|'['code']'} ['dump'] [parname=value [...]]";
  1241. # If no parameter is specified list available script functions
  1242. if (!defined ($script)) {
  1243. $response = "Available HomeMatic script functions:\n".
  1244. "-------------------------------------\n";
  1245. foreach my $scr (keys %{$HMCCU_SCRIPTS}) {
  1246. $response .= "$scr ".$HMCCU_SCRIPTS->{$scr}{syntax}."\n".
  1247. $HMCCU_SCRIPTS->{$scr}{description}."\n\n";
  1248. }
  1249. $response .= $usage;
  1250. return $response;
  1251. }
  1252. return HMCCU_SetError ($hash, $usage) if (defined ($dump) && $dump ne 'dump');
  1253. # Execute script
  1254. $response = HMCCU_HMScriptExt ($hash, $script, $h);
  1255. return HMCCU_SetError ($hash, -2, $response) if ($response =~ /^ERROR:/);
  1256. HMCCU_SetState ($hash, "OK");
  1257. return $response if (! $ccureadings || defined ($dump));
  1258. foreach my $line (split /\n/, $response) {
  1259. my @tokens = split /=/, $line;
  1260. next if (@tokens != 2);
  1261. my $reading;
  1262. my ($int, $add, $chn, $dpt, $nam, $flags) = HMCCU_ParseObject ($hash, $tokens[0],
  1263. $HMCCU_FLAG_INTERFACE);
  1264. ($add, $chn) = HMCCU_GetAddress ($hash, $nam, '', '') if ($flags == $HMCCU_FLAGS_NCD);
  1265. if ($flags == $HMCCU_FLAGS_IACD || $flags == $HMCCU_FLAGS_NCD) {
  1266. $objects{$add}{$chn}{$dpt} = $tokens[1];
  1267. $objcount++;
  1268. }
  1269. else {
  1270. # If output is not related to a channel store reading in I/O device
  1271. my $Value = HMCCU_Substitute ($tokens[1], $substitute, 0, undef, $tokens[0]);
  1272. my $rn = $tokens[0];
  1273. $rn =~ s/\:/\./g;
  1274. $rn =~ s/[^A-Za-z\d_\.-]+/_/g;
  1275. readingsSingleUpdate ($hash, $rn, $Value, 1);
  1276. }
  1277. }
  1278. HMCCU_UpdateMultipleDevices ($hash, \%objects) if ($objcount > 0);
  1279. return defined ($dump) ? $response : undef;
  1280. }
  1281. elsif ($opt eq 'rpcserver') {
  1282. my $action = shift @$a;
  1283. $action = shift @$a if ($action eq $opt);
  1284. $usage = "Usage: set $name $opt {'on'|'off'|'restart'}";
  1285. return HMCCU_SetError ($hash, $usage)
  1286. if (!defined ($action) || $action !~ /^(on|off|restart)$/);
  1287. if ($action eq 'on') {
  1288. if ($ccuflags =~ /(extrpc|procrpc)/) {
  1289. return HMCCU_SetError ($hash, "Start of RPC server failed")
  1290. if (!HMCCU_StartExtRPCServer ($hash));
  1291. }
  1292. else {
  1293. return HMCCU_SetError ($hash, "Start of RPC server failed")
  1294. if (!HMCCU_StartIntRPCServer ($hash));
  1295. }
  1296. }
  1297. elsif ($action eq 'off') {
  1298. if ($ccuflags =~ /(extrpc|procrpc)/) {
  1299. return HMCCU_SetError ($hash, "Stop of RPC server failed")
  1300. if (!HMCCU_StopExtRPCServer ($hash));
  1301. }
  1302. else {
  1303. return HMCCU_SetError ($hash, "Stop of RPC server failed")
  1304. if (!HMCCU_StopRPCServer ($hash));
  1305. }
  1306. }
  1307. elsif ($action eq 'restart') {
  1308. return "HMCCU: No RPC server running" if (!HMCCU_IsRPCServerRunning ($hash, undef, undef));
  1309. if ($ccuflags !~ /(extrpc|procrpc)/) {
  1310. return "HMCCU: Can't stop RPC server" if (!HMCCURPC_StopRPCServer ($hash));
  1311. HMCCU_SetRPCState ($hash, 'restarting');
  1312. DoTrigger ($name, "RPC server restarting");
  1313. }
  1314. else {
  1315. return HMCCU_SetError ($hash, "HMCCU: restart not supported by external RPC server");
  1316. }
  1317. }
  1318. return HMCCU_SetState ($hash, "OK");
  1319. }
  1320. elsif ($opt eq 'ackmessages') {
  1321. my $response = HMCCU_HMScriptExt ($hash, "!ClearUnreachable", undef);
  1322. return HMCCU_SetError ($hash, -2, $response) if ($response =~ /^ERROR:/);
  1323. return HMCCU_SetState ($hash, "OK", "Unreach errors in CCU cleared");
  1324. }
  1325. elsif ($opt eq 'defaults') {
  1326. my $rc = HMCCU_SetDefaults ($hash);
  1327. return HMCCU_SetError ($hash, "HMCCU: No default attributes found") if ($rc == 0);
  1328. return HMCCU_SetState ($hash, "OK");
  1329. }
  1330. elsif ($opt eq 'cleardefaults') {
  1331. %HMCCU_CUST_CHN_DEFAULTS = ();
  1332. %HMCCU_CUST_DEV_DEFAULTS = ();
  1333. return HMCCU_SetState ($hash, "OK", "Default attributes deleted");
  1334. }
  1335. elsif ($opt eq 'importdefaults') {
  1336. my $filename = shift @$a;
  1337. $usage = "Usage: set $name $opt filename";
  1338. return HMCCU_SetError ($hash, $usage) if (!defined ($filename));
  1339. my $rc = HMCCU_ImportDefaults ($filename);
  1340. return HMCCU_SetError ($hash, -16) if ($rc == 0);
  1341. if ($rc < 0) {
  1342. $rc = -$rc;
  1343. return HMCCU_SetError ($hash, "Syntax error in default attribute file $filename line $rc");
  1344. }
  1345. return HMCCU_SetState ($hash, "OK", "Default attributes read from file $filename");
  1346. }
  1347. else {
  1348. return $usage;
  1349. }
  1350. }
  1351. ######################################################################
  1352. # Get commands
  1353. ######################################################################
  1354. sub HMCCU_Get ($@)
  1355. {
  1356. my ($hash, $a, $h) = @_;
  1357. my $name = shift @$a;
  1358. my $opt = shift @$a;
  1359. my $options = "defaults:noArg exportdefaults devicelist dump dutycycle:noArg vars update".
  1360. " updateccu parfile configdesc firmware rpcevents:noArg rpcstate:noArg deviceinfo";
  1361. my $usage = "HMCCU: Unknown argument $opt, choose one of $options";
  1362. my $host = $hash->{host};
  1363. return "HMCCU: I/O device not initialized. Try again later." if ($hash->{hmccu}{ccu}{delayed});
  1364. return "HMCCU: CCU busy, choose one of rpcstate:noArg"
  1365. if ($opt ne 'rpcstate' && HMCCU_IsRPCStateBlocking ($hash));
  1366. my $ccuflags = HMCCU_GetFlags ($name);
  1367. my $ccureadings = AttrVal ($name, "ccureadings", $ccuflags =~ /noReadings/ ? 0 : 1);
  1368. my $parfile = AttrVal ($name, "parfile", '');
  1369. my $readname;
  1370. my $readaddr;
  1371. my $result = '';
  1372. my $rc;
  1373. if ($opt eq 'dump') {
  1374. my $content = shift @$a;
  1375. my $filter = shift @$a;
  1376. $filter = '.*' if (!defined ($filter));
  1377. $usage = "Usage: get $name dump {'datapoints'|'devtypes'} [filter]";
  1378. my %foper = (1, "R", 2, "W", 4, "E", 3, "RW", 5, "RE", 6, "WE", 7, "RWE");
  1379. my %ftype = (2, "B", 4, "F", 16, "I", 20, "S");
  1380. return HMCCU_SetError ($hash, $usage) if (!defined ($content));
  1381. if ($content eq 'devtypes') {
  1382. foreach my $devtype (sort keys %{$hash->{hmccu}{dp}}) {
  1383. $result .= $devtype."\n" if ($devtype =~ /$filter/);
  1384. }
  1385. }
  1386. elsif ($content eq 'datapoints') {
  1387. foreach my $devtype (sort keys %{$hash->{hmccu}{dp}}) {
  1388. next if ($devtype !~ /$filter/);
  1389. foreach my $chn (sort keys %{$hash->{hmccu}{dp}{$devtype}{ch}}) {
  1390. foreach my $dpt (sort keys %{$hash->{hmccu}{dp}{$devtype}{ch}{$chn}}) {
  1391. my $t = $hash->{hmccu}{dp}{$devtype}{ch}{$chn}{$dpt}{type};
  1392. my $o = $hash->{hmccu}{dp}{$devtype}{ch}{$chn}{$dpt}{oper};
  1393. $result .= $devtype.".".$chn.".".$dpt." [".
  1394. (exists($ftype{$t}) ? $ftype{$t} : $t)."] [".
  1395. (exists($foper{$o}) ? $foper{$o} : $o)."]\n";
  1396. }
  1397. }
  1398. }
  1399. }
  1400. else {
  1401. return HMCCU_SetError ($hash, $usage);
  1402. }
  1403. return HMCCU_SetState ($hash, "OK", ($result eq '') ? "No data found" : $result);
  1404. }
  1405. elsif ($opt eq 'vars') {
  1406. my $varname = shift @$a;
  1407. $usage = "Usage: get $name vars {regexp}[,...]";
  1408. return HMCCU_SetError ($hash, $usage) if (!defined ($varname));
  1409. ($rc, $result) = HMCCU_GetVariables ($hash, $varname);
  1410. return HMCCU_SetError ($hash, $rc, $result) if ($rc < 0);
  1411. return HMCCU_SetState ($hash, "OK", $ccureadings ? undef : $result);
  1412. }
  1413. elsif ($opt eq 'update' || $opt eq 'updateccu') {
  1414. my $devexp = shift @$a;
  1415. $devexp = '.*' if (!defined ($devexp));
  1416. $usage = "Usage: get $name $opt [device-expr [{'State'|'Value'}]]";
  1417. my $ccuget = shift @$a;
  1418. $ccuget = 'Attr' if (!defined ($ccuget));
  1419. return HMCCU_SetError ($hash, $usage) if ($ccuget !~ /^(Attr|State|Value)$/);
  1420. my ($co, $ce) = HMCCU_UpdateClients ($hash, $devexp, $ccuget, ($opt eq 'updateccu') ? 1 : 0, undef);
  1421. return HMCCU_SetState ($hash, "OK",
  1422. "$co client devices successfully updated. Update for $ce client devices failed");
  1423. }
  1424. elsif ($opt eq 'parfile') {
  1425. my $par_parfile = shift @$a;
  1426. my @parameters;
  1427. my $parcount;
  1428. if (defined ($par_parfile)) {
  1429. $parfile = $par_parfile;
  1430. }
  1431. else {
  1432. return HMCCU_SetError ($hash, "No parameter file specified") if ($parfile eq '');
  1433. }
  1434. # Read parameter file
  1435. if (open (PARFILE, "<$parfile")) {
  1436. @parameters = <PARFILE>;
  1437. $parcount = scalar @parameters;
  1438. close (PARFILE);
  1439. }
  1440. else {
  1441. return HMCCU_SetError ($hash, -16);
  1442. }
  1443. return HMCCU_SetError ($hash, "Empty parameter file") if ($parcount < 1);
  1444. ($rc, $result) = HMCCU_GetChannel ($hash, \@parameters);
  1445. return HMCCU_SetError ($hash, $rc) if ($rc < 0);
  1446. return HMCCU_SetState ($hash, "OK", $ccureadings ? undef : $result);
  1447. }
  1448. elsif ($opt eq 'deviceinfo') {
  1449. my $device = shift @$a;
  1450. $usage = "Usage: get $name $opt device [{'State'|'Value'}]";
  1451. return HMCCU_SetError ($hash, $usage) if (!defined ($device));
  1452. my $ccuget = shift @$a;
  1453. $ccuget = 'Attr' if (!defined ($ccuget));
  1454. return HMCCU_SetError ($hash, $usage) if ($ccuget !~ /^(Attr|State|Value)$/);
  1455. return HMCCU_SetError ($hash, -1) if (!HMCCU_IsValidDeviceOrChannel ($hash, $device, $HMCCU_FL_ALL));
  1456. $result = HMCCU_GetDeviceInfo ($hash, $device, $ccuget);
  1457. return HMCCU_SetError ($hash, -2) if ($result eq '' || $result =~ /^ERROR:.*/);
  1458. HMCCU_SetState ($hash, "OK");
  1459. return HMCCU_FormatDeviceInfo ($result);
  1460. }
  1461. elsif ($opt eq 'rpcevents') {
  1462. if ($ccuflags =~ /(extrpc|procrpc)/) {
  1463. # my ($rpcdev, $save) = HMCCU_GetRPCDevice ($hash, 0, undef);
  1464. # return HMCCU_SetError ($hash, "HMCCU: External RPC server not found") if ($rpcdev eq '');
  1465. # $result = AnalyzeCommandChain (undef, "get $rpcdev rpcevents");
  1466. # return HMCCU_SetState ($hash, "OK", $result) if (defined ($result));
  1467. # return HMCCU_SetError ($hash, "No event statistics available");
  1468. # }
  1469. # elsif ($ccuflags =~ /procrpc/) {
  1470. $result = '';
  1471. my @iflist = HMCCU_GetRPCInterfaceList ($hash);
  1472. foreach my $ifname (@iflist) {
  1473. my ($rpcdev, $save) = HMCCU_GetRPCDevice ($hash, 0, $ifname);
  1474. if ($rpcdev eq '') {
  1475. Log3 $name, 2, "HMCCU: Can't find HMCCURPCPROC device for interface $ifname";
  1476. next;
  1477. }
  1478. my $res = AnalyzeCommandChain (undef, "get $rpcdev rpcevents");
  1479. $result .= $res if (defined ($result));
  1480. }
  1481. return HMCCU_SetState ($hash, "OK", $result) if ($result ne '');
  1482. return HMCCU_SetError ($hash, "No event statistics available");
  1483. }
  1484. else {
  1485. return HMCCU_SetError ($hash, "No event statistics available")
  1486. if (!exists ($hash->{hmccu}{evs}) || !exists ($hash->{hmccu}{evr}));
  1487. foreach my $stkey (sort keys %{$hash->{hmccu}{evr}}) {
  1488. $result .= "S: ".$stkey." = ".$hash->{hmccu}{evs}{$stkey}."\n";
  1489. $result .= "R: ".$stkey." = ".$hash->{hmccu}{evr}{$stkey}."\n";
  1490. }
  1491. return HMCCU_SetState ($hash, "OK", $result);
  1492. }
  1493. }
  1494. elsif ($opt eq 'rpcstate') {
  1495. my @hm_pids = ();
  1496. my @hm_tids = ();
  1497. $result = "No RPC processes or threads are running";
  1498. if (HMCCU_IsRPCServerRunning ($hash, \@hm_pids, \@hm_tids)) {
  1499. $result = "RPC process(es) running with pid(s) ".
  1500. join (',', @hm_pids) if (scalar (@hm_pids) > 0);
  1501. $result = "RPC thread(s) running with tid(s) ".
  1502. join (',', @hm_tids) if (scalar (@hm_tids) > 0);
  1503. }
  1504. return HMCCU_SetState ($hash, "OK", $result);
  1505. }
  1506. elsif ($opt eq 'devicelist') {
  1507. my ($devcount, $chncount, $ifcount, $prgcount, $gcount) = HMCCU_GetDeviceList ($hash);
  1508. return HMCCU_SetError ($hash, -2) if ($devcount < 0);
  1509. return HMCCU_SetError ($hash, "No devices received from CCU") if ($devcount == 0);
  1510. $result = "Read $devcount devices with $chncount channels from CCU";
  1511. my $optcmd = shift @$a;
  1512. if (defined ($optcmd)) {
  1513. if ($optcmd eq 'dump') {
  1514. $result .= "\n-----------------------------------------\n";
  1515. my $n = 0;
  1516. foreach my $add (sort keys %{$hash->{hmccu}{dev}}) {
  1517. if ($hash->{hmccu}{dev}{$add}{addtype} eq 'dev') {
  1518. $result .= "Device ".'"'.$hash->{hmccu}{dev}{$add}{name}.'"'." [".$add."] ".
  1519. "Type=".$hash->{hmccu}{dev}{$add}{type}."\n";
  1520. $n = 0;
  1521. }
  1522. else {
  1523. $result .= " Channel $n ".'"'.$hash->{hmccu}{dev}{$add}{name}.'"'.
  1524. " [".$add."]\n";
  1525. $n++;
  1526. }
  1527. }
  1528. return $result;
  1529. }
  1530. elsif ($optcmd eq 'create') {
  1531. $usage = "Usage: get $name create {devexp|chnexp} [t={'chn'|'dev'|'all'}] [s=suffix] ".
  1532. "[p=prefix] [f=format] ['defattr'] ['duplicates'] [save] [attr=val [...]]";
  1533. my $devdefaults = 0;
  1534. my $duplicates = 0;
  1535. my $savedef = 0;
  1536. my $newcount = 0;
  1537. # Process command line parameters
  1538. my $devspec = shift @$a;
  1539. my $devprefix = exists ($h->{p}) ? $h->{p} : '';
  1540. my $devsuffix = exists ($h->{'s'}) ? $h->{'s'} : '';
  1541. my $devtype = exists ($h->{t}) ? $h->{t} : 'dev';
  1542. my $devformat = exists ($h->{f}) ? $h->{f} : '%n';
  1543. return HMCCU_SetError ($hash, $usage)
  1544. if ($devtype !~ /^(dev|chn|all)$/ || !defined ($devspec));
  1545. foreach my $defopt (@$a) {
  1546. if ($defopt eq 'defattr') { $devdefaults = 1; }
  1547. elsif ($defopt eq 'duplicates') { $duplicates = 1; }
  1548. elsif ($defopt eq 'save') { $savedef = 1; }
  1549. else { return HMCCU_SetError ($hash, $usage); }
  1550. }
  1551. # Get list of existing client devices
  1552. my @devlist = HMCCU_FindClientDevices ($hash, "(HMCCUDEV|HMCCUCHN)", undef, undef);
  1553. foreach my $add (sort keys %{$hash->{hmccu}{dev}}) {
  1554. my $defmod = $hash->{hmccu}{dev}{$add}{addtype} eq 'dev' ? 'HMCCUDEV' : 'HMCCUCHN';
  1555. my $ccuname = $hash->{hmccu}{dev}{$add}{name};
  1556. my $ccudevname = HMCCU_GetDeviceName ($hash, $add, $ccuname);
  1557. next if ($devtype ne 'all' && $devtype ne $hash->{hmccu}{dev}{$add}{addtype});
  1558. next if (HMCCU_ExprNotMatch ($ccuname, $devspec, 1));
  1559. # Build FHEM device name
  1560. my $devname = $devformat;
  1561. $devname = $devprefix.$devname.$devsuffix;
  1562. $devname =~ s/%n/$ccuname/g;
  1563. $devname =~ s/%d/$ccudevname/g;
  1564. $devname =~ s/%a/$add/g;
  1565. $devname =~ s/[^A-Za-z\d_\.]+/_/g;
  1566. # Check for duplicate device definitions
  1567. if (!$duplicates) {
  1568. next if (exists ($defs{$devname}));
  1569. my $devexists = 0;
  1570. foreach my $exdev (@devlist) {
  1571. if ($defs{$exdev}->{ccuaddr} eq $add) {
  1572. $devexists = 1;
  1573. last;
  1574. }
  1575. }
  1576. next if ($devexists);
  1577. }
  1578. # Define new client device
  1579. my $ret = CommandDefine (undef, $devname." $defmod ".$add);
  1580. if ($ret) {
  1581. Log3 $name, 2, "HMCCU: Define command failed $devname $defmod $ccuname";
  1582. Log3 $name, 2, "$defmod: $ret";
  1583. $result .= "\nCan't create device $devname. $ret";
  1584. next;
  1585. }
  1586. # Set device attributes
  1587. HMCCU_SetDefaults ($defs{$devname}) if ($devdefaults);
  1588. foreach my $da (keys %$h) {
  1589. next if ($da =~ /^[pstf]$/);
  1590. $ret = CommandAttr (undef, "$devname $da ".$h->{$da});
  1591. if ($ret) {
  1592. Log3 $name, 2, "HMCCU: Attr command failed $devname $da ".$h->{$da};
  1593. Log3 $name, 2, "$defmod: $ret";
  1594. }
  1595. }
  1596. Log3 $name, 2, "$defmod: Created device $devname";
  1597. $result .= "\nCreated device $devname";
  1598. $newcount++;
  1599. }
  1600. CommandSave (undef, undef) if ($newcount > 0 && $savedef);
  1601. $result .= "\nCreated $newcount client devices";
  1602. }
  1603. }
  1604. return HMCCU_SetState ($hash, "OK", $result);
  1605. }
  1606. elsif ($opt eq 'dutycycle') {
  1607. my $dc = HMCCU_GetDutyCycle ($hash);
  1608. return HMCCU_SetState ($hash, "OK", "Read $dc duty cycle values");
  1609. }
  1610. elsif ($opt eq 'firmware') {
  1611. my $devtype = shift @$a;
  1612. $devtype = '.*' if (!defined ($devtype));
  1613. my $dtexp = $devtype;
  1614. $dtexp = '.*' if ($devtype eq 'full');
  1615. my $dc = HMCCU_GetFirmwareVersions ($hash, $dtexp);
  1616. return "Found no firmware downloads" if ($dc == 0);
  1617. $result = "Found $dc firmware downloads. Click on the new version number for download\n\n";
  1618. if ($devtype eq 'full') {
  1619. $result .=
  1620. "Type Available Date\n".
  1621. "-----------------------------------------\n";
  1622. foreach my $ct (keys %{$hash->{hmccu}{type}}) {
  1623. $result .= sprintf "%-20s <a href=\"http://www.eq-3.de/%s\">%-9s</a> %-10s\n",
  1624. $ct, $hash->{hmccu}{type}{$ct}{download},
  1625. $hash->{hmccu}{type}{$ct}{firmware}, $hash->{hmccu}{type}{$ct}{date};
  1626. }
  1627. }
  1628. else {
  1629. my @devlist = HMCCU_FindClientDevices ($hash, "(HMCCUDEV|HMCCUCHN)", undef, undef);
  1630. return $result if (scalar (@devlist) == 0);
  1631. $result .=
  1632. "Device Type Current Available Date\n".
  1633. "---------------------------------------------------------------------------\n";
  1634. foreach my $dev (@devlist) {
  1635. my $ch = $defs{$dev};
  1636. my $ct = uc($ch->{ccutype});
  1637. my $fw = defined ($ch->{firmware}) ? $ch->{firmware} : 'N/A';
  1638. next if (!exists ($hash->{hmccu}{type}{$ct}) || $ct !~ /$dtexp/);
  1639. $result .= sprintf "%-25s %-20s %-7s <a href=\"http://www.eq-3.de/%s\">%-9s</a> %-10s\n",
  1640. $ch->{NAME}, $ct, $fw, $hash->{hmccu}{type}{$ct}{download},
  1641. $hash->{hmccu}{type}{$ct}{firmware}, $hash->{hmccu}{type}{$ct}{date};
  1642. }
  1643. }
  1644. return HMCCU_SetState ($hash, "OK", $result);
  1645. }
  1646. elsif ($opt eq 'defaults') {
  1647. $result = HMCCU_GetDefaults ($hash, 1);
  1648. return HMCCU_SetState ($hash, "OK", $result);
  1649. }
  1650. elsif ($opt eq 'exportdefaults') {
  1651. my $filename = shift @$a;
  1652. $usage = "Usage: get $name $opt filename";
  1653. return HMCCU_SetError ($hash, $usage) if (!defined ($filename));
  1654. my $rc = HMCCU_ExportDefaults ($filename);
  1655. return HMCCU_SetError ($hash, -16) if ($rc == 0);
  1656. return HMCCU_SetState ($hash, "OK", "Default attributes written to $filename");
  1657. }
  1658. elsif ($opt eq 'aggregation') {
  1659. my $rule = shift @$a;
  1660. $usage = "Usage: get $name $opt {'all'|'rule'}";
  1661. return HMCCU_SetError ($hash, $usage) if (!defined ($rule));
  1662. if ($rule eq 'all') {
  1663. foreach my $r (keys %{$hash->{hmccu}{agg}}) {
  1664. my $rc = HMCCU_AggregateReadings ($hash, $r);
  1665. $result .= "$r = $rc\n";
  1666. }
  1667. }
  1668. else {
  1669. return HMCCU_SetError ($hash, "HMCCU: Aggregation rule does not exist")
  1670. if (!exists ($hash->{hmccu}{agg}{$rule}));
  1671. $result = HMCCU_AggregateReadings ($hash, $rule);
  1672. $result = "$rule = $result";
  1673. }
  1674. return HMCCU_SetState ($hash, "OK", $ccureadings ? undef : $result);
  1675. }
  1676. elsif ($opt eq 'configdesc') {
  1677. my $ccuobj = shift @$a;
  1678. $usage = "Usage: get $name $opt {device|channel}";
  1679. return HMCCU_SetError ($hash, $usage) if (!defined ($ccuobj));
  1680. my ($rc, $res) = HMCCU_RPCGetConfig ($hash, $ccuobj, "getParamsetDescription", undef);
  1681. return HMCCU_SetError ($hash, $rc) if ($rc < 0);
  1682. return HMCCU_SetState ($hash, "OK", $res);
  1683. }
  1684. else {
  1685. if (exists ($hash->{hmccu}{agg})) {
  1686. my @rules = keys %{$hash->{hmccu}{agg}};
  1687. $usage .= " aggregation:all,".join (',', @rules) if (scalar (@rules) > 0);
  1688. }
  1689. return $usage;
  1690. }
  1691. }
  1692. ######################################################################
  1693. # Parse CCU object specification.
  1694. #
  1695. # Supported address types:
  1696. # Classic Homematic and Homematic-IP addresses.
  1697. # Team addresses with leading * for BidCos-RF.
  1698. # CCU virtual remote addresses (BidCoS:ChnNo)
  1699. # OSRAM lightify addresses (OL-...)
  1700. # Homematic virtual layer addresses (if known by HMCCU)
  1701. #
  1702. # Possible syntax for datapoints:
  1703. # Interface.Address:Channel.Datapoint
  1704. # Address:Channel.Datapoint
  1705. # Channelname.Datapoint
  1706. #
  1707. # Possible syntax for channels:
  1708. # Interface.Address:Channel
  1709. # Address:Channel
  1710. # Channelname
  1711. #
  1712. # If object name doesn't match the rules above it's treated as name.
  1713. # With parameter flags one can specify if result is filled up with
  1714. # default values for interface or datapoint.
  1715. #
  1716. # Return list of detected attributes (empty string if attribute is
  1717. # not detected):
  1718. # (Interface, Address, Channel, Datapoint, Name, Flags)
  1719. # Flags is a bitmask of detected attributes.
  1720. ######################################################################
  1721. sub HMCCU_ParseObject ($$$)
  1722. {
  1723. my ($hash, $object, $flags) = @_;
  1724. my ($i, $a, $c, $d, $n, $f) = ('', '', '', '', '', '', 0);
  1725. my $extaddr;
  1726. # Check if address is already known by HMCCU. Substitute device address by ZZZ0000000
  1727. # to allow external addresses like HVL
  1728. if ($object =~ /^.+\.(.+):[0-9]{1,2}\..+$/ ||
  1729. $object =~ /^.+\.(.+):[0-9]{1,2}$/ ||
  1730. $object =~ /^(.+):[0-9]{1,2}\..+$/ ||
  1731. $object =~ /^(.+):[0-9]{1,2}$/ ||
  1732. $object =~ /^(.+)$/) {
  1733. $extaddr = $1;
  1734. if (!HMCCU_IsDevAddr ($extaddr, 0) &&
  1735. exists ($hash->{hmccu}{dev}{$extaddr}) && $hash->{hmccu}{dev}{$extaddr}{valid}) {
  1736. $object =~ s/$extaddr/$HMCCU_EXT_ADDR/;
  1737. }
  1738. }
  1739. if ($object =~ /^(.+?)\.([\*]*[A-Z]{3}[0-9]{7}):([0-9]{1,2})\.(.+)$/ ||
  1740. $object =~ /^(.+?)\.([0-9A-F]{12,14}):([0-9]{1,2})\.(.+)$/ ||
  1741. $object =~ /^(.+?)\.(OL-.+):([0-9]{1,2})\.(.+)$/ ||
  1742. $object =~ /^(.+?)\.(BidCoS-RF):([0-9]{1,2})\.(.+)$/) {
  1743. #
  1744. # Interface.Address:Channel.Datapoint [30=11110]
  1745. #
  1746. $f = $HMCCU_FLAGS_IACD;
  1747. ($i, $a, $c, $d) = ($1, $2, $3, $4);
  1748. }
  1749. elsif ($object =~ /^(.+)\.([\*]*[A-Z]{3}[0-9]{7}):([0-9]{1,2})$/ ||
  1750. $object =~ /^(.+)\.([0-9A-F]{12,14}):([0-9]{1,2})$/ ||
  1751. $object =~ /^(.+)\.(OL-.+):([0-9]{1,2})$/ ||
  1752. $object =~ /^(.+)\.(BidCoS-RF):([0-9]{1,2})$/) {
  1753. #
  1754. # Interface.Address:Channel [26=11010]
  1755. #
  1756. $f = $HMCCU_FLAGS_IAC | ($flags & $HMCCU_FLAG_DATAPOINT);
  1757. ($i, $a, $c, $d) = ($1, $2, $3, $flags & $HMCCU_FLAG_DATAPOINT ? '.*' : '');
  1758. }
  1759. elsif ($object =~ /^([\*]*[A-Z]{3}[0-9]{7}):([0-9]{1,2})\.(.+)$/ ||
  1760. $object =~ /^([0-9A-F]{12,14}):([0-9]{1,2})\.(.+)$/ ||
  1761. $object =~ /^(OL-.+):([0-9]{1,2})\.(.+)$/ ||
  1762. $object =~ /^(BidCoS-RF):([0-9]{1,2})\.(.+)$/) {
  1763. #
  1764. # Address:Channel.Datapoint [14=01110]
  1765. #
  1766. $f = $HMCCU_FLAGS_ACD;
  1767. ($a, $c, $d) = ($1, $2, $3);
  1768. }
  1769. elsif ($object =~ /^([\*]*[A-Z]{3}[0-9]{7}):([0-9]{1,2})$/ ||
  1770. $object =~ /^([0-9A-Z]{12,14}):([0-9]{1,2})$/ ||
  1771. $object =~ /^(OL-.+):([0-9]{1,2})$/ ||
  1772. $object =~ /^(BidCoS-RF):([0-9]{1,2})$/) {
  1773. #
  1774. # Address:Channel [10=01010]
  1775. #
  1776. $f = $HMCCU_FLAGS_AC | ($flags & $HMCCU_FLAG_DATAPOINT);
  1777. ($a, $c, $d) = ($1, $2, $flags & $HMCCU_FLAG_DATAPOINT ? '.*' : '');
  1778. }
  1779. elsif ($object =~ /^([\*]*[A-Z]{3}[0-9]{7})$/ ||
  1780. $object =~ /^([0-9A-Z]{12,14})$/ ||
  1781. $object =~ /^(OL-.+)$/ ||
  1782. $object eq 'BidCoS') {
  1783. #
  1784. # Address
  1785. #
  1786. $f = $HMCCU_FLAG_ADDRESS;
  1787. $a = $1;
  1788. }
  1789. elsif ($object =~ /^(.+?)\.([A-Z_]+)$/) {
  1790. #
  1791. # Name.Datapoint
  1792. #
  1793. $f = $HMCCU_FLAGS_ND;
  1794. ($n, $d) = ($1, $2);
  1795. }
  1796. elsif ($object =~ /^.+$/) {
  1797. #
  1798. # Name [1=00001]
  1799. #
  1800. $f = $HMCCU_FLAG_NAME | ($flags & $HMCCU_FLAG_DATAPOINT);
  1801. ($n, $d) = ($object, $flags & $HMCCU_FLAG_DATAPOINT ? '.*' : '');
  1802. }
  1803. else {
  1804. $f = 0;
  1805. }
  1806. # Restore external address (i.e. HVL device address)
  1807. $a = $extaddr if ($a eq $HMCCU_EXT_ADDR);
  1808. # Check if name is a valid channel name
  1809. if ($f & $HMCCU_FLAG_NAME) {
  1810. my ($add, $chn) = HMCCU_GetAddress ($hash, $n, '', '');
  1811. if ($chn ne '') {
  1812. $f = $f | $HMCCU_FLAG_CHANNEL;
  1813. }
  1814. if ($flags & $HMCCU_FLAG_FULLADDR) {
  1815. ($i, $a, $c) = (HMCCU_GetDeviceInterface ($hash, $add, 'BidCos-RF'), $add, $chn);
  1816. $f |= $HMCCU_FLAG_INTERFACE;
  1817. $f |= $HMCCU_FLAG_ADDRESS if ($add ne '');
  1818. $f |= $HMCCU_FLAG_CHANNEL if ($chn ne '');
  1819. }
  1820. }
  1821. elsif ($f & $HMCCU_FLAG_ADDRESS && $i eq '' &&
  1822. ($flags & $HMCCU_FLAG_FULLADDR || $flags & $HMCCU_FLAG_INTERFACE)) {
  1823. $i = HMCCU_GetDeviceInterface ($hash, $a, 'BidCos-RF');
  1824. $f |= $HMCCU_FLAG_INTERFACE;
  1825. }
  1826. return ($i, $a, $c, $d, $n, $f);
  1827. }
  1828. ######################################################################
  1829. # Filter reading by datapoint and optionally by channel name or
  1830. # channel address.
  1831. # Parameter channel can be a channel name or a channel address without
  1832. # interface specification.
  1833. # Filter rule syntax is either:
  1834. # [N:]{Channel-Number|Channel-Name-Expr}!Datapoint-Expr
  1835. # or
  1836. # [N:][Channel-Number.]Datapoint-Expr
  1837. # Multiple filter rules must be separated by ;
  1838. ######################################################################
  1839. sub HMCCU_FilterReading ($$$)
  1840. {
  1841. my ($hash, $chn, $dpt) = @_;
  1842. my $name = $hash->{NAME};
  1843. my $fnc = "FilterReading";
  1844. my $hmccu_hash = HMCCU_GetHash ($hash);
  1845. return 1 if (!defined ($hmccu_hash));
  1846. my $grf = AttrVal ($hmccu_hash->{NAME}, 'ccudef-readingfilter', '.*');
  1847. # $grf = '.*' if ($grf eq '');
  1848. my $rf = AttrVal ($name, 'ccureadingfilter', $grf);
  1849. # $rf = $grf.";".$rf if ($rf ne $grf && $grf ne '.*' && $grf ne '');
  1850. $rf = $grf.";".$rf if ($rf ne $grf && $grf ne '.*');
  1851. my $chnnam = '';
  1852. my $chnnum = '';
  1853. my $devadd = '';
  1854. # Get channel name and channel number
  1855. if (HMCCU_IsValidChannel ($hmccu_hash, $chn, $HMCCU_FL_ADDRESS)) {
  1856. $chnnam = HMCCU_GetChannelName ($hmccu_hash, $chn, '');
  1857. ($devadd, $chnnum) = HMCCU_SplitChnAddr ($chn);
  1858. }
  1859. else {
  1860. ($devadd, $chnnum) = HMCCU_GetAddress ($hash, $chn, '', '');
  1861. $chnnam = $chn;
  1862. }
  1863. HMCCU_Trace ($hash, 2, $fnc, "chn=$chn, chnnam=$chnnam chnnum=$chnnum dpt=$dpt, rules=$rf");
  1864. foreach my $r (split (';', $rf)) {
  1865. my $rm = 1;
  1866. my $cn = '';
  1867. # Negative filter
  1868. if ($r =~ /^N:/) {
  1869. $rm = 0;
  1870. $r =~ s/^N://;
  1871. }
  1872. # Get filter criteria
  1873. my ($c, $f) = split ("!", $r);
  1874. if (defined ($f)) {
  1875. next if ($c eq '' || $chnnam eq '' || $chnnum eq '');
  1876. $cn = $c if ($c =~ /^([0-9]{1,2})$/);
  1877. }
  1878. else {
  1879. $c = '';
  1880. if ($r =~ /^([0-9]{1,2})\.(.+)$/) {
  1881. $cn = $1;
  1882. $f = $2;
  1883. }
  1884. else {
  1885. $cn = '';
  1886. $f = $r;
  1887. }
  1888. }
  1889. HMCCU_Trace ($hash, 2, undef, " check rm=$rm f=$f cn=$cn c=$c");
  1890. # Positive filter
  1891. return 1 if (
  1892. $rm && (
  1893. (
  1894. ($cn ne '' && "$chnnum" eq "$cn") ||
  1895. ($c ne '' && $chnnam =~ /$c/) ||
  1896. ($cn eq '' && $c eq '')
  1897. ) && $dpt =~ /$f/
  1898. )
  1899. );
  1900. # Negate filter
  1901. return 1 if (
  1902. !$rm && (
  1903. ($cn ne '' && "$chnnum" ne "$cn") ||
  1904. ($c ne '' && $chnnam !~ /$c/) ||
  1905. $dpt !~ /$f/
  1906. )
  1907. );
  1908. HMCCU_Trace ($hash, 2, undef, " check result false");
  1909. }
  1910. return 0;
  1911. }
  1912. ######################################################################
  1913. # Build reading name
  1914. #
  1915. # Parameters:
  1916. #
  1917. # Interface,Address,ChannelNo,Datapoint,ChannelNam,ReadingFormat
  1918. # ReadingFormat := { name[lc] | datapoint[lc] | address[lc] }
  1919. #
  1920. # Valid combinations:
  1921. #
  1922. # ChannelName,Datapoint
  1923. # Address,Datapoint
  1924. # Address,ChannelNo,Datapoint
  1925. #
  1926. # Reading names can be modified by setting attribut ccureadingname.
  1927. # Returns list of readings names.
  1928. ######################################################################
  1929. sub HMCCU_GetReadingName ($$$$$$$)
  1930. {
  1931. my ($hash, $i, $a, $c, $d, $n, $rf) = @_;
  1932. my $name = $hash->{NAME};
  1933. my $hmccu_hash = HMCCU_GetHash ($hash);
  1934. return '' if (!defined ($hmccu_hash));
  1935. my $rn = '';
  1936. my @rnlist;
  1937. Log3 $name, 1, "HMCCU: ChannelNo undefined: Addr=".$a if (!defined ($c));
  1938. $rf = HMCCU_GetAttrReadingFormat ($hash, $hmccu_hash) if (!defined ($rf));
  1939. my $gsr = AttrVal ($hmccu_hash->{NAME}, 'ccudef-readingname', '');
  1940. my $sr = AttrVal ($name, 'ccureadingname', $gsr);
  1941. $sr .= ";".$gsr if ($sr ne $gsr && $gsr ne '');
  1942. # Datapoint is mandatory
  1943. return '' if ($d eq '');
  1944. if ($rf eq 'datapoint' || $rf eq 'datapointlc') {
  1945. $rn = (defined ($c) && $c ne '') ? $c.'.'.$d : $d;
  1946. }
  1947. elsif ($rf eq 'name' || $rf eq 'namelc') {
  1948. if ($n eq '') {
  1949. if ($a ne '' && $c ne '') { $n = HMCCU_GetChannelName ($hmccu_hash, $a.':'.$c, ''); }
  1950. elsif ($a ne '' && $c eq '') { $n = HMCCU_GetDeviceName ($hmccu_hash, $a, ''); }
  1951. else { return ''; }
  1952. }
  1953. # Substitue unsupported characters in reading name
  1954. $n = HMCCU_CorrectName ($n);
  1955. return '' if ($n eq '');
  1956. $rn = $n.'.'.$d;
  1957. }
  1958. elsif ($rf eq 'address' || $rf eq 'addresslc') {
  1959. if ($a eq '' && $n ne '') {
  1960. ($a, $c) = HMCCU_GetAddress ($hmccu_hash, $n, '', '');
  1961. }
  1962. if ($a ne '') {
  1963. my $t = $a;
  1964. $i = HMCCU_GetDeviceInterface ($hmccu_hash, $a, '') if ($i eq '');
  1965. $t = $i.'.'.$t if ($i ne '');
  1966. $t = $t.'.'.$c if ($c ne '');
  1967. $rn = $t.'.'.$d;
  1968. }
  1969. }
  1970. push (@rnlist, $rn);
  1971. # Rename and/or add reading names
  1972. if ($sr ne '') {
  1973. my @rules = split (';', $sr);
  1974. foreach my $rr (@rules) {
  1975. my ($rold, $rnew) = split (':', $rr);
  1976. next if (!defined ($rnew));
  1977. if ($rnlist[0] =~ /$rold/) {
  1978. if ($rnew =~ /^\+(.+)$/) {
  1979. my $radd = $1;
  1980. $radd =~ s/$rold/$radd/;
  1981. push (@rnlist, $radd);
  1982. }
  1983. else {
  1984. $rnlist[0] =~ s/$rold/$rnew/;
  1985. }
  1986. }
  1987. }
  1988. }
  1989. # Convert to lowercase
  1990. $rnlist[0] = lc($rnlist[0]) if ($rf =~ /lc$/);
  1991. return @rnlist;
  1992. }
  1993. ######################################################################
  1994. # Format reading value depending on attribute stripnumber.
  1995. # Syntax of attribute stripnumber:
  1996. # [datapoint-expr!]format[;...]
  1997. # Valid formats:
  1998. # 0 = Remove all digits
  1999. # 1 = Preserve 1 digit
  2000. # 2 = Remove trailing zeroes
  2001. # -n = Round value to specified number of digits (-0 is allowed)
  2002. # %f = Format for numbers. String suffix is allowed.
  2003. ######################################################################
  2004. sub HMCCU_FormatReadingValue ($$$)
  2005. {
  2006. my ($hash, $value, $dpt) = @_;
  2007. my $stripnumber = AttrVal ($hash->{NAME}, 'stripnumber', 'null');
  2008. return $value if ($stripnumber eq 'null' || $value !~ /^[+-]?\d*\.?\d+(?:(?:e|E)\d+)?$/);
  2009. my $isint = $value =~ /^[+-]?[0-9]+$/ ? 1 : 0;
  2010. foreach my $sr (split (';', $stripnumber)) {
  2011. my ($d, $s) = split ('!', $sr);
  2012. if (defined ($s)) {
  2013. next if ($d eq '' || $dpt !~ /$d/);
  2014. }
  2015. else {
  2016. $s = $sr;
  2017. }
  2018. if ($s eq '0' && !$isint) { return sprintf ("%d", $value); }
  2019. elsif ($s eq '1' && !$isint) { return sprintf ("%.1f", $value); }
  2020. elsif ($s eq '2' && !$isint) { return sprintf ("%g", $value); }
  2021. elsif ($s =~ /^-([0-9])$/ && !$isint) { my $f = '%.'.$1.'f'; return sprintf ($f, $value); }
  2022. elsif ($s =~ /^%.+$/) { return sprintf ($s, $value); }
  2023. }
  2024. return $value;
  2025. }
  2026. ######################################################################
  2027. # Log message if trace flag is set.
  2028. # Will output multiple log file entries if parameter msg is separated
  2029. # by <br>
  2030. ######################################################################
  2031. sub HMCCU_Trace ($$$$)
  2032. {
  2033. my ($hash, $level, $fnc, $msg) = @_;
  2034. my $name = $hash->{NAME};
  2035. my $type = $hash->{TYPE};
  2036. return if (!HMCCU_IsFlag ($name, "trace"));
  2037. foreach my $m (split ("<br>", $msg)) {
  2038. $m = "$fnc: $m" if (defined ($fnc) && $fnc ne '');
  2039. Log3 $name, $level, "$type: $m";
  2040. }
  2041. }
  2042. ######################################################################
  2043. # Log message and return parameter rc.
  2044. ######################################################################
  2045. sub HMCCU_Log ($$$$)
  2046. {
  2047. my ($hash, $level, $msg, $rc) = @_;
  2048. my $name = "n/a";
  2049. my $type = "n/a";
  2050. $name = $hash->{NAME} if (exists ($hash->{NAME}));
  2051. $type = $hash->{TYPE} if (exists ($hash->{TYPE}));
  2052. Log3 $name, $level, "$type: [$name] $msg";
  2053. return $rc;
  2054. }
  2055. ######################################################################
  2056. # Set error state and write log file message
  2057. # Parameter text can be an error code (integer < 0) or an error text.
  2058. # Parameter addinfo is optional.
  2059. ######################################################################
  2060. sub HMCCU_SetError ($@)
  2061. {
  2062. my ($hash, $text, $addinfo) = @_;
  2063. my $name = $hash->{NAME};
  2064. my $type = $hash->{TYPE};
  2065. my $msg;
  2066. my %errlist = (
  2067. -1 => 'Invalid device/channel name or address',
  2068. -2 => 'Execution of CCU script or command failed',
  2069. -3 => 'Cannot detect IO device',
  2070. -4 => 'Device deleted in CCU',
  2071. -5 => 'No response from CCU',
  2072. -6 => 'Update of readings disabled. Set attribute ccureadings first',
  2073. -7 => 'Invalid channel number',
  2074. -8 => 'Invalid datapoint',
  2075. -9 => 'Interface does not support RPC calls',
  2076. -10 => 'No readable datapoints found',
  2077. -11 => 'No state channel defined',
  2078. -12 => 'No control channel defined',
  2079. -13 => 'No state datapoint defined',
  2080. -14 => 'No control datapoint defined',
  2081. -15 => 'No state values defined',
  2082. -16 => 'Cannot open file',
  2083. -17 => 'Cannot detect or create external RPC device',
  2084. -18 => 'Type of system variable not supported',
  2085. -19 => 'Device not initialized'
  2086. );
  2087. $msg = exists ($errlist{$text}) ? $errlist{$text} : $text;
  2088. $msg = $type.": ".$name." ". $msg;
  2089. if (defined ($addinfo) && $addinfo ne '') {
  2090. $msg .= ". $addinfo";
  2091. }
  2092. Log3 $name, 1, $msg;
  2093. return HMCCU_SetState ($hash, "Error", $msg);
  2094. }
  2095. ######################################################################
  2096. # Set state of device if attribute ccuflags = ackState
  2097. ######################################################################
  2098. sub HMCCU_SetState ($@)
  2099. {
  2100. my ($hash, $text, $retval) = @_;
  2101. my $name = $hash->{NAME};
  2102. my $ccuflags = HMCCU_GetFlags ($name);
  2103. $ccuflags .= ',ackState' if ($hash->{TYPE} eq 'HMCCU' && $ccuflags !~ /ackState/);
  2104. if (defined ($hash) && defined ($text) && $ccuflags =~ /ackState/) {
  2105. readingsSingleUpdate ($hash, 'state', $text, 1)
  2106. if (ReadingsVal ($name, 'state', '') ne $text);
  2107. }
  2108. return $retval;
  2109. }
  2110. ######################################################################
  2111. # Set state of RPC server. Update all client devices if overall state
  2112. # is 'running'.
  2113. # Parameters iface and msg are optional. If iface is set function
  2114. # was called by HMCCURPCPROC device.
  2115. ######################################################################
  2116. sub HMCCU_SetRPCState ($@)
  2117. {
  2118. my ($hash, $state, $iface, $msg) = @_;
  2119. my $name = $hash->{NAME};
  2120. my $ccuflags = HMCCU_GetFlags ($name);
  2121. my $filter;
  2122. my $rpcstate = $state;
  2123. if ($ccuflags =~ /intrpc/ || $ccuflags !~ /(intrpc|extrpc|procrpc)/) {
  2124. if ($state ne $hash->{RPCState}) {
  2125. $hash->{RPCState} = $state;
  2126. readingsSingleUpdate ($hash, "rpcstate", $state, 1);
  2127. HMCCU_Log ($hash, 4, "Set rpcstate to $state", undef);
  2128. HMCCU_Log ($hash, 1, $msg, undef) if (defined ($msg));
  2129. HMCCU_Log ($hash, 1, "All RPC servers $state", undef);
  2130. DoTrigger ($name, "RPC server $state");
  2131. if ($state eq 'running') {
  2132. my ($c_ok, $c_err) = HMCCU_UpdateClients ($hash, '.*', 'Attr', 0, $filter);
  2133. HMCCU_Log ($hash, 2, "Updated devices. Success=$c_ok Failed=$c_err", undef);
  2134. }
  2135. }
  2136. }
  2137. elsif (defined ($iface) && $ccuflags =~ /(procrpc|extrpc)/) {
  2138. # Set interface state
  2139. my $ifname = HMCCU_GetRPCServerInfo ($hash, $iface, 'name');
  2140. $hash->{hmccu}{interfaces}{$ifname}{state} = $state if (defined ($ifname));
  2141. # Count number of processes in state running, error or inactive
  2142. # Prepare filter for updating client devices
  2143. my %stc = ("running" => 0, "error" => 0, "inactive" => 0);
  2144. my @iflist = HMCCU_GetRPCInterfaceList ($hash);
  2145. foreach my $i (@iflist) {
  2146. my $st = $hash->{hmccu}{interfaces}{$i}{state};
  2147. $stc{$st}++ if (exists ($stc{$st}));
  2148. if ($hash->{hmccu}{interfaces}{$i}{manager} eq 'HMCCU') {
  2149. $filter = defined ($filter) ? "$filter|$i" : $i;
  2150. }
  2151. }
  2152. # Determine overall process state
  2153. my $rpcstate = 'null';
  2154. $rpcstate = "running" if ($stc{"running"} == scalar (@iflist));
  2155. $rpcstate = "inactive" if ($stc{"inactive"} == scalar (@iflist));
  2156. $rpcstate = "error" if ($stc{"error"} == scalar (@iflist));
  2157. if ($rpcstate =~ /^(running|inactive|error)$/) {
  2158. if ($rpcstate ne $hash->{RPCState}) {
  2159. $hash->{RPCState} = $rpcstate;
  2160. readingsSingleUpdate ($hash, "rpcstate", $rpcstate, 1);
  2161. HMCCU_Log ($hash, 4, "Set rpcstate to $rpcstate", undef);
  2162. HMCCU_Log ($hash, 1, $msg, undef) if (defined ($msg));
  2163. HMCCU_Log ($hash, 1, "All RPC servers $rpcstate", undef);
  2164. DoTrigger ($name, "RPC server $rpcstate");
  2165. if ($rpcstate eq 'running') {
  2166. my ($c_ok, $c_err) = HMCCU_UpdateClients ($hash, '.*', 'Attr', 0, $filter);
  2167. HMCCU_Log ($hash, 2, "Updated devices. Success=$c_ok Failed=$c_err", undef);
  2168. }
  2169. }
  2170. }
  2171. }
  2172. # Set I/O device state
  2173. if ($rpcstate eq 'running' || $rpcstate eq 'inactive') {
  2174. HMCCU_SetState ($hash, "OK");
  2175. }
  2176. elsif ($rpcstate eq 'error') {
  2177. HMCCU_SetState ($hash, "error");
  2178. }
  2179. else {
  2180. HMCCU_SetState ($hash, "busy");
  2181. }
  2182. return undef;
  2183. }
  2184. ######################################################################
  2185. # Substitute first occurrence of regular expression or fixed string.
  2186. # Floating point values are ignored without datapoint specification.
  2187. # Integer values are compared with complete value.
  2188. # mode: 0=Substitute regular expression, 1=Substitute text
  2189. ######################################################################
  2190. sub HMCCU_Substitute ($$$$$)
  2191. {
  2192. my ($value, $substrule, $mode, $chn, $dpt) = @_;
  2193. my $rc = 0;
  2194. my $newvalue;
  2195. return $value if (!defined ($substrule) || $substrule eq '');
  2196. # Remove channel number from datapoint if specified
  2197. if ($dpt =~ /^([0-9]{1,2})\.(.+)$/) {
  2198. ($chn, $dpt) = ($1, $2);
  2199. }
  2200. my @rulelist = split (';', $substrule);
  2201. foreach my $rule (@rulelist) {
  2202. my @ruletoks = split ('!', $rule);
  2203. if (@ruletoks == 2 && $dpt ne '' && $mode == 0) {
  2204. my @dptlist = split (',', $ruletoks[0]);
  2205. foreach my $d (@dptlist) {
  2206. my $c = -1;
  2207. if ($d =~ /^([0-9]{1,2})\.(.+)$/) {
  2208. ($c, $d) = ($1, $2);
  2209. }
  2210. if ($d eq $dpt && ($c == -1 || !defined($chn) || $c == $chn)) {
  2211. ($rc, $newvalue) = HMCCU_SubstRule ($value, $ruletoks[1], $mode);
  2212. return $newvalue;
  2213. }
  2214. }
  2215. }
  2216. elsif (@ruletoks == 1) {
  2217. return $value if ($value !~ /^[+-]?\d+$/ && $value =~ /^[+-]?\d*\.?\d+(?:(?:e|E)\d+)?$/);
  2218. ($rc, $newvalue) = HMCCU_SubstRule ($value, $ruletoks[0], $mode);
  2219. return $newvalue if ($rc == 1);
  2220. }
  2221. }
  2222. return $value;
  2223. }
  2224. ######################################################################
  2225. # Execute substitution list.
  2226. # Syntax for single substitution: {#n-n|regexp|text}:newtext
  2227. # mode=0: Substitute regular expression
  2228. # mode=1: Substitute text (for setting statevals)
  2229. # newtext can contain ':'. Parameter ${value} in newtext is
  2230. # substituted by original value.
  2231. # Return (status, value)
  2232. # status=1: value = substituted value
  2233. # status=0: value = original value
  2234. ######################################################################
  2235. sub HMCCU_SubstRule ($$$)
  2236. {
  2237. my ($value, $substitutes, $mode ) = @_;
  2238. my $rc = 0;
  2239. $substitutes =~ s/\$\{value\}/$value/g;
  2240. my @sub_list = split /,/,$substitutes;
  2241. foreach my $s (@sub_list) {
  2242. my ($regexp, $text) = split /:/,$s,2;
  2243. next if (!defined ($regexp) || !defined($text));
  2244. if ($regexp =~ /^#([+-]?\d*\.?\d+?)\-([+-]?\d*\.?\d+?)$/) {
  2245. my ($mi, $ma) = ($1, $2);
  2246. if ($value =~ /^\d*\.?\d+?$/ && $value >= $mi && $value <= $ma) {
  2247. $value = $text;
  2248. $rc = 1;
  2249. }
  2250. }
  2251. elsif ($mode == 0 && $value =~ /$regexp/ && $value !~ /^[+-]?\d+$/) {
  2252. my $x = eval { $value =~ s/$regexp/$text/ };
  2253. $rc = 1 if (defined ($x));
  2254. last;
  2255. }
  2256. elsif (($mode == 1 || $value =~ /^[+-]?\d+$/) && $value =~ /^$regexp$/) {
  2257. my $x = eval { $value =~ s/^$regexp$/$text/ };
  2258. $rc = 1 if (defined ($x));
  2259. last;
  2260. }
  2261. }
  2262. return ($rc, $value);
  2263. }
  2264. ######################################################################
  2265. # Substitute datapoint variables in string by datapoint value. The
  2266. # value depends on the character preceding the variable name. Syntax
  2267. # of variable names is:
  2268. # {$|$$|%|%%}{[cn.]Name}
  2269. # {$|$$|%|%%}[cn.]Name
  2270. # % = Original / raw value
  2271. # %% = Previous original / raw value
  2272. # $ = Converted / formatted value
  2273. # $$ = Previous converted / formatted value
  2274. ######################################################################
  2275. sub HMCCU_SubstVariables ($$$)
  2276. {
  2277. my ($clhash, $text, $dplist) = @_;
  2278. my @varlist;
  2279. if (defined ($dplist)) {
  2280. @varlist = split (',', $dplist);
  2281. }
  2282. else {
  2283. @varlist = keys %{$clhash->{hmccu}{dp}};
  2284. }
  2285. # Substitute datapoint variables by value
  2286. foreach my $dp (@varlist) {
  2287. my ($chn, $dpt) = split (/\./, $dp);
  2288. if (defined ($clhash->{hmccu}{dp}{$dp}{OSVAL})) {
  2289. $text =~ s/\$\$\{?$dp\}?/$clhash->{hmccu}{dp}{$dp}{OSVAL}/g;
  2290. $text =~ s/\$\$\{?$dpt\}?/$clhash->{hmccu}{dp}{$dp}{OSVAL}/g;
  2291. }
  2292. if (defined ($clhash->{hmccu}{dp}{$dp}{SVAL})) {
  2293. $text =~ s/\$\{?$dp\}?/$clhash->{hmccu}{dp}{$dp}{SVAL}/g;
  2294. $text =~ s/\$\{?$dpt\}?/$clhash->{hmccu}{dp}{$dp}{SVAL}/g;
  2295. }
  2296. if (defined ($clhash->{hmccu}{dp}{$dp}{OVAL})) {
  2297. $text =~ s/\%\%\{?$dp\}?/$clhash->{hmccu}{dp}{$dp}{OVAL}/g;
  2298. $text =~ s/\%\%\{?$dpt\}?/$clhash->{hmccu}{dp}{$dp}{OVAL}/g;
  2299. }
  2300. if (defined ($clhash->{hmccu}{dp}{$dp}{VAL})) {
  2301. $text =~ s/\%\{?$dp\}?/$clhash->{hmccu}{dp}{$dp}{VAL}/g;
  2302. $text =~ s/\%\{?$dpt\}?/$clhash->{hmccu}{dp}{$dp}{VAL}/g;
  2303. }
  2304. }
  2305. return $text;
  2306. }
  2307. ######################################################################
  2308. # Update all datapoint/readings of all client devices matching
  2309. # specified regular expression. Update will fail if device is deleted
  2310. # or disabled or if attribute ccureadings of a device is set to 0.
  2311. # If fromccu is 1 regular expression is compared to CCU device name.
  2312. # Otherwise it's compared to FHEM device name. If ifname is specified
  2313. # only devices belonging to interface ifname are updated.
  2314. ######################################################################
  2315. sub HMCCU_UpdateClients ($$$$$)
  2316. {
  2317. my ($hash, $devexp, $ccuget, $fromccu, $ifname) = @_;
  2318. my $fhname = $hash->{NAME};
  2319. my $c_ok = 0;
  2320. my $c_err = 0;
  2321. my $filter = "ccudevstate=active";
  2322. $filter .= ",ccuif=$ifname" if (defined ($ifname));
  2323. if ($fromccu) {
  2324. foreach my $name (sort keys %{$hash->{hmccu}{adr}}) {
  2325. next if ($name !~ /$devexp/ || !($hash->{hmccu}{adr}{$name}{valid}));
  2326. my @devlist = HMCCU_FindClientDevices ($hash, "(HMCCUDEV|HMCCUCHN)", undef, $filter);
  2327. foreach my $d (@devlist) {
  2328. my $ch = $defs{$d};
  2329. next if (!defined ($ch->{IODev}) || !defined ($ch->{ccuaddr}));
  2330. next if ($ch->{ccuaddr} ne $hash->{hmccu}{adr}{$name}{address});
  2331. my $rc = HMCCU_GetUpdate ($ch, $hash->{hmccu}{adr}{$name}{address}, $ccuget);
  2332. if ($rc <= 0) {
  2333. if ($rc == -10) {
  2334. Log3 $fhname, 3, "HMCCU: Device $name has no readable datapoints";
  2335. }
  2336. else {
  2337. Log3 $fhname, 2, "HMCCU: Update of device $name failed";
  2338. }
  2339. $c_err++;
  2340. }
  2341. else {
  2342. $c_ok++;
  2343. }
  2344. }
  2345. }
  2346. }
  2347. else {
  2348. my @devlist = HMCCU_FindClientDevices ($hash, "(HMCCUDEV|HMCCUCHN)", $devexp, $filter);
  2349. Log3 $fhname, 2, "HMCCU: No client devices matching $devexp" if (scalar (@devlist) == 0);
  2350. foreach my $d (@devlist) {
  2351. my $ch = $defs{$d};
  2352. next if (!defined ($ch->{IODev}) || !defined ($ch->{ccuaddr}));
  2353. my $rc = HMCCU_GetUpdate ($ch, $ch->{ccuaddr}, $ccuget);
  2354. if ($rc <= 0) {
  2355. if ($rc == -10) {
  2356. Log3 $fhname, 3, "HMCCU: Device ".$ch->{ccuaddr}." has no readable datapoints";
  2357. }
  2358. else {
  2359. Log3 $fhname, 2, "HMCCU: Update of device ".$ch->{ccuaddr}." failed"
  2360. if ($ch->{ccuif} ne 'VirtualDevices');
  2361. }
  2362. $c_err++;
  2363. }
  2364. else {
  2365. $c_ok++;
  2366. }
  2367. }
  2368. }
  2369. return ($c_ok, $c_err);
  2370. }
  2371. ##########################################################################
  2372. # Update parameters in internal device tables and client devices.
  2373. # Parameter devices is a hash reference with following keys:
  2374. # {address}
  2375. # {address}{flag} := [N, D, R] (N=New, D=Deleted, R=Renamed)
  2376. # {address}{addtype} := [chn, dev]
  2377. # {address}{channels} := Number of channels
  2378. # {address}{name} := Device or channel name
  2379. # {address}{type} := Homematic device type
  2380. # {address}{usetype} := Usage type
  2381. # {address}{interface} := Device interface ID
  2382. # {address}{firmware} := Firmware version of device
  2383. # {address}{version} := Version of RPC device description
  2384. # {address}{rxmode} := Transmit mode
  2385. # {address}{chndir} := Channel direction: 0=none, 1=sensor, 2=actor
  2386. # If flag is 'D' the hash must contain an entry for the device address
  2387. # and for each channel address.
  2388. ##########################################################################
  2389. sub HMCCU_UpdateDeviceTable ($$)
  2390. {
  2391. my ($hash, $devices) = @_;
  2392. my $name = $hash->{NAME};
  2393. my $devcount = 0;
  2394. my $chncount = 0;
  2395. # Update internal device table
  2396. foreach my $da (keys %{$devices}) {
  2397. my $nm = $hash->{hmccu}{dev}{$da}{name} if (defined ($hash->{hmccu}{dev}{$da}{name}));
  2398. $nm = $devices->{$da}{name} if (defined ($devices->{$da}{name}));
  2399. if ($devices->{$da}{flag} eq 'N' && defined ($nm)) {
  2400. my $at = '';
  2401. if (defined ($devices->{$da}{addtype})) {
  2402. $at = $devices->{$da}{addtype};
  2403. }
  2404. else {
  2405. $at = 'chn' if (HMCCU_IsChnAddr ($da, 0));
  2406. $at = 'dev' if (HMCCU_IsDevAddr ($da, 0));
  2407. }
  2408. if ($at eq '') {
  2409. Log3 $name, 2, "HMCCU: Cannot detect type of address $da";
  2410. next;
  2411. }
  2412. Log3 $name, 2, "HMCCU: Duplicate name for device/channel $nm address=$da in CCU."
  2413. if (exists ($hash->{hmccu}{adr}{$nm}) && $at ne $hash->{hmccu}{adr}{$nm}{addtype});
  2414. # Updated or new device/channel
  2415. $hash->{hmccu}{dev}{$da}{addtype} = $at;
  2416. $hash->{hmccu}{dev}{$da}{name} = $nm if (defined ($nm));
  2417. $hash->{hmccu}{dev}{$da}{valid} = 1;
  2418. $hash->{hmccu}{dev}{$da}{channels} = $devices->{$da}{channels}
  2419. if (defined ($devices->{$da}{channels}));
  2420. $hash->{hmccu}{dev}{$da}{type} = $devices->{$da}{type}
  2421. if (defined ($devices->{$da}{type}));
  2422. $hash->{hmccu}{dev}{$da}{usetype} = $devices->{$da}{usetype}
  2423. if (defined ($devices->{$da}{usetype}));
  2424. $hash->{hmccu}{dev}{$da}{interface} = $devices->{$da}{interface}
  2425. if (defined ($devices->{$da}{interface}));
  2426. $hash->{hmccu}{dev}{$da}{version} = $devices->{$da}{version}
  2427. if (defined ($devices->{$da}{version}));
  2428. $hash->{hmccu}{dev}{$da}{firmware} = $devices->{$da}{firmware}
  2429. if (defined ($devices->{$da}{firmware}));
  2430. $hash->{hmccu}{dev}{$da}{rxmode} = $devices->{$da}{rxmode}
  2431. if (defined ($devices->{$da}{rxmode}));
  2432. $hash->{hmccu}{dev}{$da}{chndir} = $devices->{$da}{chndir}
  2433. if (defined ($devices->{$da}{chndir}));
  2434. $hash->{hmccu}{adr}{$nm}{address} = $da;
  2435. $hash->{hmccu}{adr}{$nm}{addtype} = $hash->{hmccu}{dev}{$da}{addtype};
  2436. $hash->{hmccu}{adr}{$nm}{valid} = 1 if (defined ($nm));
  2437. }
  2438. elsif ($devices->{$da}{flag} eq 'D' && exists ($hash->{hmccu}{dev}{$da})) {
  2439. # Device deleted, mark as invalid
  2440. $hash->{hmccu}{dev}{$da}{valid} = 0;
  2441. $hash->{hmccu}{adr}{$nm}{valid} = 0 if (defined ($nm));
  2442. }
  2443. elsif ($devices->{$da}{flag} eq 'R' && exists ($hash->{hmccu}{dev}{$da})) {
  2444. # Device replaced, change address
  2445. my $na = $devices->{hmccu}{newaddr};
  2446. # Copy device entries and delete old device entries
  2447. foreach my $k (keys %{$hash->{hmccu}{dev}{$da}}) {
  2448. $hash->{hmccu}{dev}{$na}{$k} = $hash->{hmccu}{dev}{$da}{$k};
  2449. }
  2450. $hash->{hmccu}{adr}{$nm}{address} = $na;
  2451. delete $hash->{hmccu}{dev}{$da};
  2452. }
  2453. }
  2454. # Delayed initialization if CCU was not ready during FHEM start
  2455. if ($hash->{hmccu}{ccu}{delayed} == 1) {
  2456. # Initialize interface and port lists
  2457. HMCCU_AttrInterfacesPorts ($hash, 'rpcinterfaces', $attr{$name}{rpcinterfaces})
  2458. if (exists ($attr{$name}{rpcinterfaces}));
  2459. HMCCU_AttrInterfacesPorts ($hash, 'rpcport', $attr{$name}{rpcport})
  2460. if (exists ($attr{$name}{rpcport}));
  2461. # Initialize pending client devices
  2462. my @cdev = HMCCU_FindClientDevices ($hash, '(HMCCUDEV|HMCCUCHN|HMCCURPCPROC)', undef, 'ccudevstate=pending');
  2463. if (scalar (@cdev) > 0) {
  2464. HMCCU_Log ($hash, 2, "Initializing ".scalar(@cdev)." client devices in state 'pending'", 0);
  2465. foreach my $cd (@cdev) {
  2466. my $ch = $defs{$cd};
  2467. my $ct = $ch->{TYPE};
  2468. my $rc = 0;
  2469. if ($ct eq 'HMCCUDEV') {
  2470. $rc = HMCCUDEV_InitDevice ($hash, $ch);
  2471. }
  2472. elsif ($ct eq 'HMCCUCHN') {
  2473. $rc = HMCCUCHN_InitDevice ($hash, $ch);
  2474. }
  2475. elsif ($ct eq 'HMCCURPCPROC') {
  2476. $rc = HMCCURPCPROC_InitDevice ($hash, $ch);
  2477. }
  2478. HMCCU_Log ($hash, 3, "Can't initialize client device ".$ch->{NAME}, 0) if ($rc > 0);
  2479. }
  2480. }
  2481. $hash->{hmccu}{ccu}{delayed} = 0;
  2482. }
  2483. # Update client devices
  2484. my @devlist = HMCCU_FindClientDevices ($hash, "(HMCCUDEV|HMCCUCHN)", undef, undef);
  2485. foreach my $d (@devlist) {
  2486. my $ch = $defs{$d};
  2487. my $ct = $ch->{TYPE};
  2488. next if (!exists ($ch->{ccuaddr}));
  2489. my $ca = $ch->{ccuaddr};
  2490. next if (!exists ($devices->{$ca}));
  2491. if ($devices->{$ca}{flag} eq 'N') {
  2492. # New device or new device information
  2493. $ch->{ccudevstate} = 'active';
  2494. if ($ct eq 'HMCCUDEV') {
  2495. $ch->{ccutype} = $hash->{hmccu}{dev}{$ca}{type}
  2496. if (defined ($hash->{hmccu}{dev}{$ca}{type}));
  2497. $ch->{firmware} = $devices->{$ca}{firmware}
  2498. if (defined ($devices->{$ca}{firmware}));
  2499. }
  2500. else {
  2501. $ch->{chntype} = $devices->{$ca}{usetype}
  2502. if (defined ($devices->{$ca}{usetype}));
  2503. my ($add, $chn) = HMCCU_SplitChnAddr ($ca);
  2504. $ch->{ccutype} = $devices->{$add}{type}
  2505. if (defined ($devices->{$add}{type}));
  2506. $ch->{firmware} = $devices->{$add}{firmware}
  2507. if (defined ($devices->{$add}{firmware}));
  2508. }
  2509. $ch->{ccuname} = $hash->{hmccu}{dev}{$ca}{name}
  2510. if (defined ($hash->{hmccu}{dev}{$ca}{name}));
  2511. $ch->{ccuif} = $hash->{hmccu}{dev}{$ca}{interface}
  2512. if (defined ($devices->{$ca}{interface}));
  2513. $ch->{channels} = $hash->{hmccu}{dev}{$ca}{channels}
  2514. if (defined ($hash->{hmccu}{dev}{$ca}{channels}));
  2515. }
  2516. elsif ($devices->{$ca}{flag} eq 'D') {
  2517. # Deleted device
  2518. $ch->{ccudevstate} = 'deleted';
  2519. }
  2520. elsif ($devices->{$ca}{flag} eq 'R') {
  2521. # Replaced device
  2522. $ch->{ccuaddr} = $devices->{$ca}{newaddr};
  2523. }
  2524. }
  2525. # Update internals of I/O device
  2526. foreach my $adr (keys %{$hash->{hmccu}{dev}}) {
  2527. if (exists ($hash->{hmccu}{dev}{$adr}{addtype})) {
  2528. $devcount++ if ($hash->{hmccu}{dev}{$adr}{addtype} eq 'dev');
  2529. $chncount++ if ($hash->{hmccu}{dev}{$adr}{addtype} eq 'chn');
  2530. }
  2531. }
  2532. $hash->{ccudevices} = $devcount;
  2533. $hash->{ccuchannels} = $chncount;
  2534. return ($devcount, $chncount);
  2535. }
  2536. ######################################################################
  2537. # Update a single client device datapoint considering scaling, reading
  2538. # format and value substitution.
  2539. # Return stored value.
  2540. ######################################################################
  2541. sub HMCCU_UpdateSingleDatapoint ($$$$)
  2542. {
  2543. my ($hash, $chn, $dpt, $value) = @_;
  2544. my $hmccu_hash = HMCCU_GetHash ($hash);
  2545. return $value if (!defined ($hmccu_hash));
  2546. my %objects;
  2547. my $ccuaddr = $hash->{ccuaddr};
  2548. my ($devaddr, $chnnum) = HMCCU_SplitChnAddr ($ccuaddr);
  2549. $objects{$devaddr}{$chn}{$dpt} = $value;
  2550. my $rc = HMCCU_UpdateSingleDevice ($hmccu_hash, $hash, \%objects);
  2551. return (ref ($rc)) ? $rc->{$devaddr}{$chn}{$dpt} : $value;
  2552. }
  2553. ######################################################################
  2554. # Update readings of client device.
  2555. # Parameter objects is a hash reference which contains updated data
  2556. # for any device:
  2557. # {devaddr}{channelno}{datapoint} = value
  2558. # If client device is virtual device group: check if group members are
  2559. # affected by updates and update readings in virtual group device.
  2560. # Return a hash reference with datapoints and new values:
  2561. # {devaddr}{datapoint} = value
  2562. ######################################################################
  2563. sub HMCCU_UpdateSingleDevice ($$$)
  2564. {
  2565. my ($ccuhash, $clthash, $objects) = @_;
  2566. my $ccuname = $ccuhash->{NAME};
  2567. my $cltname = $clthash->{NAME};
  2568. my $clttype = $clthash->{TYPE};
  2569. my $fnc = "UpdateSingleDevice";
  2570. return 0 if (!defined ($clthash->{IODev}) || !defined ($clthash->{ccuaddr}));
  2571. return 0 if ($clthash->{IODev} != $ccuhash);
  2572. # Check for updated data
  2573. my ($devaddr, $cnum) = HMCCU_SplitChnAddr ($clthash->{ccuaddr});
  2574. return 0 if (!exists ($objects->{$devaddr}));
  2575. return 0 if ($clttype eq 'HMCUCCHN' && !exists ($objects->{$devaddr}{$cnum}) &&
  2576. !exists ($objects->{$devaddr}{0}));
  2577. my $ccuflags = HMCCU_GetFlags ($ccuname);
  2578. # Build device list including virtual devices
  2579. my @grplist = ($cltname);
  2580. my @virlist = HMCCU_FindClientDevices ($ccuhash, "HMCCUDEV", undef, "ccuif=VirtualDevices");
  2581. foreach my $vd (@virlist) {
  2582. my $vh = $defs{$vd};
  2583. next if (!defined ($vh->{ccugroup}));
  2584. foreach my $gadd (split (",", $vh->{ccugroup})) {
  2585. if ("$gadd" eq "$devaddr") {
  2586. push @grplist, $vd;
  2587. last;
  2588. }
  2589. }
  2590. }
  2591. HMCCU_Trace ($clthash, 2, $fnc,
  2592. "$cltname Virlist = ".join(',', @virlist)."<br>".
  2593. "$cltname Grplist = ".join(',', @grplist)."<br>".
  2594. "$cltname Objects = ".join(',', keys %{$objects}));
  2595. # Store the resulting readings
  2596. my %results;
  2597. # Update device considering foreign device data assigned to group device.
  2598. # Devices are not updated when:
  2599. # - Device is disabled
  2600. # - Attribute ccureadings is set to 0
  2601. # - Device is not in state active
  2602. foreach my $cn (@grplist) {
  2603. my $ch = $defs{$cn};
  2604. my $ct = $ch->{TYPE};
  2605. my $disable = AttrVal ($cn, 'disable', 0);
  2606. my $update = AttrVal ($cn, 'ccureadings', 1);
  2607. next if ($update == 0 || $disable == 1 || $ch->{ccudevstate} ne 'active');
  2608. my $cf = HMCCU_GetFlags ($cn);
  2609. my $peer = AttrVal ($cn, 'peer', 'null');
  2610. HMCCU_Trace ($ch, 2, $fnc, "Processing device $cn");
  2611. my $crf = HMCCU_GetAttrReadingFormat ($ch, $ccuhash);
  2612. my $substitute = HMCCU_GetAttrSubstitute ($ch, $ccuhash);
  2613. my ($sc, $st, $cc, $cd) = HMCCU_GetSpecialDatapoints ($ch, '', 'STATE', '', '');
  2614. my @devlist = ($ch->{ccuaddr});
  2615. push @devlist, split (",", $ch->{ccugroup})
  2616. if ($ch->{ccuif} eq 'VirtualDevices' && exists ($ch->{ccugroup}));
  2617. readingsBeginUpdate ($ch);
  2618. # Update devices
  2619. foreach my $dev (@devlist) {
  2620. my ($da, $cnum) = HMCCU_SplitChnAddr ($dev);
  2621. next if (!exists ($objects->{$da}));
  2622. next if ($clttype eq 'HMCUCCHN' && !exists ($objects->{$da}{$cnum}) &&
  2623. !exists ($objects->{$da}{0}));
  2624. # Update channels of device
  2625. foreach my $chnnum (keys (%{$objects->{$da}})) {
  2626. next if ($ct eq 'HMCCUCHN' && "$chnnum" ne "$cnum" && "$chnnum" ne "0");
  2627. next if ("$chnnum" eq "0" && $cf =~ /nochn0/);
  2628. my $chnadd = "$da:$chnnum";
  2629. # Update datapoints of channel
  2630. foreach my $dpt (keys (%{$objects->{$da}{$chnnum}})) {
  2631. my $value = $objects->{$da}{$chnnum}{$dpt};
  2632. next if (!defined ($value));
  2633. # Store datapoint raw value in device hash
  2634. if (exists ($clthash->{hmccu}{dp}{"$chnnum.$dpt"}{VAL})) {
  2635. $clthash->{hmccu}{dp}{"$chnnum.$dpt"}{OVAL} = $clthash->{hmccu}{dp}{"$chnnum.$dpt"}{VAL};
  2636. }
  2637. else {
  2638. $clthash->{hmccu}{dp}{"$chnnum.$dpt"}{OVAL} = $value;
  2639. }
  2640. $clthash->{hmccu}{dp}{"$chnnum.$dpt"}{VAL} = $value;
  2641. HMCCU_Trace ($ch, 2, $fnc, "dev=$cn, chnadd=$chnadd, dpt=$dpt, value=$value");
  2642. if (HMCCU_FilterReading ($ch, $chnadd, $dpt)) {
  2643. my @readings = HMCCU_GetReadingName ($ch, '', $da, $chnnum, $dpt, '', $crf);
  2644. my $svalue = HMCCU_ScaleValue ($ch, $chnnum, $dpt, $value, 0);
  2645. my $fvalue = HMCCU_FormatReadingValue ($ch, $svalue, $dpt);
  2646. my $cvalue = HMCCU_Substitute ($fvalue, $substitute, 0, $chnnum, $dpt);
  2647. my %calcs = HMCCU_CalculateReading ($ch, $chnnum, $dpt);
  2648. # Store the resulting value after scaling, formatting and substitution
  2649. if (exists ($clthash->{hmccu}{dp}{"$chnnum.$dpt"}{OSVAL})) {
  2650. $clthash->{hmccu}{dp}{"$chnnum.$dpt"}{OSVAL} = $clthash->{hmccu}{dp}{"$chnnum.$dpt"}{SVAL};
  2651. }
  2652. else {
  2653. $clthash->{hmccu}{dp}{"$chnnum.$dpt"}{OSVAL} = $cvalue;
  2654. }
  2655. $clthash->{hmccu}{dp}{"$chnnum.$dpt"}{SVAL} = $cvalue;
  2656. $results{$da}{$chnnum}{$dpt} = $cvalue;
  2657. HMCCU_Trace ($ch, 2, $fnc,
  2658. "device=$cltname, readings=".join(',', @readings).
  2659. ", orgvalue=$value value=$cvalue peer=$peer");
  2660. # Update readings
  2661. foreach my $rn (@readings) {
  2662. HMCCU_BulkUpdate ($ch, $rn, $fvalue, $cvalue) if ($rn ne '');
  2663. }
  2664. foreach my $clcr (keys %calcs) {
  2665. HMCCU_BulkUpdate ($ch, $clcr, $calcs{$clcr}, $calcs{$clcr});
  2666. }
  2667. HMCCU_BulkUpdate ($ch, 'control', $fvalue, $cvalue)
  2668. if ($cd ne '' && $dpt eq $cd && $chnnum eq $cc);
  2669. HMCCU_BulkUpdate ($ch, 'state', $fvalue, $cvalue)
  2670. if ($dpt eq $st && ($sc eq '' || $sc eq $chnnum));
  2671. # Update peers
  2672. HMCCU_UpdatePeers ($ch, "$chnnum.$dpt", $cvalue, $peer) if ($peer ne 'null');
  2673. }
  2674. }
  2675. }
  2676. }
  2677. # Calculate and update HomeMatic state
  2678. if ($ccuflags !~ /nohmstate/) {
  2679. my ($hms_read, $hms_chn, $hms_dpt, $hms_val) = HMCCU_GetHMState ($cn, $ccuname, undef);
  2680. HMCCU_BulkUpdate ($ch, $hms_read, $hms_val, $hms_val) if (defined ($hms_val));
  2681. }
  2682. readingsEndUpdate ($ch, 1);
  2683. }
  2684. return \%results;
  2685. }
  2686. ######################################################################
  2687. # Update readings of multiple client devices.
  2688. # Parameter objects is a hash reference:
  2689. # {devaddr}
  2690. # {devaddr}{channelno}
  2691. # {devaddr}{channelno}{datapoint} = value
  2692. # Return number of updated devices.
  2693. ######################################################################
  2694. sub HMCCU_UpdateMultipleDevices ($$)
  2695. {
  2696. my ($hash, $objects) = @_;
  2697. my $name = $hash->{NAME};
  2698. my $fnc = "UpdateMultipleDevices";
  2699. my $c = 0;
  2700. # Check syntax
  2701. return 0 if (!defined ($hash) || !defined ($objects));
  2702. # Update reading in matching client devices
  2703. my @devlist = HMCCU_FindClientDevices ($hash, "(HMCCUDEV|HMCCUCHN)", undef,
  2704. "ccudevstate=active");
  2705. foreach my $d (@devlist) {
  2706. my $ch = $defs{$d};
  2707. my $rc = HMCCU_UpdateSingleDevice ($hash, $ch, $objects);
  2708. $c++ if (ref ($rc));
  2709. }
  2710. return $c;
  2711. }
  2712. ######################################################################
  2713. # Update peer devices.
  2714. # Syntax of peer definitions is:
  2715. # channel.datapoint[,...]:condition:type:action
  2716. # condition := valid perl expression. Any channel.datapoint
  2717. # combination is substituted by the corresponding value. If channel
  2718. # is preceded by a % it's substituted by the raw value. If it's
  2719. # preceded by a $ it's substituted by the formated/converted value.
  2720. # If % or $ is doubled the old values are used.
  2721. # type := type of action. Valid types are ccu, hmccu and fhem.
  2722. # action := Action to be performed if result of condition is true.
  2723. # Depending on type action type this could be an assignment or a
  2724. # FHEM command. If action contains $value this parameter is
  2725. # substituted by the original value of the datapoint which has
  2726. # triggered the action.
  2727. # assignment := channel.datapoint=expression
  2728. ######################################################################
  2729. sub HMCCU_UpdatePeers ($$$$)
  2730. {
  2731. my ($clt_hash, $chndpt, $val, $peerattr) = @_;
  2732. my $fnc = "UpdatePeers";
  2733. HMCCU_Trace ($clt_hash, 2, $fnc, "chndpt=$chndpt val=$val peer=$peerattr");
  2734. my @rules = split (/[;\n]+/, $peerattr);
  2735. foreach my $r (@rules) {
  2736. HMCCU_Trace ($clt_hash, 2, $fnc, "rule=$r");
  2737. my ($vars, $cond, $type, $act) = split (/:/, $r, 4);
  2738. next if (!defined ($act));
  2739. HMCCU_Trace ($clt_hash, 2, $fnc, "vars=$vars, cond=$cond, type=$type, act=$act");
  2740. next if ($cond !~ /$chndpt/);
  2741. # Check if rule is affected by datapoint update
  2742. my $ex = 0;
  2743. foreach my $dpt (split (",", $vars)) {
  2744. HMCCU_Trace ($clt_hash, 2, $fnc, "dpt=$dpt");
  2745. $ex = 1 if ($ex == 0 && $dpt eq $chndpt);
  2746. if (!exists ($clt_hash->{hmccu}{dp}{$dpt})) {
  2747. HMCCU_Trace ($clt_hash, 2, $fnc, "Datapoint $dpt does not exist on hash");
  2748. }
  2749. last if ($ex == 1);
  2750. }
  2751. next if (! $ex);
  2752. # Substitute variables and evaluate condition
  2753. $cond = HMCCU_SubstVariables ($clt_hash, $cond, $vars);
  2754. my $e = eval "$cond";
  2755. HMCCU_Trace ($clt_hash, 2, $fnc, "eval $cond = $e") if (defined ($e));
  2756. HMCCU_Trace ($clt_hash, 2, $fnc, "Error in eval $cond") if (!defined ($e));
  2757. HMCCU_Trace ($clt_hash, 2, $fnc, "NoMatch in eval $cond") if (defined ($e) && $e eq '');
  2758. next if (!defined ($e) || $e eq '');
  2759. # Substitute variables and execute action
  2760. if ($type eq 'ccu' || $type eq 'hmccu') {
  2761. my ($aobj, $aexp) = split (/=/, $act);
  2762. $aexp =~ s/\$value/$val/g;
  2763. $aexp = HMCCU_SubstVariables ($clt_hash, $aexp, $vars);
  2764. HMCCU_Trace ($clt_hash, 2, $fnc, "set $aobj to $aexp");
  2765. HMCCU_SetDatapoint ($clt_hash, "$type:$aobj", $aexp);
  2766. }
  2767. elsif ($type eq 'fhem') {
  2768. $act =~ s/\$value/$val/g;
  2769. $act = HMCCU_SubstVariables ($clt_hash, $act, $vars);
  2770. HMCCU_Trace ($clt_hash, 2, $fnc, "Execute command $act");
  2771. AnalyzeCommandChain (undef, $act);
  2772. }
  2773. }
  2774. }
  2775. ######################################################################
  2776. # Get list of valid RPC interfaces.
  2777. # Binary interfaces are ignored if internal RPC server is used.
  2778. # Default interface is BidCos-RF.
  2779. ######################################################################
  2780. sub HMCCU_GetRPCInterfaceList ($)
  2781. {
  2782. my ($hash) = @_;
  2783. my $name = $hash->{NAME};
  2784. my @interfaces = ($HMCCU_RPC_INTERFACE_DEFAULT);
  2785. my $ccuflags = HMCCU_GetFlags ($name);
  2786. if (defined ($hash->{hmccu}{rpcports})) {
  2787. foreach my $p (split (',', $hash->{hmccu}{rpcports})) {
  2788. my $ifname = HMCCU_GetRPCServerInfo ($hash, $p, 'name');
  2789. next if (!defined ($ifname));
  2790. my $iftype = HMCCU_GetRPCServerInfo ($hash, $ifname, 'type');
  2791. next if ($ifname eq $HMCCU_RPC_INTERFACE_DEFAULT ||
  2792. ($iftype eq 'B' && $ccuflags !~ /(extrpc|procrpc)/) ||
  2793. !exists ($hash->{hmccu}{interfaces}{$ifname}));
  2794. push (@interfaces, $ifname);
  2795. }
  2796. }
  2797. return @interfaces;
  2798. }
  2799. ######################################################################
  2800. # Get list of valid RPC ports.
  2801. # Binary interfaces are ignored if internal RPC server is used.
  2802. # Default port is 2001.
  2803. ######################################################################
  2804. sub HMCCU_GetRPCPortList ($)
  2805. {
  2806. my ($hash) = @_;
  2807. my $name = $hash->{NAME};
  2808. my @ports = ($HMCCU_RPC_PORT_DEFAULT);
  2809. my $ccuflags = HMCCU_GetFlags ($name);
  2810. if (defined ($hash->{hmccu}{rpcports})) {
  2811. foreach my $p (split (',', $hash->{hmccu}{rpcports})) {
  2812. my $ifname = HMCCU_GetRPCServerInfo ($hash, $p, 'name');
  2813. next if (!defined ($ifname));
  2814. my $iftype = HMCCU_GetRPCServerInfo ($hash, $ifname, 'type');
  2815. next if ($p == $HMCCU_RPC_PORT_DEFAULT ||
  2816. ($iftype eq 'B' && $ccuflags !~ /(extrpc|procrpc)/) ||
  2817. !exists ($hash->{hmccu}{interfaces}{$ifname}));
  2818. push (@ports, $p);
  2819. }
  2820. }
  2821. return @ports;
  2822. }
  2823. ######################################################################
  2824. # Build RPC callback URL
  2825. # Parameter hash might be a HMCCU or a HMCCURPC hash.
  2826. ######################################################################
  2827. sub HMCCU_GetRPCCallbackURL ($$$$$)
  2828. {
  2829. my ($hash, $localaddr, $cbport, $clkey, $iface) = @_;
  2830. return undef if (!defined ($hash));
  2831. my $hmccu_hash = $hash->{TYPE} eq 'HMCCURPC' ? $hash->{IODev} : $hash;
  2832. return undef if (!exists ($hmccu_hash->{hmccu}{interfaces}{$iface}) &&
  2833. !exists ($hmccu_hash->{hmccu}{ifports}{$iface}));
  2834. my $ifname = $iface =~ /^[0-9]+$/ ? $hmccu_hash->{hmccu}{ifports}{$iface} : $iface;
  2835. return undef if (!exists ($hmccu_hash->{hmccu}{interfaces}{$ifname}));
  2836. return $hmccu_hash->{hmccu}{interfaces}{$ifname}{prot}."://$localaddr:$cbport/fh".
  2837. $hmccu_hash->{hmccu}{interfaces}{$ifname}{port};
  2838. }
  2839. ######################################################################
  2840. # Get RPC server information.
  2841. # Parameter iface can be a port number or an interface name.
  2842. # Valid values for info are:
  2843. # url, port, prot, host, type, name, flags, device.
  2844. ######################################################################
  2845. sub HMCCU_GetRPCServerInfo ($$$)
  2846. {
  2847. my ($hash, $iface, $info) = @_;
  2848. return undef if (!defined ($hash));
  2849. return undef if (!exists ($hash->{hmccu}{interfaces}{$iface}) &&
  2850. !exists ($hash->{hmccu}{ifports}{$iface}));
  2851. my $ifname = $iface =~ /^[0-9]+$/ ? $hash->{hmccu}{ifports}{$iface} : $iface;
  2852. return undef if (!exists ($hash->{hmccu}{interfaces}{$ifname}));
  2853. return $ifname if ($info eq 'name');
  2854. return $hash->{hmccu}{interfaces}{$ifname}{$info};
  2855. }
  2856. ######################################################################
  2857. # Check if RPC interface is of specified type.
  2858. # Parameter type is A for XML or B for binary.
  2859. ######################################################################
  2860. sub HMCCU_IsRPCType ($$$)
  2861. {
  2862. my ($hash, $iface, $type) = @_;
  2863. my $rpctype = HMCCU_GetRPCServerInfo ($hash, $iface, 'type');
  2864. return 0 if (!defined ($rpctype));
  2865. return $rpctype eq $type ? 1 : 0;
  2866. }
  2867. ######################################################################
  2868. # Register RPC callbacks at CCU if RPC-Server already in server loop
  2869. ######################################################################
  2870. sub HMCCU_RPCRegisterCallback ($)
  2871. {
  2872. my ($hash) = @_;
  2873. my $name = $hash->{NAME};
  2874. my $localaddr = $hash->{hmccu}{localaddr};
  2875. my $rpcinterval = AttrVal ($name, 'rpcinterval', $HMCCU_INIT_INTERVAL2);
  2876. my @rpcports = HMCCU_GetRPCPortList ($hash);
  2877. foreach my $port (@rpcports) {
  2878. my $clkey = 'CB'.$port;
  2879. my $cburl = HMCCU_GetRPCCallbackURL ($hash, $localaddr, $hash->{hmccu}{rpc}{$clkey}{cbport},
  2880. $clkey, $port);
  2881. next if (!defined ($cburl));
  2882. my $url = HMCCU_GetRPCServerInfo ($hash, $port, 'url');
  2883. next if (!defined ($url));
  2884. my $rpcflags = HMCCU_GetRPCServerInfo ($hash, $port, 'flags');
  2885. if ($hash->{hmccu}{rpc}{$clkey}{loop} == 1 ||
  2886. $hash->{hmccu}{rpc}{$clkey}{state} eq "register") {
  2887. $hash->{hmccu}{rpc}{$clkey}{port} = $port;
  2888. $hash->{hmccu}{rpc}{$clkey}{clurl} = $url;
  2889. $hash->{hmccu}{rpc}{$clkey}{cburl} = $cburl;
  2890. $hash->{hmccu}{rpc}{$clkey}{loop} = 2;
  2891. $hash->{hmccu}{rpc}{$clkey}{state} = $rpcflags =~ /forceInit/ ? "running" : "registered";
  2892. Log3 $name, 1, "HMCCU: Registering callback $cburl with ID $clkey at $url";
  2893. my $rpcclient = RPC::XML::Client->new ($url);
  2894. $rpcclient->send_request ("init", $cburl, $clkey);
  2895. Log3 $name, 1, "HMCCU: RPC callback with URL $cburl initialized";
  2896. }
  2897. }
  2898. # Schedule reading of RPC queue
  2899. InternalTimer (gettimeofday()+$rpcinterval, 'HMCCU_ReadRPCQueue', $hash, 0);
  2900. }
  2901. ######################################################################
  2902. # Deregister RPC callbacks at CCU
  2903. ######################################################################
  2904. sub HMCCU_RPCDeRegisterCallback ($)
  2905. {
  2906. my ($hash) = @_;
  2907. my $name = $hash->{NAME};
  2908. foreach my $clkey (keys %{$hash->{hmccu}{rpc}}) {
  2909. my $rpchash = \%{$hash->{hmccu}{rpc}{$clkey}};
  2910. if (exists ($rpchash->{cburl}) && $rpchash->{cburl} ne '') {
  2911. my $port = $rpchash->{port};
  2912. my $rpcclient = RPC::XML::Client->new ($rpchash->{clurl});
  2913. Log3 $name, 1, "HMCCU: Deregistering RPC server ".$rpchash->{cburl}.
  2914. " at ".$rpchash->{clurl};
  2915. $rpcclient->send_request("init", $rpchash->{cburl});
  2916. $rpchash->{cburl} = '';
  2917. $rpchash->{clurl} = '';
  2918. $rpchash->{cbport} = 0;
  2919. }
  2920. }
  2921. }
  2922. ######################################################################
  2923. # Initialize statistic counters
  2924. ######################################################################
  2925. sub HMCCU_ResetCounters ($)
  2926. {
  2927. my ($hash) = @_;
  2928. my @counters = ('total', 'EV', 'ND', 'IN', 'DD', 'RA', 'RD', 'UD', 'EX', 'SL', 'ST');
  2929. foreach my $cnt (@counters) {
  2930. $hash->{hmccu}{ev}{$cnt} = 0;
  2931. }
  2932. delete $hash->{hmccu}{evs};
  2933. delete $hash->{hmccu}{evr};
  2934. $hash->{hmccu}{evtimeout} = 0;
  2935. $hash->{hmccu}{evtime} = 0;
  2936. }
  2937. ######################################################################
  2938. # Start external RPC server via RPC device.
  2939. # Return number of RPC servers or 0 on error.
  2940. ######################################################################
  2941. sub HMCCU_StartExtRPCServer ($)
  2942. {
  2943. my ($hash) = @_;
  2944. my $name = $hash->{NAME};
  2945. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  2946. my $attrset = 0;
  2947. # Change RPC type to procrpc
  2948. if ($ccuflags =~ /extrpc/) {
  2949. $ccuflags =~ s/extrpc/procrpc/g;
  2950. CommandAttr (undef, "$name ccuflags $ccuflags");
  2951. $attrset = 1;
  2952. # Disable existing devices of type HMCCURPC
  2953. foreach my $d (keys %defs) {
  2954. my $ch = $defs{$d};
  2955. next if (!exists ($ch->{TYPE}) || !exists ($ch->{NAME}));
  2956. next if ($ch->{TYPE} ne 'HMCCURPC');
  2957. CommandAttr (undef, $ch->{NAME}." disable 1") if (IsDisabled ($ch->{NAME}) != 1);
  2958. }
  2959. }
  2960. # if ($ccuflags =~ /(extrpc|procrpc)/) {
  2961. # Search RPC device. Create one if none exists
  2962. # my ($rpcdev, $save) = HMCCU_GetRPCDevice ($hash, 1, undef);
  2963. # return HMCCU_Log ($hash, 0, "Can't find or create HMCCURPC device", 0) if ($rpcdev eq '');
  2964. # CommandSave (undef, undef) if ($save);
  2965. #
  2966. # my ($rc, $msg) = HMCCURPC_StartRPCServer ($defs{$rpcdev});
  2967. # HMCCU_SetRPCState ($hash, 'starting') if ($rc);
  2968. # Log3 $name, 0, "HMCCURPC: $msg" if (!$rc && defined ($msg));
  2969. # return $rc;
  2970. # }
  2971. # elsif ($ccuflags =~ /procrpc/) {
  2972. my $c = 0;
  2973. my $d = 0;
  2974. my $s = 0;
  2975. my @iflist = HMCCU_GetRPCInterfaceList ($hash);
  2976. foreach my $ifname1 (@iflist) {
  2977. my ($rpcdev, $save) = HMCCU_GetRPCDevice ($hash, 1, $ifname1);
  2978. next if ($rpcdev eq '' || !defined ($hash->{hmccu}{interfaces}{$ifname1}{device}));
  2979. $d++;
  2980. $s++ if ($save);
  2981. }
  2982. # Save FHEM config if new RPC devices were defined or attribute has changed
  2983. if ($s > 0 || $attrset) {
  2984. HMCCU_Log ($hash, 1, "Saving FHEM config", 0);
  2985. CommandSave (undef, undef);
  2986. }
  2987. if ($d == scalar (@iflist)) {
  2988. foreach my $ifname2 (@iflist) {
  2989. my $dh = $defs{$hash->{hmccu}{interfaces}{$ifname2}{device}};
  2990. $hash->{hmccu}{interfaces}{$ifname2}{manager} = 'HMCCU';
  2991. my ($rc, $msg) = HMCCURPCPROC_StartRPCServer ($dh);
  2992. if (!$rc) {
  2993. HMCCU_SetRPCState ($hash, 'error', $ifname2, $msg);
  2994. }
  2995. else {
  2996. $c++;
  2997. }
  2998. }
  2999. HMCCU_SetRPCState ($hash, 'starting') if ($c > 0);
  3000. return $c;
  3001. }
  3002. else {
  3003. HMCCU_Log ($hash, 0, "Definition of some RPC devices failed", undef);
  3004. }
  3005. # }
  3006. return 0;
  3007. }
  3008. ######################################################################
  3009. # Stop external RPC server via RPC device.
  3010. ######################################################################
  3011. sub HMCCU_StopExtRPCServer ($)
  3012. {
  3013. my ($hash) = @_;
  3014. my $name = $hash->{NAME};
  3015. if (HMCCU_IsFlag ($name, "(extrpc|procrpc)")) {
  3016. # return HMCCU_Log ($hash, 0, "Module HMCCURPC not loaded", 0) if (!exists ($modules{'HMCCURPC'}));
  3017. #
  3018. # my ($rpcdev, $save) = HMCCU_GetRPCDevice ($hash, 0, undef);
  3019. # return HMCCU_Log ($hash, 0, "Can't find RPC device", 0) if ($rpcdev eq '');
  3020. # HMCCU_SetRPCState ($hash, 'stopping');
  3021. # return HMCCURPC_StopRPCServer ($defs{$rpcdev});
  3022. # }
  3023. # elsif ($ccuflags =~ /procrpc/) {
  3024. return HMCCU_Log ($hash, 0, "Module HMCCURPCPROC not loaded", 0) if (!exists ($modules{'HMCCURPCPROC'}));
  3025. HMCCU_SetRPCState ($hash, 'stopping');
  3026. my $rc = 1;
  3027. my @iflist = HMCCU_GetRPCInterfaceList ($hash);
  3028. foreach my $ifname (@iflist) {
  3029. my ($rpcdev, $save) = HMCCU_GetRPCDevice ($hash, 0, $ifname);
  3030. if ($rpcdev eq '') {
  3031. Log3 $name, 0, "HMCCU: Can't find RPC device";
  3032. next;
  3033. }
  3034. $hash->{hmccu}{interfaces}{$ifname}{manager} = 'HMCCU';
  3035. $rc &= HMCCURPCPROC_StopRPCServer ($defs{$rpcdev});
  3036. }
  3037. return $rc;
  3038. }
  3039. }
  3040. ######################################################################
  3041. # Start internal file queue based RPC server.
  3042. # Return number of RPC server processes or 0 on error.
  3043. ######################################################################
  3044. sub HMCCU_StartIntRPCServer ($)
  3045. {
  3046. my ($hash) = @_;
  3047. my $name = $hash->{NAME};
  3048. # Timeouts
  3049. my $timeout = AttrVal ($name, 'rpctimeout', '0.01,0.25');
  3050. my ($to_read, $to_write) = split (",", $timeout);
  3051. $to_write = $to_read if (!defined ($to_write));
  3052. # Address and ports
  3053. my $rpcqueue = AttrVal ($name, 'rpcqueue', '/tmp/ccuqueue');
  3054. my $localaddr = AttrVal ($name, 'rpcserveraddr', '');
  3055. my $rpcserverport = AttrVal ($name, 'rpcserverport', 5400);
  3056. my $rpcinterval = AttrVal ($name, 'rpcinterval', $HMCCU_INIT_INTERVAL1);
  3057. my @rpcportlist = HMCCU_GetRPCPortList ($hash);
  3058. my $serveraddr = HMCCU_GetRPCServerInfo ($hash, $rpcportlist[0], 'host');
  3059. my $fork_cnt = 0;
  3060. HMCCU_Log ($hash, 1, "Internal RPC server is depricated and will be removed soon. Set ccuflags to procrpc", 0);
  3061. # Check for running RPC server processes
  3062. my @hm_pids;
  3063. my @hm_tids;
  3064. HMCCU_IsRPCServerRunning ($hash, \@hm_pids, \@hm_tids);
  3065. if (scalar (@hm_pids) > 0) {
  3066. return HMCCU_Log ($hash, 0, "RPC server(s) already running with PIDs ".join (',', @hm_pids),
  3067. scalar (@hm_pids));
  3068. }
  3069. elsif (scalar (@hm_tids) > 0) {
  3070. return HMCCU_Log ($hash, 1, "RPC server(s) already running with TIDs ".join (',', @hm_tids),
  3071. 0);
  3072. }
  3073. # Detect local IP address
  3074. if ($localaddr eq '') {
  3075. $localaddr = HMCCU_TCPConnect ($serveraddr, $rpcportlist[0]);
  3076. return HMCCU_Log ($hash, 1, "Can't connect to RPC host $serveraddr port".$rpcportlist[0], 0)
  3077. if ($localaddr eq '');
  3078. }
  3079. $hash->{hmccu}{localaddr} = $localaddr;
  3080. my $ccunum = $hash->{CCUNum};
  3081. # Fork child processes
  3082. foreach my $port (@rpcportlist) {
  3083. my $clkey = 'CB'.$port;
  3084. my $rpcqueueport = $rpcqueue."_".$port."_".$ccunum;
  3085. my $callbackport = $rpcserverport+$port+($ccunum*10);
  3086. # Clear event queue
  3087. HMCCU_ResetRPCQueue ($hash, $port);
  3088. # Create child process
  3089. Log3 $name, 2, "HMCCU: Create child process with timeouts $to_read and $to_write";
  3090. my $child = SubProcess->new ({ onRun => \&HMCCU_CCURPC_OnRun,
  3091. onExit => \&HMCCU_CCURPC_OnExit, timeoutread => $to_read, timeoutwrite => $to_write });
  3092. $child->{serveraddr} = $serveraddr;
  3093. $child->{serverport} = $port;
  3094. $child->{callbackport} = $callbackport;
  3095. $child->{devname} = $name;
  3096. $child->{queue} = $rpcqueueport;
  3097. # Start child process
  3098. my $pid = $child->run ();
  3099. if (!defined ($pid)) {
  3100. Log3 $name, 1, "HMCCU: No RPC process for server $clkey started";
  3101. next;
  3102. }
  3103. Log3 $name, 0, "HMCCU: Child process for server $clkey started with PID $pid";
  3104. $fork_cnt++;
  3105. # Store child process parameters
  3106. $hash->{hmccu}{rpc}{$clkey}{child} = $child;
  3107. $hash->{hmccu}{rpc}{$clkey}{cbport} = $callbackport;
  3108. $hash->{hmccu}{rpc}{$clkey}{loop} = 0;
  3109. $hash->{hmccu}{rpc}{$clkey}{pid} = $pid;
  3110. $hash->{hmccu}{rpc}{$clkey}{queue} = $rpcqueueport;
  3111. $hash->{hmccu}{rpc}{$clkey}{state} = "starting";
  3112. push (@hm_pids, $pid);
  3113. }
  3114. $hash->{hmccu}{rpccount} = $fork_cnt;
  3115. if ($fork_cnt > 0) {
  3116. # Set internals
  3117. $hash->{RPCPID} = join (',', @hm_pids);
  3118. $hash->{RPCPRC} = "internal";
  3119. HMCCU_SetRPCState ($hash, 'starting');
  3120. # Initialize statistic counters
  3121. HMCCU_ResetCounters ($hash);
  3122. Log3 $name, 0, "RPC server(s) starting";
  3123. DoTrigger ($name, "RPC server starting");
  3124. InternalTimer (gettimeofday()+$rpcinterval, 'HMCCU_ReadRPCQueue', $hash, 0);
  3125. }
  3126. return $fork_cnt;
  3127. }
  3128. ######################################################################
  3129. # Stop RPC server(s) by sending SIGINT to process(es)
  3130. ######################################################################
  3131. sub HMCCU_StopRPCServer ($)
  3132. {
  3133. my ($hash) = @_;
  3134. my $name = $hash->{NAME};
  3135. my $pid = 0;
  3136. # Deregister callback URLs in CCU
  3137. HMCCU_RPCDeRegisterCallback ($hash);
  3138. # Send signal SIGINT to RPC server processes
  3139. foreach my $clkey (keys %{$hash->{hmccu}{rpc}}) {
  3140. my $rpchash = \%{$hash->{hmccu}{rpc}{$clkey}};
  3141. if (exists ($rpchash->{pid}) && $rpchash->{pid} != 0) {
  3142. Log3 $name, 0, "HMCCU: Stopping RPC server $clkey with PID ".$rpchash->{pid};
  3143. kill ('INT', $rpchash->{pid});
  3144. $rpchash->{state} = "stopping";
  3145. }
  3146. else {
  3147. $rpchash->{state} = "inactive";
  3148. }
  3149. }
  3150. # Update status
  3151. HMCCU_SetRPCState ($hash, 'stopping') if ($hash->{hmccu}{rpccount} > 0);
  3152. # Wait
  3153. sleep (1);
  3154. # Check if processes were terminated
  3155. my @hm_pids;
  3156. my @hm_tids;
  3157. HMCCU_IsRPCServerRunning ($hash, \@hm_pids, \@hm_tids);
  3158. if (scalar (@hm_pids) > 0) {
  3159. foreach my $pid (@hm_pids) {
  3160. Log3 $name, 0, "HMCCU: Stopping RPC server with PID $pid";
  3161. kill ('INT', $pid);
  3162. }
  3163. }
  3164. Log3 $name, 0, "HMCCU: Externally launched RPC server detected." if (scalar (@hm_tids) > 0);
  3165. # Wait
  3166. sleep (1);
  3167. # Kill the rest
  3168. @hm_pids = ();
  3169. @hm_tids = ();
  3170. if (HMCCU_IsRPCServerRunning ($hash, \@hm_pids, \@hm_tids)) {
  3171. foreach my $pid (@hm_pids) {
  3172. kill ('KILL', $pid);
  3173. }
  3174. }
  3175. # Store number of running RPC servers
  3176. $hash->{hmccu}{rpccount} = HMCCU_IsRPCServerRunning ($hash, undef, undef);
  3177. return $hash->{hmccu}{rpccount} > 0 ? 0 : 1;
  3178. }
  3179. ######################################################################
  3180. # Check status of RPC server depending on internal RPCState.
  3181. # Return 1 if RPC server is stopping, starting or restarting. During
  3182. # this phases CCU reacts very slowly so any get or set command from
  3183. # HMCCU devices are disabled.
  3184. ######################################################################
  3185. sub HMCCU_IsRPCStateBlocking ($)
  3186. {
  3187. my ($hash) = @_;
  3188. if ($hash->{RPCState} eq "starting" ||
  3189. $hash->{RPCState} eq "restarting" ||
  3190. $hash->{RPCState} eq "stopping") {
  3191. return 1;
  3192. }
  3193. else {
  3194. return 0;
  3195. }
  3196. }
  3197. ######################################################################
  3198. # Check if RPC servers are running.
  3199. # Return number of running RPC servers. If paramters pids or tids are
  3200. # defined also return process or thread IDs.
  3201. ######################################################################
  3202. sub HMCCU_IsRPCServerRunning ($$$)
  3203. {
  3204. my ($hash, $pids, $tids) = @_;
  3205. my $name = $hash->{NAME};
  3206. my $c = 0;
  3207. my $ccuflags = HMCCU_GetFlags ($name);
  3208. if (HMCCU_IsFlag ($name, "(extrpc|procrpc)")) {
  3209. # @$tids = () if (defined ($tids));
  3210. # my ($rpcdev, $save) = HMCCU_GetRPCDevice ($hash, 0, undef);
  3211. # if ($rpcdev ne '') {
  3212. # my ($r, $a) = HMCCURPC_CheckThreadState ($defs{$rpcdev}, 6, 'running', $tids);
  3213. # $c = $r;
  3214. # }
  3215. # }
  3216. # elsif ($ccuflags =~ /procrpc/) {
  3217. @$pids = () if (defined ($pids));
  3218. my @iflist = HMCCU_GetRPCInterfaceList ($hash);
  3219. foreach my $ifname (@iflist) {
  3220. my ($rpcdev, $save) = HMCCU_GetRPCDevice ($hash, 0, $ifname);
  3221. next if ($rpcdev eq '');
  3222. my $rc = HMCCURPCPROC_CheckProcessState ($defs{$rpcdev}, 'running');
  3223. if ($rc < 0 || $rc > 1) {
  3224. push (@$pids, $rc);
  3225. $c++;
  3226. }
  3227. }
  3228. }
  3229. else {
  3230. @$pids = () if (defined ($pids));
  3231. foreach my $clkey (keys %{$hash->{hmccu}{rpc}}) {
  3232. if (defined ($hash->{hmccu}{rpc}{$clkey}{pid})) {
  3233. my $pid = $hash->{hmccu}{rpc}{$clkey}{pid};
  3234. if ($pid != 0 && kill (0, $pid)) {
  3235. push (@$pids, $pid) if (defined ($pids));
  3236. $c++;
  3237. }
  3238. }
  3239. }
  3240. }
  3241. return $c;
  3242. }
  3243. ######################################################################
  3244. # Get channels and datapoints of CCU device
  3245. ######################################################################
  3246. sub HMCCU_GetDeviceInfo ($$$)
  3247. {
  3248. my ($hash, $device, $ccuget) = @_;
  3249. my $name = $hash->{NAME};
  3250. my $devname = '';
  3251. my $hmccu_hash = HMCCU_GetHash ($hash);
  3252. return '' if (!defined ($hmccu_hash));
  3253. $ccuget = HMCCU_GetAttribute ($hmccu_hash, $hash, 'ccuget', 'Value') if ($ccuget eq 'Attr');
  3254. my ($int, $add, $chn, $dpt, $nam, $flags) = HMCCU_ParseObject ($hmccu_hash, $device, 0);
  3255. if ($flags == $HMCCU_FLAG_ADDRESS) {
  3256. $devname = HMCCU_GetDeviceName ($hmccu_hash, $add, '');
  3257. return '' if ($devname eq '');
  3258. }
  3259. else {
  3260. $devname = $nam;
  3261. }
  3262. my $response = HMCCU_HMScriptExt ($hmccu_hash, "!GetDeviceInfo",
  3263. { devname => $devname, ccuget => $ccuget });
  3264. HMCCU_Trace ($hash, 2, undef,
  3265. "Device=$device Devname=$devname<br>".
  3266. "Script response = \n".$response."<br>".
  3267. "Script = GetDeviceInfo");
  3268. return $response;
  3269. }
  3270. ######################################################################
  3271. # Make device info readable
  3272. # n=number, b=bool, f=float, i=integer, s=string, a=alarm, p=presence
  3273. # e=enumeration
  3274. ######################################################################
  3275. sub HMCCU_FormatDeviceInfo ($)
  3276. {
  3277. my ($devinfo) = @_;
  3278. my %vtypes = (0, "n", 2, "b", 4, "f", 6, "a", 8, "n", 11, "s", 16, "i", 20, "s", 23, "p", 29, "e");
  3279. my $result = '';
  3280. my $c_oaddr = '';
  3281. foreach my $dpspec (split ("\n", $devinfo)) {
  3282. my ($c, $c_addr, $c_name, $d_name, $d_type, $d_value, $d_flags) = split (";", $dpspec);
  3283. if ($c_addr ne $c_oaddr) {
  3284. $result .= "CHN $c_addr $c_name\n";
  3285. $c_oaddr = $c_addr;
  3286. }
  3287. my $t = exists ($vtypes{$d_type}) ? $vtypes{$d_type} : $d_type;
  3288. $result .= " DPT {$t} $d_name = $d_value [$d_flags]\n";
  3289. }
  3290. return $result;
  3291. }
  3292. ######################################################################
  3293. # Get available firmware versions from EQ-3 server.
  3294. # Firmware version, date and download link are stored in hash
  3295. # {hmccu}{type}{$type} in elements {firmware}, {date} and {download}.
  3296. # Parameter type can be a regular expression matching valid Homematic
  3297. # device types in upper case letters. Default is '.*'.
  3298. # Return number of available firmware downloads.
  3299. ######################################################################
  3300. sub HMCCU_GetFirmwareVersions ($$)
  3301. {
  3302. my ($hash, $type) = @_;
  3303. my $name = $hash->{NAME};
  3304. my $ccureqtimeout = AttrVal ($name, "ccuReqTimeout", $HMCCU_TIMEOUT_REQUEST);
  3305. my $url = "http://www.eq-3.de/service/downloads.html";
  3306. my $response = GetFileFromURL ($url, $ccureqtimeout, "suchtext=&suche_in=&downloadart=11");
  3307. my @download = $response =~ m/<a.href="(Downloads\/Software\/Firmware\/[^"]+)/g;
  3308. my $dc = 0;
  3309. my @ts = localtime (time);
  3310. $ts[4] += 1;
  3311. $ts[5] += 1900;
  3312. foreach my $dl (@download) {
  3313. my $dd = $ts[3];
  3314. my $mm = $ts[4];
  3315. my $yy = $ts[5];
  3316. my $fw;
  3317. my $date = "$dd.$mm.$yy";
  3318. my @path = split (/\//, $dl);
  3319. my $file = pop @path;
  3320. next if ($file !~ /(\.tgz|\.tar\.gz)/);
  3321. $file =~ s/_update_V?/\|/;
  3322. my ($dt, $rest) = split (/\|/, $file);
  3323. next if (!defined ($rest));
  3324. $dt =~ s/_/-/g;
  3325. $dt = uc($dt);
  3326. next if ($dt !~ /$type/);
  3327. if ($rest =~ /^([\d_]+)([0-9]{2})([0-9]{2})([0-9]{2})\./) {
  3328. # Filename with version and date
  3329. ($fw, $yy, $mm, $dd) = ($1, $2, $3, $4);
  3330. $yy += 2000 if ($yy < 100);
  3331. $date = "$dd.$mm.$yy";
  3332. $fw =~ s/_$//;
  3333. }
  3334. elsif ($rest =~ /^([\d_]+)\./) {
  3335. # Filename with version
  3336. $fw = $1;
  3337. }
  3338. else {
  3339. $fw = $rest;
  3340. }
  3341. $fw =~ s/_/\./g;
  3342. # Compare firmware dates
  3343. if (exists ($hash->{hmccu}{type}{$dt}{date})) {
  3344. my ($dd1, $mm1, $yy1) = split (/\./, $hash->{hmccu}{type}{$dt}{date});
  3345. my $v1 = $yy1*10000+$mm1*100+$dd1;
  3346. my $v2 = $yy*10000+$mm*100+$dd;
  3347. next if ($v1 > $v2);
  3348. }
  3349. $dc++;
  3350. $hash->{hmccu}{type}{$dt}{firmware} = $fw;
  3351. $hash->{hmccu}{type}{$dt}{date} = $date;
  3352. $hash->{hmccu}{type}{$dt}{download} = $dl;
  3353. }
  3354. return $dc;
  3355. }
  3356. ######################################################################
  3357. # Read CCU device identified by device or channel name via Homematic
  3358. # Script.
  3359. # Return (device count, channel count) or (-1, -1) on error.
  3360. ######################################################################
  3361. sub HMCCU_GetDevice ($$)
  3362. {
  3363. my ($hash, $name) = @_;
  3364. my $devcount = 0;
  3365. my $chncount = 0;
  3366. my $devname;
  3367. my $devtype;
  3368. my %objects = ();
  3369. my $response = HMCCU_HMScriptExt ($hash, "!GetDevice", { name => $name });
  3370. return (-1, -1) if ($response eq '' || $response =~ /^ERROR:.*/);
  3371. my @scrlines = split /\n/,$response;
  3372. foreach my $hmdef (@scrlines) {
  3373. my @hmdata = split /;/,$hmdef;
  3374. next if (scalar (@hmdata) == 0);
  3375. my $typeprefix = '';
  3376. if ($hmdata[0] eq 'D') {
  3377. next if (scalar (@hmdata) != 6);
  3378. # 1=Interface 2=Device-Address 3=Device-Name 4=Device-Type 5=Channel-Count
  3379. $objects{$hmdata[2]}{addtype} = 'dev';
  3380. $objects{$hmdata[2]}{channels} = $hmdata[5];
  3381. $objects{$hmdata[2]}{flag} = 'N';
  3382. $objects{$hmdata[2]}{interface} = $hmdata[1];
  3383. $objects{$hmdata[2]}{name} = $hmdata[3];
  3384. $typeprefix = "CUX-" if ($hmdata[2] =~ /^CUX/);
  3385. $typeprefix = "HVL-" if ($hmdata[1] eq 'HVL');
  3386. $objects{$hmdata[2]}{type} = $typeprefix . $hmdata[4];
  3387. $objects{$hmdata[2]}{chndir} = 0;
  3388. $devname = $hmdata[3];
  3389. $devtype = $typeprefix . $hmdata[4];
  3390. }
  3391. elsif ($hmdata[0] eq 'C') {
  3392. next if (scalar (@hmdata) != 4);
  3393. # 1=Channel-Address 2=Channel-Name 3=Direction
  3394. $objects{$hmdata[1]}{addtype} = 'chn';
  3395. $objects{$hmdata[1]}{channels} = 1;
  3396. $objects{$hmdata[1]}{flag} = 'N';
  3397. $objects{$hmdata[1]}{name} = $hmdata[2];
  3398. $objects{$hmdata[1]}{valid} = 1;
  3399. $objects{$hmdata[1]}{chndir} = $hmdata[3];
  3400. }
  3401. }
  3402. if (scalar (keys %objects) > 0) {
  3403. # Update HMCCU device tables
  3404. ($devcount, $chncount) = HMCCU_UpdateDeviceTable ($hash, \%objects);
  3405. # Read available datapoints for device type
  3406. HMCCU_GetDatapointList ($hash, $devname, $devtype) if (defined ($devname) && defined ($devtype));
  3407. }
  3408. return ($devcount, $chncount);
  3409. }
  3410. ######################################################################
  3411. # Read list of CCU devices, channels, interfaces, programs and groups
  3412. # via Homematic Script.
  3413. # Update data of client devices if not current.
  3414. # Return counters (devices, channels, interfaces, programs, groups)
  3415. # or (-1, -1, -1, -1, -1) on error.
  3416. ######################################################################
  3417. sub HMCCU_GetDeviceList ($)
  3418. {
  3419. my ($hash) = @_;
  3420. my $name = $hash->{NAME};
  3421. my $devcount = 0;
  3422. my $chncount = 0;
  3423. my $ifcount = 0;
  3424. my $prgcount = 0;
  3425. my $gcount = 0;
  3426. my %objects = ();
  3427. # Read devices, channels, interfaces and groups from CCU
  3428. my $response = HMCCU_HMScriptExt ($hash, "!GetDeviceList", undef);
  3429. return (-1, -1, -1, -1, -1) if ($response eq '' || $response =~ /^ERROR:.*/);
  3430. my $groups = HMCCU_HMScriptExt ($hash, "!GetGroupDevices", undef);
  3431. # CCU is reachable
  3432. $hash->{ccustate} = 'active';
  3433. # Delete old entries
  3434. %{$hash->{hmccu}{dev}} = ();
  3435. %{$hash->{hmccu}{adr}} = ();
  3436. %{$hash->{hmccu}{grp}} = ();
  3437. %{$hash->{hmccu}{prg}} = ();
  3438. $hash->{hmccu}{updatetime} = time ();
  3439. # Device hash elements for HMCCU_UpdateDeviceTable():
  3440. #
  3441. # {address}{flag} := [N, D, R]
  3442. # {address}{addtype} := [chn, dev]
  3443. # {address}{channels} := Number of channels
  3444. # {address}{name} := Device or channel name
  3445. # {address}{type} := Homematic device type
  3446. # {address}{usetype} := Usage type
  3447. # {address}{interface} := Device interface ID
  3448. # {address}{firmware} := Firmware version of device
  3449. # {address}{version} := Version of RPC device description
  3450. # {address}{rxmode} := Transmit mode
  3451. # {address}{chndir} := Channel direction: 1=sensor 2=actor 0=none
  3452. my @scrlines = split /\n/,$response;
  3453. foreach my $hmdef (@scrlines) {
  3454. my @hmdata = split /;/,$hmdef;
  3455. next if (scalar (@hmdata) == 0);
  3456. my $typeprefix = '';
  3457. if ($hmdata[0] eq 'D') {
  3458. next if (scalar (@hmdata) != 6);
  3459. # 1=Interface 2=Device-Address 3=Device-Name 4=Device-Type 5=Channel-Count
  3460. $objects{$hmdata[2]}{addtype} = 'dev';
  3461. $objects{$hmdata[2]}{channels} = $hmdata[5];
  3462. $objects{$hmdata[2]}{flag} = 'N';
  3463. $objects{$hmdata[2]}{interface} = $hmdata[1];
  3464. $objects{$hmdata[2]}{name} = $hmdata[3];
  3465. $typeprefix = "CUX-" if ($hmdata[2] =~ /^CUX/);
  3466. $typeprefix = "HVL-" if ($hmdata[1] eq 'HVL');
  3467. $objects{$hmdata[2]}{type} = $typeprefix . $hmdata[4];
  3468. $objects{$hmdata[2]}{chndir} = 0;
  3469. # CCU information (address = BidCoS-RF)
  3470. if ($hmdata[2] eq 'BidCoS-RF') {
  3471. $hash->{ccuname} = $hmdata[3];
  3472. $hash->{ccuaddr} = $hmdata[2];
  3473. $hash->{ccuif} = $hmdata[1];
  3474. }
  3475. }
  3476. elsif ($hmdata[0] eq 'C') {
  3477. next if (scalar (@hmdata) != 4);
  3478. # 1=Channel-Address 2=Channel-Name 3=Direction
  3479. $objects{$hmdata[1]}{addtype} = 'chn';
  3480. $objects{$hmdata[1]}{channels} = 1;
  3481. $objects{$hmdata[1]}{flag} = 'N';
  3482. $objects{$hmdata[1]}{name} = $hmdata[2];
  3483. $objects{$hmdata[1]}{valid} = 1;
  3484. $objects{$hmdata[1]}{chndir} = $hmdata[3];
  3485. }
  3486. elsif ($hmdata[0] eq 'I') {
  3487. next if (scalar (@hmdata) != 4);
  3488. # 1=Interface-Name 2=Interface Info 3=URL
  3489. my $ifurl = $hmdata[3];
  3490. if ($ifurl =~ /^([^:]+):\/\/([^:]+):([0-9]+)/) {
  3491. my ($prot, $ipaddr, $port) = ($1, $2, $3);
  3492. next if (!defined ($port) || $port eq '');
  3493. if ($hash->{ccuip} ne 'N/A') {
  3494. $ifurl =~ s/127\.0\.0\.1/$hash->{ccuip}/;
  3495. $ipaddr =~ s/127\.0\.0\.1/$hash->{ccuip}/;
  3496. }
  3497. else {
  3498. $ifurl =~ s/127\.0\.0\.1/$hash->{host}/;
  3499. $ipaddr =~ s/127\.0\.0\.1/$hash->{host}/;
  3500. }
  3501. if ($HMCCU_RPC_FLAG{$port} =~ /forceASCII/) {
  3502. $ifurl =~ s/xmlrpc_bin/xmlrpc/;
  3503. $prot = "xmlrpc";
  3504. }
  3505. # Perl module RPC::XML::Client.pm does not support URLs starting with xmlrpc://
  3506. $ifurl =~ s/xmlrpc:/http:/;
  3507. $prot =~ s/^xmlrpc$/http/;
  3508. $hash->{hmccu}{interfaces}{$hmdata[1]}{url} = $ifurl;
  3509. $hash->{hmccu}{interfaces}{$hmdata[1]}{prot} = $prot;
  3510. $hash->{hmccu}{interfaces}{$hmdata[1]}{type} = $prot eq 'http' ? 'A' : 'B';
  3511. $hash->{hmccu}{interfaces}{$hmdata[1]}{port} = $port;
  3512. $hash->{hmccu}{interfaces}{$hmdata[1]}{host} = $ipaddr;
  3513. $hash->{hmccu}{interfaces}{$hmdata[1]}{state} = 'inactive';
  3514. $hash->{hmccu}{interfaces}{$hmdata[1]}{manager} = 'null';
  3515. $hash->{hmccu}{interfaces}{$hmdata[1]}{flags} = $HMCCU_RPC_FLAG{$port};
  3516. $hash->{hmccu}{ifports}{$port} = $hmdata[1];
  3517. $ifcount++;
  3518. }
  3519. }
  3520. elsif ($hmdata[0] eq 'P') {
  3521. next if (scalar (@hmdata) != 4);
  3522. # 1=Program-Name 2=Active-Flag 3=Internal-Flag
  3523. $hash->{hmccu}{prg}{$hmdata[1]}{active} = $hmdata[2];
  3524. $hash->{hmccu}{prg}{$hmdata[1]}{internal} = $hmdata[3];
  3525. $prgcount++;
  3526. }
  3527. }
  3528. if (scalar (keys %objects) > 0) {
  3529. # Update some CCU I/O device information
  3530. $hash->{ccuinterfaces} = join (',', keys %{$hash->{hmccu}{interfaces}});
  3531. # Update HMCCU device tables
  3532. ($devcount, $chncount) = HMCCU_UpdateDeviceTable ($hash, \%objects);
  3533. # Read available datapoints for each device type
  3534. # This will lead to problems if some devices have different firmware versions
  3535. # or links to system variables !
  3536. HMCCU_GetDatapointList ($hash, undef, undef);
  3537. }
  3538. # Store group configurations
  3539. if ($groups !~ /^ERROR:.*/ && $groups ne '') {
  3540. my @gnames = ($groups =~ m/"NAME":"([^"]+)"/g);
  3541. my @gmembers = ($groups =~ m/"groupMembers":\[[^\]]+\]/g);
  3542. my @gtypes = ($groups =~ m/"groupType":\{"id":"([^"]+)"/g);
  3543. foreach my $gm (@gmembers) {
  3544. my $gn = shift @gnames;
  3545. my $gt = shift @gtypes;
  3546. my @ml = ($gm =~ m/,"id":"([^"]+)"/g);
  3547. $hash->{hmccu}{grp}{$gn}{type} = $gt;
  3548. $hash->{hmccu}{grp}{$gn}{devs} = join (',', @ml);
  3549. $gcount++;
  3550. }
  3551. }
  3552. # Store asset counters
  3553. $hash->{hmccu}{ccu}{devcount} = $devcount;
  3554. $hash->{hmccu}{ccu}{chncount} = $chncount;
  3555. $hash->{hmccu}{ccu}{ifcount} = $ifcount;
  3556. $hash->{hmccu}{ccu}{prgcount} = $prgcount;
  3557. $hash->{hmccu}{ccu}{gcount} = $gcount;
  3558. readingsBeginUpdate ($hash);
  3559. readingsBulkUpdate ($hash, "count_devices", $devcount);
  3560. readingsBulkUpdate ($hash, "count_channels", $chncount);
  3561. readingsBulkUpdate ($hash, "count_interfaces", $ifcount);
  3562. readingsBulkUpdate ($hash, "count_programs", $prgcount);
  3563. readingsBulkUpdate ($hash, "count_groups", $gcount);
  3564. readingsEndUpdate ($hash, 1);
  3565. return ($devcount, $chncount, $ifcount, $prgcount, $gcount);
  3566. }
  3567. ######################################################################
  3568. # Read list of datapoints for all or one CCU device type(s).
  3569. # Function must not be called before GetDeviceList.
  3570. # Return number of datapoints.
  3571. ######################################################################
  3572. sub HMCCU_GetDatapointList ($$$)
  3573. {
  3574. my ($hash, $devname, $devtype) = @_;
  3575. my $name = $hash->{NAME};
  3576. my @devunique;
  3577. if (defined ($devname) && defined ($devtype)) {
  3578. return 0 if (exists ($hash->{hmccu}{dp}{$devtype}));
  3579. push @devunique, $devname;
  3580. }
  3581. else {
  3582. if (exists ($hash->{hmccu}{dp})) {
  3583. delete $hash->{hmccu}{dp};
  3584. }
  3585. # Select one device for each device type
  3586. my %alltypes;
  3587. foreach my $add (sort keys %{$hash->{hmccu}{dev}}) {
  3588. next if ($hash->{hmccu}{dev}{$add}{addtype} ne 'dev');
  3589. my $dt = $hash->{hmccu}{dev}{$add}{type};
  3590. if (defined ($dt)) {
  3591. if ($dt ne '' && !exists ($alltypes{$dt})) {
  3592. $alltypes{$dt} = 1;
  3593. push @devunique, $hash->{hmccu}{dev}{$add}{name};
  3594. }
  3595. }
  3596. else {
  3597. Log3 $name, 2, "HMCCU: Corrupt or invalid entry in device table for device $add";
  3598. }
  3599. }
  3600. }
  3601. if (scalar (@devunique) == 0) {
  3602. Log3 $name, 2, "HMCCU: No device types found in device table. Cannot read datapoints.";
  3603. return 0;
  3604. }
  3605. my $devlist = join (',', @devunique);
  3606. my $response = HMCCU_HMScriptExt ($hash, "!GetDatapointList",
  3607. { list => $devlist });
  3608. if ($response eq '' || $response =~ /^ERROR:.*/) {
  3609. Log3 $name, 2, "HMCCU: Cannot get datapoint list";
  3610. return 0;
  3611. }
  3612. my $c = 0;
  3613. foreach my $dpspec (split /\n/,$response) {
  3614. my ($iface, $chna, $devt, $devc, $dptn, $dptt, $dpto) = split (";", $dpspec);
  3615. $devt = "CUX-".$devt if ($iface eq 'CUxD');
  3616. $devt = "HVL-".$devt if ($iface eq 'HVL');
  3617. $hash->{hmccu}{dp}{$devt}{spc}{ontime} = $devc.".".$dptn if ($dptn eq "ON_TIME");
  3618. $hash->{hmccu}{dp}{$devt}{spc}{ramptime} = $devc.".".$dptn if ($dptn eq "RAMP_TIME");
  3619. $hash->{hmccu}{dp}{$devt}{spc}{submit} = $devc.".".$dptn if ($dptn eq "SUBMIT");
  3620. $hash->{hmccu}{dp}{$devt}{spc}{level} = $devc.".".$dptn if ($dptn eq "LEVEL");
  3621. $hash->{hmccu}{dp}{$devt}{ch}{$devc}{$dptn}{type} = $dptt;
  3622. $hash->{hmccu}{dp}{$devt}{ch}{$devc}{$dptn}{oper} = $dpto;
  3623. if (exists ($hash->{hmccu}{dp}{$devt}{cnt}{$dptn})) {
  3624. $hash->{hmccu}{dp}{$devt}{cnt}{$dptn}++;
  3625. }
  3626. else {
  3627. $hash->{hmccu}{dp}{$devt}{cnt}{$dptn} = 1;
  3628. }
  3629. $c++;
  3630. }
  3631. return $c;
  3632. }
  3633. ######################################################################
  3634. # Check if device/channel name or address is valid and refers to an
  3635. # existing device or channel.
  3636. # mode: Bit combination: 1=Address 2=Name 4=Special address
  3637. ######################################################################
  3638. sub HMCCU_IsValidDeviceOrChannel ($$$)
  3639. {
  3640. my ($hash, $param, $mode) = @_;
  3641. return HMCCU_IsValidDevice ($hash, $param, $mode) || HMCCU_IsValidChannel ($hash, $param, $mode) ? 1 : 0;
  3642. }
  3643. ######################################################################
  3644. # Check if device name or address is valid and refers to an existing
  3645. # device.
  3646. # mode: Bit combination: 1=Address 2=Name 4=Special address
  3647. ######################################################################
  3648. sub HMCCU_IsValidDevice ($$$)
  3649. {
  3650. my ($hash, $param, $mode) = @_;
  3651. # Address
  3652. if ($mode & $HMCCU_FL_STADDRESS) {
  3653. # Address with interface
  3654. if (HMCCU_IsDevAddr ($param, 1)) {
  3655. my ($i, $a) = split (/\./, $param);
  3656. return 0 if (! exists ($hash->{hmccu}{dev}{$a}));
  3657. return $hash->{hmccu}{dev}{$a}{valid};
  3658. }
  3659. # Address without interface
  3660. if (HMCCU_IsDevAddr ($param, 0)) {
  3661. return 0 if (! exists ($hash->{hmccu}{dev}{$param}));
  3662. return $hash->{hmccu}{dev}{$param}{valid};
  3663. }
  3664. # Special address for Non-Homematic devices
  3665. if (($mode & $HMCCU_FL_EXADDRESS) && exists ($hash->{hmccu}{dev}{$param})) {
  3666. return $hash->{hmccu}{dev}{$param}{valid} && $hash->{hmccu}{dev}{$param}{addtype} eq 'dev' ? 1 : 0;
  3667. }
  3668. }
  3669. # Name
  3670. if (($mode & 2) && exists ($hash->{hmccu}{adr}{$param})) {
  3671. return $hash->{hmccu}{adr}{$param}{valid} && $hash->{hmccu}{adr}{$param}{addtype} eq 'dev' ? 1 : 0;
  3672. }
  3673. return 0;
  3674. }
  3675. ######################################################################
  3676. # Check if channel name or address is valid and refers to an existing
  3677. # channel.
  3678. # mode: Bit combination: 1=Address 2=Name 4=Special address
  3679. ######################################################################
  3680. sub HMCCU_IsValidChannel ($$$)
  3681. {
  3682. my ($hash, $param, $mode) = @_;
  3683. # Standard address for Homematic devices
  3684. if ($mode & $HMCCU_FL_STADDRESS) {
  3685. # Address with interface
  3686. if (($mode & $HMCCU_FL_STADDRESS) && HMCCU_IsChnAddr ($param, 1)) {
  3687. my ($i, $a) = split (/\./, $param);
  3688. return 0 if (! exists ($hash->{hmccu}{dev}{$a}));
  3689. return $hash->{hmccu}{dev}{$a}{valid};
  3690. }
  3691. # Address without interface
  3692. if (HMCCU_IsChnAddr ($param, 0)) {
  3693. return 0 if (! exists ($hash->{hmccu}{dev}{$param}));
  3694. return $hash->{hmccu}{dev}{$param}{valid};
  3695. }
  3696. }
  3697. # Special address for Non-Homematic devices
  3698. if (($mode & $HMCCU_FL_EXADDRESS) && exists ($hash->{hmccu}{dev}{$param})) {
  3699. return $hash->{hmccu}{dev}{$param}{valid} && $hash->{hmccu}{dev}{$param}{addtype} eq 'chn' ? 1 : 0;
  3700. }
  3701. # Name
  3702. if (($mode & 2) && exists ($hash->{hmccu}{adr}{$param})) {
  3703. return $hash->{hmccu}{adr}{$param}{valid} && $hash->{hmccu}{adr}{$param}{addtype} eq 'chn' ? 1 : 0;
  3704. }
  3705. return 0;
  3706. }
  3707. ######################################################################
  3708. # Get CCU parameters of device or channel.
  3709. # Returns list containing interface, deviceaddress, name, type and
  3710. # channels.
  3711. ######################################################################
  3712. sub HMCCU_GetCCUDeviceParam ($$)
  3713. {
  3714. my ($hash, $param) = @_;
  3715. my $name = $hash->{NAME};
  3716. my $devadd;
  3717. my $add = undef;
  3718. my $chn = undef;
  3719. if (HMCCU_IsDevAddr ($param, 1) || HMCCU_IsChnAddr ($param, 1)) {
  3720. my $i;
  3721. ($i, $add) = split (/\./, $param);
  3722. }
  3723. else {
  3724. if (HMCCU_IsDevAddr ($param, 0) || HMCCU_IsChnAddr ($param, 0)) {
  3725. $add = $param;
  3726. }
  3727. else {
  3728. if (exists ($hash->{hmccu}{adr}{$param})) {
  3729. $add = $hash->{hmccu}{adr}{$param}{address};
  3730. }
  3731. }
  3732. }
  3733. return (undef, undef, undef, undef) if (!defined ($add));
  3734. ($devadd, $chn) = split (':', $add);
  3735. return (undef, undef, undef, undef) if (!defined ($devadd) ||
  3736. !exists ($hash->{hmccu}{dev}{$devadd}) || $hash->{hmccu}{dev}{$devadd}{valid} == 0);
  3737. return ($hash->{hmccu}{dev}{$devadd}{interface}, $add, $hash->{hmccu}{dev}{$add}{name},
  3738. $hash->{hmccu}{dev}{$devadd}{type}, $hash->{hmccu}{dev}{$add}{channels});
  3739. }
  3740. ######################################################################
  3741. # Get list of valid datapoints for device type.
  3742. # hash = hash of client or IO device
  3743. # devtype = Homematic device type
  3744. # chn = Channel number, -1=all channels
  3745. # oper = Valid operation: 1=Read, 2=Write, 4=Event
  3746. # dplistref = Reference for array with datapoints.
  3747. # Return number of datapoints.
  3748. ######################################################################
  3749. sub HMCCU_GetValidDatapoints ($$$$$)
  3750. {
  3751. my ($hash, $devtype, $chn, $oper, $dplistref) = @_;
  3752. my $hmccu_hash = HMCCU_GetHash ($hash);
  3753. return 0 if (HMCCU_IsFlag ($hmccu_hash->{NAME}, "dptnocheck"));
  3754. return 0 if (!exists ($hmccu_hash->{hmccu}{dp}));
  3755. return HMCCU_Log ($hash, 2, "chn undefined", 0) if (!defined ($chn));
  3756. if ($chn >= 0) {
  3757. if (exists ($hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$chn})) {
  3758. foreach my $dp (sort keys %{$hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$chn}}) {
  3759. if ($hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$chn}{$dp}{oper} & $oper) {
  3760. push @$dplistref, $dp;
  3761. }
  3762. }
  3763. }
  3764. }
  3765. else {
  3766. if (exists ($hmccu_hash->{hmccu}{dp}{$devtype})) {
  3767. foreach my $ch (sort keys %{$hmccu_hash->{hmccu}{dp}{$devtype}{ch}}) {
  3768. foreach my $dp (sort keys %{$hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$ch}}) {
  3769. if ($hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$ch}{$dp}{oper} & $oper) {
  3770. push @$dplistref, $ch.".".$dp;
  3771. }
  3772. }
  3773. }
  3774. }
  3775. }
  3776. return scalar (@$dplistref);
  3777. }
  3778. ######################################################################
  3779. # Get datapoint attribute.
  3780. # Valid attributes are 'oper' or 'type'.
  3781. ######################################################################
  3782. sub HMCCU_GetDatapointAttr ($$$$$)
  3783. {
  3784. my ($hash, $devtype, $chnno, $dpt, $attr) = @_;
  3785. return undef if ($attr ne 'oper' && $attr ne 'type');
  3786. return undef if (!exists ($hash->{hmccu}{dp}{$devtype}));
  3787. return undef if (!exists ($hash->{hmccu}{dp}{$devtype}{ch}{$chnno}));
  3788. return undef if (!exists ($hash->{hmccu}{dp}{$devtype}{ch}{$chnno}{$dpt}));
  3789. return $hash->{hmccu}{dp}{$devtype}{ch}{$chnno}{$dpt}{$attr};
  3790. }
  3791. ######################################################################
  3792. # Find a datapoint for device type.
  3793. # hash = hash of client or IO device
  3794. # devtype = Homematic device type
  3795. # chn = Channel number, -1=all channels
  3796. # oper = Valid operation: 1=Read, 2=Write, 4=Event
  3797. # Return channel of first match or -1.
  3798. ######################################################################
  3799. sub HMCCU_FindDatapoint ($$$$$)
  3800. {
  3801. my ($hash, $devtype, $chn, $dpt, $oper) = @_;
  3802. my $hmccu_hash = HMCCU_GetHash ($hash);
  3803. return -1 if (!exists ($hmccu_hash->{hmccu}{dp}));
  3804. if ($chn >= 0) {
  3805. if (exists ($hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$chn})) {
  3806. foreach my $dp (sort keys %{$hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$chn}}) {
  3807. return $chn if ($dp eq $dpt &&
  3808. $hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$chn}{$dp}{oper} & $oper);
  3809. }
  3810. }
  3811. }
  3812. else {
  3813. if (exists ($hmccu_hash->{hmccu}{dp}{$devtype})) {
  3814. foreach my $ch (sort keys %{$hmccu_hash->{hmccu}{dp}{$devtype}{ch}}) {
  3815. foreach my $dp (sort keys %{$hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$ch}}) {
  3816. return $ch if ($dp eq $dpt &&
  3817. $hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$ch}{$dp}{oper} & $oper);
  3818. }
  3819. }
  3820. }
  3821. }
  3822. return -1;
  3823. }
  3824. ######################################################################
  3825. # Get channel number and datapoint name for special datapoint.
  3826. # Valid modes are ontime, ramptime, submit, level
  3827. ######################################################################
  3828. sub HMCCU_GetSwitchDatapoint ($$$)
  3829. {
  3830. my ($hash, $devtype, $mode) = @_;
  3831. my $hmccu_hash = HMCCU_GetHash ($hash);
  3832. if (exists ($hmccu_hash->{hmccu}{dp}{$devtype}{spc}{$mode})) {
  3833. return $hmccu_hash->{hmccu}{dp}{$devtype}{spc}{$mode};
  3834. }
  3835. else {
  3836. return '';
  3837. }
  3838. }
  3839. ######################################################################
  3840. # Check if datapoint is valid.
  3841. # Parameter chn can be a channel address or a channel number. If dpt
  3842. # contains a channel number parameter chn should be set to undef.
  3843. # Parameter dpt can contain a channel number.
  3844. # Parameter oper specifies access flag:
  3845. # 1 = datapoint readable
  3846. # 2 = datapoint writeable
  3847. # Return 1 if ccuflags is set to dptnocheck or datapoint is valid.
  3848. # Otherwise 0.
  3849. ######################################################################
  3850. sub HMCCU_IsValidDatapoint ($$$$$)
  3851. {
  3852. my ($hash, $devtype, $chn, $dpt, $oper) = @_;
  3853. my $fnc = "IsValidDatapoint";
  3854. my $hmccu_hash = HMCCU_GetHash ($hash);
  3855. return 0 if (!defined ($hmccu_hash));
  3856. if ($hash->{TYPE} eq 'HMCCU' && !defined ($devtype)) {
  3857. $devtype = HMCCU_GetDeviceType ($hmccu_hash, $chn, 'null');
  3858. }
  3859. return 1 if (HMCCU_IsFlag ($hmccu_hash->{NAME}, "dptnocheck"));
  3860. return 1 if (!exists ($hmccu_hash->{hmccu}{dp}));
  3861. my $chnno;
  3862. if (defined ($chn)) {
  3863. if ($chn =~ /^[0-9]{1,2}$/) {
  3864. HMCCU_Trace ($hash, 2, $fnc, "$chn is a channel number");
  3865. $chnno = $chn;
  3866. }
  3867. elsif (HMCCU_IsValidChannel ($hmccu_hash, $chn, $HMCCU_FL_ADDRESS)) {
  3868. HMCCU_Trace ($hash, 2, $fnc, "$chn is a valid channel address");
  3869. my ($a, $c) = split(":",$chn);
  3870. $chnno = $c;
  3871. }
  3872. else {
  3873. HMCCU_Trace ($hash, 2, $fnc, "$chn is not a valid channel address or number");
  3874. return 0;
  3875. }
  3876. }
  3877. elsif ($dpt =~ /^([0-9]{1,2})\.(.+)$/) {
  3878. $chnno = $1;
  3879. $dpt = $2;
  3880. HMCCU_Trace ($hash, 2, $fnc, "$dpt contains channel number");
  3881. }
  3882. else {
  3883. HMCCU_Trace ($hash, 2, $fnc, "channel number missing in datapoint $dpt");
  3884. return 0;
  3885. }
  3886. HMCCU_Trace ($hash, 2, $fnc, "devtype=$devtype, chnno=$chnno, dpt=$dpt");
  3887. return (exists ($hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$chnno}{$dpt}) &&
  3888. ($hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$chnno}{$dpt}{oper} & $oper)) ? 1 : 0;
  3889. }
  3890. ######################################################################
  3891. # Get list of device or channel addresses for which device or channel
  3892. # name matches regular expression.
  3893. # Parameter mode can be 'dev' or 'chn'.
  3894. # Return number of matching entries.
  3895. ######################################################################
  3896. sub HMCCU_GetMatchingDevices ($$$$)
  3897. {
  3898. my ($hash, $regexp, $mode, $listref) = @_;
  3899. my $c = 0;
  3900. foreach my $name (sort keys %{$hash->{hmccu}{adr}}) {
  3901. next if ($name !~/$regexp/ || $hash->{hmccu}{adr}{$name}{addtype} ne $mode ||
  3902. $hash->{hmccu}{adr}{$name}{valid} == 0);
  3903. push (@$listref, $hash->{hmccu}{adr}{$name}{address});
  3904. $c++;
  3905. }
  3906. return $c;
  3907. }
  3908. ######################################################################
  3909. # Get name of a CCU device by address.
  3910. # Channel number will be removed if specified.
  3911. ######################################################################
  3912. sub HMCCU_GetDeviceName ($$$)
  3913. {
  3914. my ($hash, $addr, $default) = @_;
  3915. if (HMCCU_IsValidDeviceOrChannel ($hash, $addr, $HMCCU_FL_ADDRESS)) {
  3916. $addr =~ s/:[0-9]+$//;
  3917. return $hash->{hmccu}{dev}{$addr}{name};
  3918. }
  3919. return $default;
  3920. }
  3921. ######################################################################
  3922. # Get name of a CCU device channel by address.
  3923. ######################################################################
  3924. sub HMCCU_GetChannelName ($$$)
  3925. {
  3926. my ($hash, $addr, $default) = @_;
  3927. if (HMCCU_IsValidChannel ($hash, $addr, $HMCCU_FL_ADDRESS)) {
  3928. return $hash->{hmccu}{dev}{$addr}{name};
  3929. }
  3930. return $default;
  3931. }
  3932. ######################################################################
  3933. # Get type of a CCU device by address.
  3934. # Channel number will be removed if specified.
  3935. ######################################################################
  3936. sub HMCCU_GetDeviceType ($$$)
  3937. {
  3938. my ($hash, $addr, $default) = @_;
  3939. if (HMCCU_IsValidDeviceOrChannel ($hash, $addr, $HMCCU_FL_ADDRESS)) {
  3940. $addr =~ s/:[0-9]+$//;
  3941. return $hash->{hmccu}{dev}{$addr}{type};
  3942. }
  3943. return $default;
  3944. }
  3945. ######################################################################
  3946. # Get number of channels of a CCU device.
  3947. # Channel number will be removed if specified.
  3948. ######################################################################
  3949. sub HMCCU_GetDeviceChannels ($$$)
  3950. {
  3951. my ($hash, $addr, $default) = @_;
  3952. if (HMCCU_IsValidDeviceOrChannel ($hash, $addr, $HMCCU_FL_ADDRESS)) {
  3953. $addr =~ s/:[0-9]+$//;
  3954. return $hash->{hmccu}{dev}{$addr}{channels};
  3955. }
  3956. return 0;
  3957. }
  3958. ######################################################################
  3959. # Get interface of a CCU device by address.
  3960. # Channel number will be removed if specified.
  3961. ######################################################################
  3962. sub HMCCU_GetDeviceInterface ($$$)
  3963. {
  3964. my ($hash, $addr, $default) = @_;
  3965. if (HMCCU_IsValidDeviceOrChannel ($hash, $addr, $HMCCU_FL_ADDRESS)) {
  3966. $addr =~ s/:[0-9]+$//;
  3967. return $hash->{hmccu}{dev}{$addr}{interface};
  3968. }
  3969. return $default;
  3970. }
  3971. ######################################################################
  3972. # Get address of a CCU device or channel by CCU name or FHEM device
  3973. # name defined via HMCCUCHN or HMCCUDEV. FHEM device names must be
  3974. # preceded by "hmccu:". CCU names can be preceded by "ccu:".
  3975. # Return array with device address and channel no. If name is not
  3976. # found or refers to a device the specified default values will be
  3977. # returned.
  3978. ######################################################################
  3979. sub HMCCU_GetAddress ($$$$)
  3980. {
  3981. my ($hash, $name, $defadd, $defchn) = @_;
  3982. my $add = $defadd;
  3983. my $chn = $defchn;
  3984. my $chnno = $defchn;
  3985. my $addr = '';
  3986. my $type = '';
  3987. if ($name =~ /^hmccu:.+$/) {
  3988. # Name is a FHEM device name
  3989. $name =~ s/^hmccu://;
  3990. if ($name =~ /^([^:]+):([0-9]{1,2})$/) {
  3991. $name = $1;
  3992. $chnno = $2;
  3993. }
  3994. return ($defadd, $defchn) if (!exists ($defs{$name}));
  3995. my $dh = $defs{$name};
  3996. return ($defadd, $defchn) if ($dh->{TYPE} ne 'HMCCUCHN' && $dh->{TYPE} ne 'HMCCUDEV');
  3997. ($add, $chn) = HMCCU_SplitChnAddr ($dh->{ccuaddr});
  3998. $chn = $chnno if ($chn eq '');
  3999. return ($add, $chn);
  4000. }
  4001. elsif ($name =~ /^ccu:.+$/) {
  4002. # Name is a CCU device or channel name
  4003. $name =~ s/^ccu://;
  4004. }
  4005. if (exists ($hash->{hmccu}{adr}{$name})) {
  4006. # Name known by HMCCU
  4007. $addr = $hash->{hmccu}{adr}{$name}{address};
  4008. $type = $hash->{hmccu}{adr}{$name}{addtype};
  4009. }
  4010. elsif (exists ($hash->{hmccu}{dev}{$name})) {
  4011. # Address known by HMCCU
  4012. $addr = $name;
  4013. $type = $hash->{hmccu}{dev}{$name}{addtype};
  4014. }
  4015. else {
  4016. # Address not known. Query CCU
  4017. my ($dc, $cc) = HMCCU_GetDevice ($hash, $name);
  4018. if ($dc > 0 && $cc > 0 && exists ($hash->{hmccu}{adr}{$name})) {
  4019. $addr = $hash->{hmccu}{adr}{$name}{address};
  4020. $type = $hash->{hmccu}{adr}{$name}{addtype};
  4021. }
  4022. }
  4023. if ($addr ne '') {
  4024. if ($type eq 'chn') {
  4025. ($add, $chn) = split (":", $addr);
  4026. }
  4027. else {
  4028. $add = $addr;
  4029. }
  4030. }
  4031. return ($add, $chn);
  4032. }
  4033. ######################################################################
  4034. # Get addresses of group member devices.
  4035. # Group 'virtual' is ignored.
  4036. # Return list of device addresses or empty list on error.
  4037. ######################################################################
  4038. sub HMCCU_GetGroupMembers ($$)
  4039. {
  4040. my ($hash, $group) = @_;
  4041. return $group ne 'virtual' && exists ($hash->{hmccu}{grp}{$group}) ?
  4042. split (',', $hash->{hmccu}{grp}{$group}{devs}) : ();
  4043. }
  4044. ######################################################################
  4045. # Check if parameter is a channel address (syntax)
  4046. # f=1: Interface required.
  4047. ######################################################################
  4048. sub HMCCU_IsChnAddr ($$)
  4049. {
  4050. my ($id, $f) = @_;
  4051. if ($f) {
  4052. return ($id =~ /^.+\.[\*]*[A-Z]{3}[0-9]{7}:[0-9]{1,2}$/ ||
  4053. $id =~ /^.+\.[0-9A-F]{12,14}:[0-9]{1,2}$/ ||
  4054. $id =~ /^.+\.OL-.+:[0-9]{1,2}$/ ||
  4055. $id =~ /^.+\.BidCoS-RF:[0-9]{1,2}$/) ? 1 : 0;
  4056. }
  4057. else {
  4058. return ($id =~ /^[\*]*[A-Z]{3}[0-9]{7}:[0-9]{1,2}$/ ||
  4059. $id =~ /^[0-9A-F]{12,14}:[0-9]{1,2}$/ ||
  4060. $id =~ /^OL-.+:[0-9]{1,2}$/ ||
  4061. $id =~ /^BidCoS-RF:[0-9]{1,2}$/) ? 1 : 0;
  4062. }
  4063. }
  4064. ######################################################################
  4065. # Check if parameter is a device address (syntax)
  4066. # f=1: Interface required.
  4067. ######################################################################
  4068. sub HMCCU_IsDevAddr ($$)
  4069. {
  4070. my ($id, $f) = @_;
  4071. if ($f) {
  4072. return ($id =~ /^.+\.[\*]*[A-Z]{3}[0-9]{7}$/ ||
  4073. $id =~ /^.+\.[0-9A-F]{12,14}$/ ||
  4074. $id =~ /^.+\.OL-.+$/ ||
  4075. $id =~ /^.+\.BidCoS-RF$/) ? 1 : 0;
  4076. }
  4077. else {
  4078. return ($id =~ /^[\*]*[A-Z]{3}[0-9]{7}$/ ||
  4079. $id =~ /^[0-9A-F]{12,14}$/ ||
  4080. $id =~ /^OL-.+$/ ||
  4081. $id eq 'BidCoS-RF') ? 1 : 0;
  4082. }
  4083. }
  4084. ######################################################################
  4085. # Split channel address into device address and channel number.
  4086. # Returns device address only if parameter is already a device address.
  4087. ######################################################################
  4088. sub HMCCU_SplitChnAddr ($)
  4089. {
  4090. my ($addr) = @_;
  4091. my ($dev, $chn) = split (':', $addr);
  4092. $chn = '' if (!defined ($chn));
  4093. return ($dev, $chn);
  4094. }
  4095. ######################################################################
  4096. # Get list of client devices matching the specified criteria.
  4097. # If no criteria is specified all device names will be returned.
  4098. # Parameters modexp and namexp are regular expressions for module
  4099. # name and device name. Parameter internal contains a comma separated
  4100. # list of expressions like internal=valueexp.
  4101. # All parameters can be undefined. In this case all devices will be
  4102. # returned.
  4103. ######################################################################
  4104. sub HMCCU_FindClientDevices ($$$$)
  4105. {
  4106. my ($hash, $modexp, $namexp, $internal) = @_;
  4107. my @devlist = ();
  4108. foreach my $d (keys %defs) {
  4109. my $ch = $defs{$d};
  4110. my $m = 1;
  4111. next if (!defined ($ch->{TYPE}) || !defined ($ch->{NAME}));
  4112. next if (defined ($modexp) && $ch->{TYPE} !~ /$modexp/);
  4113. next if (defined ($namexp) && $ch->{NAME} !~ /$namexp/);
  4114. next if (defined ($hash) && exists ($ch->{IODev}) && $ch->{IODev} != $hash);
  4115. if (defined ($internal)) {
  4116. foreach my $intspec (split (',', $internal)) {
  4117. my ($i, $v) = split ('=', $intspec);
  4118. if (defined ($v) && exists ($ch->{$i}) && $ch->{$i} !~ /$v/) {
  4119. $m = 0;
  4120. last;
  4121. }
  4122. }
  4123. }
  4124. push @devlist, $ch->{NAME} if ($m == 1);
  4125. }
  4126. return @devlist;
  4127. }
  4128. ######################################################################
  4129. # Get name of assigned client device of type HMCCURPC or HMCCURPCPROC.
  4130. # Create a RPC device of type HMCCURPC or HMCCURPCPROC if none is
  4131. # found and parameter create is set to 1.
  4132. # Return (devname, create).
  4133. # Return empty string for devname if RPC device cannot be identified
  4134. # or created. Return create = 1 if device has been created and
  4135. # configuration should be saved.
  4136. ######################################################################
  4137. sub HMCCU_GetRPCDevice ($$$)
  4138. {
  4139. my ($hash, $create, $ifname) = @_;
  4140. my $name = $hash->{NAME};
  4141. my $rpcdevname;
  4142. my $rpcdevtype = 'HMCCURPCPROC';
  4143. my $rpchost = $hash->{host};
  4144. my $ccuflags = HMCCU_GetFlags ($name);
  4145. if ($ccuflags =~ /(procrpc|extrpc)/) {
  4146. return (HMCCU_Log ($hash, 1, "Interface not defined for RPC server of type HMCCURPCPROC", ''), 0)
  4147. if (!defined ($ifname));
  4148. $rpcdevname = HMCCU_GetRPCServerInfo ($hash, $ifname, 'device');
  4149. $rpchost = HMCCU_GetRPCServerInfo ($hash, $ifname, 'host');
  4150. return ($rpcdevname, 0) if (defined ($rpcdevname) || !defined ($rpchost));
  4151. # $rpcdevtype = 'HMCCURPCPROC';
  4152. }
  4153. # elsif ($ccuflags =~ /extrpc/) {
  4154. # if (defined ($hash->{RPCDEV})) {
  4155. # if (exists ($defs{$hash->{RPCDEV}})) {
  4156. # my $rpchash = $defs{$hash->{RPCDEV}};
  4157. # return (HMCCU_Log ($hash, 1, "RPC device ".$hash->{RPCDEV}." is not assigned to $name", ''), 0)
  4158. # if (!defined ($rpchash->{IODev}) || $rpchash->{IODev} != $hash);
  4159. # }
  4160. # else {
  4161. # return (HMCCU_Log ($hash, 1, "RPC device ".$hash->{RPCDEV}." not found", ''), 0);
  4162. # }
  4163. # return $hash->{RPCDEV};
  4164. # }
  4165. # }
  4166. else {
  4167. return (HMCCU_Log ($hash, 1, "No need for RPC device when using internal RPC server", ''), 0);
  4168. }
  4169. # Search for RPC devices associated with I/O device
  4170. my @devlist;
  4171. foreach my $dev (keys %defs) {
  4172. my $devhash = $defs{$dev};
  4173. next if ($devhash->{TYPE} ne $rpcdevtype);
  4174. my $ip = 'null';
  4175. my $addrnum = inet_aton ($devhash->{host});
  4176. $ip = inet_ntoa ($addrnum) if (defined ($addrnum));
  4177. next if ($devhash->{host} ne $rpchost && $ip ne $rpchost);
  4178. # next if ($rpcdevtype eq 'HMCCURPCPROC' && $devhash->{rpcinterface} ne $ifname);
  4179. next if ($devhash->{rpcinterface} ne $ifname);
  4180. push @devlist, $devhash->{NAME};
  4181. }
  4182. my $devcnt = scalar (@devlist);
  4183. if ($devcnt == 1) {
  4184. # if ($ccuflags =~ /extrpc/) {
  4185. # $hash->{RPCDEV} = $devlist[0];
  4186. # }
  4187. # else {
  4188. $hash->{hmccu}{interfaces}{$ifname}{device} = $devlist[0];
  4189. # }
  4190. return ($devlist[0], 0);
  4191. }
  4192. elsif ($devcnt > 1) {
  4193. return (HMCCU_Log ($hash, 2, "Found more than one RPC device for interface $ifname", ''), 0);
  4194. }
  4195. HMCCU_Log ($hash, 1, "No RPC device defined for interface $ifname", undef);
  4196. # Create RPC device
  4197. if ($create) {
  4198. my $alias = "CCU RPC";
  4199. my $rpccreate = "d_rpc $rpcdevtype ".$hash->{host};
  4200. $rpcdevname = "d_rpc";
  4201. if (defined ($ifname)) {
  4202. $rpcdevname = makeDeviceName ("d_rpc".$ifname);
  4203. $alias .= " $ifname";
  4204. $rpccreate = "$rpcdevname $rpcdevtype $rpchost $ifname";
  4205. }
  4206. HMCCU_Log ($hash, 1, "Creating new RPC device $rpcdevname", undef);
  4207. my $ret = CommandDefine (undef, $rpccreate);
  4208. if (!defined ($ret)) {
  4209. # RPC device created. Set/copy some attributes from HMCCU device
  4210. my %rpcdevattr = ('room' => 'copy', 'group' => 'copy', 'icon' => 'copy',
  4211. 'stateFormat' => 'rpcstate/state', 'eventMap' => '/rpcserver on:on/rpcserver off:off/',
  4212. 'verbose' => 2, 'alias' => $alias );
  4213. foreach my $a (keys %rpcdevattr) {
  4214. my $v = $rpcdevattr{$a} eq 'copy' ? AttrVal ($name, $a, '') : $rpcdevattr{$a};
  4215. CommandAttr (undef, "$rpcdevname $a $v") if ($v ne '');
  4216. }
  4217. # $hash->{RPCDEV} = $rpcdevname if ($ccuflags =~ /extrpc/);
  4218. return ($rpcdevname, 1);
  4219. }
  4220. else {
  4221. Log3 $name, 1, "HMCCU: [$name] Definition of RPC device failed.";
  4222. Log3 $name, 1, "HMCCU: [$name] $ret";
  4223. }
  4224. }
  4225. return ('', 0);
  4226. }
  4227. ######################################################################
  4228. # Assign IO device to client device.
  4229. # Wrapper function for AssignIOPort()
  4230. # Parameter $hash refers to a client device of type HMCCURPCPROC,
  4231. # HMCCUDEV or HMCCUCHN.
  4232. # Parameters ioname and ifname are optional.
  4233. # Return 1 on success or 0 on error.
  4234. ######################################################################
  4235. sub HMCCU_AssignIODevice ($$$)
  4236. {
  4237. my ($hash, $ioname, $ifname) = @_;
  4238. my $type = $hash->{TYPE};
  4239. my $name = $hash->{NAME};
  4240. my $hmccu_hash;
  4241. AssignIoPort ($hash, $ioname);
  4242. $hmccu_hash = $hash->{IODev} if (exists ($hash->{IODev}));
  4243. if (!defined ($hmccu_hash) || !exists ($hmccu_hash->{TYPE}) || $hmccu_hash->{TYPE} ne 'HMCCU') {
  4244. Log3 $name, 1, "$type: [$name] Can't assign I/O device";
  4245. return 0;
  4246. }
  4247. if ($type eq 'HMCCURPCPROC' && defined ($ifname)) {
  4248. # Register RPC device
  4249. $hmccu_hash->{hmccu}{interfaces}{$ifname}{device} = $name;
  4250. }
  4251. return 1;
  4252. }
  4253. ######################################################################
  4254. # Get hash of HMCCU IO device which is responsible for device or
  4255. # channel specified by parameter. If param is undef the first device
  4256. # of type HMCCU will be returned.
  4257. ######################################################################
  4258. sub HMCCU_FindIODevice ($)
  4259. {
  4260. my ($param) = @_;
  4261. foreach my $dn (sort keys %defs) {
  4262. my $ch = $defs{$dn};
  4263. next if (!exists ($ch->{TYPE}));
  4264. next if ($ch->{TYPE} ne 'HMCCU');
  4265. my $disabled = AttrVal ($ch->{NAME}, 'disable', 0);
  4266. next if ($disabled);
  4267. return $ch if (!defined ($param));
  4268. return $ch if (HMCCU_IsValidDeviceOrChannel ($ch, $param, $HMCCU_FL_ALL));
  4269. }
  4270. return undef;
  4271. }
  4272. ######################################################################
  4273. # Get states of IO devices
  4274. ######################################################################
  4275. sub HMCCU_IODeviceStates ()
  4276. {
  4277. my $active = 0;
  4278. my $inactive = 0;
  4279. # Search for first HMCCU device
  4280. foreach my $dn (sort keys %defs) {
  4281. my $ch = $defs{$dn};
  4282. next if (!exists ($ch->{TYPE}));
  4283. next if ($ch->{TYPE} ne 'HMCCU');
  4284. if (exists ($ch->{ccustate}) && $ch->{ccustate} eq 'active') {
  4285. $active++;
  4286. }
  4287. else {
  4288. $inactive++;
  4289. }
  4290. }
  4291. return ($active, $inactive);
  4292. }
  4293. ######################################################################
  4294. # Get hash of HMCCU IO device. Useful for client devices. Accepts hash
  4295. # of HMCCU, HMCCUDEV or HMCCUCHN device as parameter.
  4296. # If hash is 0 or undefined the hash of the first device of type HMCCU
  4297. # will be returned.
  4298. ######################################################################
  4299. sub HMCCU_GetHash ($@)
  4300. {
  4301. my ($hash) = @_;
  4302. if (defined ($hash) && $hash != 0) {
  4303. if ($hash->{TYPE} eq 'HMCCUDEV' || $hash->{TYPE} eq 'HMCCUCHN') {
  4304. return $hash->{IODev} if (exists ($hash->{IODev}));
  4305. return HMCCU_FindIODevice ($hash->{ccuaddr}) if (exists ($hash->{ccuaddr}));
  4306. }
  4307. elsif ($hash->{TYPE} eq 'HMCCU') {
  4308. return $hash;
  4309. }
  4310. }
  4311. # Search for first HMCCU device
  4312. foreach my $dn (sort keys %defs) {
  4313. my $ch = $defs{$dn};
  4314. next if (!exists ($ch->{TYPE}));
  4315. return $ch if ($ch->{TYPE} eq 'HMCCU');
  4316. }
  4317. return undef;
  4318. }
  4319. ######################################################################
  4320. # Get attribute of client device. Fallback to attribute of IO device.
  4321. ######################################################################
  4322. sub HMCCU_GetAttribute ($$$$)
  4323. {
  4324. my ($hmccu_hash, $cl_hash, $attr_name, $attr_def) = @_;
  4325. my $value = AttrVal ($cl_hash->{NAME}, $attr_name, '');
  4326. $value = AttrVal ($hmccu_hash->{NAME}, $attr_name, $attr_def) if ($value eq '');
  4327. return $value;
  4328. }
  4329. ######################################################################
  4330. # Get number of occurrences of datapoint.
  4331. # Return 0 if datapoint does not exist.
  4332. ######################################################################
  4333. sub HMCCU_GetDatapointCount ($$$)
  4334. {
  4335. my ($hash, $devtype, $dpt) = @_;
  4336. if (exists ($hash->{hmccu}{dp}{$devtype}{cnt}{$dpt})) {
  4337. return $hash->{hmccu}{dp}{$devtype}{cnt}{$dpt};
  4338. }
  4339. else {
  4340. return 0;
  4341. }
  4342. }
  4343. ######################################################################
  4344. # Get channels and datapoints from attributes statechannel,
  4345. # statedatapoint and controldatapoint.
  4346. # Return attribute values. Attribute controldatapoint is splitted into
  4347. # controlchannel and datapoint name. If attribute statedatapoint
  4348. # contains channel number it is splitted into statechannel and
  4349. # datapoint name.
  4350. # If controldatapoint is not specified it will synchronized with
  4351. # statedatapoint.
  4352. ######################################################################
  4353. sub HMCCU_GetSpecialDatapoints ($$$$$)
  4354. {
  4355. # my ($hash, $defsc, $defsd, $defcc, $defcd) = @_;
  4356. my ($hash, $sc, $sd, $cc, $cd) = @_;
  4357. my $name = $hash->{NAME};
  4358. my $type = $hash->{TYPE};
  4359. my $statedatapoint = AttrVal ($name, 'statedatapoint', '');
  4360. my $statechannel = AttrVal ($name, 'statechannel', '');
  4361. my $controldatapoint = AttrVal ($name, 'controldatapoint', $statedatapoint);
  4362. if ($statedatapoint ne '') {
  4363. if ($statedatapoint =~ /^([0-9]+)\.(.+)$/) {
  4364. ($sc, $sd) = ($1, $2);
  4365. }
  4366. else {
  4367. $sd = $statedatapoint;
  4368. }
  4369. }
  4370. $sc = $statechannel if ($statechannel ne '' && $sc eq '');
  4371. if ($controldatapoint ne '') {
  4372. if ($controldatapoint =~ /^([0-9]+)\.(.+)$/) {
  4373. ($cc, $cd) = ($1, $2);
  4374. }
  4375. else {
  4376. $cd = $controldatapoint;
  4377. }
  4378. }
  4379. # For devices of type HMCCUCHN extract channel numbers from CCU device address
  4380. if ($type eq 'HMCCUCHN') {
  4381. $sc = $hash->{ccuaddr};
  4382. $sc =~ s/^[\*]*[0-9A-Z]+://;
  4383. $cc = $sc;
  4384. }
  4385. # Try to find state channel
  4386. my $c = -1;
  4387. if ($sc eq '' && $sd ne '') {
  4388. $c = HMCCU_FindDatapoint ($hash, $hash->{ccutype}, -1, $sd, 3);
  4389. $sc = $c if ($c >= 0);
  4390. }
  4391. # Try to find control channel
  4392. if ($cc eq '' && $cd ne '') {
  4393. $c = HMCCU_FindDatapoint ($hash, $hash->{ccutype}, -1, $cd, 3);
  4394. $cc = $c if ($c >= 0);
  4395. }
  4396. # By default set control channel and datapoint to state channel and datapoint
  4397. $cc = $sc if ($cc eq '');
  4398. $cd = $sd if ($cd eq '');
  4399. return ($sc, $sd, $cc, $cd);
  4400. }
  4401. ######################################################################
  4402. # Get attribute ccuflags.
  4403. # Default value is 'null'. With version 4.2.009 flag extrpc is
  4404. # substituted by procrpc.
  4405. ######################################################################
  4406. sub HMCCU_GetFlags ($)
  4407. {
  4408. my ($name) = @_;
  4409. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  4410. $ccuflags =~ s/extrpc/procrpc/g;
  4411. return $ccuflags;
  4412. }
  4413. ######################################################################
  4414. # Check if specific CCU flag is set.
  4415. ######################################################################
  4416. sub HMCCU_IsFlag ($$)
  4417. {
  4418. my ($name, $flag) = @_;
  4419. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  4420. return $ccuflags =~ /$flag/ ? 1 : 0;
  4421. }
  4422. ######################################################################
  4423. # Get reading format considering default attribute
  4424. # ccudef-readingformat defined in I/O device.
  4425. # Default reading format for virtual groups is always 'name'.
  4426. ######################################################################
  4427. sub HMCCU_GetAttrReadingFormat ($$)
  4428. {
  4429. my ($clhash, $iohash) = @_;
  4430. my $clname = $clhash->{NAME};
  4431. my $ioname = $iohash->{NAME};
  4432. my $rfdef = '';
  4433. if (exists ($clhash->{ccutype}) && $clhash->{ccutype} =~ /^HM-CC-VG/) {
  4434. $rfdef = 'name';
  4435. }
  4436. else {
  4437. $rfdef = AttrVal ($ioname, 'ccudef-readingformat', 'datapoint');
  4438. }
  4439. return AttrVal ($clname, 'ccureadingformat', $rfdef);
  4440. }
  4441. ######################################################################
  4442. # Get attributes substitute and substexcl considering default
  4443. # attribute ccudef-substitute defined in I/O device.
  4444. # Substitute ${xxx} by datapoint value.
  4445. ######################################################################
  4446. sub HMCCU_GetAttrSubstitute ($$)
  4447. {
  4448. my ($clhash, $iohash) = @_;
  4449. my $fnc = "GetAttrSubstitute";
  4450. my $clname = $clhash->{NAME};
  4451. my $ioname = $iohash->{NAME};
  4452. my $substdef = AttrVal ($ioname, 'ccudef-substitute', '');
  4453. my $subst = AttrVal ($clname, 'substitute', $substdef);
  4454. $subst .= ";$substdef" if ($subst ne $substdef && $substdef ne '');
  4455. HMCCU_Trace ($clhash, 2, $fnc, "subst = $subst");
  4456. return $subst if ($subst !~ /\$\{.+\}/);
  4457. $subst = HMCCU_SubstVariables ($clhash, $subst, undef);
  4458. HMCCU_Trace ($clhash, 2, $fnc, "subst_vars = $subst");
  4459. return $subst;
  4460. }
  4461. ######################################################################
  4462. # Clear RPC queue
  4463. ######################################################################
  4464. sub HMCCU_ResetRPCQueue ($$)
  4465. {
  4466. my ($hash, $port) = @_;
  4467. my $name = $hash->{NAME};
  4468. my $rpcqueue = AttrVal ($name, 'rpcqueue', '/tmp/ccuqueue');
  4469. my $clkey = 'CB'.$port;
  4470. if (HMCCU_QueueOpen ($hash, $rpcqueue."_".$port."_".$hash->{CCUNum})) {
  4471. HMCCU_QueueReset ($hash);
  4472. while (defined (HMCCU_QueueDeq ($hash))) { }
  4473. HMCCU_QueueClose ($hash);
  4474. }
  4475. $hash->{hmccu}{rpc}{$clkey}{queue} = '' if (exists ($hash->{hmccu}{rpc}{$clkey}{queue}));
  4476. }
  4477. ######################################################################
  4478. # Process RPC server event
  4479. ######################################################################
  4480. sub HMCCU_ProcessEvent ($$)
  4481. {
  4482. my ($hash, $event) = @_;
  4483. my $name = $hash->{NAME};
  4484. my $rh = \%{$hash->{hmccu}{rpc}};
  4485. return undef if (!defined ($event) || $event eq '');
  4486. my @t = split (/\|/, $event);
  4487. my $tc = scalar (@t);
  4488. # Update statistic counters
  4489. if (exists ($hash->{hmccu}{ev}{$t[0]})) {
  4490. $hash->{hmccu}{evtime} = time ();
  4491. $hash->{hmccu}{ev}{total}++;
  4492. $hash->{hmccu}{ev}{$t[0]}++;
  4493. $hash->{hmccu}{evtimeout} = 0 if ($hash->{hmccu}{evtimeout} == 1);
  4494. }
  4495. else {
  4496. my $errtok = $t[0];
  4497. $errtok =~ s/([\x00-\xFF])/sprintf("0x%X ",ord($1))/eg;
  4498. return HMCCU_Log ($hash, 2, "Received unknown event from CCU: ".$errtok, undef);
  4499. }
  4500. # Check event syntax
  4501. return HMCCU_Log ($hash, 2, "Wrong number of parameters in event $event", undef)
  4502. if (exists ($rpceventargs{$t[0]}) && ($tc-1) != $rpceventargs{$t[0]});
  4503. if ($t[0] eq 'EV') {
  4504. #
  4505. # Update of datapoint
  4506. # Input: EV|Adress|Datapoint|Value
  4507. # Output: EV, DevAdd, ChnNo, Reading='', Value
  4508. #
  4509. return HMCCU_Log ($hash, 2, "Invalid channel ".$t[1], undef)
  4510. if (!HMCCU_IsValidChannel ($hash, $t[1], $HMCCU_FL_ADDRESS));
  4511. my ($add, $chn) = split (/:/, $t[1]);
  4512. return ($t[0], $add, $chn, $t[2], $t[3]);
  4513. }
  4514. elsif ($t[0] eq 'SL') {
  4515. #
  4516. # RPC server enters server loop
  4517. # Input: SL|Pid|Servername
  4518. # Output: SL, Servername, Pid
  4519. #
  4520. my $clkey = $t[2];
  4521. return HMCCU_Log ($hash, 0, "Received SL event for unknown RPC server $clkey", undef)
  4522. if (!exists ($rh->{$clkey}));
  4523. Log3 $name, 0, "HMCCU: Received SL event. RPC server $clkey enters server loop";
  4524. $rh->{$clkey}{loop} = 1 if ($rh->{$clkey}{pid} == $t[1]);
  4525. return ($t[0], $clkey, $t[1]);
  4526. }
  4527. elsif ($t[0] eq 'IN') {
  4528. #
  4529. # RPC server initialized
  4530. # Input: IN|INIT|State|Servername
  4531. # Output: IN, Servername, Running, NotRunning, ClientsUpdated, UpdateErrors
  4532. #
  4533. my $clkey = $t[3];
  4534. my $norun = 0;
  4535. my $run = 0;
  4536. return HMCCU_Log ($hash, 0, "Received IN event for unknown RPC server $clkey", undef)
  4537. if (!exists ($rh->{$clkey}));
  4538. Log3 $name, 0, "HMCCU: Received IN event. RPC server $clkey initialized.";
  4539. $rh->{$clkey}{state} = $rh->{$clkey}{pid} != 0 ? "running" : "initialized";
  4540. # Check if all RPC servers were initialized. Set overall status
  4541. foreach my $ser (keys %{$rh}) {
  4542. $norun++ if ($rh->{$ser}{state} ne "running" && $rh->{$ser}{pid} != 0);
  4543. $norun++ if ($rh->{$ser}{state} ne "initialized" && $rh->{$ser}{pid} == 0);
  4544. $run++ if ($rh->{$ser}{state} eq "running");
  4545. }
  4546. HMCCU_SetRPCState ($hash, 'running') if ($norun == 0);
  4547. $hash->{hmccu}{rpcinit} = $run;
  4548. return ($t[0], $clkey, $run, $norun);
  4549. }
  4550. elsif ($t[0] eq 'EX') {
  4551. #
  4552. # RPC server shutdown
  4553. # Input: EX|SHUTDOWN|Pid|Servername
  4554. # Output: EX, Servername, Pid, Flag, Run
  4555. #
  4556. my $clkey = $t[3];
  4557. my $run = 0;
  4558. return HMCCU_Log ($hash, 0, "Received EX event for unknown RPC server $clkey", undef)
  4559. if (!exists ($rh->{$clkey}));
  4560. Log3 $name, 0, "HMCCU: Received EX event. RPC server $clkey terminated.";
  4561. my $f = $hash->{RPCState} eq "restarting" ? 2 : 1;
  4562. delete $rh->{$clkey};
  4563. # Check if all RPC servers were terminated. Set overall status
  4564. foreach my $ser (keys %{$rh}) {
  4565. $run++ if ($rh->{$ser}{state} ne "inactive");
  4566. }
  4567. if ($run == 0) {
  4568. HMCCU_SetRPCState ($hash, 'inactive') if ($f == 1);
  4569. $hash->{RPCPID} = '0';
  4570. }
  4571. $hash->{hmccu}{rpccount} = $run;
  4572. $hash->{hmccu}{rpcinit} = $run;
  4573. return ($t[0], $clkey, $t[2], $f, $run);
  4574. }
  4575. elsif ($t[0] eq 'ND') {
  4576. #
  4577. # CCU device added
  4578. # Input: ND|C/D|Address|Type|Version|Firmware|RxMode
  4579. # Output: ND, DevAdd, C/D, Type, Version, Firmware, RxMode
  4580. #
  4581. return ($t[0], $t[2], $t[1], $t[3], $t[4], $t[5], $t[6]);
  4582. }
  4583. elsif ($t[0] eq 'DD' || $t[0] eq 'RA') {
  4584. #
  4585. # CCU device added, deleted or readded
  4586. # Input: {DD,RA}|Address
  4587. # Output: {DD,RA}, DevAdd
  4588. #
  4589. return ($t[0], $t[1]);
  4590. }
  4591. elsif ($t[0] eq 'UD') {
  4592. #
  4593. # CCU device updated
  4594. # Input: UD|Address|Hint
  4595. # Output: UD, DevAdd, Hint
  4596. #
  4597. return ($t[0], $t[1], $t[2]);
  4598. }
  4599. elsif ($t[0] eq 'RD') {
  4600. #
  4601. # CCU device replaced
  4602. # Input: RD|Address1|Address2
  4603. # Output: RD, Address1, Address2
  4604. #
  4605. return ($t[0], $t[1], $t[2]);
  4606. }
  4607. elsif ($t[0] eq 'ST') {
  4608. #
  4609. # Statistic data. Store snapshots of sent and received events.
  4610. # Input: ST|nTotal|nEV|nND|nDD|nRD|nRA|nUD|nIN|nSL|nEX
  4611. # Output: ST, ...
  4612. #
  4613. my @stkeys = ('total', 'EV', 'ND', 'DD', 'RD', 'RA', 'UD', 'IN', 'SL', 'EX');
  4614. for (my $i=0; $i<10; $i++) {
  4615. $hash->{hmccu}{evs}{$stkeys[$i]} = $t[$i+1];
  4616. $hash->{hmccu}{evr}{$stkeys[$i]} = $hash->{hmccu}{ev}{$stkeys[$i]};
  4617. }
  4618. return @t;
  4619. }
  4620. else {
  4621. my $errtok = $t[0];
  4622. $errtok =~ s/([\x00-\xFF])/sprintf("0x%X ",ord($1))/eg;
  4623. Log3 $name, 2, "HMCCU: Received unknown event from CCU: ".$errtok;
  4624. }
  4625. return undef;
  4626. }
  4627. ######################################################################
  4628. # Timer function for reading RPC queue
  4629. ######################################################################
  4630. sub HMCCU_ReadRPCQueue ($)
  4631. {
  4632. my ($hash) = @_;
  4633. my $name = $hash->{NAME};
  4634. my $eventno = 0;
  4635. my $f = 0;
  4636. my @newdevices;
  4637. my @deldevices;
  4638. my @termpids;
  4639. my $newcount = 0;
  4640. my $devcount = 0;
  4641. my %events = ();
  4642. my %devices = ();
  4643. my $ccuflags = HMCCU_GetFlags ($name);
  4644. my $rpcinterval = AttrVal ($name, 'rpcinterval', 5);
  4645. my $rpcqueue = AttrVal ($name, 'rpcqueue', '/tmp/ccuqueue');
  4646. my $rpcevtimeout = AttrVal ($name, 'rpcevtimeout', $HMCCU_TIMEOUT_EVENT);
  4647. my $maxevents = $rpcinterval*10;
  4648. $maxevents = 50 if ($maxevents > 50);
  4649. $maxevents = 10 if ($maxevents < 10);
  4650. my @portlist = HMCCU_GetRPCPortList ($hash);
  4651. foreach my $port (@portlist) {
  4652. my $clkey = 'CB'.$port;
  4653. next if (!exists ($hash->{hmccu}{rpc}{$clkey}{queue}));
  4654. my $queuename = $hash->{hmccu}{rpc}{$clkey}{queue};
  4655. next if ($queuename eq '');
  4656. if (!HMCCU_QueueOpen ($hash, $queuename)) {
  4657. Log3 $name, 1, "HMCCU: Can't open file queue $queuename";
  4658. next;
  4659. }
  4660. my $element = HMCCU_QueueDeq ($hash);
  4661. while (defined ($element)) {
  4662. Log3 $name, 2, "HMCCU: Event = $element" if ($ccuflags =~ /logEvents/);
  4663. my ($et, @par) = HMCCU_ProcessEvent ($hash, $element);
  4664. if (defined ($et)) {
  4665. if ($et eq 'EV') {
  4666. $events{$par[0]}{$par[1]}{$par[2]} = $par[3];
  4667. $eventno++;
  4668. last if ($eventno == $maxevents);
  4669. }
  4670. elsif ($et eq 'ND') {
  4671. # push (@newdevices, $par[1]);
  4672. $newcount++ if (!exists ($hash->{hmccu}{dev}{$par[0]}));
  4673. # $hash->{hmccu}{dev}{$par[1]}{chntype} = $par[3];
  4674. $devices{$par[0]}{flag} = 'N';
  4675. $devices{$par[0]}{version} = $par[3];
  4676. if ($par[1] eq 'D') {
  4677. $devices{$par[0]}{addtype} = 'dev';
  4678. $devices{$par[0]}{type} = $par[2];
  4679. $devices{$par[0]}{firmware} = $par[4];
  4680. $devices{$par[0]}{rxmode} = $par[5];
  4681. }
  4682. else {
  4683. $devices{$par[0]}{addtype} = 'chn';
  4684. $devices{$par[0]}{usetype} = $par[2];
  4685. }
  4686. $devcount++;
  4687. }
  4688. elsif ($et eq 'DD') {
  4689. # push (@deldevices, $par[0]);
  4690. $devices{$par[0]}{flag} = 'D';
  4691. $devcount++;
  4692. # $delcount++;
  4693. }
  4694. elsif ($et eq 'RD') {
  4695. $devices{$par[0]}{flag} = 'R';
  4696. $devices{$par[0]}{newaddr} = $par[1];
  4697. $devcount++;
  4698. }
  4699. elsif ($et eq 'SL') {
  4700. InternalTimer (gettimeofday()+$HMCCU_INIT_INTERVAL1,
  4701. 'HMCCU_RPCRegisterCallback', $hash, 0);
  4702. $f = -1;
  4703. last;
  4704. }
  4705. elsif ($et eq 'EX') {
  4706. push (@termpids, $par[1]);
  4707. $f = $par[2];
  4708. last;
  4709. }
  4710. }
  4711. last if ($f == -1);
  4712. # Read next element from queue
  4713. $element = HMCCU_QueueDeq ($hash);
  4714. }
  4715. HMCCU_QueueClose ($hash);
  4716. }
  4717. # Update readings
  4718. HMCCU_UpdateMultipleDevices ($hash, \%events) if ($eventno > 0);
  4719. # Update device table and client device parameter
  4720. HMCCU_UpdateDeviceTable ($hash, \%devices) if ($devcount > 0);
  4721. return if ($f == -1);
  4722. # Check if events from CCU timed out
  4723. if ($hash->{hmccu}{evtime} > 0 && time()-$hash->{hmccu}{evtime} > $rpcevtimeout &&
  4724. $hash->{hmccu}{evtimeout} == 0) {
  4725. $hash->{hmccu}{evtimeout} = 1;
  4726. $hash->{ccustate} = HMCCU_TCPConnect ($hash->{host}, 8181) ne '' ? 'timeout' : 'unreachable';
  4727. Log3 $name, 2, "HMCCU: Received no events from CCU since $rpcevtimeout seconds";
  4728. DoTrigger ($name, "No events from CCU since $rpcevtimeout seconds");
  4729. }
  4730. else {
  4731. $hash->{ccustate} = 'active' if ($hash->{ccustate} ne 'active');
  4732. }
  4733. my @hm_pids;
  4734. my @hm_tids;
  4735. HMCCU_IsRPCServerRunning ($hash, \@hm_pids, \@hm_tids);
  4736. my $nhm_pids = scalar (@hm_pids);
  4737. my $nhm_tids = scalar (@hm_tids);
  4738. Log3 $name, 1, "HMCCU: Externally launched RPC server(s) detected. f=$f" if ($nhm_tids > 0);
  4739. if ($f > 0) {
  4740. # At least one RPC server has been stopped. Update PID list
  4741. $hash->{RPCPID} = $nhm_pids > 0 ? join(',',@hm_pids) : '0';
  4742. Log3 $name, 0, "HMCCU: RPC server(s) with PID(s) ".join(',',@termpids)." shut down. f=$f";
  4743. # Output statistic counters
  4744. foreach my $cnt (sort keys %{$hash->{hmccu}{ev}}) {
  4745. Log3 $name, 3, "HMCCU: Eventcount $cnt = ".$hash->{hmccu}{ev}{$cnt};
  4746. }
  4747. }
  4748. if ($f == 2 && $nhm_pids == 0) {
  4749. # All RPC servers terminated and restart flag set
  4750. if ($ccuflags !~ /(extrpc|procrpc)/) {
  4751. return if (HMCCU_StartIntRPCServer ($hash));
  4752. }
  4753. Log3 $name, 0, "HMCCU: Restart of RPC server failed";
  4754. }
  4755. if ($nhm_pids > 0) {
  4756. # Reschedule reading of RPC queues if at least one RPC server is running
  4757. InternalTimer (gettimeofday()+$rpcinterval, 'HMCCU_ReadRPCQueue', $hash, 0);
  4758. }
  4759. else {
  4760. # No more RPC servers active
  4761. Log3 $name, 0, "HMCCU: Periodical check found no RPC Servers";
  4762. # Deregister existing callbacks
  4763. HMCCU_RPCDeRegisterCallback ($hash);
  4764. # Cleanup hash variables
  4765. my @clkeylist = keys %{$hash->{hmccu}{rpc}};
  4766. foreach my $clkey (@clkeylist) {
  4767. delete $hash->{hmccu}{rpc}{$clkey};
  4768. }
  4769. $hash->{hmccu}{rpccount} = 0;
  4770. $hash->{hmccu}{rpcinit} = 0;
  4771. $hash->{RPCPID} = '0';
  4772. $hash->{RPCPRC} = 'none';
  4773. HMCCU_SetRPCState ($hash, 'inactive');
  4774. Log3 $name, 0, "HMCCU: All RPC servers stopped";
  4775. DoTrigger ($name, "All RPC servers stopped");
  4776. }
  4777. }
  4778. ######################################################################
  4779. # Execute Homematic command on CCU.
  4780. # If parameter mode is 1 an empty string is a valid result.
  4781. ######################################################################
  4782. sub HMCCU_HMCommand ($$$)
  4783. {
  4784. my ($hash, $cmd, $mode) = @_;
  4785. my $name = $hash->{NAME};
  4786. my $fnc = "HMCommand";
  4787. my $ccureqtimeout = AttrVal ($name, "ccuReqTimeout", $HMCCU_TIMEOUT_REQUEST);
  4788. my $url = "http://".$hash->{host}.":8181/do.exe?r1=".urlEncode($cmd);
  4789. my $value;
  4790. HMCCU_Trace ($hash, 2, $fnc, "URL=$url");
  4791. my $response = GetFileFromURL ($url, $ccureqtimeout);
  4792. if (defined ($response)) {
  4793. $response =~ m/<r1>(.*)<\/r1>/;
  4794. $value = $1;
  4795. HMCCU_Trace ($hash, 2, $fnc, "Response = $response");
  4796. }
  4797. else {
  4798. HMCCU_Trace ($hash, 2, $fnc, "Response undefined");
  4799. }
  4800. if ($mode == 1) {
  4801. return (defined ($value) && $value ne 'null') ? $value : undef;
  4802. }
  4803. else {
  4804. return (defined ($value) && $value ne '' && $value ne 'null') ? $value : undef;
  4805. }
  4806. }
  4807. ######################################################################
  4808. # Execute Homematic command on CCU without waiting for response.
  4809. ######################################################################
  4810. sub HMCCU_HMCommandNB ($$$)
  4811. {
  4812. my ($hash, $cmd, $cbfunc) = @_;
  4813. my $name = $hash->{NAME};
  4814. my $fnc = "HMCommandNB";
  4815. my $hmccu_hash = HMCCU_GetHash ($hash);
  4816. my $ccureqtimeout = AttrVal ($hmccu_hash->{NAME}, "ccuReqTimeout", $HMCCU_TIMEOUT_REQUEST);
  4817. my $url = "http://".$hmccu_hash->{host}.":8181/do.exe?r1=".urlEncode($cmd);
  4818. HMCCU_Trace ($hash, 2, $fnc, "URL=$url");
  4819. if (defined ($cbfunc)) {
  4820. my $param = { url => $url, timeout => $ccureqtimeout, method => "GET",
  4821. callback => $cbfunc, devhash => $hash };
  4822. HttpUtils_NonblockingGet ($param);
  4823. }
  4824. else {
  4825. my $param = { url => $url, timeout => $ccureqtimeout, method => "GET",
  4826. callback => \&HMCCU_HMCommandCB, devhash => $hash };
  4827. HttpUtils_NonblockingGet ($param);
  4828. }
  4829. }
  4830. ######################################################################
  4831. # Default callback function for non blocking CCU request.
  4832. ######################################################################
  4833. sub HMCCU_HMCommandCB ($$$)
  4834. {
  4835. my ($param, $err, $data) = @_;
  4836. my $hash = $param->{devhash};
  4837. my $fnc = "HMCommandCB";
  4838. HMCCU_Log ($hash, 2, "Error during CCU request. $err", undef) if ($err ne '');
  4839. HMCCU_Trace ($hash, 2, $fnc, "URL=".$param->{url}."<br>Response=$data");
  4840. }
  4841. ######################################################################
  4842. # Execute Homematic script on CCU.
  4843. # Parameters: device-hash, script-code or script-name, parameter-hash
  4844. # If content of hmscript starts with a ! the following text is treated
  4845. # as name of an internal HomeMatic script function.
  4846. # If content of hmscript is enclosed in [] the content is treated as
  4847. # HomeMatic script code.
  4848. # Otherwise hmscript is the name of a file containing Homematic script
  4849. # code.
  4850. # Return script output or error message starting with "ERROR:".
  4851. ######################################################################
  4852. sub HMCCU_HMScriptExt ($$$)
  4853. {
  4854. my ($hash, $hmscript, $params) = @_;
  4855. my $name = $hash->{NAME};
  4856. my $host = $hash->{host};
  4857. my $code = $hmscript;
  4858. my $scrname = '';
  4859. if (!exists ($hash->{host})) {
  4860. Log3 $name, 2, "HMCCU: CCU host name not defined. Name=$name Type=".$hash->{TYPE};
  4861. return "ERROR: CCU host name not defined";
  4862. }
  4863. # Check for internal script
  4864. if ($hmscript =~ /^!(.*)$/) {
  4865. $scrname = $1;
  4866. return "ERROR: Can't find internal script $scrname" if (!exists ($HMCCU_SCRIPTS->{$scrname}));
  4867. $code = $HMCCU_SCRIPTS->{$scrname}{code};
  4868. }
  4869. elsif ($hmscript =~ /^\[(.*)\]$/) {
  4870. $code = $1;
  4871. }
  4872. else {
  4873. if (open (SCRFILE, "<$hmscript")) {
  4874. my @lines = <SCRFILE>;
  4875. $code = join ("\n", @lines);
  4876. close (SCRFILE);
  4877. }
  4878. else {
  4879. return "ERROR: Can't open script file";
  4880. }
  4881. }
  4882. # Check and replace variables
  4883. if (defined ($params)) {
  4884. my @parnames = keys %{$params};
  4885. if ($scrname ne '') {
  4886. if (scalar (@parnames) != $HMCCU_SCRIPTS->{$scrname}{parameters}) {
  4887. return "ERROR: Wrong number of parameters. Usage: $scrname ".
  4888. $HMCCU_SCRIPTS->{$scrname}{syntax};
  4889. }
  4890. foreach my $p (split (/[, ]+/, $HMCCU_SCRIPTS->{$scrname}{syntax})) {
  4891. return "ERROR: Missing definition of parameter $p" if (!exists ($params->{$p}));
  4892. }
  4893. }
  4894. foreach my $svar (keys %{$params}) {
  4895. next if ($code !~ /\$$svar/);
  4896. $code =~ s/\$$svar/$params->{$svar}/g;
  4897. }
  4898. }
  4899. else {
  4900. if ($scrname ne '' && $HMCCU_SCRIPTS->{$scrname}{parameters} > 0) {
  4901. return "ERROR: Wrong number of parameters. Usage: $scrname ".
  4902. $HMCCU_SCRIPTS->{$scrname}{syntax};
  4903. }
  4904. }
  4905. # Execute script on CCU
  4906. my $url = "http://".$host.":8181/tclrega.exe";
  4907. my $ua = new LWP::UserAgent ();
  4908. my $response = $ua->post($url, Content => $code);
  4909. if ($response->is_success ()) {
  4910. my $output = $response->content;
  4911. $output =~ s/<xml>.*<\/xml>//;
  4912. $output =~ s/\r//g;
  4913. return $output;
  4914. }
  4915. else {
  4916. my $msg = $response->status_line();
  4917. Log3 $name, 2, "HMCCU: HMScript failed. $msg";
  4918. return "ERROR: HMScript failed. $msg";
  4919. }
  4920. }
  4921. ######################################################################
  4922. # Bulk update of reading considering attribute substexcl.
  4923. ######################################################################
  4924. sub HMCCU_BulkUpdate ($$$$)
  4925. {
  4926. my ($hash, $reading, $orgval, $subval) = @_;
  4927. my $excl = AttrVal ($hash->{NAME}, 'substexcl', '');
  4928. readingsBulkUpdate ($hash, $reading, ($excl ne '' && $reading =~ /$excl/ ? $orgval : $subval));
  4929. }
  4930. ######################################################################
  4931. # Get datapoint value from CCU and update reading.
  4932. ######################################################################
  4933. sub HMCCU_GetDatapoint ($@)
  4934. {
  4935. my ($hash, $param) = @_;
  4936. my $name = $hash->{NAME};
  4937. my $fnc = "GetDatapoint";
  4938. my $hmccu_hash;
  4939. my $value = '';
  4940. $hmccu_hash = HMCCU_GetHash ($hash);
  4941. return (-3, $value) if (!defined ($hmccu_hash));
  4942. return (-4, $value) if ($hash->{TYPE} ne 'HMCCU' && $hash->{ccudevstate} eq 'deleted');
  4943. my $readingformat = HMCCU_GetAttrReadingFormat ($hash, $hmccu_hash);
  4944. my ($statechn, $statedpt, $controlchn, $controldpt) = HMCCU_GetSpecialDatapoints (
  4945. $hash, '', 'STATE', '', '');
  4946. my $ccuget = HMCCU_GetAttribute ($hmccu_hash, $hash, 'ccuget', 'Value');
  4947. my $ccureqtimeout = AttrVal ($hmccu_hash->{NAME}, "ccuReqTimeout", $HMCCU_TIMEOUT_REQUEST);
  4948. my $cmd = '';
  4949. my ($int, $add, $chn, $dpt, $nam, $flags) = HMCCU_ParseObject ($hmccu_hash, $param,
  4950. $HMCCU_FLAG_INTERFACE);
  4951. return (-1, $value) if ($flags != $HMCCU_FLAGS_IACD && $flags != $HMCCU_FLAGS_NCD);
  4952. if ($flags == $HMCCU_FLAGS_IACD) {
  4953. $cmd = '(datapoints.Get("'.$int.'.'.$add.':'.$chn.'.'.$dpt.'")).'.$ccuget.'()';
  4954. }
  4955. elsif ($flags == $HMCCU_FLAGS_NCD) {
  4956. $cmd = '(dom.GetObject(ID_CHANNELS)).Get("'.$nam.'").DPByHssDP("'.$dpt.'").'.$ccuget.'()';
  4957. ($add, $chn) = HMCCU_GetAddress ($hmccu_hash, $nam, '', '');
  4958. }
  4959. HMCCU_Trace ($hash, 2, $fnc, "CMD=$cmd, param=$param, ccuget=$ccuget");
  4960. $value = HMCCU_HMCommand ($hmccu_hash, $cmd, 1);
  4961. if (defined ($value) && $value ne '' && $value ne 'null') {
  4962. $value = HMCCU_UpdateSingleDatapoint ($hash, $chn, $dpt, $value);
  4963. HMCCU_Trace ($hash, 2, $fnc, "Value of $chn.$dpt = $value");
  4964. return (1, $value);
  4965. }
  4966. else {
  4967. HMCCU_Log ($hash, 1, "Error CMD = $cmd", 0);
  4968. return (-2, '');
  4969. }
  4970. }
  4971. ######################################################################
  4972. # Set datapoint on CCU.
  4973. # Parameter param is a valid CCU or FHEM datapoint specification:
  4974. # [ccu:]address:channelnumber.datapoint
  4975. # [ccu:]channelname.datapoint
  4976. # hmccu:hmccudev_name.channelnumber.datapoint
  4977. # hmccu:hmccuchn_name.datapoint
  4978. ######################################################################
  4979. sub HMCCU_SetDatapoint ($$$)
  4980. {
  4981. my ($hash, $param, $value) = @_;
  4982. my $fnc = "SetDatapoint";
  4983. my $type = $hash->{TYPE};
  4984. my $hmccu_hash = HMCCU_GetHash ($hash);
  4985. return -3 if (!defined ($hmccu_hash));
  4986. return -4 if (exists ($hash->{ccudevstate}) && $hash->{ccudevstate} eq 'deleted');
  4987. my $name = $hmccu_hash->{NAME};
  4988. my $cdname = $hash->{NAME};
  4989. my $ccureqtimeout = AttrVal ($name, "ccuReqTimeout", $HMCCU_TIMEOUT_REQUEST);
  4990. my $ccuflags = HMCCU_GetFlags ($name);
  4991. my $readingformat = HMCCU_GetAttrReadingFormat ($hash, $hmccu_hash);
  4992. my $ccuverify = AttrVal ($cdname, 'ccuverify', 0);
  4993. HMCCU_Trace ($hash, 2, $fnc, "param=$param, value=$value");
  4994. if ($param =~ /^hmccu:.+$/) {
  4995. my @t = split (/\./, $param);
  4996. return -1 if (scalar (@t) < 2 || scalar (@t) > 3);
  4997. my $fhdpt = pop @t;
  4998. my ($fhadd, $fhchn) = HMCCU_GetAddress ($hmccu_hash, $t[0], '', '');
  4999. $fhchn = $t[1] if (scalar (@t) == 2);
  5000. return -1 if ($fhadd eq '' || $fhchn eq '');
  5001. $param = "$fhadd:$fhchn.$fhdpt";
  5002. }
  5003. elsif ($param =~ /^ccu:(.+)$/) {
  5004. $param = $1;
  5005. }
  5006. my $cmd = '';
  5007. my ($int, $add, $chn, $dpt, $nam, $flags) = HMCCU_ParseObject ($hmccu_hash, $param,
  5008. $HMCCU_FLAG_INTERFACE);
  5009. return -1 if ($flags != $HMCCU_FLAGS_IACD && $flags != $HMCCU_FLAGS_NCD);
  5010. if ($hash->{ccutype} eq 'HM-Dis-EP-WM55' && $dpt eq 'SUBMIT') {
  5011. $value = HMCCU_EncodeEPDisplay ($value);
  5012. }
  5013. else {
  5014. $value = HMCCU_ScaleValue ($hash, $chn, $dpt, $value, 1);
  5015. }
  5016. my $dpttype = HMCCU_GetDatapointAttr ($hmccu_hash, $hash->{ccutype}, $chn, $dpt, 'type');
  5017. if (defined ($dpttype) && $dpttype == $HMCCU_TYPE_STRING) {
  5018. $value = "'".$value."'";
  5019. }
  5020. if ($flags == $HMCCU_FLAGS_IACD) {
  5021. $cmd = '(datapoints.Get("'.$int.'.'.$add.':'.$chn.'.'.$dpt.'")).State('.$value.')';
  5022. $nam = HMCCU_GetChannelName ($hmccu_hash, $add.":".$chn, '');
  5023. }
  5024. elsif ($flags == $HMCCU_FLAGS_NCD) {
  5025. $cmd = '(dom.GetObject(ID_CHANNELS)).Get("'.$nam.'").DPByHssDP("'.$dpt.'").State('.$value.')';
  5026. ($add, $chn) = HMCCU_GetAddress ($hmccu_hash, $nam, '', '');
  5027. }
  5028. my $addr = $add.":".$chn;
  5029. if ($ccuflags =~ /nonBlocking/) {
  5030. HMCCU_HMCommandNB ($hash, $cmd, undef);
  5031. return 0;
  5032. }
  5033. # Execute command (blocking)
  5034. my $response = HMCCU_HMCommand ($hmccu_hash, $cmd, 1);
  5035. HMCCU_Trace ($hash, 2, $fnc,
  5036. "Addr=$addr Name=$nam<br>".
  5037. "Script response = \n".(defined ($response) ? $response: 'undef')."<br>".
  5038. "Script = \n".$cmd);
  5039. return -2 if (!defined ($response));
  5040. # Verify setting of datapoint value or update reading with new datapoint value
  5041. if (HMCCU_IsValidDatapoint ($hash, $hash->{ccutype}, $addr, $dpt, 1)) {
  5042. if ($ccuverify == 1) {
  5043. my ($rc, $result) = HMCCU_GetDatapoint ($hash, $param);
  5044. return $rc;
  5045. }
  5046. elsif ($ccuverify == 2) {
  5047. HMCCU_UpdateSingleDatapoint ($hash, $chn, $dpt, $value);
  5048. }
  5049. }
  5050. return 0;
  5051. }
  5052. ######################################################################
  5053. # Scale, spread and/or shift datapoint value.
  5054. # Mode: 0 = Get/Divide, 1 = Set/Multiply
  5055. # Supports reversing of value if value range is specified. Syntax for
  5056. # Rule is:
  5057. # [ChannelNo.]Datapoint:Factor
  5058. # [!][ChannelNo.]Datapoint:Min:Max:Range1:Range2
  5059. # If Datapoint name starts with a ! the value is reversed. In case of
  5060. # an error original value is returned.
  5061. ######################################################################
  5062. sub HMCCU_ScaleValue ($$$$$)
  5063. {
  5064. my ($hash, $chnno, $dpt, $value, $mode) = @_;
  5065. my $name = $hash->{NAME};
  5066. my $ccuscaleval = AttrVal ($name, 'ccuscaleval', '');
  5067. return $value if ($ccuscaleval eq '');
  5068. my @sl = split (',', $ccuscaleval);
  5069. foreach my $sr (@sl) {
  5070. my $f = 1.0;
  5071. my @a = split (':', $sr);
  5072. my $n = scalar (@a);
  5073. next if ($n != 2 && $n != 5);
  5074. my $rev = 0;
  5075. my $dn = $a[0];
  5076. my $cn = $chnno;
  5077. if ($dn =~ /^\!(.+)$/) {
  5078. # Invert
  5079. $dn = $1;
  5080. $rev = 1;
  5081. }
  5082. if ($dn =~ /^([0-9]{1,2})\.(.+)$/) {
  5083. # Compare channel number
  5084. $cn = $1;
  5085. $dn = $2;
  5086. }
  5087. next if ($dpt ne $dn || ($chnno ne '' && $cn ne $chnno));
  5088. if ($n == 2) {
  5089. $f = ($a[1] == 0.0) ? 1.0 : $a[1];
  5090. return ($mode == 0) ? $value/$f : $value*$f;
  5091. }
  5092. else {
  5093. # Do not scale if value out of range or interval wrong
  5094. return $value if ($a[1] > $a[2] || $a[3] > $a[4]);
  5095. return $value if ($mode == 0 && ($value < $a[1] || $value > $a[2]));
  5096. # return $value if ($mode == 1 && ($value >= $a[1] && $value <= $a[2]));
  5097. return $value if ($mode == 1 && ($value < $a[3] || $value > $a[4]));
  5098. # Reverse value
  5099. if ($rev) {
  5100. my $dr = ($mode == 0) ? $a[1]+$a[2] : $a[3]+$a[4];
  5101. $value = $dr-$value;
  5102. }
  5103. my $d1 = $a[2]-$a[1];
  5104. my $d2 = $a[4]-$a[3];
  5105. return $value if ($d1 == 0.0 || $d2 == 0.0);
  5106. $f = $d1/$d2;
  5107. return ($mode == 0) ? $value/$f+$a[3] : ($value-$a[3])*$f;
  5108. }
  5109. }
  5110. return $value;
  5111. }
  5112. ######################################################################
  5113. # Get CCU system variables and update readings.
  5114. # System variable readings are stored in I/O device. Unsupported
  5115. # characters in variable names are substituted.
  5116. ######################################################################
  5117. sub HMCCU_GetVariables ($$)
  5118. {
  5119. my ($hash, $pattern) = @_;
  5120. my $name = $hash->{NAME};
  5121. my $count = 0;
  5122. my $result = '';
  5123. my $ccureadings = AttrVal ($name, 'ccureadings', HMCCU_IsFlag ($name, "noReadings") ? 0 : 1);
  5124. my $response = HMCCU_HMScriptExt ($hash, "!GetVariables", undef);
  5125. return (-2, $response) if ($response eq '' || $response =~ /^ERROR:.*/);
  5126. readingsBeginUpdate ($hash) if ($ccureadings);
  5127. foreach my $vardef (split /\n/, $response) {
  5128. my @vardata = split /=/, $vardef;
  5129. next if (@vardata != 3);
  5130. next if ($vardata[0] !~ /$pattern/);
  5131. my $rn = HMCCU_CorrectName ($vardata[0]);
  5132. my $value = HMCCU_FormatReadingValue ($hash, $vardata[2], $vardata[0]);
  5133. readingsBulkUpdate ($hash, $rn, $value) if ($ccureadings);
  5134. $result .= $vardata[0].'='.$vardata[2]."\n";
  5135. $count++;
  5136. }
  5137. readingsEndUpdate ($hash, 1) if ($ccureadings);
  5138. return ($count, $result);
  5139. }
  5140. ######################################################################
  5141. # Timer function for periodic update of CCU system variables.
  5142. ######################################################################
  5143. sub HMCCU_UpdateVariables ($)
  5144. {
  5145. my ($hash) = @_;
  5146. if (exists ($hash->{hmccu}{ccuvarspat})) {
  5147. HMCCU_GetVariables ($hash, $hash->{hmccu}{ccuvarspat});
  5148. InternalTimer (gettimeofday ()+$hash->{hmccu}{ccuvarsint}, "HMCCU_UpdateVariables", $hash);
  5149. }
  5150. }
  5151. ######################################################################
  5152. # Set CCU system variable. If parameter vartype is undefined system
  5153. # variable must exist in CCU. Following variable types are supported:
  5154. # bool, list, number, text. Parameter params is a hash reference of
  5155. # script parameters.
  5156. # Return 0 on success, error code on error.
  5157. ######################################################################
  5158. sub HMCCU_SetVariable ($$$$$)
  5159. {
  5160. my ($hash, $varname, $value, $vartype, $params) = @_;
  5161. my $name = $hash->{NAME};
  5162. my $ccureqtimeout = AttrVal ($name, "ccuReqTimeout", $HMCCU_TIMEOUT_REQUEST);
  5163. my %varfnc = (
  5164. "bool" => "!CreateBoolVariable", "list", "!CreateListVariable",
  5165. "number" => "!CreateNumericVariable", "text", "!CreateStringVariable"
  5166. );
  5167. if (!defined ($vartype)) {
  5168. my $cmd = qq(dom.GetObject("$varname").State("$value"));
  5169. my $response = HMCCU_HMCommand ($hash, $cmd, 1);
  5170. return HMCCU_Log ($hash, 1, "CMD=$cmd", -2) if (!defined ($response));
  5171. }
  5172. else {
  5173. return -18 if (!exists ($varfnc{$vartype}));
  5174. # Set default values for variable attributes
  5175. $params->{name} = $varname if (!exists ($params->{name}));
  5176. $params->{init} = $value if (!exists ($params->{init}));
  5177. $params->{unit} = "" if (!exists ($params->{unit}));
  5178. $params->{desc} = "" if (!exists ($params->{desc}));
  5179. $params->{min} = "0" if ($vartype eq 'number' && !exists ($params->{min}));
  5180. $params->{max} = "65000" if ($vartype eq 'number' && !exists ($params->{max}));
  5181. $params->{list} = $value if ($vartype eq 'list' && !exists ($params->{list}));
  5182. $params->{valtrue} = "ist wahr" if ($vartype eq 'bool' && !exists ($params->{valtrue}));
  5183. $params->{valfalse} = "ist falsch" if ($vartype eq 'bool' && !exists ($params->{valfalse}));
  5184. my $rc = HMCCU_HMScriptExt ($hash, $varfnc{$vartype}, $params);
  5185. return HMCCU_Log ($hash, 1, $rc, -2) if ($rc =~ /^ERROR:.*/);
  5186. }
  5187. return 0;
  5188. }
  5189. ######################################################################
  5190. # Update all datapoints / readings of device or channel considering
  5191. # attribute ccureadingfilter.
  5192. # Parameter $ccuget can be 'State', 'Value' or 'Attr'.
  5193. ######################################################################
  5194. sub HMCCU_GetUpdate ($$$)
  5195. {
  5196. my ($cl_hash, $addr, $ccuget) = @_;
  5197. my $name = $cl_hash->{NAME};
  5198. my $type = $cl_hash->{TYPE};
  5199. my $fnc = "GetUpdate";
  5200. my $disable = AttrVal ($name, 'disable', 0);
  5201. return 1 if ($disable == 1);
  5202. my $hmccu_hash = HMCCU_GetHash ($cl_hash);
  5203. return -3 if (!defined ($hmccu_hash));
  5204. return -4 if ($type ne 'HMCCU' && $cl_hash->{ccudevstate} eq 'deleted');
  5205. my $nam = '';
  5206. my $list = '';
  5207. my $script = '';
  5208. $ccuget = HMCCU_GetAttribute ($hmccu_hash, $cl_hash, 'ccuget', 'Value') if ($ccuget eq 'Attr');
  5209. if (HMCCU_IsValidChannel ($hmccu_hash, $addr, $HMCCU_FL_ADDRESS)) {
  5210. $nam = HMCCU_GetChannelName ($hmccu_hash, $addr, '');
  5211. return -1 if ($nam eq '');
  5212. my ($stadd, $stchn) = split (':', $addr);
  5213. my $stnam = HMCCU_GetChannelName ($hmccu_hash, "$stadd:0", '');
  5214. $list = $stnam eq '' ? $nam : $stnam . "," . $nam;
  5215. $script = "!GetDatapointsByChannel";
  5216. }
  5217. elsif (HMCCU_IsValidDevice ($hmccu_hash, $addr, $HMCCU_FL_ADDRESS)) {
  5218. $nam = HMCCU_GetDeviceName ($hmccu_hash, $addr, '');
  5219. return -1 if ($nam eq '');
  5220. $list = $nam;
  5221. $script = "!GetDatapointsByDevice";
  5222. # Consider members of group device
  5223. if ($type eq 'HMCCUDEV' && $cl_hash->{ccuif} eq 'VirtualDevices' &&
  5224. exists ($cl_hash->{ccugroup})) {
  5225. foreach my $gd (split (",", $cl_hash->{ccugroup})) {
  5226. $nam = HMCCU_GetDeviceName ($hmccu_hash, $gd, '');
  5227. $list .= ','.$nam if ($nam ne '');
  5228. }
  5229. }
  5230. }
  5231. else {
  5232. return -1;
  5233. }
  5234. my $response = HMCCU_HMScriptExt ($hmccu_hash, $script,
  5235. { list => $list, ccuget => $ccuget });
  5236. HMCCU_Trace ($cl_hash, 2, $fnc, "Addr=$addr Name=$nam Script=$script<br>".
  5237. "Script response = \n".$response);
  5238. return -2 if ($response eq '' || $response =~ /^ERROR:.*/);
  5239. my @dpdef = split /\n/, $response;
  5240. my $count = pop (@dpdef);
  5241. return -10 if (!defined ($count) || $count == 0);
  5242. my %events = ();
  5243. foreach my $dp (@dpdef) {
  5244. my ($chnname, $dpspec, $value) = split /=/, $dp;
  5245. next if (!defined ($value));
  5246. my ($iface, $chnadd, $dpt) = split /\./, $dpspec;
  5247. next if (!defined ($dpt));
  5248. my ($add, $chn) = ('', '');
  5249. if ($iface eq 'sysvar' && $chnadd eq 'link') {
  5250. ($add, $chn) = HMCCU_GetAddress ($hmccu_hash, $chnname, '', '');
  5251. }
  5252. else {
  5253. ($add, $chn) = HMCCU_SplitChnAddr ($chnadd);
  5254. }
  5255. next if ($chn eq '');
  5256. $events{$add}{$chn}{$dpt} = $value;
  5257. }
  5258. HMCCU_UpdateSingleDevice ($hmccu_hash, $cl_hash, \%events);
  5259. return 1;
  5260. }
  5261. ######################################################################
  5262. # Get multiple datapoints of channels and update readings of client
  5263. # devices.
  5264. # Returncodes: -1 = Invalid channel/datapoint in list
  5265. # -2 = CCU script execution failed
  5266. # -3 = Cannot detect IO device
  5267. # On success number of updated readings is returned.
  5268. ######################################################################
  5269. sub HMCCU_GetChannel ($$)
  5270. {
  5271. my ($hash, $chnref) = @_;
  5272. my $name = $hash->{NAME};
  5273. my $type = $hash->{TYPE};
  5274. my $count = 0;
  5275. my $chnlist = '';
  5276. my $result = '';
  5277. my %chnpars;
  5278. my %objects = ();
  5279. my $objcount = 0;
  5280. my $ccuget = AttrVal ($name, 'ccuget', 'Value');
  5281. # Build channel list. Datapoints and substitution rules are ignored.
  5282. foreach my $chndef (@$chnref) {
  5283. my ($channel, $substitute) = split /\s+/, $chndef;
  5284. next if (!defined ($channel) || $channel =~ /^#/ || $channel eq '');
  5285. my ($int, $add, $chn, $dpt, $nam, $flags) = HMCCU_ParseObject ($hash, $channel,
  5286. $HMCCU_FLAG_INTERFACE | $HMCCU_FLAG_DATAPOINT);
  5287. if ($flags == $HMCCU_FLAGS_IACD || $flags == $HMCCU_FLAGS_NCD) {
  5288. $nam = HMCCU_GetChannelName ($hash, $add.':'.$chn, '') if ($flags == $HMCCU_FLAGS_IACD);
  5289. $chnlist = $chnlist eq '' ? $nam : $chnlist.','.$nam;
  5290. $chnpars{$nam}{sub} = $substitute;
  5291. $chnpars{$nam}{dpt} = $dpt;
  5292. }
  5293. else {
  5294. return (-1, $result);
  5295. }
  5296. }
  5297. return (0, $result) if ($chnlist eq '');
  5298. my $response = HMCCU_HMScriptExt ($hash, "!GetChannel",
  5299. { list => $chnlist, ccuget => $ccuget });
  5300. return (-2, $result) if ($response eq '' || $response =~ /^ERROR:.*/);
  5301. # Output format is Channelname=Interface.Channeladdress.Datapoint=Value
  5302. foreach my $dpdef (split /\n/, $response) {
  5303. my ($chnname, $dptaddr, $value) = split /=/, $dpdef;
  5304. next if (!defined ($value));
  5305. my ($iface, $chnaddr, $dpt) = split /\./, $dptaddr;
  5306. next if (!defined ($dpt));
  5307. my ($add, $chn) = HMCCU_SplitChnAddr ($chnaddr);
  5308. next if ($chn eq '');
  5309. if (defined ($chnpars{$chnname}{dpt}) && $chnpars{$chnname}{dpt} ne '') {
  5310. next if ($dpt !~ $chnpars{$chnname}{dpt});
  5311. }
  5312. $value = HMCCU_Substitute ($value, $chnpars{$chnname}{sub}, 0, $chn, $dpt);
  5313. $objects{$add}{$chn}{$dpt} = $value;
  5314. $objcount++;
  5315. }
  5316. $count = HMCCU_UpdateMultipleDevices ($hash, \%objects) if ($objcount > 0);
  5317. return ($count, $result);
  5318. }
  5319. ######################################################################
  5320. # Get RPC paramSet or paramSetDescription
  5321. ######################################################################
  5322. sub HMCCU_RPCGetConfig ($$$$)
  5323. {
  5324. my ($hash, $param, $mode, $filter) = @_;
  5325. my $name = $hash->{NAME};
  5326. my $type = $hash->{TYPE};
  5327. my $fnc = "RPCGetConfig";
  5328. my $method = $mode eq 'listParamset' ? 'getParamset' : $mode;
  5329. my $addr;
  5330. my $result = '';
  5331. my $res = '';
  5332. my $hmccu_hash = HMCCU_GetHash ($hash);
  5333. return (-3, $result) if (!defined ($hmccu_hash));
  5334. return (-4, $result) if ($type ne 'HMCCU' && $hash->{ccudevstate} eq 'deleted');
  5335. my $ccuflags = HMCCU_GetFlags ($name);
  5336. my $ccureadings = AttrVal ($name, 'ccureadings', $ccuflags =~ /noReadings/ ? 0 : 1);
  5337. my $readingformat = HMCCU_GetAttrReadingFormat ($hash, $hmccu_hash);
  5338. my $substitute = HMCCU_GetAttrSubstitute ($hash, $hmccu_hash);
  5339. my ($int, $add, $chn, $dpt, $nam, $flags) = HMCCU_ParseObject ($hmccu_hash, $param,
  5340. $HMCCU_FLAG_FULLADDR);
  5341. return (-1, '') if (!($flags & $HMCCU_FLAG_ADDRESS));
  5342. $addr = $add;
  5343. $addr .= ':'.$chn if ($flags & $HMCCU_FLAG_CHANNEL);
  5344. my $rpctype = HMCCU_GetRPCServerInfo ($hmccu_hash, $int, 'type');
  5345. my $port = HMCCU_GetRPCServerInfo ($hmccu_hash, $int, 'port');
  5346. return (-9, '') if (!defined ($rpctype) || !defined ($port));
  5347. if ($rpctype eq 'B') {
  5348. # Search RPC device
  5349. my $rpcdev = HMCCU_GetRPCDevice ($hmccu_hash, 0, $int);
  5350. return (-17, '') if ($rpcdev eq '');
  5351. HMCCU_Trace ($hash, 2, $fnc, "Method=$method Addr=$addr Port=$port");
  5352. if ($ccuflags =~ /(extrpc|procrpc)/) {
  5353. # $res = HMCCURPC_SendBinRequest ($defs{$rpcdev}, $port, $method, $BINRPC_STRING, $addr,
  5354. # $BINRPC_STRING, "MASTER");
  5355. # }
  5356. # elsif ($ccuflags =~ /procrpc/) {
  5357. $res = HMCCURPCPROC_SendRequest ($defs{$rpcdev}, $method, $BINRPC_STRING, $addr,
  5358. $BINRPC_STRING, "MASTER");
  5359. }
  5360. }
  5361. else {
  5362. my $url = HMCCU_GetRPCServerInfo ($hmccu_hash, $int, 'url');
  5363. return (-9, '') if (!defined ($url));
  5364. HMCCU_Trace ($hash, 2, $fnc, "Method=$method Addr=$addr Port=$port");
  5365. my $client = RPC::XML::Client->new ($url);
  5366. $res = $client->simple_request ($method, $addr, "MASTER");
  5367. }
  5368. return (-5, "Function not available") if (!defined ($res));
  5369. if (defined ($res)) {
  5370. HMCCU_Trace ($hash, 2, $fnc,
  5371. "Dump of RPC request $method $addr. Result type=".ref($res)."<br>".
  5372. HMCCU_RefToString ($res));
  5373. }
  5374. if (ref ($res) eq 'HASH') {
  5375. my $parcount = scalar (keys %$res);
  5376. if (exists ($res->{faultString})) {
  5377. Log3 $name, 1, "HMCCU: ".$res->{faultString};
  5378. return (-2, $res->{faultString});
  5379. }
  5380. elsif ($parcount == 0) {
  5381. return (-5, "CCU returned no data");
  5382. }
  5383. }
  5384. else {
  5385. return (-2, defined ($RPC::XML::ERROR) ? $RPC::XML::ERROR : '');
  5386. }
  5387. if ($mode eq 'getParamsetDescription') {
  5388. foreach my $key (sort keys %$res) {
  5389. my $oper = '';
  5390. $oper .= 'R' if ($res->{$key}->{OPERATIONS} & 1);
  5391. $oper .= 'W' if ($res->{$key}->{OPERATIONS} & 2);
  5392. $oper .= 'E' if ($res->{$key}->{OPERATIONS} & 4);
  5393. $result .= $key.": ".$res->{$key}->{TYPE}." [".$oper."]\n";
  5394. }
  5395. }
  5396. elsif ($mode eq 'listParamset') {
  5397. foreach my $key (sort keys %$res) {
  5398. next if ($key !~ /$filter/);
  5399. my $value = $res->{$key};
  5400. $result .= "$key=$value\n";
  5401. }
  5402. }
  5403. else {
  5404. readingsBeginUpdate ($hash) if ($ccureadings);
  5405. foreach my $key (sort keys %$res) {
  5406. next if ($key !~ /$filter/);
  5407. my $value = $res->{$key};
  5408. $result .= "$key=$value\n";
  5409. next if (!$ccureadings);
  5410. $value = HMCCU_FormatReadingValue ($hash, $value, $key);
  5411. $value = HMCCU_Substitute ($value, $substitute, 0, $chn, $key);
  5412. my @readings = HMCCU_GetReadingName ($hash, $int, $add, $chn, $key, $nam, $readingformat);
  5413. foreach my $rn (@readings) {
  5414. next if ($rn eq '');
  5415. $rn = "R-".$rn;
  5416. readingsBulkUpdate ($hash, $rn, $value);
  5417. }
  5418. }
  5419. readingsEndUpdate ($hash, 1) if ($ccureadings);
  5420. }
  5421. return (0, $result);
  5422. }
  5423. ######################################################################
  5424. # Set RPC paramSet
  5425. ######################################################################
  5426. sub HMCCU_RPCSetConfig ($$$)
  5427. {
  5428. my ($hash, $param, $parref) = @_;
  5429. my $name = $hash->{NAME};
  5430. my $type = $hash->{TYPE};
  5431. my $ccuflags = HMCCU_GetFlags ($name);
  5432. my $addr;
  5433. my $res;
  5434. my $hmccu_hash = HMCCU_GetHash ($hash);
  5435. return -3 if (!defined ($hmccu_hash));
  5436. return -4 if ($type ne 'HMCCU' && $hash->{ccudevstate} eq 'deleted');
  5437. my ($int, $add, $chn, $dpt, $nam, $flags) = HMCCU_ParseObject ($hmccu_hash, $param,
  5438. $HMCCU_FLAG_FULLADDR);
  5439. return -1 if (!($flags & $HMCCU_FLAG_ADDRESS));
  5440. $addr = $add;
  5441. $addr .= ':'.$chn if ($flags & $HMCCU_FLAG_CHANNEL);
  5442. my $rpctype = HMCCU_GetRPCServerInfo ($hmccu_hash, $int, 'type');
  5443. return -9 if (!defined ($rpctype));
  5444. my $port = HMCCU_GetRPCServerInfo ($hmccu_hash, $int, 'port');
  5445. return -9 if (!defined ($port));
  5446. if ($ccuflags =~ /trace/) {
  5447. my $ps = '';
  5448. foreach my $p (keys %$parref) {
  5449. $ps .= ", ".$p."=".$parref->{$p};
  5450. }
  5451. Log3 $name, 2, "HMCCU: RPCSetConfig: addr=$addr".$ps;
  5452. }
  5453. if ($rpctype eq 'B') {
  5454. # Search RPC device
  5455. my $rpcdev = HMCCU_GetRPCDevice ($hmccu_hash, 0, $int);
  5456. return -17 if ($rpcdev eq '');
  5457. # Rebuild parameter hash for binary encoding
  5458. my %binpar;
  5459. foreach my $e (keys %$parref) {
  5460. $binpar{$e}{T} = $BINRPC_STRING;
  5461. $binpar{$e}{V} = $parref->{$e};
  5462. }
  5463. if ($ccuflags =~ /(extrpc|procrpc)/) {
  5464. # $res = HMCCURPC_SendBinRequest ($defs{$rpcdev}, $port, "putParamset", $BINRPC_STRING, $addr,
  5465. # $BINRPC_STRING, "MASTER", $BINRPC_STRUCT, \%binpar);
  5466. # }
  5467. # elsif ($ccuflags =~ /procrpc/) {
  5468. $res = HMCCURPCPROC_SendRequest ($defs{$rpcdev}, "putParamset", $BINRPC_STRING, $addr,
  5469. $BINRPC_STRING, "MASTER", $BINRPC_STRUCT, \%binpar);
  5470. }
  5471. }
  5472. else {
  5473. my $url = HMCCU_GetRPCServerInfo ($hmccu_hash, $int, 'url');
  5474. return -9 if (!defined ($url));
  5475. my $client = RPC::XML::Client->new ($url);
  5476. $res = $client->simple_request ("putParamset", $addr, "MASTER", $parref);
  5477. }
  5478. return -5 if (! defined ($res));
  5479. return HMCCU_Log ($hash, 1, "HMCCU: RPC request failed. ".$res->{faultString}, -2)
  5480. if (ref ($res) && exists ($res->{faultString}));
  5481. return 0;
  5482. }
  5483. ######################################################################
  5484. # *** FILEQUEUE FUNCTIONS ***
  5485. ######################################################################
  5486. ######################################################################
  5487. # Open file queue
  5488. ######################################################################
  5489. sub HMCCU_QueueOpen ($$)
  5490. {
  5491. my ($hash, $queue_file) = @_;
  5492. my $idx_file = $queue_file . '.idx';
  5493. $queue_file .= '.dat';
  5494. my $mode = '0666';
  5495. umask (0);
  5496. $hash->{hmccu}{queue}{block_size} = 64;
  5497. $hash->{hmccu}{queue}{seperator} = "\n";
  5498. $hash->{hmccu}{queue}{sep_length} = length $hash->{hmccu}{queue}{seperator};
  5499. $hash->{hmccu}{queue}{queue_file} = $queue_file;
  5500. $hash->{hmccu}{queue}{idx_file} = $idx_file;
  5501. $hash->{hmccu}{queue}{queue} = new IO::File $queue_file, O_CREAT | O_RDWR, oct($mode) or return 0;
  5502. $hash->{hmccu}{queue}{idx} = new IO::File $idx_file, O_CREAT | O_RDWR, oct($mode) or return 0;
  5503. ### Default ptr to 0, replace it with value in idx file if one exists
  5504. $hash->{hmccu}{queue}{idx}->sysseek(0, SEEK_SET);
  5505. $hash->{hmccu}{queue}{idx}->sysread($hash->{hmccu}{queue}{ptr}, 1024);
  5506. $hash->{hmccu}{queue}{ptr} = '0' unless $hash->{hmccu}{queue}{ptr};
  5507. if($hash->{hmccu}{queue}{ptr} > -s $queue_file)
  5508. {
  5509. $hash->{hmccu}{queue}{idx}->truncate(0) or return 0;
  5510. $hash->{hmccu}{queue}{idx}->sysseek(0, SEEK_SET);
  5511. $hash->{hmccu}{queue}{idx}->syswrite('0') or return 0;
  5512. }
  5513. return 1;
  5514. }
  5515. ######################################################################
  5516. # Close file queue
  5517. ######################################################################
  5518. sub HMCCU_QueueClose ($)
  5519. {
  5520. my ($hash) = @_;
  5521. if (exists ($hash->{hmccu}{queue})) {
  5522. $hash->{hmccu}{queue}{idx}->close();
  5523. $hash->{hmccu}{queue}{queue}->close();
  5524. delete $hash->{hmccu}{queue};
  5525. }
  5526. }
  5527. sub HMCCU_QueueReset ($)
  5528. {
  5529. my ($hash) = @_;
  5530. $hash->{hmccu}{queue}{idx}->truncate(0) or return 0;
  5531. $hash->{hmccu}{queue}{idx}->sysseek(0, SEEK_SET);
  5532. $hash->{hmccu}{queue}{idx}->syswrite('0') or return 0;
  5533. $hash->{hmccu}{queue}{queue}->sysseek($hash->{hmccu}{queue}{ptr} = 0, SEEK_SET);
  5534. return 1;
  5535. }
  5536. ######################################################################
  5537. # Put value in file queue
  5538. ######################################################################
  5539. sub HMCCU_QueueEnq ($$)
  5540. {
  5541. my ($hash, $element) = @_;
  5542. return 0 if (!exists ($hash->{hmccu}{queue}));
  5543. $hash->{hmccu}{queue}{queue}->sysseek(0, SEEK_END);
  5544. $element =~ s/$hash->{hmccu}{queue}{seperator}//g;
  5545. $hash->{hmccu}{queue}{queue}->syswrite($element.$hash->{hmccu}{queue}{seperator}) or return 0;
  5546. return 1;
  5547. }
  5548. ######################################################################
  5549. # Return next value in file queue
  5550. ######################################################################
  5551. sub HMCCU_QueueDeq ($)
  5552. {
  5553. my ($hash) = @_;
  5554. my $name = $hash->{NAME};
  5555. my $sep_length = $hash->{hmccu}{queue}{sep_length};
  5556. my $element = '';
  5557. return undef if (!exists ($hash->{hmccu}{queue}));
  5558. $hash->{hmccu}{queue}{queue}->sysseek($hash->{hmccu}{queue}{ptr}, SEEK_SET);
  5559. my $i;
  5560. while($hash->{hmccu}{queue}{queue}->sysread($_, $hash->{hmccu}{queue}{block_size})) {
  5561. $i = index($_, $hash->{hmccu}{queue}{seperator});
  5562. if($i != -1) {
  5563. $element .= substr($_, 0, $i);
  5564. $hash->{hmccu}{queue}{ptr} += $i + $sep_length;
  5565. $hash->{hmccu}{queue}{queue}->sysseek($hash->{hmccu}{queue}{ptr}, SEEK_SET);
  5566. last;
  5567. }
  5568. else {
  5569. # Seperator not found, go back 'sep_length' spaces to ensure we don't miss it between reads
  5570. Log3 $name, 2, "HMCCU: HMCCU_QueueDeq seperator not found";
  5571. $element .= substr($_, 0, -$sep_length, '');
  5572. $hash->{hmccu}{queue}{ptr} += $hash->{hmccu}{queue}{block_size} - $sep_length;
  5573. $hash->{hmccu}{queue}{queue}->sysseek($hash->{hmccu}{queue}{ptr}, SEEK_SET);
  5574. }
  5575. }
  5576. ## If queue seek pointer is at the EOF, truncate the queue file
  5577. if($hash->{hmccu}{queue}{queue}->sysread($_, 1) == 0)
  5578. {
  5579. $hash->{hmccu}{queue}{queue}->truncate(0) or return undef;
  5580. $hash->{hmccu}{queue}{queue}->sysseek($hash->{hmccu}{queue}{ptr} = 0, SEEK_SET);
  5581. }
  5582. ## Set idx file contents to point to the current seek position in queue file
  5583. $hash->{hmccu}{queue}{idx}->truncate(0) or return undef;
  5584. $hash->{hmccu}{queue}{idx}->sysseek(0, SEEK_SET);
  5585. $hash->{hmccu}{queue}{idx}->syswrite($hash->{hmccu}{queue}{ptr}) or return undef;
  5586. return ($element ne '') ? $element : undef;
  5587. }
  5588. ######################################################################
  5589. # *** HELPER FUNCTIONS ***
  5590. ######################################################################
  5591. ######################################################################
  5592. # Determine HomeMatic state considering datapoint values specified
  5593. # in attributes ccudef-hmstatevals and hmstatevals.
  5594. # Return (reading, channel, datapoint, value)
  5595. ######################################################################
  5596. sub HMCCU_GetHMState ($$$)
  5597. {
  5598. my ($name, $ioname, $defval) = @_;
  5599. my @hmstate = ('hmstate', undef, undef, $defval);
  5600. my $fnc = "GetHMState";
  5601. my $clhash = $defs{$name};
  5602. my $cltype = $clhash->{TYPE};
  5603. return @hmstate if ($cltype ne 'HMCCUDEV' && $cltype ne 'HMCCUCHN');
  5604. my $ghmstatevals = AttrVal ($ioname, 'ccudef-hmstatevals', $HMCCU_DEF_HMSTATE);
  5605. my $hmstatevals = AttrVal ($name, 'hmstatevals', $ghmstatevals);
  5606. $hmstatevals .= ";".$ghmstatevals if ($hmstatevals ne $ghmstatevals);
  5607. # Get reading name
  5608. if ($hmstatevals =~ /^=([^;]*);/) {
  5609. $hmstate[0] = $1;
  5610. $hmstatevals =~ s/^=[^;]*;//;
  5611. }
  5612. HMCCU_Trace ($clhash, 2, $fnc, "hmstatevals=$hmstatevals");
  5613. # Default hmstate is equal to state
  5614. $hmstate[3] = ReadingsVal ($name, 'state', undef) if (!defined ($defval));
  5615. # Substitute variables
  5616. $hmstatevals = HMCCU_SubstVariables ($clhash, $hmstatevals, undef);
  5617. my @rulelist = split (";", $hmstatevals);
  5618. foreach my $rule (@rulelist) {
  5619. my ($dptexpr, $subst) = split ('!', $rule, 2);
  5620. my $dp = '';
  5621. next if (!defined ($dptexpr) || !defined ($subst));
  5622. HMCCU_Trace ($clhash, 2, $fnc, "dptexpr=$dptexpr, subst=$subst");
  5623. foreach my $d (keys %{$clhash->{hmccu}{dp}}) {
  5624. HMCCU_Trace ($clhash, 2, $fnc, "Check $d match $dptexpr");
  5625. if ($d =~ /$dptexpr/) {
  5626. $dp = $d;
  5627. last;
  5628. }
  5629. }
  5630. next if ($dp eq '');
  5631. my ($chn, $dpt) = split (/\./, $dp);
  5632. my $value = HMCCU_FormatReadingValue ($clhash, $clhash->{hmccu}{dp}{$dp}{VAL}, $hmstate[0]);
  5633. my ($rc, $newvalue) = HMCCU_SubstRule ($value, $subst, 0);
  5634. return ($hmstate[0], $chn, $dpt, $newvalue) if ($rc);
  5635. }
  5636. return @hmstate;
  5637. }
  5638. ######################################################################
  5639. # Calculate time difference in seconds between current time and
  5640. # specified timestamp
  5641. ######################################################################
  5642. sub HMCCU_GetTimeSpec ($)
  5643. {
  5644. my ($ts) = @_;
  5645. return -1 if ($ts !~ /^[0-9]{2}:[0-9]{2}$/ && $ts !~ /^[0-9]{2}:[0-9]{2}:[0-9]{2}$/);
  5646. my (undef, $h, $m, $s) = GetTimeSpec ($ts);
  5647. return -1 if (!defined ($h));
  5648. $s += $h*3600+$m*60;
  5649. my @lt = localtime;
  5650. my $cs = $lt[2]*3600+$lt[1]*60+$lt[0];
  5651. $s += 86400 if ($cs > $s);
  5652. return ($s-$cs);
  5653. }
  5654. ######################################################################
  5655. # Calculate special readings. Requires hash of client device, channel
  5656. # number and datapoint. Supported functions:
  5657. # dewpoint, absolute humidity, increasing/decreasing counters,
  5658. # minimum/maximum, average, sum.
  5659. # Return readings array with reading/value pairs.
  5660. ######################################################################
  5661. sub HMCCU_CalculateReading ($$$)
  5662. {
  5663. my ($cl_hash, $chnno, $dpt) = @_;
  5664. my $name = $cl_hash->{NAME};
  5665. my @result = ();
  5666. my $ccucalculate = AttrVal ($name, 'ccucalculate', '');
  5667. return @result if ($ccucalculate eq '');
  5668. my @calclist = split (/[;\n]+/, $ccucalculate);
  5669. foreach my $calculation (@calclist) {
  5670. my ($vt, $rn, $dpts) = split (':', $calculation);
  5671. next if (!defined ($rn));
  5672. # Get parameters values stored in device hash
  5673. my @dplist = defined ($dpts) ? split (',', $dpts) : ();
  5674. next if (@dplist > 0 && !(grep { $_ eq "$chnno.$dpt"} @dplist));
  5675. my @pars = ();
  5676. foreach my $dp (@dplist) {
  5677. if (exists ($cl_hash->{hmccu}{dp}{$dp}{VAL})) {
  5678. push @pars, $cl_hash->{hmccu}{dp}{$dp}{VAL};
  5679. }
  5680. }
  5681. if ($vt eq 'dewpoint' || $vt eq 'abshumidity') {
  5682. # Dewpoint and absolute humidity
  5683. next if (scalar (@pars) < 2);
  5684. my ($tmp, $hum) = @pars;
  5685. if ($tmp >= 0.0) {
  5686. $a = 7.5;
  5687. $b = 237.3;
  5688. }
  5689. else {
  5690. $a = 7.6;
  5691. $b = 240.7;
  5692. }
  5693. my $sdd = 6.1078*(10.0**(($a*$tmp)/($b+$tmp)));
  5694. my $dd = $hum/100.0*$sdd;
  5695. if ($dd != 0.0) {
  5696. if ($vt eq 'dewpoint') {
  5697. my $v = log($dd/6.1078)/log(10.0);
  5698. my $td = $b*$v/($a-$v);
  5699. push (@result, $rn, (sprintf "%.1f", $td));
  5700. }
  5701. else {
  5702. my $af = 100000.0*18.016/8314.3*$dd/($tmp+273.15);
  5703. push (@result, $rn, (sprintf "%.1f", $af));
  5704. }
  5705. }
  5706. }
  5707. elsif ($vt eq 'min' || $vt eq 'max') {
  5708. # Minimum or maximum values
  5709. next if (scalar (@pars) < 1);
  5710. my $newval = shift @pars;
  5711. my $curval = ReadingsVal ($name, $rn, 0);
  5712. $curval = $newval if ($vt eq 'min' && $newval < $curval);
  5713. $curval = $newval if ($vt eq 'max' && $newval > $curval);
  5714. push (@result, $rn, $curval);
  5715. }
  5716. elsif ($vt eq 'inc' || $vt eq 'dec') {
  5717. # Increasing or decreasing values without reset
  5718. next if (scalar (@pars) < 1);
  5719. my $newval = shift @pars;
  5720. my $oldval = ReadingsVal ($name, $rn."_old", 0);
  5721. my $curval = ReadingsVal ($name, $rn, 0);
  5722. if (($vt eq 'inc' && $newval < $curval) || ($vt eq 'dec' && $newval > $curval)) {
  5723. $oldval = $curval;
  5724. push (@result, $rn."_old", $oldval);
  5725. }
  5726. $curval = $newval+$oldval;
  5727. push (@result, $rn, $curval);
  5728. }
  5729. elsif ($vt eq 'avg') {
  5730. # Average value
  5731. next if (scalar (@pars) < 1);
  5732. my $newval = shift @pars;
  5733. my $cnt = ReadingsVal ($name, $rn."_cnt", 0);
  5734. my $sum = ReadingsVal ($name, $rn."_sum", 0);
  5735. $cnt++;
  5736. $sum += $newval;
  5737. my $curval = $sum/$cnt;
  5738. push (@result, $rn."_cnt", $cnt, $rn."_sum", $sum, $rn, $curval);
  5739. }
  5740. elsif ($vt eq 'sum') {
  5741. # Sum of values
  5742. next if (scalar (@pars) < 1);
  5743. my $newval = shift @pars;
  5744. my $curval = ReadingsVal ($name, $rn, 0);
  5745. $curval += $newval;
  5746. push (@result, $rn, $curval);
  5747. }
  5748. }
  5749. return @result;
  5750. }
  5751. ######################################################################
  5752. # Encode command string for e-paper display
  5753. #
  5754. # Parameters:
  5755. #
  5756. # msg := parameter=value[,...]
  5757. #
  5758. # text1-3=Text
  5759. # icon1-3=IconName
  5760. # sound=SoundName
  5761. # signal=SignalName
  5762. # pause=1-160
  5763. # repeat=0-15
  5764. #
  5765. # Returns undef on error or encoded string on success
  5766. ######################################################################
  5767. sub HMCCU_EncodeEPDisplay ($)
  5768. {
  5769. my ($msg) = @_;
  5770. # set defaults
  5771. $msg = '' if (!defined ($msg));
  5772. my %disp_icons = (
  5773. ico_off => '0x80', ico_on => '0x81', ico_open => '0x82', ico_closed => '0x83',
  5774. ico_error => '0x84', ico_ok => '0x85', ico_info => '0x86', ico_newmsg => '0x87',
  5775. ico_svcmsg => '0x88'
  5776. );
  5777. my %disp_sounds = (
  5778. snd_off => '0xC0', snd_longlong => '0xC1', snd_longshort => '0xC2',
  5779. snd_long2short => '0xC3', snd_short => '0xC4', snd_shortshort => '0xC5',
  5780. snd_long => '0xC6'
  5781. );
  5782. my %disp_signals = (
  5783. sig_off => '0xF0', sig_red => '0xF1', sig_green => '0xF2', sig_orange => '0xF3'
  5784. );
  5785. # Parse command string
  5786. my @text = ('', '', '');
  5787. my @icon = ('', '', '');
  5788. my %conf = (sound => 'snd_off', signal => 'sig_off', repeat => 1, pause => 10);
  5789. foreach my $tok (split (',', $msg)) {
  5790. my ($par, $val) = split ('=', $tok);
  5791. next if (!defined ($val));
  5792. if ($par =~ /^text([1-3])$/) {
  5793. $text[$1-1] = substr ($val, 0, 12);
  5794. }
  5795. elsif ($par =~ /^icon([1-3])$/) {
  5796. $icon[$1-1] = $val;
  5797. }
  5798. elsif ($par =~ /^(sound|pause|repeat|signal)$/) {
  5799. $conf{$1} = $val;
  5800. }
  5801. }
  5802. my $cmd = '0x02,0x0A';
  5803. for (my $c=0; $c<3; $c++) {
  5804. if ($text[$c] ne '' || $icon[$c] ne '') {
  5805. $cmd .= ',0x12';
  5806. # Hex code
  5807. if ($text[$c] =~ /^0x[0-9A-F]{2}$/) {
  5808. $cmd .= ','.$text[$c];
  5809. }
  5810. # Predefined text code #0-9
  5811. elsif ($text[$c] =~ /^#([0-9])$/) {
  5812. $cmd .= sprintf (",0x8%1X", $1);
  5813. }
  5814. # Convert string to hex codes
  5815. else {
  5816. $text[$c] =~ s/\\_/ /g;
  5817. foreach my $ch (split ('', $text[$c])) {
  5818. $cmd .= sprintf (",0x%02X", ord ($ch));
  5819. }
  5820. }
  5821. # Icon
  5822. if ($icon[$c] ne '' && exists ($disp_icons{$icon[$c]})) {
  5823. $cmd .= ',0x13,'.$disp_icons{$icon[$c]};
  5824. }
  5825. }
  5826. $cmd .= ',0x0A';
  5827. }
  5828. # Sound
  5829. my $snd = $disp_sounds{snd_off};
  5830. $snd = $disp_sounds{$conf{sound}} if (exists ($disp_sounds{$conf{sound}}));
  5831. $cmd .= ',0x14,'.$snd.',0x1C';
  5832. # Repeat
  5833. my $rep = $conf{repeat} if ($conf{repeat} >= 0 && $conf{repeat} <= 15);
  5834. $rep = 1 if ($rep < 0);
  5835. $rep = 15 if ($rep > 15);
  5836. if ($rep == 0) {
  5837. $cmd .= ',0xDF';
  5838. }
  5839. else {
  5840. $cmd .= sprintf (",0x%02X", 0xD0+$rep-1);
  5841. }
  5842. $cmd .= ',0x1D';
  5843. # Pause
  5844. my $pause = $conf{pause};
  5845. $pause = 1 if ($pause < 1);
  5846. $pause = 160 if ($pause > 160);
  5847. $cmd .= sprintf (",0xE%1X,0x16", int(($pause-1)/10));
  5848. # Signal
  5849. my $sig = $disp_signals{sig_off};
  5850. $sig = $disp_signals{$conf{signal}} if (exists ($disp_signals{$conf{signal}}));
  5851. $cmd .= ','.$sig.',0x03';
  5852. return $cmd;
  5853. }
  5854. ######################################################################
  5855. # Convert reference to string recursively
  5856. # Supports reference to ARRAY, HASH and SCALAR and scalar values.
  5857. ######################################################################
  5858. sub HMCCU_RefToString ($)
  5859. {
  5860. my ($r) = @_;
  5861. my $result = '';
  5862. if (ref ($r) eq 'ARRAY') {
  5863. $result .= "[\n";
  5864. foreach my $e (@$r) {
  5865. $result .= "," if ($result ne '[');
  5866. $result .= HMCCU_RefToString ($e);
  5867. }
  5868. $result .= "\n]";
  5869. }
  5870. elsif (ref ($r) eq 'HASH') {
  5871. $result .= "{\n";
  5872. foreach my $k (sort keys %$r) {
  5873. $result .= "," if ($result ne '{');
  5874. $result .= "$k=".HMCCU_RefToString ($r->{$k});
  5875. }
  5876. $result .= "\n}";
  5877. }
  5878. elsif (ref ($r) eq 'SCALAR') {
  5879. $result .= $$r;
  5880. }
  5881. else {
  5882. $result .= $r;
  5883. }
  5884. return $result;
  5885. }
  5886. ######################################################################
  5887. # Match string with regular expression considering illegal regular
  5888. # expressions. Return parameter e if regular expression is incorrect.
  5889. ######################################################################
  5890. sub HMCCU_ExprMatch ($$$)
  5891. {
  5892. my ($t, $r, $e) = @_;
  5893. my $x = eval { $t =~ /$r/ };
  5894. return $e if (!defined ($x));
  5895. return "$x" eq '' ? 0 : 1;
  5896. }
  5897. sub HMCCU_ExprNotMatch ($$$)
  5898. {
  5899. my ($t, $r, $e) = @_;
  5900. my $x = eval { $t !~ /$r/ };
  5901. return $e if (!defined ($x));
  5902. return "$x" eq '' ? 0 : 1;
  5903. }
  5904. ######################################################################
  5905. # Read duty cycles of interfaces 2001 and 2010 and update readings.
  5906. ######################################################################
  5907. sub HMCCU_GetDutyCycle ($)
  5908. {
  5909. my ($hash) = @_;
  5910. my $name = $hash->{NAME};
  5911. my $dc = 0;
  5912. my @rpcports = HMCCU_GetRPCPortList ($hash);
  5913. readingsBeginUpdate ($hash);
  5914. foreach my $port (@rpcports) {
  5915. next if ($port != 2001 && $port != 2010);
  5916. my $url = HMCCU_GetRPCServerInfo ($hash, $port, 'url');
  5917. next if (!defined ($url));
  5918. my $rpcclient = RPC::XML::Client->new ($url);
  5919. my $response = $rpcclient->simple_request ("listBidcosInterfaces");
  5920. next if (!defined ($response) || ref($response) ne 'ARRAY');
  5921. foreach my $iface (@$response) {
  5922. next if (ref ($iface) ne 'HASH');
  5923. next if (!exists ($iface->{DUTY_CYCLE}));
  5924. $dc++;
  5925. my $type = exists ($iface->{TYPE}) ? $iface->{TYPE} : HMCCU_GetRPCServerInfo ($hash, $port, 'name');
  5926. readingsBulkUpdate ($hash, "iface_addr_$dc", $iface->{ADDRESS});
  5927. readingsBulkUpdate ($hash, "iface_conn_$dc", $iface->{CONNECTED});
  5928. readingsBulkUpdate ($hash, "iface_type_$dc", $type);
  5929. readingsBulkUpdate ($hash, "iface_ducy_$dc", $iface->{DUTY_CYCLE});
  5930. }
  5931. }
  5932. readingsEndUpdate ($hash, 1);
  5933. return $dc;
  5934. }
  5935. ######################################################################
  5936. # Check if TCP port is reachable.
  5937. # Parameter timeout should be a multiple of 20 plus 5.
  5938. ######################################################################
  5939. sub HMCCU_TCPPing ($$$)
  5940. {
  5941. my ($addr, $port, $timeout) = @_;
  5942. if ($timeout > 0) {
  5943. my $t = time ();
  5944. while (time () < $t+$timeout) {
  5945. return 1 if (HMCCU_TCPConnect ($addr, $port) ne '');
  5946. sleep (20);
  5947. }
  5948. return 0;
  5949. }
  5950. else {
  5951. return HMCCU_TCPConnect ($addr, $port) eq '' ? 0 : 1;
  5952. }
  5953. }
  5954. ######################################################################
  5955. # Check if TCP connection to specified host and port is possible.
  5956. # Return empty string on error or local IP address on success.
  5957. ######################################################################
  5958. sub HMCCU_TCPConnect ($$)
  5959. {
  5960. my ($addr, $port) = @_;
  5961. my $socket = IO::Socket::INET->new (PeerAddr => $addr, PeerPort => $port);
  5962. if ($socket) {
  5963. my $ipaddr = $socket->sockhost ();
  5964. close ($socket);
  5965. return $ipaddr if (defined ($ipaddr));
  5966. }
  5967. return '';
  5968. }
  5969. ######################################################################
  5970. # Resolve hostname.
  5971. # Return value defip if hostname can't be resolved.
  5972. ######################################################################
  5973. sub HMCCU_ResolveName ($$)
  5974. {
  5975. my ($hname, $defip) = @_;
  5976. my $ip = $defip;
  5977. my $addrnum = inet_aton ($hname);
  5978. $ip = inet_ntoa ($addrnum) if (defined ($addrnum));
  5979. return $ip;
  5980. }
  5981. ######################################################################
  5982. # Substitute invalid characters in reading name.
  5983. # Substitution rules: ':' => '.', any other illegal character => '_'
  5984. ######################################################################
  5985. sub HMCCU_CorrectName ($)
  5986. {
  5987. my ($rn) = @_;
  5988. $rn =~ s/\:/\./g;
  5989. $rn =~ s/[^A-Za-z\d_\.-]+/_/g;
  5990. return $rn;
  5991. }
  5992. ######################################################################
  5993. # *** SUBPROCESS PART ***
  5994. ######################################################################
  5995. # Child process. Must be global to allow access by RPC callbacks
  5996. my $hmccu_child;
  5997. # Queue file
  5998. my %child_queue;
  5999. my $cpqueue = \%child_queue;
  6000. # Statistic data of child process
  6001. my %child_hash = (
  6002. "total", 0,
  6003. "writeerror", 0,
  6004. "EV", 0,
  6005. "ND", 0,
  6006. "DD", 0,
  6007. "RD", 0,
  6008. "RA", 0,
  6009. "UD", 0,
  6010. "IN", 0,
  6011. "EX", 0,
  6012. "SL", 0
  6013. );
  6014. my $cphash = \%child_hash;
  6015. ######################################################################
  6016. # Subprocess: Write event to parent process
  6017. ######################################################################
  6018. sub HMCCU_CCURPC_Write ($$)
  6019. {
  6020. my ($et, $msg) = @_;
  6021. my $name = $hmccu_child->{devname};
  6022. $cphash->{total}++;
  6023. $cphash->{$et}++;
  6024. HMCCU_QueueEnq ($cpqueue, $et."|".$msg);
  6025. }
  6026. ######################################################################
  6027. # Subprocess: Initialize RPC server. Return 1 on success.
  6028. ######################################################################
  6029. sub HMCCU_CCURPC_OnRun ($)
  6030. {
  6031. $hmccu_child = shift;
  6032. my $name = $hmccu_child->{devname};
  6033. my $serveraddr = $hmccu_child->{serveraddr};
  6034. my $serverport = $hmccu_child->{serverport};
  6035. my $callbackport = $hmccu_child->{callbackport};
  6036. my $queuefile = $hmccu_child->{queue};
  6037. my $clkey = "CB".$serverport;
  6038. my $ccurpc_server;
  6039. # Create, open and reset queue file
  6040. Log3 $name, 0, "CCURPC: $clkey Creating file queue $queuefile";
  6041. if (!HMCCU_QueueOpen ($cpqueue, $queuefile)) {
  6042. Log3 $name, 0, "CCURPC: $clkey Can't create queue";
  6043. return 0;
  6044. }
  6045. # Reset event queue
  6046. HMCCU_QueueReset ($cpqueue);
  6047. while (defined (HMCCU_QueueDeq ($cpqueue))) { }
  6048. # Create RPC server
  6049. Log3 $name, 0, "CCURPC: Initializing RPC server $clkey";
  6050. $ccurpc_server = RPC::XML::Server->new (port=>$callbackport);
  6051. if (!ref($ccurpc_server))
  6052. {
  6053. Log3 $name, 0, "CCURPC: Can't create RPC callback server on port $callbackport. Port in use?";
  6054. return 0;
  6055. }
  6056. else {
  6057. Log3 $name, 0, "CCURPC: Callback server created listening on port $callbackport";
  6058. }
  6059. # Format of signature:
  6060. # string par1 ... parN
  6061. # Callback for events
  6062. # Parameters: Server, InterfaceId, Address, ValueKey, Value
  6063. Log3 $name, 1, "CCURPC: $clkey Adding callback for events";
  6064. $ccurpc_server->add_method (
  6065. { name=>"event",
  6066. signature=> ["string string string string string","string string string string int","string string string string double","string string string string boolean","string string string string i4"],
  6067. code=>\&HMCCU_CCURPC_EventCB
  6068. }
  6069. );
  6070. # Callback for new devices
  6071. # Parameters: Server, InterfaceId, DeviceDescriptions[]
  6072. Log3 $name, 1, "CCURPC: $clkey Adding callback for new devices";
  6073. $ccurpc_server->add_method (
  6074. { name=>"newDevices",
  6075. signature=>["string string array"],
  6076. code=>\&HMCCU_CCURPC_NewDevicesCB
  6077. }
  6078. );
  6079. # Callback for deleted devices
  6080. # Parameters: Server, InterfaceId, Addresses[]
  6081. Log3 $name, 1, "CCURPC: $clkey Adding callback for deleted devices";
  6082. $ccurpc_server->add_method (
  6083. { name=>"deleteDevices",
  6084. signature=>["string string array"],
  6085. code=>\&HMCCU_CCURPC_DeleteDevicesCB
  6086. }
  6087. );
  6088. # Callback for modified devices
  6089. # Parameters: Server, InterfaceId, Address, Hint
  6090. Log3 $name, 1, "CCURPC: $clkey Adding callback for modified devices";
  6091. $ccurpc_server->add_method (
  6092. { name=>"updateDevice",
  6093. signature=>["string string string int"],
  6094. code=>\&HMCCU_CCURPC_UpdateDeviceCB
  6095. }
  6096. );
  6097. # Callback for replaced devices
  6098. # Parameters: Server, InterfaceId, OldAddress, NewAddress
  6099. Log3 $name, 1, "CCURPC: $clkey Adding callback for replaced devices";
  6100. $ccurpc_server->add_method (
  6101. { name=>"replaceDevice",
  6102. signature=>["string string string string"],
  6103. code=>\&HMCCU_CCURPC_ReplaceDeviceCB
  6104. }
  6105. );
  6106. # Callback for readded devices
  6107. # Parameters: Server, InterfaceId, Addresses[]
  6108. Log3 $name, 1, "CCURPC: $clkey Adding callback for readded devices";
  6109. $ccurpc_server->add_method (
  6110. { name=>"replaceDevice",
  6111. signature=>["string string array"],
  6112. code=>\&HMCCU_CCURPC_ReaddDeviceCB
  6113. }
  6114. );
  6115. # Dummy implementation, always return an empty array
  6116. # Parameters: Server, InterfaceId
  6117. Log3 $name, 1, "CCURPC: $clkey Adding callback for list devices";
  6118. $ccurpc_server->add_method (
  6119. { name=>"listDevices",
  6120. signature=>["string string"],
  6121. code=>\&HMCCU_CCURPC_ListDevicesCB
  6122. }
  6123. );
  6124. # Enter server loop
  6125. HMCCU_CCURPC_Write ("SL", "$$|$clkey");
  6126. Log3 $name, 0, "CCURPC: $clkey Entering server loop";
  6127. $ccurpc_server->server_loop;
  6128. Log3 $name, 0, "CCURPC: $clkey Server loop terminated";
  6129. # Server loop exited by SIGINT
  6130. HMCCU_CCURPC_Write ("EX", "SHUTDOWN|$$|$clkey");
  6131. return 1;
  6132. }
  6133. ######################################################################
  6134. # Subprocess: Called when RPC server loop is terminated
  6135. ######################################################################
  6136. sub HMCCU_CCURPC_OnExit ()
  6137. {
  6138. # Output statistics
  6139. foreach my $et (sort keys %child_hash) {
  6140. Log3 $hmccu_child->{devname}, 2, "CCURPC: Eventcount $et = ".$cphash->{$et};
  6141. }
  6142. }
  6143. ######################################################################
  6144. # Subprocess: Callback for new devices
  6145. ######################################################################
  6146. sub HMCCU_CCURPC_NewDevicesCB ($$$)
  6147. {
  6148. my ($server, $cb, $a) = @_;
  6149. my $devcount = scalar (@$a);
  6150. my $name = $hmccu_child->{devname};
  6151. my $c = 0;
  6152. my $msg = '';
  6153. Log3 $name, 2, "CCURPC: $cb NewDevice received $devcount device specifications";
  6154. for my $dev (@$a) {
  6155. my $msg = '';
  6156. if ($dev->{ADDRESS} =~ /:[0-9]{1,2}$/) {
  6157. $msg = "C|".$dev->{ADDRESS}."|".$dev->{TYPE}."|".$dev->{VERSION}."|null|null";
  6158. }
  6159. else {
  6160. # Wired devices do not have a RX_MODE attribute
  6161. my $rx = exists ($dev->{RX_MODE}) ? $dev->{RX_MODE} : 'null';
  6162. $msg = "D|".$dev->{ADDRESS}."|".$dev->{TYPE}."|".$dev->{VERSION}."|".
  6163. $dev->{FIRMWARE}."|".$rx;
  6164. }
  6165. HMCCU_CCURPC_Write ("ND", $msg);
  6166. }
  6167. return;
  6168. }
  6169. ######################################################################
  6170. # Subprocess: Callback for deleted devices
  6171. ######################################################################
  6172. sub HMCCU_CCURPC_DeleteDevicesCB ($$$)
  6173. {
  6174. my ($server, $cb, $a) = @_;
  6175. my $name = $hmccu_child->{devname};
  6176. my $devcount = scalar (@$a);
  6177. Log3 $name, 2, "CCURPC: $cb DeleteDevice received $devcount device addresses";
  6178. for my $dev (@$a) {
  6179. HMCCU_CCURPC_Write ("DD", $dev);
  6180. }
  6181. return;
  6182. }
  6183. ######################################################################
  6184. # Subprocess: Callback for modified devices
  6185. ######################################################################
  6186. sub HMCCU_CCURPC_UpdateDeviceCB ($$$$)
  6187. {
  6188. my ($server, $cb, $devid, $hint) = @_;
  6189. HMCCU_CCURPC_Write ("UD", $devid."|".$hint);
  6190. return;
  6191. }
  6192. ######################################################################
  6193. # Subprocess: Callback for replaced devices
  6194. ######################################################################
  6195. sub HMCCU_CCURPC_ReplaceDeviceCB ($$$$)
  6196. {
  6197. my ($server, $cb, $devid1, $devid2) = @_;
  6198. HMCCU_CCURPC_Write ("RD", $devid1."|".$devid2);
  6199. return;
  6200. }
  6201. ######################################################################
  6202. # Subprocess: Callback for readded devices
  6203. ######################################################################
  6204. sub HMCCU_CCURPC_ReaddDevicesCB ($$$)
  6205. {
  6206. my ($server, $cb, $a) = @_;
  6207. my $name = $hmccu_child->{devname};
  6208. my $devcount = scalar (@$a);
  6209. Log3 $name, 2, "CCURPC: $cb ReaddDevice received $devcount device addresses";
  6210. for my $dev (@$a) {
  6211. HMCCU_CCURPC_Write ("RA", $dev);
  6212. }
  6213. return;
  6214. }
  6215. ######################################################################
  6216. # Subprocess: Callback for handling CCU events
  6217. ######################################################################
  6218. sub HMCCU_CCURPC_EventCB ($$$$$)
  6219. {
  6220. my ($server, $cb, $devid, $attr, $val) = @_;
  6221. my $name = $hmccu_child->{devname};
  6222. HMCCU_CCURPC_Write ("EV", $devid."|".$attr."|".$val);
  6223. if (($cphash->{EV} % 500) == 0) {
  6224. Log3 $name, 3, "CCURPC: $cb Received 500 events from CCU since last check";
  6225. my @stkeys = ('total', 'EV', 'ND', 'DD', 'RD', 'RA', 'UD', 'IN', 'SL', 'EX');
  6226. my $msg = '';
  6227. foreach my $stkey (@stkeys) {
  6228. $msg .= '|' if ($msg ne '');
  6229. $msg .= $cphash->{$stkey};
  6230. }
  6231. HMCCU_CCURPC_Write ("ST", $msg);
  6232. }
  6233. # Never remove this statement!
  6234. return;
  6235. }
  6236. ######################################################################
  6237. # Subprocess: Callback for list devices
  6238. ######################################################################
  6239. sub HMCCU_CCURPC_ListDevicesCB ($$)
  6240. {
  6241. my ($server, $cb) = @_;
  6242. my $name = $hmccu_child->{devname};
  6243. $cb = "unknown" if (!defined ($cb));
  6244. Log3 $name, 1, "CCURPC: $cb ListDevices. Sending init to HMCCU";
  6245. HMCCU_CCURPC_Write ("IN", "INIT|1|$cb");
  6246. return RPC::XML::array->new();
  6247. }
  6248. 1;
  6249. =pod
  6250. =item device
  6251. =item summary provides interface between FHEM and Homematic CCU2
  6252. =begin html
  6253. <a name="HMCCU"></a>
  6254. <h3>HMCCU</h3>
  6255. <ul>
  6256. The module provides an interface between FHEM and a Homematic CCU2. HMCCU is the
  6257. I/O device for the client devices HMCCUDEV and HMCCUCHN. The module requires the
  6258. additional Perl modules IO::File, RPC::XML::Client, RPC::XML::Server and SubProcess
  6259. (part of FHEM).
  6260. </br></br>
  6261. <a name="HMCCUdefine"></a>
  6262. <b>Define</b><br/><br/>
  6263. <ul>
  6264. <code>define &lt;name&gt; HMCCU &lt;HostOrIP&gt; [&lt;ccu-number&gt;] [waitforccu=&lt;timeout&gt;]
  6265. [ccudelay=&lt;delay&gt;] [delayedinit=&lt;delay&gt;]</code>
  6266. <br/><br/>
  6267. Example:<br/>
  6268. <code>define myccu HMCCU 192.168.1.10 ccudelay=180</code>
  6269. <br/><br/>
  6270. The parameter <i>HostOrIP</i> is the hostname or IP address of a Homematic CCU2 or CCU3. If you have
  6271. more than one CCU you can specifiy a unique CCU number with parameter <i>ccu-number</i>. With
  6272. option <i>waitforccu</i> HMCCU will wait for the specified time if CCU is not reachable.
  6273. Parameter <i>timeout</i> should be a multiple of 20 in seconds. Warning: This option will
  6274. block the start of FHEM for <i>timeout</i> seconds.<br/>
  6275. The option <i>ccudelay</i> specifies the time for delayed initialization of CCU environment if
  6276. the CCU is not reachable during FHEM startup (i.e. in case of a power failure). The default value
  6277. for <i>delay</i> is 180 seconds. Increase this value if your CCU needs more time to start up
  6278. after a power failure. This option will not block the start of FHEM.<br/>
  6279. With option <i>delayedinit</i> the CCU ennvironment will be initialized after the specified time,
  6280. no matter if CCU is reachable or not. As long as CCU environment is not initialized all client
  6281. devices of type HMCCUCHN or HMCCUDEV are in state 'pending' and all commands are disabled.<br/><br/>
  6282. For automatic update of Homematic device datapoints and FHEM readings one have to:
  6283. <br/><br/>
  6284. <ul>
  6285. <li>Define used RPC interfaces with attribute 'rpcinterfaces'</li>
  6286. <li>Start RPC servers with command 'set rpcserver on'</li>
  6287. <li>Optionally enable automatic start of RPC servers with attribute 'rpcserver'</li>
  6288. </ul><br/>
  6289. Then start with the definition of client devices using modules HMCCUDEV (CCU devices)
  6290. and HMCCUCHN (CCU channels) or with command 'get devicelist create'.<br/>
  6291. Maybe it's helpful to set the following FHEM standard attributes for the HMCCU I/O
  6292. device:<br/><br/>
  6293. <ul>
  6294. <li>Shortcut for RPC server control: eventMap /rpcserver on:on/rpcserver off:off/</li>
  6295. </ul>
  6296. </ul>
  6297. <br/>
  6298. <a name="HMCCUset"></a>
  6299. <b>Set</b><br/><br/>
  6300. <ul>
  6301. <li><b>set &lt;name&gt; ackmessages</b><br/>
  6302. Acknowledge device was unreachable messages in CCU.
  6303. </li><br/>
  6304. <li><b>set &lt;name&gt; cleardefaults</b><br/>
  6305. Clear default attributes imported from file.
  6306. </li><br/>
  6307. <li><b>set &lt;name&gt; datapoint {&lt;[ccu:]ccuobject&gt;|&lt;hmccu:fhemobject&gt;}.
  6308. &lt;datapoint&gt; &lt;value&gt;</b><br/>
  6309. Set datapoint of CCU channel in "raw" mode. The value is not scaled or substituted. If
  6310. target object is preceded by string "hmccu:" the following parameter <i>fhemobject</i>
  6311. must be a FHEM device of type HMCCUDEV or HMCCUCHN. If device type is HMCCUDEV the device
  6312. name must be followed by a ':' and a valid channel number.<br/><br/>
  6313. Examples:<br/>
  6314. <code>set d_ccu datapoint ABC1234567:1.STATE true</code><br/>
  6315. <code>set d_ccu datapoint hmccu:mychndevice.STATE true</code><br/>
  6316. <code>set d_ccu datapoint hmccu:mydevdevice:1.STATE true</code>
  6317. </li><br/>
  6318. <li><b>set &lt;name&gt; defaults</b><br/>
  6319. Set default attributes for I/O device.
  6320. </li><br/>
  6321. <li><b>set &lt;name&gt; delete &lt;ccuobject&gt; [&lt;objecttype&gt;]</b><br/>
  6322. Delete object in CCU. Default object type is OT_VARDP. Valid object types are<br/>
  6323. OT_DEVICE=device, OT_VARDP=variable.
  6324. </li><br/>
  6325. <li><b>set &lt;name&gt; execute &lt;program&gt;</b><br/>
  6326. Execute a CCU program.
  6327. <br/><br/>
  6328. Example:<br/>
  6329. <code>set d_ccu execute PR-TEST</code>
  6330. </li><br/>
  6331. <li><b>set &lt;name&gt; hmscript {&lt;script-file&gt;|'!'&lt;function&gt;|'['&lt;code&gt;']'} [dump]
  6332. [&lt;parname&gt;=&lt;value&gt; [...]]</b><br/>
  6333. Execute Homematic script on CCU. If script code contains parameter in format $parname
  6334. they are substituted by corresponding command line parameters <i>parname</i>.<br/>
  6335. If output of script contains lines in format Object=Value readings in existing
  6336. corresponding FHEM devices will be set. <i>Object</i> can be the name of a CCU system
  6337. variable or a valid channel and datapoint specification. Readings for system variables
  6338. are set in the I/O device. Datapoint related readings are set in client devices. If option
  6339. 'dump' is specified the result of script execution is displayed in FHEM web interface.
  6340. Execute command without parameters will list available script functions.
  6341. </li><br/>
  6342. <li><b>set &lt;name&gt; importdefaults &lt;filename&gt;</b><br/>
  6343. Import default attributes from file.
  6344. </li><br/>
  6345. <li><b>set &lt;name&gt; rpcserver {on | off | restart}</b><br/>
  6346. Start, stop or restart RPC server(s). This command executed with option 'on'
  6347. will fork a RPC server process for each RPC interface defined in attribute 'rpcinterfaces'.
  6348. Until operation is completed only a few set/get commands are available and you
  6349. may get the error message 'CCU busy'.
  6350. </li><br/>
  6351. <li><b>set &lt;name&gt; var &lt;variable&gt; &lt;Value&gt;</b><br/>
  6352. Set CCU system variable value. Special characters \_ in <i>value</i> are
  6353. substituted by blanks.
  6354. </li>
  6355. </ul>
  6356. <br/>
  6357. <a name="HMCCUget"></a>
  6358. <b>Get</b><br/><br/>
  6359. <ul>
  6360. <li><b>get &lt;name&gt; aggregation {&lt;rule&gt;|all}</b><br/>
  6361. Process aggregation rule defined with attribute ccuaggregate.
  6362. </li><br/>
  6363. <li><b>get &lt;name&gt; configdesc {&lt;device&gt;|&lt;channel&gt;}</b><br/>
  6364. Get configuration parameter description of CCU device or channel (similar
  6365. to device settings in CCU). Not every CCU device or channel provides a configuration
  6366. parameter description. So result may be empty.
  6367. </li><br/>
  6368. <li><b>get &lt;name&gt; defaults</b><br/>
  6369. List device types and channels with default attributes available.
  6370. </li><br/>
  6371. <li><b>get &lt;name&gt; deviceinfo &lt;device-name&gt; [{State | <u>Value</u>}]</b><br/>
  6372. List device channels and datapoints. If option 'State' is specified the device is
  6373. queried directly. Otherwise device information from CCU is listed.
  6374. </li><br/>
  6375. <li><b>get &lt;name&gt; devicelist [dump]</b><br/>
  6376. Read list of devices and channels from CCU. This command is executed automatically
  6377. after the definition of an I/O device. It must be executed manually after
  6378. module HMCCU is reloaded or after devices have changed in CCU (added, removed or
  6379. renamed). With option 'dump' devices are displayed in browser window. If a RPC
  6380. server is running HMCCU will raise events "<i>count</i> devices added in CCU" or
  6381. "<i>count</i> devices deleted in CCU". It's recommended to set up a notification
  6382. which reacts with execution of command 'get devicelist' on these events.
  6383. </li><br/>
  6384. <li><b>get &lt;name&gt; devicelist create &lt;devexp&gt; [t={chn|<u>dev</u>|all}]
  6385. [p=&lt;prefix&gt;] [s=&lt;suffix&gt;] [f=&lt;format&gt;] [defattr] [duplicates]
  6386. [save] [&lt;attr&gt;=&lt;value&gt; [...]]</b><br/>
  6387. With option 'create' HMCCU will automatically create client devices for all CCU devices
  6388. and channels matching specified regular expression. With option t=chn or t=dev (default)
  6389. the creation of devices is limited to CCU channels or devices.<br/>
  6390. Optionally a <i>prefix</i> and/or a
  6391. <i>suffix</i> for the FHEM device name can be specified. The parameter <i>format</i>
  6392. defines a template for the FHEM device names. Prefix, suffix and format can contain
  6393. format identifiers which are substituted by corresponding values of the CCU device or
  6394. channel: %n = CCU object name (channel or device), %d = CCU device name, %a = CCU address.
  6395. In addition a list of default attributes for the created client devices can be specified.
  6396. If option 'defattr' is specified HMCCU tries to set default attributes for device.
  6397. With option 'duplicates' HMCCU will overwrite existing devices and/or create devices
  6398. for existing device addresses. Option 'save' will save FHEM config after device definition.
  6399. </li><br/>
  6400. <li><b>get &lt;name&gt; dump {datapoints|devtypes} [&lt;filter&gt;]</b><br/>
  6401. Dump all Homematic devicetypes or all devices including datapoints currently
  6402. defined in FHEM.
  6403. </li><br/>
  6404. <li><b>get &lt;name&gt; dutycycle</b><br/>
  6405. Read CCU interface and gateway information. For each interface/gateway the following
  6406. information is stored in readings:<br/>
  6407. iface_addr_n = interface address<br/>
  6408. iface_type_n = interface type<br/>
  6409. iface_conn_n = interface connection state (1=connected, 0=disconnected)<br/>
  6410. iface_ducy_n = duty cycle of interface (0-100)
  6411. </li><br/>
  6412. <li><b>get &lt;name&gt; exportdefaults &lt;filename&gt;</b><br/>
  6413. Export default attributes into file.
  6414. </li><br/>
  6415. <li><b>get &lt;name&gt; firmware [{&lt;type-expr&gt; | full}]</b><br/>
  6416. Get available firmware downloads from eq-3.de. List FHEM devices with current and available
  6417. firmware version. By default only firmware version of defined HMCCUDEV or HMCCUCHN
  6418. devices are listet. With option 'full' all available firmware versions are listed.
  6419. With parameter <i>type-expr</i> one can filter displayed firmware versions by
  6420. Homematic device type.
  6421. </li><br/>
  6422. <li><b>get &lt;name&gt; parfile [&lt;parfile&gt;]</b><br/>
  6423. Get values of all channels / datapoints specified in <i>parfile</i>. The parameter
  6424. <i>parfile</i> can also be defined as an attribute. The file must contain one channel /
  6425. definition per line.
  6426. <br/><br/>
  6427. The syntax of Parfile entries is:
  6428. <br/><br/>
  6429. {[&lt;interface&gt;.]&lt;channel-address&gt; | &lt;channel-name&gt;}
  6430. [.&lt;datapoint-expr&gt;] [&lt;subst-rules&gt;]
  6431. <br/><br/>
  6432. Empty lines or lines starting with a # are ignored.
  6433. </li><br/>
  6434. <li><b>get &lt;name&gt; rpcstate</b><br/>
  6435. Check if RPC server process is running.
  6436. </li><br/>
  6437. <li><b>get &lt;name&gt; update [&lt;devexp&gt; [{State | <u>Value</u>}]]</b><br/>
  6438. Update all datapoints / readings of client devices with <u>FHEM device name</u>(!) matching
  6439. <i>devexp</i>. With option 'State' all CCU devices are queried directly. This can be
  6440. time consuming.
  6441. </li><br/>
  6442. <li><b>get &lt;name&gt; updateccu [&lt;devexp&gt; [{State | <u>Value</u>}]]</b><br/>
  6443. Update all datapoints / readings of client devices with <u>CCU device name</u>(!) matching
  6444. <i>devexp</i>. With option 'State' all CCU devices are queried directly. This can be
  6445. time consuming.
  6446. </li><br/>
  6447. <li><b>get &lt;name&gt; vars &lt;regexp&gt;</b><br/>
  6448. Get CCU system variables matching <i>regexp</i> and store them as readings.
  6449. </li>
  6450. </ul>
  6451. <br/>
  6452. <a name="HMCCUattr"></a>
  6453. <b>Attributes</b><br/>
  6454. <br/>
  6455. <ul>
  6456. <li><b>ccuaggregate &lt;rule&gt;[;...]</b><br/>
  6457. Define aggregation rules for client device readings. With an aggregation rule
  6458. it's easy to detect if some or all client device readings are set to a specific
  6459. value, i.e. detect all devices with low battery or detect all open windows.<br/>
  6460. Aggregation rules are automatically executed as a reaction on reading events of
  6461. HMCCU client devices. An aggregation rule consists of several parameters separated
  6462. by comma:<br/><br/>
  6463. <ul>
  6464. <li><b>name:&lt;rule-name&gt;</b><br/>
  6465. Name of aggregation rule</li>
  6466. <li><b>filter:{name|alias|group|room|type}=&lt;incl-expr&gt;[!&lt;excl-expr&gt;]</b><br/>
  6467. Filter criteria, i.e. "type=^HM-Sec-SC.*"</li>
  6468. <li><b>read:&lt;read-expr&gt;</b><br/>
  6469. Expression for reading names, i.e. "STATE"</li>
  6470. <li><b>if:{any|all|min|max|sum|avg|lt|gt|le|ge}=&lt;value&gt;</b><br/>
  6471. Condition, i.e. "any=open" or initial value, i.e. max=0</li>
  6472. <li><b>else:&lt;value&gt;</b><br/>
  6473. Complementary value, i.e. "closed"</li>
  6474. <li><b>prefix:{&lt;text&gt;|RULE}</b><br/>
  6475. Prefix for reading names with aggregation results</li>
  6476. <li><b>coll:{&lt;attribute&gt;|NAME}[!&lt;default-text&gt;]</b><br/>
  6477. Attribute of matching devices stored in aggregation results. Default text in case
  6478. of no matching devices found is optional.</li>
  6479. <li><b>html:&lt;template-file&gt;</b><br/>
  6480. Create HTML code with matching devices.</li>
  6481. </ul><br/>
  6482. Aggregation results will be stored in readings <i>prefix</i>count, <i>prefix</i>list,
  6483. <i>prefix</i>match, <i>prefix</i>state and <i>prefix</i>table.<br/><br/>
  6484. Format of a line in <i>template-file</i> is &lt;keyword&gt;:&lt;html-code&gt;. See
  6485. FHEM Wiki for an example. Valid keywords are:<br/><br/>
  6486. <ul>
  6487. <li><b>begin-html</b>: Start of html code.</li>
  6488. <li><b>begin-table</b>: Start of table (i.e. the table header)</li>
  6489. <li><b>row-odd</b>: HTML code for odd lines. A tag &lt;reading/&gt is replaced by a matching device.</li>
  6490. <li><b>row-even</b>: HTML code for event lines.</li>
  6491. <li><b>end-table</b>: End of table.</li>
  6492. <li><b>default</b>: HTML code for no matches.</li>
  6493. <li><b>end-html</b>: End of html code.</li>
  6494. </ul><br/>
  6495. Example: Find open windows<br/>
  6496. name=lock,filter:type=^HM-Sec-SC.*,read:STATE,if:any=open,else:closed,prefix:lock_,coll:NAME!All windows closed<br/><br/>
  6497. Example: Find devices with low batteries. Generate reading in HTML format.<br/>
  6498. name=battery,filter:name=.*,read:(LOWBAT|LOW_BAT),if:any=yes,else:no,prefix:batt_,coll:NAME!All batteries OK,html:/home/battery.cfg<br/>
  6499. </li><br/>
  6500. <li><b>ccudef-hmstatevals &lt;subst-rule[;...]&gt;</b><br/>
  6501. Set global rules for calculation of reading hmstate.
  6502. </li><br/>
  6503. <li><b>ccudef-readingfilter &lt;filter-rule[;...]&gt;</b><br/>
  6504. Set global reading/datapoint filter. This filter is added to the filter specified by
  6505. client device attribute 'ccureadingfilter'.
  6506. </li><br/>
  6507. <li><b>ccudef-readingformat {name | address | <u>datapoint</u> | namelc | addresslc |
  6508. datapointlc}</b><br/>
  6509. Set global reading format. This format is the default for all readings except readings
  6510. of virtual device groups.
  6511. </li><br/>
  6512. <li><b>ccudef-readingname &lt;old-readingname-expr&gt;:[+]&lt;new-readingname&gt;
  6513. [;...]</b><br/>
  6514. Set global rules for reading name substitution. These rules are added to the rules
  6515. specified by client device attribute 'ccureadingname'.
  6516. </li><br/>
  6517. <li><b>ccudef-substitute &lt;subst-rule&gt;[;...]</b><br/>
  6518. Set global substitution rules for datapoint value. These rules are added to the rules
  6519. specified by client device attribute 'substitute'.
  6520. </li><br/>
  6521. <li><b>ccudefaults &lt;filename&gt;</b><br/>
  6522. Load default attributes for HMCCUCHN and HMCCUDEV devices from specified file. Best
  6523. practice for creating a custom default attribute file is by exporting predefined default
  6524. attributes from HMCCU with command 'get exportdefaults'.
  6525. </li><br/>
  6526. <li><b>ccuflags {&lt;flags&gt;}</b><br/>
  6527. Control behaviour of several HMCCU functions. Parameter <i>flags</i> is a comma
  6528. seperated list of the following strings:<br/>
  6529. ackState - Acknowledge command execution by setting STATE to error or success.<br/>
  6530. dptnocheck - Do not check within set or get commands if datapoint is valid<br/>
  6531. intrpc - Use internal RPC server. This is the default.<br/>
  6532. extrpc - Same as procrpc (see below)<br/>
  6533. logEvents - Write events from CCU into FHEM logfile<br/>
  6534. nonBlocking - Use non blocking (asynchronous) CCU requests<br/>
  6535. noReadings - Do not create or update readings<br/>
  6536. procrpc - Use external RPC server provided by module HMCCPRPCPROC. During first RPC
  6537. server start HMCCU will create a HMCCURPCPROC device for each interface confiugured
  6538. in attribute 'rpcinterface'<br/>
  6539. Flags intrpc, extrpc and procrpc cannot be combined.
  6540. </li><br/>
  6541. <li><b>ccuget {State | <u>Value</u>}</b><br/>
  6542. Set read access method for CCU channel datapoints. Method 'State' is slower than
  6543. 'Value' because each request is sent to the device. With method 'Value' only CCU
  6544. is queried. Default is 'Value'. Method for write access to datapoints is always
  6545. 'State'.
  6546. </li><br/>
  6547. <li><b>ccuGetVars &lt;interval&gt;[&lt;pattern&gt;]</b><br/>
  6548. Read CCU system variables periodically and update readings. If pattern is specified
  6549. only variables matching this expression are stored as readings.
  6550. </li><br/>
  6551. <li><b>ccuReqTimeout &lt;Seconds&gt;</b><br/>
  6552. Set timeout for CCU request. Default is 4 seconds. This timeout affects several
  6553. set and get commands, i.e. "set datapoint" or "set var". If a command runs into
  6554. a timeout FHEM will block for <i>Seconds</i>.
  6555. </li>
  6556. <li><b>ccureadings {0 | <u>1</u>}</b><br/>
  6557. Deprecated. Readings are written by default. To deactivate readings set flag noReadings
  6558. in attribute ccuflags.
  6559. </li><br/>
  6560. <li><b>parfile &lt;filename&gt;</b><br/>
  6561. Define parameter file for command 'get parfile'.
  6562. </li><br/>
  6563. <li><b>rpcinterfaces &lt;interface&gt;[,...]</b><br/>
  6564. Specify list of CCU RPC interfaces. HMCCU will register a RPC server for each interface.
  6565. Interface BidCos-RF is default and always active. Valid interfaces are:<br/><br/>
  6566. <ul>
  6567. <li>BidCos-Wired (Port 2000)</li>
  6568. <li>BidCos-RF (Port 2001)</li>
  6569. <li>Homegear (Port 2003)</li>
  6570. <li>HmIP-RF (Port 2010)</li>
  6571. <li>HVL (Port 7000)</li>
  6572. <li>CUxD (Port 8701)</li>
  6573. <li>VirtualDevice (Port 9292)</li>
  6574. </ul>
  6575. </li><br/>
  6576. <li><b>rpcinterval &lt;Seconds&gt;</b><br/>
  6577. Specifiy how often RPC queue is read. Default is 5 seconds.
  6578. </li><br/>
  6579. <li><b>rpcport &lt;value[,...]&gt;</b><br/>
  6580. Deprecated, use 'rpcinterfaces' instead. Specify list of RPC ports on CCU. Default is
  6581. 2001. Valid RPC ports are:<br/><br/>
  6582. <ul>
  6583. <li>2000 = Wired components</li>
  6584. <li>2001 = BidCos-RF (wireless 868 MHz components with BidCos protocol)</li>
  6585. <li>2003 = Homegear (experimental)</li>
  6586. <li>2010 = HM-IP (wireless 868 MHz components with IPv6 protocol)</li>
  6587. <li>7000 = HVL (Homematic Virtual Layer devices)</li>
  6588. <li>8701 = CUxD (only supported with external RPC server HMCCURPC)</li>
  6589. <li>9292 = CCU group devices (especially heating groups)</li>
  6590. </ul>
  6591. </li><br/>
  6592. <li><b>rpcqueue &lt;queue-file&gt;</b><br/>
  6593. Specify name of RPC queue file. This parameter is only a prefix (including the
  6594. pathname) for the queue files with extension .idx and .dat. Default is
  6595. /tmp/ccuqueue. If FHEM is running on a SD card it's recommended that the queue
  6596. files are placed on a RAM disk.
  6597. </li><br/>
  6598. <li><b>rpcserver {on | <u>off</u>}</b><br/>
  6599. Specify if RPC server is automatically started on FHEM startup.
  6600. </li><br/>
  6601. <li><b>rpcserveraddr &lt;ip-or-name&gt;</b><br/>
  6602. Specify network interface by IP address or DNS name where RPC server should listen
  6603. on. By default HMCCU automatically detects the IP address. This attribute should be used
  6604. if the FHEM server has more than one network interface.
  6605. </li><br/>
  6606. <li><b>rpcserverport &lt;base-port&gt;</b><br/>
  6607. Specify base port for RPC server. The real listening port of an RPC server is
  6608. calculated by the formula: base-port + rpc-port + (10 * ccu-number). Default
  6609. value for <i>base-port</i> is 5400.<br/>
  6610. The value ccu-number is only relevant if more than one CCU is connected to FHEM.
  6611. Example: If <i>base-port</i> is 5000, protocol is BidCos (rpc-port 2001) and only
  6612. one CCU is connected the resulting RPC server port is 5000+2001+(10*0) = 7001.
  6613. </li><br/>
  6614. <li><b>substitute &lt;subst-rule&gt;:&lt;substext&gt;[,...]</b><br/>
  6615. Define substitions for datapoint values. Syntax of <i>subst-rule</i> is<br/><br/>
  6616. [[&lt;channelno.&gt;]&lt;datapoint&gt;[,...]!]&lt;{#n1-m1|regexp1}&gt;:&lt;text1&gt;[,...]
  6617. <br/>
  6618. Substitutions for parfile values must be specified in parfiles.
  6619. </li><br/>
  6620. <li><b>stripchar &lt;character&gt;</b><br/>
  6621. Strip the specified character from variable or device name in set commands. This
  6622. is useful if a variable should be set in CCU using the reading with trailing colon.
  6623. </li>
  6624. </ul>
  6625. </ul>
  6626. =end html
  6627. =cut