88_HMCCU.pm 226 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109
  1. ##############################################################################
  2. #
  3. # 88_HMCCU.pm
  4. #
  5. # $Id: 88_HMCCU.pm 16298 2018-03-01 08:04:35Z zap $
  6. #
  7. # Version 4.2.003
  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. #
  14. # (c) 2018 by zap (zap01 <at> t-online <dot> de)
  15. #
  16. ##############################################################################
  17. #
  18. # define <name> HMCCU <hostname_or_ip_of_ccu> [ccunumber] [waitforccu=<seconds>]
  19. #
  20. # set <name> ackmessages
  21. # set <name> cleardefaults
  22. # set <name> defaults
  23. # set <name> delete <name> [{ OT_VARDP | OT_DEVICE }]
  24. # set <name> execute <ccu_program>
  25. # set <name> importdefaults <filename>
  26. # set <name> hmscript {<scriptfile>|!<function>|'['<code>']'} [dump] [<parname>=<value> [...]]
  27. # set <name> rpcserver {on|off|restart}
  28. # set <name> var [<type>] <name> <value> [<parameter>=<value> [...]]
  29. #
  30. # get <name> aggregation {<rule>|all}
  31. # get <name> configdesc {<device>|<channel>}
  32. # get <name> defaults
  33. # get <name> deviceinfo <device>
  34. # get <name> devicelist [dump]
  35. # get <name> devicelist create <devexp> [t={chn|dev|all}] [s=<suffix>] [p=<prefix>] [f=<format>]
  36. # [defattr] [duplicates] [save] [<attr>=<val> [...]]}]
  37. # get <name> dump {devtypes|datapoints} [<filter>]
  38. # get <name> dutycycle
  39. # get <name> exportdefaults {filename}
  40. # get <name> firmware
  41. # get <name> parfile [<parfile>]
  42. # get <name> rpcevents
  43. # get <name> rpcstate
  44. # get <name> update [<fhemdevexp> [{ State | Value }]]
  45. # get <name> updateccu [<devexp> [{ State | Value }]]
  46. # get <name> vars <regexp>
  47. #
  48. # attr <name> ccuaggregate <rules>
  49. # attr <name> ccudef-hmstatevals <subst_rules>
  50. # attr <name> ccudef-readingfilter <filter_rule>
  51. # attr <name> ccudef-readingname <rules>
  52. # attr <name> ccudef-substitute <subst_rule>
  53. # attr <name> ccudefaults <filename>
  54. # attr <name> ccuflags { intrpc,extrpc,procrpc,dptnocheck,noagg,logEvents,noReadings,nonBlocking }
  55. # attr <name> ccuget { State | Value }
  56. # attr <name> ccuReqTimeout <seconds>
  57. # attr <name> parfile <parfile>
  58. # attr <name> rpcevtimeout <seconds>
  59. # attr <name> rpcinterfaces { BidCos-Wired, BidCos-RF, HmIP-RF, VirtualDevices, Homegear, HVL }
  60. # attr <name> rpcinterval <seconds>
  61. # attr <name> rpcport <ccu_rpc_port>
  62. # attr <name> rpcqueue <file>
  63. # attr <name> rpcserver { on | off }
  64. # attr <name> rpcserveraddr <ip-or-name>
  65. # attr <name> rpcserverport <base_port>
  66. # attr <name> rpctimeout <read>[,<write>]
  67. # attr <name> stripchar <character>
  68. # attr <name> stripnumber [<datapoint-expr!]{-<digits>|0|1|2}[;...]
  69. # attr <name> substitute <subst_rule>
  70. #
  71. # filter_rule := channel-regexp!datapoint-regexp[;...]
  72. # subst_rule := [[channel.]datapoint[,...]!]<regexp>:<subtext>[,...][;...]
  73. ##############################################################################
  74. # Verbose levels:
  75. #
  76. # 0 = Log start/stop and initialization messages
  77. # 1 = Log errors
  78. # 2 = Log counters and warnings
  79. # 3 = Log events and runtime information
  80. ##############################################################################
  81. package main;
  82. no if $] >= 5.017011, warnings => 'experimental::smartmatch';
  83. use strict;
  84. use warnings;
  85. # use Data::Dumper;
  86. # use Time::HiRes qw(usleep);
  87. use IO::File;
  88. use Fcntl 'SEEK_END', 'SEEK_SET', 'O_CREAT', 'O_RDWR';
  89. use RPC::XML::Client;
  90. use RPC::XML::Server;
  91. use SetExtensions;
  92. use SubProcess;
  93. use HMCCUConf;
  94. # Import configuration data
  95. my $HMCCU_CHN_DEFAULTS = \%HMCCUConf::HMCCU_CHN_DEFAULTS;
  96. my $HMCCU_DEV_DEFAULTS = \%HMCCUConf::HMCCU_DEV_DEFAULTS;
  97. my $HMCCU_SCRIPTS = \%HMCCUConf::HMCCU_SCRIPTS;
  98. # Custom configuration data
  99. my %HMCCU_CUST_CHN_DEFAULTS;
  100. my %HMCCU_CUST_DEV_DEFAULTS;
  101. # HMCCU version
  102. my $HMCCU_VERSION = '4.2.003';
  103. # Default RPC port (BidCos-RF)
  104. my $HMCCU_RPC_PORT_DEFAULT = 2001;
  105. my $HMCCU_RPC_INTERFACE_DEFAULT = 'BidCos-RF';
  106. # Constants and default values
  107. my $HMCCU_MAX_IOERRORS = 100;
  108. my $HMCCU_MAX_QUEUESIZE = 500;
  109. my $HMCCU_TIME_WAIT = 100000;
  110. my $HMCCU_TIME_TRIGGER = 10;
  111. my $HMCCU_TIMEOUT_CONNECTION = 10;
  112. my $HMCCU_TIMEOUT_WRITE = 0.001;
  113. my $HMCCU_TIMEOUT_ACCEPT = 1;
  114. my $HMCCU_TIMEOUT_EVENT = 600;
  115. my $HMCCU_STATISTICS = 500;
  116. my $HMCCU_TIMEOUT_REQUEST = 4;
  117. # RPC port name by port number
  118. my %HMCCU_RPC_NUMPORT = (
  119. 2000 => 'BidCos-Wired', 2001 => 'BidCos-RF', 2010 => 'HmIP-RF', 9292 => 'VirtualDevices',
  120. 2003 => 'Homegear', 8701 => 'CUxD', 7000 => 'HVL'
  121. );
  122. # RPC port number by port name
  123. my %HMCCU_RPC_PORT = (
  124. 'BidCos-Wired', 2000, 'BidCos-RF', 2001, 'HmIP-RF', 2010, 'VirtualDevices', 9292,
  125. 'Homegear', 2003, 'CUxD', 8701, 'HVL', 7000
  126. );
  127. # RPC flags
  128. my %HMCCU_RPC_FLAG = (
  129. 2000 => 'forceASCII', 2001 => 'forceASCII', 2003 => '_', 2010 => '_',
  130. 7000 => 'forceInit', 8701 => 'forceInit', 9292 => '_'
  131. );
  132. # Initial intervals for registration of RPC callbacks and reading RPC queue
  133. #
  134. # X = Start RPC server
  135. # X+HMCCU_INIT_INTERVAL1 = Register RPC callback
  136. # X+HMCCU_INIT_INTERVAL2 = Read RPC Queue
  137. #
  138. my $HMCCU_INIT_INTERVAL0 = 12;
  139. my $HMCCU_INIT_INTERVAL1 = 7;
  140. my $HMCCU_INIT_INTERVAL2 = 5;
  141. # Number of arguments in RPC events
  142. my %rpceventargs = (
  143. "EV", 3,
  144. "ND", 6,
  145. "DD", 1,
  146. "RD", 2,
  147. "RA", 1,
  148. "UD", 2,
  149. "IN", 3,
  150. "EX", 3,
  151. "SL", 2,
  152. "ST", 10
  153. );
  154. # Datapoint operations
  155. my $HMCCU_OPER_READ = 1;
  156. my $HMCCU_OPER_WRITE = 2;
  157. my $HMCCU_OPER_EVENT = 4;
  158. # Datapoint types
  159. my $HMCCU_TYPE_BINARY = 2;
  160. my $HMCCU_TYPE_FLOAT = 4;
  161. my $HMCCU_TYPE_INTEGER = 16;
  162. my $HMCCU_TYPE_STRING = 20;
  163. # Flags for CCU object specification
  164. my $HMCCU_FLAG_NAME = 1;
  165. my $HMCCU_FLAG_CHANNEL = 2;
  166. my $HMCCU_FLAG_DATAPOINT = 4;
  167. my $HMCCU_FLAG_ADDRESS = 8;
  168. my $HMCCU_FLAG_INTERFACE = 16;
  169. my $HMCCU_FLAG_FULLADDR = 32;
  170. # Valid flag combinations
  171. my $HMCCU_FLAGS_IACD = $HMCCU_FLAG_INTERFACE | $HMCCU_FLAG_ADDRESS |
  172. $HMCCU_FLAG_CHANNEL | $HMCCU_FLAG_DATAPOINT;
  173. my $HMCCU_FLAGS_IAC = $HMCCU_FLAG_INTERFACE | $HMCCU_FLAG_ADDRESS | $HMCCU_FLAG_CHANNEL;
  174. my $HMCCU_FLAGS_ACD = $HMCCU_FLAG_ADDRESS | $HMCCU_FLAG_CHANNEL | $HMCCU_FLAG_DATAPOINT;
  175. my $HMCCU_FLAGS_AC = $HMCCU_FLAG_ADDRESS | $HMCCU_FLAG_CHANNEL;
  176. my $HMCCU_FLAGS_ND = $HMCCU_FLAG_NAME | $HMCCU_FLAG_DATAPOINT;
  177. my $HMCCU_FLAGS_NC = $HMCCU_FLAG_NAME | $HMCCU_FLAG_CHANNEL;
  178. my $HMCCU_FLAGS_NCD = $HMCCU_FLAG_NAME | $HMCCU_FLAG_CHANNEL | $HMCCU_FLAG_DATAPOINT;
  179. # Default values
  180. my $HMCCU_DEF_HMSTATE = '^0\.UNREACH!(1|true):unreachable;^[0-9]\.LOW_?BAT!(1|true):warn_battery';
  181. # Placeholder for external addresses (i.e. HVL)
  182. my $HMCCU_EXT_ADDR = 'ZZZ0000000';
  183. # Binary RPC data types
  184. my $BINRPC_INTEGER = 1;
  185. my $BINRPC_BOOL = 2;
  186. my $BINRPC_STRING = 3;
  187. my $BINRPC_DOUBLE = 4;
  188. my $BINRPC_BASE64 = 17;
  189. my $BINRPC_ARRAY = 256;
  190. my $BINRPC_STRUCT = 257;
  191. # Declare functions
  192. sub HMCCU_Initialize ($);
  193. sub HMCCU_Define ($$);
  194. sub HMCCU_Undef ($$);
  195. sub HMCCU_Shutdown ($);
  196. sub HMCCU_Set ($@);
  197. sub HMCCU_Get ($@);
  198. sub HMCCU_Attr ($@);
  199. sub HMCCU_AggregationRules ($$);
  200. sub HMCCU_ExportDefaults ($);
  201. sub HMCCU_ImportDefaults ($);
  202. sub HMCCU_FindDefaults ($$);
  203. sub HMCCU_SetDefaults ($);
  204. sub HMCCU_GetDefaults ($$);
  205. sub HMCCU_Notify ($$);
  206. sub HMCCU_AggregateReadings ($$);
  207. sub HMCCU_ParseObject ($$$);
  208. sub HMCCU_FilterReading ($$$);
  209. sub HMCCU_GetReadingName ($$$$$$$);
  210. sub HMCCU_FormatReadingValue ($$$);
  211. sub HMCCU_Trace ($$$$);
  212. sub HMCCU_Log ($$$$);
  213. sub HMCCU_SetError ($@);
  214. sub HMCCU_SetState ($@);
  215. sub HMCCU_SetRPCState ($@);
  216. sub HMCCU_Substitute ($$$$$);
  217. sub HMCCU_SubstRule ($$$);
  218. sub HMCCU_SubstVariables ($$$);
  219. sub HMCCU_UpdateClients ($$$$$);
  220. sub HMCCU_UpdateDeviceTable ($$);
  221. sub HMCCU_UpdateSingleDatapoint ($$$$);
  222. sub HMCCU_UpdateSingleDevice ($$$);
  223. sub HMCCU_UpdateMultipleDevices ($$);
  224. sub HMCCU_UpdatePeers ($$$$);
  225. sub HMCCU_GetRPCInterfaceList ($);
  226. sub HMCCU_GetRPCPortList ($);
  227. sub HMCCU_GetRPCCallbackURL ($$$$$);
  228. sub HMCCU_GetRPCServerInfo ($$$);
  229. sub HMCCU_IsRPCType ($$$);
  230. sub HMCCU_RPCRegisterCallback ($);
  231. sub HMCCU_RPCDeRegisterCallback ($);
  232. sub HMCCU_ResetCounters ($);
  233. sub HMCCU_StartExtRPCServer ($);
  234. sub HMCCU_StopExtRPCServer ($);
  235. sub HMCCU_StartIntRPCServer ($);
  236. sub HMCCU_StopRPCServer ($);
  237. sub HMCCU_IsRPCStateBlocking ($);
  238. sub HMCCU_IsRPCServerRunning ($$$);
  239. sub HMCCU_GetDeviceInfo ($$$);
  240. sub HMCCU_FormatDeviceInfo ($);
  241. sub HMCCU_GetFirmwareVersions ($);
  242. sub HMCCU_GetDeviceList ($);
  243. sub HMCCU_GetDatapointList ($$$);
  244. sub HMCCU_FindDatapoint ($$$$$);
  245. sub HMCCU_GetAddress ($$$$);
  246. sub HMCCU_IsDevAddr ($$);
  247. sub HMCCU_IsChnAddr ($$);
  248. sub HMCCU_SplitChnAddr ($);
  249. sub HMCCU_GetCCUObjectAttribute ($$$);
  250. sub HMCCU_FindClientDevices ($$$$);
  251. sub HMCCU_GetRPCDevice ($$$);
  252. sub HMCCU_FindIODevice ($);
  253. sub HMCCU_GetHash ($@);
  254. sub HMCCU_GetAttribute ($$$$);
  255. sub HMCCU_GetDatapointCount ($$$);
  256. sub HMCCU_GetSpecialDatapoints ($$$$$);
  257. sub HMCCU_GetAttrReadingFormat ($$);
  258. sub HMCCU_GetAttrSubstitute ($$);
  259. sub HMCCU_IsValidDeviceOrChannel ($$);
  260. sub HMCCU_IsValidDevice ($$);
  261. sub HMCCU_IsValidChannel ($$);
  262. sub HMCCU_GetCCUDeviceParam ($$);
  263. sub HMCCU_GetDatapointAttr ($$$$$);
  264. sub HMCCU_GetValidDatapoints ($$$$$);
  265. sub HMCCU_GetSwitchDatapoint ($$$);
  266. sub HMCCU_IsValidDatapoint ($$$$$);
  267. sub HMCCU_GetMatchingDevices ($$$$);
  268. sub HMCCU_GetDeviceName ($$$);
  269. sub HMCCU_GetChannelName ($$$);
  270. sub HMCCU_GetDeviceType ($$$);
  271. sub HMCCU_GetDeviceChannels ($$$);
  272. sub HMCCU_GetDeviceInterface ($$$);
  273. sub HMCCU_ResetRPCQueue ($$);
  274. sub HMCCU_ReadRPCQueue ($);
  275. sub HMCCU_ProcessEvent ($$);
  276. sub HMCCU_HMScriptExt ($$$);
  277. sub HMCCU_BulkUpdate ($$$$);
  278. sub HMCCU_GetDatapoint ($@);
  279. sub HMCCU_SetDatapoint ($$$);
  280. sub HMCCU_ScaleValue ($$$$);
  281. sub HMCCU_GetVariables ($$);
  282. sub HMCCU_SetVariable ($$$$$);
  283. sub HMCCU_GetUpdate ($$$);
  284. sub HMCCU_GetChannel ($$);
  285. sub HMCCU_RPCGetConfig ($$$$);
  286. sub HMCCU_RPCSetConfig ($$$);
  287. # File queue functions
  288. sub HMCCU_QueueOpen ($$);
  289. sub HMCCU_QueueClose ($);
  290. sub HMCCU_QueueReset ($);
  291. sub HMCCU_QueueEnq ($$);
  292. sub HMCCU_QueueDeq ($);
  293. # Helper functions
  294. sub HMCCU_GetHMState ($$$);
  295. sub HMCCU_GetTimeSpec ($);
  296. sub HMCCU_CalculateReading ($$$);
  297. sub HMCCU_EncodeEPDisplay ($);
  298. sub HMCCU_RefToString ($);
  299. sub HMCCU_ExprMatch ($$$);
  300. sub HMCCU_ExprNotMatch ($$$);
  301. sub HMCCU_GetDutyCycle ($);
  302. sub HMCCU_TCPPing ($$$);
  303. sub HMCCU_TCPConnect ($$);
  304. sub HMCCU_CorrectName ($);
  305. # Subprocess functions
  306. sub HMCCU_CCURPC_Write ($$);
  307. sub HMCCU_CCURPC_OnRun ($);
  308. sub HMCCU_CCURPC_OnExit ();
  309. sub HMCCU_CCURPC_NewDevicesCB ($$$);
  310. sub HMCCU_CCURPC_DeleteDevicesCB ($$$);
  311. sub HMCCU_CCURPC_UpdateDeviceCB ($$$$);
  312. sub HMCCU_CCURPC_ReplaceDeviceCB ($$$$);
  313. sub HMCCU_CCURPC_ReaddDevicesCB ($$$);
  314. sub HMCCU_CCURPC_EventCB ($$$$$);
  315. sub HMCCU_CCURPC_ListDevicesCB ($$);
  316. ##################################################
  317. # Initialize module
  318. ##################################################
  319. sub HMCCU_Initialize ($)
  320. {
  321. my ($hash) = @_;
  322. $hash->{DefFn} = "HMCCU_Define";
  323. $hash->{UndefFn} = "HMCCU_Undef";
  324. $hash->{SetFn} = "HMCCU_Set";
  325. $hash->{GetFn} = "HMCCU_Get";
  326. $hash->{ReadFn} = "HMCCU_Read";
  327. $hash->{AttrFn} = "HMCCU_Attr";
  328. $hash->{NotifyFn} = "HMCCU_Notify";
  329. $hash->{ShutdownFn} = "HMCCU_Shutdown";
  330. $hash->{parseParams} = 1;
  331. $hash->{AttrList} = "stripchar stripnumber ccuaggregate:textField-long".
  332. " ccudefaults rpcinterfaces:multiple-strict,".join(',',sort keys %HMCCU_RPC_PORT).
  333. " ccudef-hmstatevals:textField-long ccudef-substitute:textField-long".
  334. " ccudef-readingname:textField-long ccudef-readingfilter:textField-long".
  335. " ccudef-readingformat:name,namelc,address,addresslc,datapoint,datapointlc".
  336. " ccuflags:multiple-strict,extrpc,intrpc,procrpc,dptnocheck,noagg,nohmstate,logEvents,noReadings,nonBlocking".
  337. " ccuReqTimeout rpcdevice rpcinterval:2,3,5,7,10 rpcqueue".
  338. " rpcport:multiple-strict,".join(',',sort keys %HMCCU_RPC_NUMPORT).
  339. " rpcserver:on,off rpcserveraddr rpcserverport rpctimeout rpcevtimeout parfile substitute".
  340. " ccuget:Value,State ".
  341. $readingFnAttributes;
  342. }
  343. ######################################################################
  344. # Define device
  345. ######################################################################
  346. sub HMCCU_Define ($$)
  347. {
  348. my ($hash, $a, $h) = @_;
  349. my $name = $hash->{NAME};
  350. return "Specify CCU hostname or IP address as a parameter" if(scalar (@$a) < 3);
  351. $hash->{host} = $$a[2];
  352. $hash->{Clients} = ':HMCCUDEV:HMCCUCHN:HMCCURPC:HMCCURPCPROC:';
  353. # Check if TCL-Rega process is running on CCU
  354. my $timeout = exists ($h->{waitforccu}) ? $h->{waitforccu} : 0;
  355. if (HMCCU_TCPPing ($hash->{host}, 8181, $timeout)) {
  356. $hash->{ccustate} = 'active';
  357. }
  358. else {
  359. $hash->{ccustate} = 'unreachable';
  360. Log3 $name, 1, "HMCCU: CCU2 port 8181 is not reachable";
  361. }
  362. # Get CCU IP address
  363. $hash->{ccuip} = 'N/A';
  364. my $ccuname = inet_aton ($hash->{host});
  365. if (defined ($ccuname)) {
  366. my $ccuip = inet_ntoa ($ccuname);
  367. $hash->{ccuip} = $ccuip if (defined ($ccuip));
  368. }
  369. # Get CCU number (if more than one)
  370. if (scalar (@$a) >= 4) {
  371. return "CCU number must be in range 1-9" if ($$a[3] < 1 || $$a[3] > 9);
  372. $hash->{CCUNum} = $$a[3];
  373. }
  374. else {
  375. # Count CCU devices
  376. my $ccucount = 0;
  377. foreach my $d (keys %defs) {
  378. my $ch = $defs{$d};
  379. next if (!exists ($ch->{TYPE}));
  380. $ccucount++ if ($ch->{TYPE} eq 'HMCCU' && $ch != $hash);
  381. }
  382. $hash->{CCUNum} = $ccucount+1;
  383. }
  384. $hash->{version} = $HMCCU_VERSION;
  385. $hash->{ccutype} = 'CCU2';
  386. $hash->{RPCState} = "inactive";
  387. Log3 $name, 1, "HMCCU: Device $name. Initialized version $HMCCU_VERSION";
  388. my ($devcnt, $chncnt, $ifcount) = HMCCU_GetDeviceList ($hash);
  389. if ($devcnt > 0) {
  390. Log3 $name, 1, "HMCCU: Read $devcnt devices with $chncnt channels from CCU ".$hash->{host};
  391. }
  392. else {
  393. Log3 $name, 1, "HMCCU: No devices read from CCU ".$hash->{host};
  394. }
  395. if ($ifcount > 0) {
  396. Log3 $name, 1, "HMCCU: Read $ifcount interfaces from CCU ".$hash->{host};
  397. }
  398. else {
  399. Log3 $name, 1, "HMCCU: No RPC interfaces found on CCU ".$hash->{host};
  400. }
  401. $hash->{hmccu}{evtime} = 0;
  402. $hash->{hmccu}{evtimeout} = 0;
  403. $hash->{hmccu}{updatetime} = 0;
  404. $hash->{hmccu}{rpccount} = 0;
  405. $hash->{hmccu}{rpcports} = $HMCCU_RPC_PORT_DEFAULT;
  406. readingsBeginUpdate ($hash);
  407. readingsBulkUpdate ($hash, "state", "Initialized");
  408. readingsBulkUpdate ($hash, "rpcstate", "inactive");
  409. readingsEndUpdate ($hash, 1);
  410. $attr{$name}{stateFormat} = "rpcstate/state";
  411. return undef;
  412. }
  413. ######################################################################
  414. # Set or delete attribute
  415. ######################################################################
  416. sub HMCCU_Attr ($@)
  417. {
  418. my ($cmd, $name, $attrname, $attrval) = @_;
  419. my $hash = $defs{$name};
  420. my $rc = 0;
  421. if ($cmd eq 'set') {
  422. if ($attrname eq 'ccudefaults') {
  423. $rc = HMCCU_ImportDefaults ($attrval);
  424. return HMCCU_SetError ($hash, -16) if ($rc == 0);
  425. if ($rc < 0) {
  426. $rc = -$rc;
  427. return HMCCU_SetError ($hash,
  428. "Syntax error in default attribute file $attrval line $rc");
  429. }
  430. }
  431. elsif ($attrname eq 'ccuaggregate') {
  432. $rc = HMCCU_AggregationRules ($hash, $attrval);
  433. return HMCCU_SetError ($hash, "Syntax error in attribute ccuaggregate") if ($rc == 0);
  434. }
  435. elsif ($attrname eq 'ccuackstate') {
  436. return "HMCCU: Attribute ccuackstate is depricated. Use ccuflags with 'ackState' instead";
  437. }
  438. elsif ($attrname eq 'ccureadings') {
  439. return "HMCCU: Attribute ccureadings is depricated. Use ccuflags with 'noReadings' instead";
  440. }
  441. elsif ($attrname eq 'ccuflags') {
  442. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  443. my @flags = ($attrval =~ /(intrpc|extrpc|procrpc)/g);
  444. return "Flags extrpc, procrpc and intrpc cannot be combined" if (scalar (@flags) > 1);
  445. if ($attrval =~ /(extrpc|intrpc|procrpc)/) {
  446. my $rpcmode = $1;
  447. if ($ccuflags !~ /$rpcmode/) {
  448. return "Stop RPC server before switching RPC server"
  449. if (HMCCU_IsRPCServerRunning ($hash, undef, undef));
  450. }
  451. }
  452. }
  453. elsif ($attrname eq 'rpcdevice') {
  454. return "HMCCU: Can't find HMCCURPC device $attrval"
  455. if (!exists ($defs{$attrval}) || $defs{$attrval}->{TYPE} ne 'HMCCURPC');
  456. if (exists ($defs{$attrval}->{IODev})) {
  457. return "HMCCU: Device $attrval is not assigned to $name"
  458. if ($defs{$attrval}->{IODev} != $hash);
  459. }
  460. else {
  461. $defs{$attrval}->{IODev} = $hash;
  462. }
  463. $hash->{RPCDEV} = $attrval;
  464. }
  465. elsif ($attrname eq 'rpcinterfaces') {
  466. my @ports = split (',', $attrval);
  467. my @plist = ();
  468. foreach my $p (@ports) {
  469. my $pn = HMCCU_GetRPCServerInfo ($hash, $p, 'port');
  470. return "Illegal RPC interface $p" if (!defined ($pn));
  471. push (@plist, $pn);
  472. }
  473. return "No RPC interface specified" if (scalar (@plist) == 0);
  474. $hash->{hmccu}{rpcports} = join (',', @plist);
  475. $attr{$name}{"rpcport"} = $hash->{hmccu}{rpcports};
  476. }
  477. elsif ($attrname eq 'rpcport') {
  478. my @ports = split (',', $attrval);
  479. my @ilist = ();
  480. foreach my $p (@ports) {
  481. my $pn = HMCCU_GetRPCServerInfo ($hash, $p, 'name');
  482. return "HMCCU: Illegal RPC port $p" if (!defined ($pn));
  483. push (@ilist, $pn);
  484. }
  485. return "No RPC port specified" if (scalar (@ilist) == 0);
  486. $hash->{hmccu}{rpcports} = $attrval;
  487. $attr{$name}{"rpcinterfaces"} = join (',', @ilist);
  488. }
  489. }
  490. elsif ($cmd eq 'del') {
  491. if ($attrname eq 'ccuaggregate') {
  492. HMCCU_AggregationRules ($hash, '');
  493. }
  494. elsif ($attrname eq 'rpcdevice') {
  495. delete $hash->{RPCDEV} if (exists ($hash->{RPCDEV}));
  496. }
  497. elsif ($attrname eq 'rpcport' || $attrname eq 'rpcinterfaces') {
  498. $hash->{hmccu}{rpcports} = $HMCCU_RPC_PORT_DEFAULT;
  499. }
  500. }
  501. return undef;
  502. }
  503. ######################################################################
  504. # Parse aggregation rules for readings.
  505. # Syntax of aggregation rule is:
  506. # FilterSpec[;...]
  507. # FilterSpec := {Name|Filt|Read|Cond|Else|Pref|Coll|Html}[,...]
  508. # Name := name:Name
  509. # Filt := filter:{name|type|group|room|alias}=Regexp[!Regexp]
  510. # Read := read:Regexp
  511. # Cond := if:{any|all|min|max|sum|avg|gt|lt|ge|le}=Value
  512. # Else := else:Value
  513. # Pref := prefix:{RULE|Prefix}
  514. # Coll := coll:{NAME|Attribute}
  515. # Html := html:Template
  516. ######################################################################
  517. sub HMCCU_AggregationRules ($$)
  518. {
  519. my ($hash, $rulestr) = @_;
  520. my $name = $hash->{NAME};
  521. # Delete existing aggregation rules
  522. if (exists ($hash->{hmccu}{agg})) {
  523. delete $hash->{hmccu}{agg};
  524. }
  525. return if ($rulestr eq '');
  526. my @pars = ('name', 'filter', 'if', 'else');
  527. # Extract aggregation rules
  528. my $cnt = 0;
  529. my @rules = split (/[;\n]+/, $rulestr);
  530. foreach my $r (@rules) {
  531. $cnt++;
  532. # Set default rule parameters. Can be modified later
  533. my %opt = ( 'read' => 'state', 'prefix' => 'RULE', 'coll' => 'NAME' );
  534. # Parse aggregation rule
  535. my @specs = split (',', $r);
  536. foreach my $spec (@specs) {
  537. if ($spec =~ /^(name|filter|read|if|else|prefix|coll|html):(.+)$/) {
  538. $opt{$1} = $2;
  539. }
  540. }
  541. # Check if mandatory parameters are specified
  542. foreach my $p (@pars) {
  543. return HMCCU_Log ($hash, 1, "Parameter $p is missing in aggregation rule $cnt.", 0)
  544. if (!exists ($opt{$p}));
  545. }
  546. my $fname = $opt{name};
  547. my ($fincl, $fexcl) = split ('!', $opt{filter});
  548. my ($ftype, $fexpr) = split ('=', $fincl);
  549. return 0 if (!defined ($fexpr));
  550. my ($fcond, $fval) = split ('=', $opt{if});
  551. return 0 if (!defined ($fval));
  552. my ($fcoll, $fdflt) = split ('!', $opt{coll});
  553. $fdflt = 'no match' if (!defined ($fdflt));
  554. my $fhtml = exists ($opt{'html'}) ? $opt{'html'} : '';
  555. # Read HTML template (optional)
  556. if ($fhtml ne '') {
  557. my %tdef;
  558. my @html;
  559. # Read template file
  560. if (open (TEMPLATE, "<$fhtml")) {
  561. @html = <TEMPLATE>;
  562. close (TEMPLATE);
  563. }
  564. else {
  565. return HMCCU_Log ($hash, 1, "Can't open file $fhtml.", 0);
  566. }
  567. # Parse template
  568. foreach my $line (@html) {
  569. chomp $line;
  570. my ($key, $h) = split /:/, $line, 2;
  571. next if (!defined ($h) || $key =~ /^#/);
  572. $tdef{$key} = $h;
  573. }
  574. # Some syntax checks
  575. return HMCCU_Log ($hash, 1, "Missing definition row-odd in template file.", 0)
  576. if (!exists ($tdef{'row-odd'}));
  577. # Set default values
  578. $tdef{'begin-html'} = '' if (!exists ($tdef{'begin-html'}));
  579. $tdef{'end-html'} = '' if (!exists ($tdef{'end-html'}));
  580. $tdef{'begin-table'} = "<table>" if (!exists ($tdef{'begin-table'}));
  581. $tdef{'end-table'} = "</table>" if (!exists ($tdef{'end-table'}));
  582. $tdef{'default'} = 'no data' if (!exists ($tdef{'default'}));;
  583. $tdef{'row-even'} = $tdef{'row-odd'} if (!exists ($tdef{'row-even'}));
  584. foreach my $t (keys %tdef) {
  585. $hash->{hmccu}{agg}{$fname}{fhtml}{$t} = $tdef{$t};
  586. }
  587. }
  588. $hash->{hmccu}{agg}{$fname}{ftype} = $ftype;
  589. $hash->{hmccu}{agg}{$fname}{fexpr} = $fexpr;
  590. $hash->{hmccu}{agg}{$fname}{fexcl} = (defined ($fexcl) ? $fexcl : '');
  591. $hash->{hmccu}{agg}{$fname}{fread} = $opt{'read'};
  592. $hash->{hmccu}{agg}{$fname}{fcond} = $fcond;
  593. $hash->{hmccu}{agg}{$fname}{ftrue} = $fval;
  594. $hash->{hmccu}{agg}{$fname}{felse} = $opt{'else'};
  595. $hash->{hmccu}{agg}{$fname}{fpref} = $opt{prefix} eq 'RULE' ? $fname : $opt{prefix};
  596. $hash->{hmccu}{agg}{$fname}{fcoll} = $fcoll;
  597. $hash->{hmccu}{agg}{$fname}{fdflt} = $fdflt;
  598. }
  599. return 1;
  600. }
  601. ######################################################################
  602. # Export default attributes.
  603. ######################################################################
  604. sub HMCCU_ExportDefaults ($)
  605. {
  606. my ($filename) = @_;
  607. return 0 if (!open (DEFFILE, ">$filename"));
  608. print DEFFILE "# HMCCU default attributes for channels\n";
  609. foreach my $t (keys %{$HMCCU_CHN_DEFAULTS}) {
  610. print DEFFILE "\nchannel:$t\n";
  611. foreach my $a (sort keys %{$HMCCU_CHN_DEFAULTS->{$t}}) {
  612. print DEFFILE "$a=".$HMCCU_CHN_DEFAULTS->{$t}{$a}."\n";
  613. }
  614. }
  615. print DEFFILE "\n# HMCCU default attributes for devices\n";
  616. foreach my $t (keys %{$HMCCU_DEV_DEFAULTS}) {
  617. print DEFFILE "\ndevice:$t\n";
  618. foreach my $a (sort keys %{$HMCCU_DEV_DEFAULTS->{$t}}) {
  619. print DEFFILE "$a=".$HMCCU_DEV_DEFAULTS->{$t}{$a}."\n";
  620. }
  621. }
  622. close (DEFFILE);
  623. return 1;
  624. }
  625. ######################################################################
  626. # Import customer default attributes
  627. # Returns 1 on success. Returns negative line number on syntax errors.
  628. # Returns 0 on file open error.
  629. ######################################################################
  630. sub HMCCU_ImportDefaults ($)
  631. {
  632. my ($filename) = @_;
  633. my $modtype = '';
  634. my $ccutype = '';
  635. my $line = 0;
  636. return 0 if (!open (DEFFILE, "<$filename"));
  637. my @defaults = <DEFFILE>;
  638. close (DEFFILE);
  639. chomp (@defaults);
  640. %HMCCU_CUST_CHN_DEFAULTS = ();
  641. %HMCCU_CUST_DEV_DEFAULTS = ();
  642. foreach my $d (@defaults) {
  643. $line++;
  644. next if ($d eq '' || $d =~ /^#/);
  645. if ($d =~ /^(channel|device):/) {
  646. my @t = split (':', $d, 2);
  647. if (scalar (@t) != 2) {
  648. close (DEFFILE);
  649. return -$line;
  650. }
  651. $modtype = $t[0];
  652. $ccutype = $t[1];
  653. next;
  654. }
  655. if ($ccutype eq '' || $modtype eq '') {
  656. close (DEFFILE);
  657. return -$line;
  658. }
  659. my @av = split ('=', $d, 2);
  660. if (scalar (@av) != 2) {
  661. close (DEFFILE);
  662. return -$line;
  663. }
  664. if ($modtype eq 'channel') {
  665. $HMCCU_CUST_CHN_DEFAULTS{$ccutype}{$av[0]} = $av[1];
  666. }
  667. else {
  668. $HMCCU_CUST_DEV_DEFAULTS{$ccutype}{$av[0]} = $av[1];
  669. }
  670. }
  671. return 1;
  672. }
  673. ######################################################################
  674. # Find default attributes
  675. # Return template reference.
  676. ######################################################################
  677. sub HMCCU_FindDefaults ($$)
  678. {
  679. my ($hash, $common) = @_;
  680. my $type = $hash->{TYPE};
  681. my $ccutype = $hash->{ccutype};
  682. if ($type eq 'HMCCUCHN') {
  683. my ($adr, $chn) = split (':', $hash->{ccuaddr});
  684. foreach my $deftype (keys %HMCCU_CUST_CHN_DEFAULTS) {
  685. my @chnlst = split (',', $HMCCU_CUST_CHN_DEFAULTS{$deftype}{_channels});
  686. return \%{$HMCCU_CUST_CHN_DEFAULTS{$deftype}}
  687. if ($ccutype =~ /^($deftype)$/i && grep { $_ eq $chn} @chnlst);
  688. }
  689. foreach my $deftype (keys %{$HMCCU_CHN_DEFAULTS}) {
  690. my @chnlst = split (',', $HMCCU_CHN_DEFAULTS->{$deftype}{_channels});
  691. return \%{$HMCCU_CHN_DEFAULTS->{$deftype}}
  692. if ($ccutype =~ /^($deftype)$/i && grep { $_ eq $chn} @chnlst);
  693. }
  694. }
  695. elsif ($type eq 'HMCCUDEV' || $type eq 'HMCCU') {
  696. foreach my $deftype (keys %HMCCU_CUST_DEV_DEFAULTS) {
  697. return \%{$HMCCU_CUST_DEV_DEFAULTS{$deftype}} if ($ccutype =~ /^($deftype)$/i);
  698. }
  699. foreach my $deftype (keys %{$HMCCU_DEV_DEFAULTS}) {
  700. return \%{$HMCCU_DEV_DEFAULTS->{$deftype}} if ($ccutype =~ /^($deftype)$/i);
  701. }
  702. }
  703. return undef;
  704. }
  705. ######################################################################
  706. # Set default attributes from template
  707. ######################################################################
  708. sub HMCCU_SetDefaultsTemplate ($$)
  709. {
  710. my ($hash, $template) = @_;
  711. my $name = $hash->{NAME};
  712. foreach my $a (keys %{$template}) {
  713. next if ($a =~ /^_/);
  714. my $v = $template->{$a};
  715. CommandAttr (undef, "$name $a $v");
  716. }
  717. }
  718. ######################################################################
  719. # Set default attributes
  720. ######################################################################
  721. sub HMCCU_SetDefaults ($)
  722. {
  723. my ($hash) = @_;
  724. my $name = $hash->{NAME};
  725. # Set type specific attributes
  726. my $template = HMCCU_FindDefaults ($hash, 0);
  727. return 0 if (!defined ($template));
  728. HMCCU_SetDefaultsTemplate ($hash, $template);
  729. return 1;
  730. }
  731. ######################################################################
  732. # List default attributes for device type (mode = 0) or all
  733. # device types (mode = 1) with default attributes available.
  734. ######################################################################
  735. sub HMCCU_GetDefaults ($$)
  736. {
  737. my ($hash, $mode) = @_;
  738. my $name = $hash->{NAME};
  739. my $type = $hash->{TYPE};
  740. my $ccutype = $hash->{ccutype};
  741. my $result = '';
  742. my $deffile = '';
  743. if ($mode == 0) {
  744. my $template = HMCCU_FindDefaults ($hash, 0);
  745. return ($result eq '' ? "No default attributes defined" : $result) if (!defined ($template));
  746. foreach my $a (keys %{$template}) {
  747. next if ($a =~ /^_/);
  748. my $v = $template->{$a};
  749. $result .= $a." = ".$v."\n";
  750. }
  751. }
  752. else {
  753. $result = "HMCCU Channels:\n------------------------------\n";
  754. foreach my $deftype (sort keys %{$HMCCU_CHN_DEFAULTS}) {
  755. my $tlist = $deftype;
  756. $tlist =~ s/\|/,/g;
  757. $result .= $HMCCU_CHN_DEFAULTS->{$deftype}{_description}." ($tlist), channels ".
  758. $HMCCU_CHN_DEFAULTS->{$deftype}{_channels}."\n";
  759. }
  760. $result .= "\nHMCCU Devices:\n------------------------------\n";
  761. foreach my $deftype (sort keys %{$HMCCU_DEV_DEFAULTS}) {
  762. my $tlist = $deftype;
  763. $tlist =~ s/\|/,/g;
  764. $result .= $HMCCU_DEV_DEFAULTS->{$deftype}{_description}." ($tlist)\n";
  765. }
  766. $result .= "\nCustom Channels:\n-----------------------------\n";
  767. foreach my $deftype (sort keys %HMCCU_CUST_CHN_DEFAULTS) {
  768. my $tlist = $deftype;
  769. $tlist =~ s/\|/,/g;
  770. $result .= $HMCCU_CUST_CHN_DEFAULTS{$deftype}{_description}." ($tlist), channels ".
  771. $HMCCU_CUST_CHN_DEFAULTS{$deftype}{_channels}."\n";
  772. }
  773. $result .= "\nCustom Devices:\n-----------------------------\n";
  774. foreach my $deftype (sort keys %HMCCU_CUST_DEV_DEFAULTS) {
  775. my $tlist = $deftype;
  776. $tlist =~ s/\|/,/g;
  777. $result .= $HMCCU_CUST_DEV_DEFAULTS{$deftype}{_description}." ($tlist)\n";
  778. }
  779. }
  780. return $result;
  781. }
  782. ######################################################################
  783. # Handle FHEM events
  784. ######################################################################
  785. sub HMCCU_Notify ($$)
  786. {
  787. my ($hash, $devhash) = @_;
  788. my $name = $hash->{NAME};
  789. my $devname = $devhash->{NAME};
  790. my $devtype = $devhash->{TYPE};
  791. my $disable = AttrVal ($name, 'disable', 0);
  792. my $rpcserver = AttrVal ($name, 'rpcserver', 'off');
  793. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  794. return if ($disable);
  795. my $events = deviceEvents ($devhash, 1);
  796. return if (! $events);
  797. # Process events
  798. foreach my $event (@{$events}) {
  799. if ($devname eq 'global') {
  800. if ($event eq 'INITIALIZED') {
  801. return if ($rpcserver eq 'off');
  802. my $delay = $HMCCU_INIT_INTERVAL0;
  803. Log3 $name, 0, "HMCCU: Start of RPC server after FHEM initialization in $delay seconds";
  804. if ($ccuflags =~ /(extrpc|procrpc)/) {
  805. InternalTimer (gettimeofday()+$delay, "HMCCU_StartExtRPCServer", $hash, 0);
  806. }
  807. else {
  808. InternalTimer (gettimeofday()+$delay, "HMCCU_StartIntRPCServer", $hash, 0);
  809. }
  810. }
  811. }
  812. else {
  813. return if ($devtype ne 'HMCCUDEV' && $devtype ne 'HMCCUCHN');
  814. my ($r, $v) = split (": ", $event);
  815. return if (!defined ($v));
  816. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  817. return if ($ccuflags =~ /noagg/);
  818. foreach my $rule (keys %{$hash->{hmccu}{agg}}) {
  819. my $ftype = $hash->{hmccu}{agg}{$rule}{ftype};
  820. my $fexpr = $hash->{hmccu}{agg}{$rule}{fexpr};
  821. my $fread = $hash->{hmccu}{agg}{$rule}{fread};
  822. next if ($r !~ $fread);
  823. next if ($ftype eq 'name' && $devname !~ /$fexpr/);
  824. next if ($ftype eq 'type' && $devhash->{ccutype} !~ /$fexpr/);
  825. next if ($ftype eq 'group' && AttrVal ($devname, 'group', 'null') !~ /$fexpr/);
  826. next if ($ftype eq 'room' && AttrVal ($devname, 'room', 'null') !~ /$fexpr/);
  827. next if ($ftype eq 'alias' && AttrVal ($devname, 'alias', 'null') !~ /$fexpr/);
  828. HMCCU_AggregateReadings ($hash, $rule);
  829. }
  830. }
  831. }
  832. return;
  833. }
  834. ######################################################################
  835. # Calculate reading aggregations.
  836. # Called by Notify or via command get aggregation.
  837. ######################################################################
  838. sub HMCCU_AggregateReadings ($$)
  839. {
  840. my ($hash, $rule) = @_;
  841. my $dc = 0;
  842. my $mc = 0;
  843. my $result = '';
  844. my $rl = '';
  845. my $table = '';
  846. # Get rule parameters
  847. my $ftype = $hash->{hmccu}{agg}{$rule}{ftype};
  848. my $fexpr = $hash->{hmccu}{agg}{$rule}{fexpr};
  849. my $fexcl = $hash->{hmccu}{agg}{$rule}{fexcl};
  850. my $fread = $hash->{hmccu}{agg}{$rule}{fread};
  851. my $fcond = $hash->{hmccu}{agg}{$rule}{fcond};
  852. my $ftrue = $hash->{hmccu}{agg}{$rule}{ftrue};
  853. my $felse = $hash->{hmccu}{agg}{$rule}{felse};
  854. my $fpref = $hash->{hmccu}{agg}{$rule}{fpref};
  855. my $fhtml = exists ($hash->{hmccu}{agg}{$rule}{fhtml}) ? 1 : 0;
  856. my $resval;
  857. $resval = $ftrue if ($fcond =~ /^(max|min|sum|avg)$/);
  858. my @devlist = HMCCU_FindClientDevices ($hash, "(HMCCUDEV|HMCCUCHN)", undef, undef);
  859. foreach my $d (@devlist) {
  860. my $ch = $defs{$d};
  861. my $cn = $ch->{NAME};
  862. my $ct = $ch->{TYPE};
  863. my $fmatch = '';
  864. $fmatch = $cn if ($ftype eq 'name');
  865. $fmatch = $ch->{ccutype} if ($ftype eq 'type');
  866. $fmatch = AttrVal ($cn, 'group', '') if ($ftype eq 'group');
  867. $fmatch = AttrVal ($cn, 'room', '') if ($ftype eq 'room');
  868. $fmatch = AttrVal ($cn, 'alias', '') if ($ftype eq 'alias');
  869. next if ($fmatch eq '' || $fmatch !~ /$fexpr/ || ($fexcl ne '' && $fmatch =~ /$fexcl/));
  870. my $fcoll = $hash->{hmccu}{agg}{$rule}{fcoll} eq 'NAME' ?
  871. $cn : AttrVal ($cn, $hash->{hmccu}{agg}{$rule}{fcoll}, $cn);
  872. # Compare readings
  873. foreach my $r (keys %{$ch->{READINGS}}) {
  874. next if ($r !~ /$fread/);
  875. my $rv = $ch->{READINGS}{$r}{VAL};
  876. my $f = 0;
  877. if (($fcond eq 'any' || $fcond eq 'all') && $rv =~ /$ftrue/) {
  878. $mc++;
  879. $f = 1;
  880. }
  881. if ($fcond eq 'max' && $rv > $resval) {
  882. $resval = $rv;
  883. $mc = 1;
  884. $f = 1;
  885. }
  886. if ($fcond eq 'min' && $rv < $resval) {
  887. $resval = $rv;
  888. $mc = 1;
  889. $f = 1;
  890. }
  891. if ($fcond eq 'sum' || $fcond eq 'avg') {
  892. $resval += $rv;
  893. $mc++;
  894. $f = 1;
  895. }
  896. if (($fcond eq 'gt' && $rv > $ftrue) ||
  897. ($fcond eq 'lt' && $rv < $ftrue) ||
  898. ($fcond eq 'ge' && $rv >= $ftrue) ||
  899. ($fcond eq 'le' && $rv <= $ftrue)) {
  900. $mc++;
  901. $f = 1;
  902. }
  903. if ($f) {
  904. $rl .= ($mc > 1 ? ",$fcoll" : $fcoll);
  905. last;
  906. }
  907. }
  908. $dc++;
  909. }
  910. $rl = $hash->{hmccu}{agg}{$rule}{fdflt} if ($rl eq '');
  911. # HTML code generation
  912. if ($fhtml) {
  913. if ($rl ne '') {
  914. $table = $hash->{hmccu}{agg}{$rule}{fhtml}{'begin-html'}.
  915. $hash->{hmccu}{agg}{$rule}{fhtml}{'begin-table'};
  916. $table .= $hash->{hmccu}{agg}{$rule}{fhtml}{'header'}
  917. if (exists ($hash->{hmccu}{agg}{$rule}{fhtml}{'header'}));
  918. my $row = 1;
  919. foreach my $v (split (",", $rl)) {
  920. my $t_row = ($row % 2) ? $hash->{hmccu}{agg}{$rule}{fhtml}{'row-odd'} :
  921. $hash->{hmccu}{agg}{$rule}{fhtml}{'row-even'};
  922. $t_row =~ s/\<reading\/\>/$v/;
  923. $table .= $t_row;
  924. $row++;
  925. }
  926. $table .= $hash->{hmccu}{agg}{$rule}{fhtml}{'end-table'}.
  927. $hash->{hmccu}{agg}{$rule}{fhtml}{'end-html'};
  928. }
  929. else {
  930. $table = $hash->{hmccu}{agg}{$rule}{fhtml}{'begin-html'}.
  931. $hash->{hmccu}{agg}{$rule}{fhtml}{'default'}.
  932. $hash->{hmccu}{agg}{$rule}{fhtml}{'end-html'};
  933. }
  934. }
  935. if ($fcond eq 'any') {
  936. $result = $mc > 0 ? $ftrue : $felse;
  937. }
  938. elsif ($fcond eq 'all') {
  939. $result = $mc == $dc ? $ftrue : $felse;
  940. }
  941. elsif ($fcond eq 'min' || $fcond eq 'max' || $fcond eq 'sum') {
  942. $result = $mc > 0 ? $resval : $felse;
  943. }
  944. elsif ($fcond eq 'avg') {
  945. $result = $mc > 0 ? $resval/$mc : $felse;
  946. }
  947. elsif ($fcond =~ /^(gt|lt|ge|le)$/) {
  948. $result = $mc;
  949. }
  950. # Set readings
  951. readingsBeginUpdate ($hash);
  952. readingsBulkUpdate ($hash, $fpref.'state', $result);
  953. readingsBulkUpdate ($hash, $fpref.'match', $mc);
  954. readingsBulkUpdate ($hash, $fpref.'count', $dc);
  955. readingsBulkUpdate ($hash, $fpref.'list', $rl);
  956. readingsBulkUpdate ($hash, $fpref.'table', $table) if ($fhtml);
  957. readingsEndUpdate ($hash, 1);
  958. return $result;
  959. }
  960. ######################################################################
  961. # Delete device
  962. ######################################################################
  963. sub HMCCU_Undef ($$)
  964. {
  965. my ($hash, $arg) = @_;
  966. # Shutdown RPC server
  967. HMCCU_Shutdown ($hash);
  968. # Delete reference to IO module in client devices
  969. my @keylist = keys %defs;
  970. foreach my $d (@keylist) {
  971. if (exists ($defs{$d}) && exists($defs{$d}{IODev}) &&
  972. $defs{$d}{IODev} == $hash) {
  973. delete $defs{$d}{IODev};
  974. }
  975. }
  976. return undef;
  977. }
  978. ######################################################################
  979. # Shutdown FHEM
  980. ######################################################################
  981. sub HMCCU_Shutdown ($)
  982. {
  983. my ($hash) = @_;
  984. my $name = $hash->{NAME};
  985. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  986. # Shutdown RPC server
  987. if ($ccuflags =~ /(extrpc|procrpc)/) {
  988. HMCCU_StopExtRPCServer ($hash);
  989. }
  990. else {
  991. HMCCU_StopRPCServer ($hash);
  992. }
  993. # Remove existing timer functions
  994. RemoveInternalTimer ($hash);
  995. return undef;
  996. }
  997. ######################################################################
  998. # Set commands
  999. ######################################################################
  1000. sub HMCCU_Set ($@)
  1001. {
  1002. my ($hash, $a, $h) = @_;
  1003. my $name = shift @$a;
  1004. my $opt = shift @$a;
  1005. my $options = "var delete execute hmscript cleardefaults:noArg defaults:noArg ".
  1006. "importdefaults rpcserver:on,off datapoint ackmessages:noArg";
  1007. my $usage = "HMCCU: Unknown argument $opt, choose one of $options";
  1008. my $host = $hash->{host};
  1009. return "HMCCU: CCU busy, choose one of rpcserver:off"
  1010. if ($opt ne 'rpcserver' && HMCCU_IsRPCStateBlocking ($hash));
  1011. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  1012. $options .= ",restart" if ($ccuflags !~ /(extrpc|procrpc)/);
  1013. my $stripchar = AttrVal ($name, "stripchar", '');
  1014. my $ccureadings = AttrVal ($name, "ccureadings", $ccuflags =~ /noReadings/ ? 0 : 1);
  1015. my $ccureqtimeout = AttrVal ($name, "ccuReqTimeout", $HMCCU_TIMEOUT_REQUEST);
  1016. my $readingformat = HMCCU_GetAttrReadingFormat ($hash, $hash);
  1017. my $substitute = HMCCU_GetAttrSubstitute ($hash, $hash);
  1018. if ($opt eq 'var') {
  1019. my $vartype;
  1020. $vartype = shift @$a if (scalar (@$a) == 3);
  1021. my $objname = shift @$a;
  1022. my $objvalue = shift @$a;
  1023. $usage = "set $name $opt [{'bool'|'list'|'number'|'test'}] variable value [param=value [...]]";
  1024. my $result;
  1025. return HMCCU_SetError ($hash, $usage) if (!defined ($objvalue));
  1026. $objname =~ s/$stripchar$// if ($stripchar ne '');
  1027. $objvalue =~ s/\\_/%20/g;
  1028. $h->{name} = $objname if (!defined ($h) && defined ($vartype));
  1029. $result = HMCCU_SetVariable ($hash, $objname, $objvalue, $vartype, $h);
  1030. return HMCCU_SetError ($hash, $result) if ($result < 0);
  1031. return HMCCU_SetState ($hash, "OK");
  1032. }
  1033. elsif ($opt eq 'datapoint') {
  1034. my $objname = shift @$a;
  1035. my $objvalue = shift @$a;
  1036. $usage = "Usage: set $name $opt {ccuobject|'hmccu':fhemobject} value";
  1037. return HMCCU_SetError ($hash, $usage) if (!defined ($objvalue));
  1038. my $rc = HMCCU_SetDatapoint ($hash, $objname, $objvalue);
  1039. return HMCCU_SetError ($hash, $rc) if ($rc < 0);
  1040. return HMCCU_SetState ($hash, "OK");
  1041. }
  1042. elsif ($opt eq 'delete') {
  1043. my $objname = shift @$a;
  1044. my $objtype = shift @$a;
  1045. $objtype = "OT_VARDP" if (!defined ($objtype));
  1046. $usage = "Usage: set $name $opt ccuobject ['OT_VARDP'|'OT_DEVICE']";
  1047. return HMCCU_SetError ($hash, $usage)
  1048. if (!defined ($objname) || $objtype !~ /^(OT_VARDP|OT_DEVICE)$/);
  1049. my $result = HMCCU_HMScriptExt ($hash, "!DeleteObject", { name => $objname, type => $objtype });
  1050. return HMCCU_SetError ($hash, -2) if ($result =~ /^ERROR:.*/);
  1051. return HMCCU_SetState ($hash, "OK");
  1052. }
  1053. elsif ($opt eq 'execute') {
  1054. my $program = shift @$a;
  1055. my $response;
  1056. $usage = "Usage: set $name $opt program-name";
  1057. return HMCCU_SetError ($hash, $usage) if (!defined ($program));
  1058. my $url = qq(http://$host:8181/do.exe?r1=dom.GetObject("$program").ProgramExecute());
  1059. $response = GetFileFromURL ($url, $ccureqtimeout);
  1060. $response =~ m/<r1>(.*)<\/r1>/;
  1061. my $value = $1;
  1062. return HMCCU_SetState ($hash, "OK") if (defined ($value) && $value ne '' && $value ne 'null');
  1063. return HMCCU_SetError ($hash, "Program execution error");
  1064. }
  1065. elsif ($opt eq 'hmscript') {
  1066. my $script = shift @$a;
  1067. my $dump = shift @$a;
  1068. my $response = '';
  1069. my %objects = ();
  1070. my $objcount = 0;
  1071. $usage = "Usage: set $name $opt {file|!function|'['code']'} ['dump'] [parname=value [...]]";
  1072. # If no parameter is specified list available script functions
  1073. if (!defined ($script)) {
  1074. $response = "Available HomeMatic script functions:\n".
  1075. "-------------------------------------\n";
  1076. foreach my $scr (keys %{$HMCCU_SCRIPTS}) {
  1077. $response .= "$scr ".$HMCCU_SCRIPTS->{$scr}{syntax}."\n".
  1078. $HMCCU_SCRIPTS->{$scr}{description}."\n\n";
  1079. }
  1080. $response .= $usage;
  1081. return $response;
  1082. }
  1083. return HMCCU_SetError ($hash, $usage) if (defined ($dump) && $dump ne 'dump');
  1084. # Execute script
  1085. $response = HMCCU_HMScriptExt ($hash, $script, $h);
  1086. return HMCCU_SetError ($hash, -2, $response) if ($response =~ /^ERROR:/);
  1087. HMCCU_SetState ($hash, "OK");
  1088. return $response if (! $ccureadings || defined ($dump));
  1089. foreach my $line (split /\n/, $response) {
  1090. my @tokens = split /=/, $line;
  1091. next if (@tokens != 2);
  1092. my $reading;
  1093. my ($int, $add, $chn, $dpt, $nam, $flags) = HMCCU_ParseObject ($hash, $tokens[0],
  1094. $HMCCU_FLAG_INTERFACE);
  1095. ($add, $chn) = HMCCU_GetAddress ($hash, $nam, '', '') if ($flags == $HMCCU_FLAGS_NCD);
  1096. if ($flags == $HMCCU_FLAGS_IACD || $flags == $HMCCU_FLAGS_NCD) {
  1097. $objects{$add}{$chn}{$dpt} = $tokens[1];
  1098. $objcount++;
  1099. }
  1100. else {
  1101. # If output is not related to a channel store reading in I/O device
  1102. my $Value = HMCCU_Substitute ($tokens[1], $substitute, 0, undef, $tokens[0]);
  1103. my $rn = $tokens[0];
  1104. $rn =~ s/\:/\./g;
  1105. $rn =~ s/[^A-Za-z\d_\.-]+/_/g;
  1106. readingsSingleUpdate ($hash, $rn, $Value, 1);
  1107. }
  1108. }
  1109. HMCCU_UpdateMultipleDevices ($hash, \%objects) if ($objcount > 0);
  1110. return defined ($dump) ? $response : undef;
  1111. }
  1112. elsif ($opt eq 'rpcserver') {
  1113. my $action = shift @$a;
  1114. $action = shift @$a if ($action eq $opt);
  1115. $usage = "Usage: set $name $opt {'on'|'off'|'restart'}";
  1116. return HMCCU_SetError ($hash, $usage)
  1117. if (!defined ($action) || $action !~ /^(on|off|restart)$/);
  1118. if ($action eq 'on') {
  1119. if ($ccuflags =~ /(extrpc|procrpc)/) {
  1120. return HMCCU_SetError ($hash, "Start of RPC server failed")
  1121. if (!HMCCU_StartExtRPCServer ($hash));
  1122. }
  1123. else {
  1124. return HMCCU_SetError ($hash, "Start of RPC server failed")
  1125. if (!HMCCU_StartIntRPCServer ($hash));
  1126. }
  1127. }
  1128. elsif ($action eq 'off') {
  1129. if ($ccuflags =~ /(extrpc|procrpc)/) {
  1130. return HMCCU_SetError ($hash, "Stop of RPC server failed")
  1131. if (!HMCCU_StopExtRPCServer ($hash));
  1132. }
  1133. else {
  1134. return HMCCU_SetError ($hash, "Stop of RPC server failed")
  1135. if (!HMCCU_StopRPCServer ($hash));
  1136. }
  1137. }
  1138. elsif ($action eq 'restart') {
  1139. return "HMCCU: No RPC server running" if (!HMCCU_IsRPCServerRunning ($hash, undef, undef));
  1140. if ($ccuflags !~ /(extrpc|procrpc)/) {
  1141. return "HMCCU: Can't stop RPC server" if (!HMCCURPC_StopRPCServer ($hash));
  1142. HMCCU_SetRPCState ($hash, 'restarting');
  1143. DoTrigger ($name, "RPC server restarting");
  1144. }
  1145. else {
  1146. return HMCCU_SetError ($hash, "HMCCU: restart not supported by external RPC server");
  1147. }
  1148. }
  1149. return HMCCU_SetState ($hash, "OK");
  1150. }
  1151. elsif ($opt eq 'ackmessages') {
  1152. my $response = HMCCU_HMScriptExt ($hash, "!ClearUnreachable", undef);
  1153. return HMCCU_SetError ($hash, -2, $response) if ($response =~ /^ERROR:/);
  1154. return HMCCU_SetState ($hash, "OK", "Unreach errors in CCU cleared");
  1155. }
  1156. elsif ($opt eq 'defaults') {
  1157. my $rc = HMCCU_SetDefaults ($hash);
  1158. return HMCCU_SetError ($hash, "HMCCU: No default attributes found") if ($rc == 0);
  1159. return HMCCU_SetState ($hash, "OK");
  1160. }
  1161. elsif ($opt eq 'cleardefaults') {
  1162. %HMCCU_CUST_CHN_DEFAULTS = ();
  1163. %HMCCU_CUST_DEV_DEFAULTS = ();
  1164. return HMCCU_SetState ($hash, "OK", "Default attributes deleted");
  1165. }
  1166. elsif ($opt eq 'importdefaults') {
  1167. my $filename = shift @$a;
  1168. $usage = "Usage: set $name $opt filename";
  1169. return HMCCU_SetError ($hash, $usage) if (!defined ($filename));
  1170. my $rc = HMCCU_ImportDefaults ($filename);
  1171. return HMCCU_SetError ($hash, -16) if ($rc == 0);
  1172. if ($rc < 0) {
  1173. $rc = -$rc;
  1174. return HMCCU_SetError ($hash, "Syntax error in default attribute file $filename line $rc");
  1175. }
  1176. return HMCCU_SetState ($hash, "OK", "Default attributes read from file $filename");
  1177. }
  1178. else {
  1179. return $usage;
  1180. }
  1181. }
  1182. ######################################################################
  1183. # Get commands
  1184. ######################################################################
  1185. sub HMCCU_Get ($@)
  1186. {
  1187. my ($hash, $a, $h) = @_;
  1188. my $name = shift @$a;
  1189. my $opt = shift @$a;
  1190. my $options = "defaults:noArg exportdefaults devicelist dump dutycycle:noArg vars update".
  1191. " updateccu parfile configdesc firmware:noArg rpcevents:noArg rpcstate:noArg deviceinfo";
  1192. my $usage = "HMCCU: Unknown argument $opt, choose one of $options";
  1193. my $host = $hash->{host};
  1194. return "HMCCU: CCU busy, choose one of rpcstate:noArg"
  1195. if ($opt ne 'rpcstate' && HMCCU_IsRPCStateBlocking ($hash));
  1196. my $ccuflags = AttrVal ($name, "ccuflags", "null");
  1197. my $ccureadings = AttrVal ($name, "ccureadings", $ccuflags =~ /noReadings/ ? 0 : 1);
  1198. my $parfile = AttrVal ($name, "parfile", '');
  1199. my $readname;
  1200. my $readaddr;
  1201. my $result = '';
  1202. my $rc;
  1203. if ($opt eq 'dump') {
  1204. my $content = shift @$a;
  1205. my $filter = shift @$a;
  1206. $filter = '.*' if (!defined ($filter));
  1207. $usage = "Usage: get $name dump {'datapoints'|'devtypes'} [filter]";
  1208. my %foper = (1, "R", 2, "W", 4, "E", 3, "RW", 5, "RE", 6, "WE", 7, "RWE");
  1209. my %ftype = (2, "B", 4, "F", 16, "I", 20, "S");
  1210. return HMCCU_SetError ($hash, $usage) if (!defined ($content));
  1211. if ($content eq 'devtypes') {
  1212. foreach my $devtype (sort keys %{$hash->{hmccu}{dp}}) {
  1213. $result .= $devtype."\n" if ($devtype =~ /$filter/);
  1214. }
  1215. }
  1216. elsif ($content eq 'datapoints') {
  1217. foreach my $devtype (sort keys %{$hash->{hmccu}{dp}}) {
  1218. next if ($devtype !~ /$filter/);
  1219. foreach my $chn (sort keys %{$hash->{hmccu}{dp}{$devtype}{ch}}) {
  1220. foreach my $dpt (sort keys %{$hash->{hmccu}{dp}{$devtype}{ch}{$chn}}) {
  1221. my $t = $hash->{hmccu}{dp}{$devtype}{ch}{$chn}{$dpt}{type};
  1222. my $o = $hash->{hmccu}{dp}{$devtype}{ch}{$chn}{$dpt}{oper};
  1223. $result .= $devtype.".".$chn.".".$dpt." [".
  1224. (exists($ftype{$t}) ? $ftype{$t} : $t)."] [".
  1225. (exists($foper{$o}) ? $foper{$o} : $o)."]\n";
  1226. }
  1227. }
  1228. }
  1229. }
  1230. else {
  1231. return HMCCU_SetError ($hash, $usage);
  1232. }
  1233. return HMCCU_SetState ($hash, "OK", ($result eq '') ? "No data found" : $result);
  1234. }
  1235. elsif ($opt eq 'vars') {
  1236. my $varname = shift @$a;
  1237. $usage = "Usage: get $name vars {regexp}[,...]";
  1238. return HMCCU_SetError ($hash, $usage) if (!defined ($varname));
  1239. ($rc, $result) = HMCCU_GetVariables ($hash, $varname);
  1240. return HMCCU_SetError ($hash, $rc, $result) if ($rc < 0);
  1241. return HMCCU_SetState ($hash, "OK", $ccureadings ? undef : $result);
  1242. }
  1243. elsif ($opt eq 'update' || $opt eq 'updateccu') {
  1244. my $devexp = shift @$a;
  1245. $devexp = '.*' if (!defined ($devexp));
  1246. $usage = "Usage: get $name $opt [device-expr [{'State'|'Value'}]]";
  1247. my $ccuget = shift @$a;
  1248. $ccuget = 'Attr' if (!defined ($ccuget));
  1249. return HMCCU_SetError ($hash, $usage) if ($ccuget !~ /^(Attr|State|Value)$/);
  1250. my ($co, $ce) = HMCCU_UpdateClients ($hash, $devexp, $ccuget, ($opt eq 'updateccu') ? 1 : 0, undef);
  1251. return HMCCU_SetState ($hash, "OK",
  1252. "$co client devices successfully updated. Update for $ce client devices failed");
  1253. }
  1254. elsif ($opt eq 'parfile') {
  1255. my $par_parfile = shift @$a;
  1256. my @parameters;
  1257. my $parcount;
  1258. if (defined ($par_parfile)) {
  1259. $parfile = $par_parfile;
  1260. }
  1261. else {
  1262. return HMCCU_SetError ($hash, "No parameter file specified") if ($parfile eq '');
  1263. }
  1264. # Read parameter file
  1265. if (open (PARFILE, "<$parfile")) {
  1266. @parameters = <PARFILE>;
  1267. $parcount = scalar @parameters;
  1268. close (PARFILE);
  1269. }
  1270. else {
  1271. return HMCCU_SetError ($hash, -16);
  1272. }
  1273. return HMCCU_SetError ($hash, "Empty parameter file") if ($parcount < 1);
  1274. ($rc, $result) = HMCCU_GetChannel ($hash, \@parameters);
  1275. return HMCCU_SetError ($hash, $rc) if ($rc < 0);
  1276. return HMCCU_SetState ($hash, "OK", $ccureadings ? undef : $result);
  1277. }
  1278. elsif ($opt eq 'deviceinfo') {
  1279. my $device = shift @$a;
  1280. $usage = "Usage: get $name $opt device [{'State'|'Value'}]";
  1281. return HMCCU_SetError ($hash, $usage) if (!defined ($device));
  1282. my $ccuget = shift @$a;
  1283. $ccuget = 'Attr' if (!defined ($ccuget));
  1284. return HMCCU_SetError ($hash, $usage) if ($ccuget !~ /^(Attr|State|Value)$/);
  1285. return HMCCU_SetError ($hash, -1) if (!HMCCU_IsValidDeviceOrChannel ($hash, $device));
  1286. $result = HMCCU_GetDeviceInfo ($hash, $device, $ccuget);
  1287. return HMCCU_SetError ($hash, -2) if ($result eq '' || $result =~ /^ERROR:.*/);
  1288. HMCCU_SetState ($hash, "OK");
  1289. return HMCCU_FormatDeviceInfo ($result);
  1290. }
  1291. elsif ($opt eq 'rpcevents') {
  1292. if ($ccuflags =~ /extrpc/) {
  1293. my ($rpcdev, $save) = HMCCU_GetRPCDevice ($hash, 0, undef);
  1294. return HMCCU_SetError ($hash, "HMCCU: External RPC server not found") if ($rpcdev eq '');
  1295. $result = AnalyzeCommandChain (undef, "get $rpcdev rpcevents");
  1296. return HMCCU_SetState ($hash, "OK", $result) if (defined ($result));
  1297. return HMCCU_SetError ($hash, "No event statistics available");
  1298. }
  1299. elsif ($ccuflags =~ /procrpc/) {
  1300. $result = '';
  1301. my @iflist = HMCCU_GetRPCInterfaceList ($hash);
  1302. foreach my $ifname (@iflist) {
  1303. my ($rpcdev, $save) = HMCCU_GetRPCDevice ($hash, 0, $ifname);
  1304. if ($rpcdev eq '') {
  1305. Log3 $name, 2, "HMCCU: Can't find HMCCURPCPROC device for interface $ifname";
  1306. next;
  1307. }
  1308. my $res = AnalyzeCommandChain (undef, "get $rpcdev rpcevents");
  1309. $result .= $res if (defined ($result));
  1310. }
  1311. return HMCCU_SetState ($hash, "OK", $result) if ($result ne '');
  1312. return HMCCU_SetError ($hash, "No event statistics available");
  1313. }
  1314. else {
  1315. return HMCCU_SetError ($hash, "No event statistics available")
  1316. if (!exists ($hash->{hmccu}{evs}) || !exists ($hash->{hmccu}{evr}));
  1317. foreach my $stkey (sort keys %{$hash->{hmccu}{evr}}) {
  1318. $result .= "S: ".$stkey." = ".$hash->{hmccu}{evs}{$stkey}."\n";
  1319. $result .= "R: ".$stkey." = ".$hash->{hmccu}{evr}{$stkey}."\n";
  1320. }
  1321. return HMCCU_SetState ($hash, "OK", $result);
  1322. }
  1323. }
  1324. elsif ($opt eq 'rpcstate') {
  1325. my @hm_pids = ();
  1326. my @hm_tids = ();
  1327. $result = "No RPC processes or threads are running";
  1328. if (HMCCU_IsRPCServerRunning ($hash, \@hm_pids, \@hm_tids)) {
  1329. $result = "RPC process(es) running with pid(s) ".
  1330. join (',', @hm_pids) if (scalar (@hm_pids) > 0);
  1331. $result = "RPC thread(s) running with tid(s) ".
  1332. join (',', @hm_tids) if (scalar (@hm_tids) > 0);
  1333. }
  1334. return HMCCU_SetState ($hash, "OK", $result);
  1335. }
  1336. elsif ($opt eq 'devicelist') {
  1337. my ($devcount, $chncount, $ifcount) = HMCCU_GetDeviceList ($hash);
  1338. return HMCCU_SetError ($hash, -2) if ($devcount < 0);
  1339. return HMCCU_SetError ($hash, "No devices received from CCU") if ($devcount == 0);
  1340. $result = "Read $devcount devices with $chncount channels from CCU";
  1341. my $optcmd = shift @$a;
  1342. if (defined ($optcmd)) {
  1343. if ($optcmd eq 'dump') {
  1344. $result .= "\n-----------------------------------------\n";
  1345. my $n = 0;
  1346. foreach my $add (sort keys %{$hash->{hmccu}{dev}}) {
  1347. if ($hash->{hmccu}{dev}{$add}{addtype} eq 'dev') {
  1348. $result .= "Device ".'"'.$hash->{hmccu}{dev}{$add}{name}.'"'." [".$add."] ".
  1349. "Type=".$hash->{hmccu}{dev}{$add}{type}."\n";
  1350. $n = 0;
  1351. }
  1352. else {
  1353. $result .= " Channel $n ".'"'.$hash->{hmccu}{dev}{$add}{name}.'"'.
  1354. " [".$add."]\n";
  1355. $n++;
  1356. }
  1357. }
  1358. return $result;
  1359. }
  1360. elsif ($optcmd eq 'create') {
  1361. $usage = "Usage: get $name create {devexp|chnexp} [t={'chn'|'dev'|'all'}] [s=suffix] ".
  1362. "[p=prefix] [f=format] ['defattr'] ['duplicates'] [save] [attr=val [...]]";
  1363. my $devdefaults = 0;
  1364. my $duplicates = 0;
  1365. my $savedef = 0;
  1366. my $newcount = 0;
  1367. # Process command line parameters
  1368. my $devspec = shift @$a;
  1369. my $devprefix = exists ($h->{p}) ? $h->{p} : '';
  1370. my $devsuffix = exists ($h->{'s'}) ? $h->{'s'} : '';
  1371. my $devtype = exists ($h->{t}) ? $h->{t} : 'dev';
  1372. my $devformat = exists ($h->{f}) ? $h->{f} : '%n';
  1373. return HMCCU_SetError ($hash, $usage)
  1374. if ($devtype !~ /^(dev|chn|all)$/ || !defined ($devspec));
  1375. foreach my $defopt (@$a) {
  1376. if ($defopt eq 'defattr') { $devdefaults = 1; }
  1377. elsif ($defopt eq 'duplicates') { $duplicates = 1; }
  1378. elsif ($defopt eq 'save') { $savedef = 1; }
  1379. else { return HMCCU_SetError ($hash, $usage); }
  1380. }
  1381. # Get list of existing client devices
  1382. my @devlist = HMCCU_FindClientDevices ($hash, "(HMCCUDEV|HMCCUCHN)", undef, undef);
  1383. foreach my $add (sort keys %{$hash->{hmccu}{dev}}) {
  1384. my $defmod = $hash->{hmccu}{dev}{$add}{addtype} eq 'dev' ? 'HMCCUDEV' : 'HMCCUCHN';
  1385. my $ccuname = $hash->{hmccu}{dev}{$add}{name};
  1386. my $ccudevname = HMCCU_GetDeviceName ($hash, $add, $ccuname);
  1387. next if ($devtype ne 'all' && $devtype ne $hash->{hmccu}{dev}{$add}{addtype});
  1388. next if (HMCCU_ExprNotMatch ($ccuname, $devspec, 1));
  1389. # Build FHEM device name
  1390. my $devname = $devformat;
  1391. $devname = $devprefix.$devname.$devsuffix;
  1392. $devname =~ s/%n/$ccuname/g;
  1393. $devname =~ s/%d/$ccudevname/g;
  1394. $devname =~ s/%a/$add/g;
  1395. $devname =~ s/[^A-Za-z\d_\.]+/_/g;
  1396. # Check for duplicate device definitions
  1397. if (!$duplicates) {
  1398. next if (exists ($defs{$devname}));
  1399. my $devexists = 0;
  1400. foreach my $exdev (@devlist) {
  1401. if ($defs{$exdev}->{ccuaddr} eq $add) {
  1402. $devexists = 1;
  1403. last;
  1404. }
  1405. }
  1406. next if ($devexists);
  1407. }
  1408. # Define new client device
  1409. my $ret = CommandDefine (undef, $devname." $defmod ".$add);
  1410. if ($ret) {
  1411. Log3 $name, 2, "HMCCU: Define command failed $devname $defmod $ccuname";
  1412. Log3 $name, 2, "$defmod: $ret";
  1413. $result .= "\nCan't create device $devname. $ret";
  1414. next;
  1415. }
  1416. # Set device attributes
  1417. HMCCU_SetDefaults ($defs{$devname}) if ($devdefaults);
  1418. foreach my $da (keys %$h) {
  1419. next if ($da =~ /^[pstf]$/);
  1420. $ret = CommandAttr (undef, "$devname $da ".$h->{$da});
  1421. if ($ret) {
  1422. Log3 $name, 2, "HMCCU: Attr command failed $devname $da ".$h->{$da};
  1423. Log3 $name, 2, "$defmod: $ret";
  1424. }
  1425. }
  1426. Log3 $name, 2, "$defmod: Created device $devname";
  1427. $result .= "\nCreated device $devname";
  1428. $newcount++;
  1429. }
  1430. CommandSave (undef, undef) if ($newcount > 0 && $savedef);
  1431. $result .= "\nCreated $newcount client devices";
  1432. }
  1433. }
  1434. return HMCCU_SetState ($hash, "OK", $result);
  1435. }
  1436. elsif ($opt eq 'dutycycle') {
  1437. my $dc = HMCCU_GetDutyCycle ($hash);
  1438. return HMCCU_SetState ($hash, "OK", "Read $dc duty cycle values");
  1439. }
  1440. elsif ($opt eq 'firmware') {
  1441. my $dc = HMCCU_GetFirmwareVersions ($hash);
  1442. return "Found no firmware downloads" if ($dc == 0);
  1443. $result = "Found $dc firmware downloads.";
  1444. my @devlist = HMCCU_FindClientDevices ($hash, "(HMCCUDEV|HMCCUCHN)", undef, undef);
  1445. return $result if (scalar (@devlist) == 0);
  1446. $result .= " Click on the new version number for download\n\n".
  1447. "Device Type Current Available Date\n".
  1448. "------------------------------------------------------------------------\n";
  1449. foreach my $dev (@devlist) {
  1450. my $ch = $defs{$dev};
  1451. my $ct = uc($ch->{ccutype});
  1452. next if (!defined ($ch->{firmware}));
  1453. next if (!exists ($hash->{hmccu}{type}{$ct}));
  1454. $result .= sprintf "%-25s %-20s %-7s <a href=\"http://www.eq-3.de/%s\">%-9s</a> %-10s\n",
  1455. $ch->{NAME}, $ct, $ch->{firmware}, $hash->{hmccu}{type}{$ct}{download},
  1456. $hash->{hmccu}{type}{$ct}{firmware}, $hash->{hmccu}{type}{$ct}{date};
  1457. }
  1458. return HMCCU_SetState ($hash, "OK", $result);
  1459. }
  1460. elsif ($opt eq 'defaults') {
  1461. $result = HMCCU_GetDefaults ($hash, 1);
  1462. return HMCCU_SetState ($hash, "OK", $result);
  1463. }
  1464. elsif ($opt eq 'exportdefaults') {
  1465. my $filename = shift @$a;
  1466. $usage = "Usage: get $name $opt filename";
  1467. return HMCCU_SetError ($hash, $usage) if (!defined ($filename));
  1468. my $rc = HMCCU_ExportDefaults ($filename);
  1469. return HMCCU_SetError ($hash, -16) if ($rc == 0);
  1470. return HMCCU_SetState ($hash, "OK", "Default attributes written to $filename");
  1471. }
  1472. elsif ($opt eq 'aggregation') {
  1473. my $rule = shift @$a;
  1474. $usage = "Usage: get $name $opt {'all'|'rule'}";
  1475. return HMCCU_SetError ($hash, $usage) if (!defined ($rule));
  1476. if ($rule eq 'all') {
  1477. foreach my $r (keys %{$hash->{hmccu}{agg}}) {
  1478. my $rc = HMCCU_AggregateReadings ($hash, $r);
  1479. $result .= "$r = $rc\n";
  1480. }
  1481. }
  1482. else {
  1483. return HMCCU_SetError ($hash, "HMCCU: Aggregation rule does not exist")
  1484. if (!exists ($hash->{hmccu}{agg}{$rule}));
  1485. $result = HMCCU_AggregateReadings ($hash, $rule);
  1486. $result = "$rule = $result";
  1487. }
  1488. return HMCCU_SetState ($hash, "OK", $ccureadings ? undef : $result);
  1489. }
  1490. elsif ($opt eq 'configdesc') {
  1491. my $ccuobj = shift @$a;
  1492. $usage = "Usage: get $name $opt {device|channel}";
  1493. return HMCCU_SetError ($hash, $usage) if (!defined ($ccuobj));
  1494. my ($rc, $res) = HMCCU_RPCGetConfig ($hash, $ccuobj, "getParamsetDescription", undef);
  1495. return HMCCU_SetError ($hash, $rc) if ($rc < 0);
  1496. return HMCCU_SetState ($hash, "OK", $res);
  1497. }
  1498. else {
  1499. if (exists ($hash->{hmccu}{agg})) {
  1500. my @rules = keys %{$hash->{hmccu}{agg}};
  1501. $usage .= " aggregation:all,".join (',', @rules) if (scalar (@rules) > 0);
  1502. }
  1503. return $usage;
  1504. }
  1505. }
  1506. ######################################################################
  1507. # Parse CCU object specification.
  1508. #
  1509. # Supported address types:
  1510. # Classic Homematic and Homematic-IP addresses.
  1511. # Team addresses with leading * for BidCos-RF.
  1512. # CCU virtual remote addresses (BidCoS:ChnNo)
  1513. # OSRAM lightify addresses (OL-...)
  1514. # Homematic virtual layer addresses (if known by HMCCU)
  1515. #
  1516. # Possible syntax for datapoints:
  1517. # Interface.Address:Channel.Datapoint
  1518. # Address:Channel.Datapoint
  1519. # Channelname.Datapoint
  1520. #
  1521. # Possible syntax for channels:
  1522. # Interface.Address:Channel
  1523. # Address:Channel
  1524. # Channelname
  1525. #
  1526. # If object name doesn't match the rules above it's treated as name.
  1527. # With parameter flags one can specify if result is filled up with
  1528. # default values for interface or datapoint.
  1529. #
  1530. # Return list of detected attributes (empty string if attribute is
  1531. # not detected):
  1532. # (Interface, Address, Channel, Datapoint, Name, Flags)
  1533. # Flags is a bitmask of detected attributes.
  1534. ######################################################################
  1535. sub HMCCU_ParseObject ($$$)
  1536. {
  1537. my ($hash, $object, $flags) = @_;
  1538. my ($i, $a, $c, $d, $n, $f) = ('', '', '', '', '', '', 0);
  1539. my $extaddr;
  1540. # Check if address is already known by HMCCU. Substitute device address by ZZZ0000000
  1541. # to allow external addresses like HVL
  1542. if ($object =~ /^.+\.(.+):[0-9]{1,2}\..+$/ ||
  1543. $object =~ /^.+\.(.+):[0-9]{1,2}$/ ||
  1544. $object =~ /^(.+):[0-9]{1,2}\..+$/ ||
  1545. $object =~ /^(.+):[0-9]{1,2}$/ ||
  1546. $object =~ /^(.+)$/) {
  1547. $extaddr = $1;
  1548. if (!HMCCU_IsDevAddr ($extaddr, 0) &&
  1549. exists ($hash->{hmccu}{dev}{$extaddr}) && $hash->{hmccu}{dev}{$extaddr}{valid}) {
  1550. $object =~ s/$extaddr/$HMCCU_EXT_ADDR/;
  1551. }
  1552. }
  1553. if ($object =~ /^(.+?)\.([\*]*[A-Z]{3}[0-9]{7}):([0-9]{1,2})\.(.+)$/ ||
  1554. $object =~ /^(.+?)\.([0-9A-F]{12,14}):([0-9]{1,2})\.(.+)$/ ||
  1555. $object =~ /^(.+?)\.(OL-.+):([0-9]{1,2})\.(.+)$/ ||
  1556. $object =~ /^(.+?)\.(BidCoS-RF):([0-9]{1,2})\.(.+)$/) {
  1557. #
  1558. # Interface.Address:Channel.Datapoint [30=11110]
  1559. #
  1560. $f = $HMCCU_FLAGS_IACD;
  1561. ($i, $a, $c, $d) = ($1, $2, $3, $4);
  1562. }
  1563. elsif ($object =~ /^(.+)\.([\*]*[A-Z]{3}[0-9]{7}):([0-9]{1,2})$/ ||
  1564. $object =~ /^(.+)\.([0-9A-F]{12,14}):([0-9]{1,2})$/ ||
  1565. $object =~ /^(.+)\.(OL-.+):([0-9]{1,2})$/ ||
  1566. $object =~ /^(.+)\.(BidCoS-RF):([0-9]{1,2})$/) {
  1567. #
  1568. # Interface.Address:Channel [26=11010]
  1569. #
  1570. $f = $HMCCU_FLAGS_IAC | ($flags & $HMCCU_FLAG_DATAPOINT);
  1571. ($i, $a, $c, $d) = ($1, $2, $3, $flags & $HMCCU_FLAG_DATAPOINT ? '.*' : '');
  1572. }
  1573. elsif ($object =~ /^([\*]*[A-Z]{3}[0-9]{7}):([0-9]{1,2})\.(.+)$/ ||
  1574. $object =~ /^([0-9A-F]{12,14}):([0-9]{1,2})\.(.+)$/ ||
  1575. $object =~ /^(OL-.+):([0-9]{1,2})\.(.+)$/ ||
  1576. $object =~ /^(BidCoS-RF):([0-9]{1,2})\.(.+)$/) {
  1577. #
  1578. # Address:Channel.Datapoint [14=01110]
  1579. #
  1580. $f = $HMCCU_FLAGS_ACD;
  1581. ($a, $c, $d) = ($1, $2, $3);
  1582. }
  1583. elsif ($object =~ /^([\*]*[A-Z]{3}[0-9]{7}):([0-9]{1,2})$/ ||
  1584. $object =~ /^([0-9A-Z]{12,14}):([0-9]{1,2})$/ ||
  1585. $object =~ /^(OL-.+):([0-9]{1,2})$/ ||
  1586. $object =~ /^(BidCoS-RF):([0-9]{1,2})$/) {
  1587. #
  1588. # Address:Channel [10=01010]
  1589. #
  1590. $f = $HMCCU_FLAGS_AC | ($flags & $HMCCU_FLAG_DATAPOINT);
  1591. ($a, $c, $d) = ($1, $2, $flags & $HMCCU_FLAG_DATAPOINT ? '.*' : '');
  1592. }
  1593. elsif ($object =~ /^([\*]*[A-Z]{3}[0-9]{7})$/ ||
  1594. $object =~ /^([0-9A-Z]{12,14})$/ ||
  1595. $object =~ /^(OL-.+)$/ ||
  1596. $object eq 'BidCoS') {
  1597. #
  1598. # Address
  1599. #
  1600. $f = $HMCCU_FLAG_ADDRESS;
  1601. $a = $1;
  1602. }
  1603. elsif ($object =~ /^(.+?)\.([A-Z_]+)$/) {
  1604. #
  1605. # Name.Datapoint
  1606. #
  1607. $f = $HMCCU_FLAGS_ND;
  1608. ($n, $d) = ($1, $2);
  1609. }
  1610. elsif ($object =~ /^.+$/) {
  1611. #
  1612. # Name [1=00001]
  1613. #
  1614. $f = $HMCCU_FLAG_NAME | ($flags & $HMCCU_FLAG_DATAPOINT);
  1615. ($n, $d) = ($object, $flags & $HMCCU_FLAG_DATAPOINT ? '.*' : '');
  1616. }
  1617. else {
  1618. $f = 0;
  1619. }
  1620. # Restore external address (i.e. HVL device address)
  1621. $a = $extaddr if ($a eq $HMCCU_EXT_ADDR);
  1622. # Check if name is a valid channel name
  1623. if ($f & $HMCCU_FLAG_NAME) {
  1624. my ($add, $chn) = HMCCU_GetAddress ($hash, $n, '', '');
  1625. if ($chn ne '') {
  1626. $f = $f | $HMCCU_FLAG_CHANNEL;
  1627. }
  1628. if ($flags & $HMCCU_FLAG_FULLADDR) {
  1629. ($i, $a, $c) = (HMCCU_GetDeviceInterface ($hash, $add, 'BidCos-RF'), $add, $chn);
  1630. $f |= $HMCCU_FLAG_INTERFACE;
  1631. $f |= $HMCCU_FLAG_ADDRESS if ($add ne '');
  1632. $f |= $HMCCU_FLAG_CHANNEL if ($chn ne '');
  1633. }
  1634. }
  1635. elsif ($f & $HMCCU_FLAG_ADDRESS && $i eq '' &&
  1636. ($flags & $HMCCU_FLAG_FULLADDR || $flags & $HMCCU_FLAG_INTERFACE)) {
  1637. $i = HMCCU_GetDeviceInterface ($hash, $a, 'BidCos-RF');
  1638. $f |= $HMCCU_FLAG_INTERFACE;
  1639. }
  1640. return ($i, $a, $c, $d, $n, $f);
  1641. }
  1642. ######################################################################
  1643. # Filter reading by datapoint and optionally by channel name or
  1644. # channel address.
  1645. # Parameter channel can be a channel name or a channel address without
  1646. # interface specification.
  1647. # Filter rule syntax is either:
  1648. # [N:]{Channel-Number|Channel-Name-Expr}!Datapoint-Expr
  1649. # or
  1650. # [N:][Channel-Number.]Datapoint-Expr
  1651. # Multiple filter rules must be separated by ;
  1652. ######################################################################
  1653. sub HMCCU_FilterReading ($$$)
  1654. {
  1655. my ($hash, $chn, $dpt) = @_;
  1656. my $name = $hash->{NAME};
  1657. my $fnc = "FilterReading";
  1658. my $hmccu_hash = HMCCU_GetHash ($hash);
  1659. return 1 if (!defined ($hmccu_hash));
  1660. my $grf = AttrVal ($hmccu_hash->{NAME}, 'ccudef-readingfilter', '');
  1661. $grf = '.*' if ($grf eq '');
  1662. my $rf = AttrVal ($name, 'ccureadingfilter', $grf);
  1663. $rf = $grf.";".$rf if ($rf ne $grf && $grf ne '.*' && $grf ne '');
  1664. my $chnnam = '';
  1665. my $chnnum = '';
  1666. my $devadd = '';
  1667. # Get channel name and channel number
  1668. if (HMCCU_IsValidChannel ($hmccu_hash, $chn)) {
  1669. $chnnam = HMCCU_GetChannelName ($hmccu_hash, $chn, '');
  1670. ($devadd, $chnnum) = HMCCU_SplitChnAddr ($chn);
  1671. }
  1672. else {
  1673. ($devadd, $chnnum) = HMCCU_GetAddress ($hash, $chn, '', '');
  1674. $chnnam = $chn;
  1675. }
  1676. HMCCU_Trace ($hash, 2, $fnc, "chn=$chn, chnnam=$chnnam chnnum=$chnnum dpt=$dpt, rules=$rf");
  1677. foreach my $r (split (';', $rf)) {
  1678. my $rm = 1;
  1679. my $cn = '';
  1680. # Negative filter
  1681. if ($r =~ /^N:/) {
  1682. $rm = 0;
  1683. $r =~ s/^N://;
  1684. }
  1685. # Get filter criteria
  1686. my ($c, $f) = split ("!", $r);
  1687. if (defined ($f)) {
  1688. next if ($c eq '' || $chnnam eq '' || $chnnum eq '');
  1689. $cn = $c if ($c =~ /^([0-9]{1,2})$/);
  1690. }
  1691. else {
  1692. $c = '';
  1693. if ($r =~ /^([0-9]{1,2})\.(.+)$/) {
  1694. $cn = $1;
  1695. $f = $2;
  1696. }
  1697. else {
  1698. $cn = '';
  1699. $f = $r;
  1700. }
  1701. }
  1702. HMCCU_Trace ($hash, 2, undef, " check rm=$rm f=$f cn=$cn c=$c");
  1703. # Positive filter
  1704. return 1 if (
  1705. $rm && (
  1706. (
  1707. ($cn ne '' && "$chnnum" eq "$cn") ||
  1708. ($c ne '' && $chnnam =~ /$c/) ||
  1709. ($cn eq '' && $c eq '')
  1710. ) && $dpt =~ /$f/
  1711. )
  1712. );
  1713. # Negate filter
  1714. return 1 if (
  1715. !$rm && (
  1716. ($cn ne '' && "$chnnum" ne "$cn") ||
  1717. ($c ne '' && $chnnam !~ /$c/) ||
  1718. $dpt !~ /$f/
  1719. )
  1720. );
  1721. HMCCU_Trace ($hash, 2, undef, " check result false");
  1722. }
  1723. return 0;
  1724. }
  1725. ######################################################################
  1726. # Build reading name
  1727. #
  1728. # Parameters:
  1729. #
  1730. # Interface,Address,ChannelNo,Datapoint,ChannelNam,ReadingFormat
  1731. # ReadingFormat := { name[lc] | datapoint[lc] | address[lc] }
  1732. #
  1733. # Valid combinations:
  1734. #
  1735. # ChannelName,Datapoint
  1736. # Address,Datapoint
  1737. # Address,ChannelNo,Datapoint
  1738. #
  1739. # Reading names can be modified by setting attribut ccureadingname.
  1740. # Returns list of readings names.
  1741. ######################################################################
  1742. sub HMCCU_GetReadingName ($$$$$$$)
  1743. {
  1744. my ($hash, $i, $a, $c, $d, $n, $rf) = @_;
  1745. my $name = $hash->{NAME};
  1746. my $hmccu_hash = HMCCU_GetHash ($hash);
  1747. return '' if (!defined ($hmccu_hash));
  1748. my $rn = '';
  1749. my @rnlist;
  1750. Log3 $name, 1, "HMCCU: ChannelNo undefined: Addr=".$a if (!defined ($c));
  1751. $rf = HMCCU_GetAttrReadingFormat ($hash, $hmccu_hash) if (!defined ($rf));
  1752. my $gsr = AttrVal ($hmccu_hash->{NAME}, 'ccudef-readingname', '');
  1753. my $sr = AttrVal ($name, 'ccureadingname', $gsr);
  1754. $sr .= ";".$gsr if ($sr ne $gsr && $gsr ne '');
  1755. # Datapoint is mandatory
  1756. return '' if ($d eq '');
  1757. if ($rf eq 'datapoint' || $rf eq 'datapointlc') {
  1758. $rn = (defined ($c) && $c ne '') ? $c.'.'.$d : $d;
  1759. }
  1760. elsif ($rf eq 'name' || $rf eq 'namelc') {
  1761. if ($n eq '') {
  1762. if ($a ne '' && $c ne '') {
  1763. $n = HMCCU_GetChannelName ($hmccu_hash, $a.':'.$c, '');
  1764. }
  1765. elsif ($a ne '' && $c eq '') {
  1766. $n = HMCCU_GetDeviceName ($hmccu_hash, $a, '');
  1767. }
  1768. else {
  1769. return '';
  1770. }
  1771. }
  1772. # Substitue unsupported characters in reading name
  1773. $n = HMCCU_CorrectName ($n);
  1774. return '' if ($n eq '');
  1775. $rn = $n.'.'.$d;
  1776. }
  1777. elsif ($rf eq 'address' || $rf eq 'addresslc') {
  1778. if ($a eq '' && $n ne '') {
  1779. ($a, $c) = HMCCU_GetAddress ($hmccu_hash, $n, '', '');
  1780. }
  1781. if ($a ne '') {
  1782. my $t = $a;
  1783. $i = HMCCU_GetDeviceInterface ($hmccu_hash, $a, '') if ($i eq '');
  1784. $t = $i.'.'.$t if ($i ne '');
  1785. $t = $t.'.'.$c if ($c ne '');
  1786. $rn = $t.'.'.$d;
  1787. }
  1788. }
  1789. push (@rnlist, $rn);
  1790. # Rename and/or add reading names
  1791. if ($sr ne '') {
  1792. my @rules = split (';', $sr);
  1793. foreach my $rr (@rules) {
  1794. my ($rold, $rnew) = split (':', $rr);
  1795. next if (!defined ($rnew));
  1796. if ($rnlist[0] =~ /$rold/) {
  1797. if ($rnew =~ /^\+(.+)$/) {
  1798. my $radd = $1;
  1799. $radd =~ s/$rold/$radd/;
  1800. push (@rnlist, $radd);
  1801. }
  1802. else {
  1803. $rnlist[0] =~ s/$rold/$rnew/;
  1804. }
  1805. }
  1806. }
  1807. }
  1808. # Convert to lowercase
  1809. $rnlist[0] = lc($rnlist[0]) if ($rf =~ /lc$/);
  1810. return @rnlist;
  1811. }
  1812. ######################################################################
  1813. # Format reading value depending on attribute stripnumber.
  1814. # Syntax of attribute stripnumber:
  1815. # [datapoint-expr!]format[;...]
  1816. # Valid formats:
  1817. # 0 = Preserve all digits (default)
  1818. # 1 = Preserve 1 digit
  1819. # 2 = Remove trailing zeroes
  1820. # -n = Round value to specified number of digits (-0 is allowed)
  1821. # %f = Format for numbers. String suffix is allowed.
  1822. ######################################################################
  1823. sub HMCCU_FormatReadingValue ($$$)
  1824. {
  1825. my ($hash, $value, $dpt) = @_;
  1826. my $stripnumber = AttrVal ($hash->{NAME}, 'stripnumber', '0');
  1827. return $value if ($stripnumber eq '0' || $value !~ /^[+-]?\d*\.?\d+(?:(?:e|E)\d+)?$/);
  1828. my $isint = $value =~ /^[+-]?[0-9]+$/ ? 1 : 0;
  1829. foreach my $sr (split (';', $stripnumber)) {
  1830. my ($d, $s) = split ('!', $sr);
  1831. if (defined ($s)) {
  1832. next if ($d eq '' || $dpt !~ /$d/);
  1833. }
  1834. else {
  1835. $s = $sr;
  1836. }
  1837. if ($s eq '1' && !$isint) {
  1838. return sprintf ("%.1f", $value);
  1839. }
  1840. elsif ($s eq '2' && !$isint) {
  1841. return sprintf ("%g", $value);
  1842. }
  1843. elsif ($s =~ /^-([0-9])$/ && !$isint) {
  1844. my $fmt = '%.'.$1.'f';
  1845. return sprintf ($fmt, $value);
  1846. }
  1847. elsif ($s =~ /^%.+$/) {
  1848. return sprintf ($s, $value);
  1849. }
  1850. }
  1851. return $value;
  1852. }
  1853. ######################################################################
  1854. # Log message if trace flag is set.
  1855. # Will output multiple log file entries if parameter msg is separated
  1856. # by <br>
  1857. ######################################################################
  1858. sub HMCCU_Trace ($$$$)
  1859. {
  1860. my ($hash, $level, $fnc, $msg) = @_;
  1861. my $name = $hash->{NAME};
  1862. my $type = $hash->{TYPE};
  1863. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  1864. return if ($ccuflags !~ /trace/);
  1865. foreach my $m (split ("<br>", $msg)) {
  1866. $m = "$fnc: $m" if (defined ($fnc) && $fnc ne '');
  1867. Log3 $name, $level, "$type: $m";
  1868. }
  1869. }
  1870. ######################################################################
  1871. # Log message and return parameter rc.
  1872. ######################################################################
  1873. sub HMCCU_Log ($$$$)
  1874. {
  1875. my ($hash, $level, $msg, $rc) = @_;
  1876. my $name = $hash->{NAME};
  1877. my $type = $hash->{TYPE};
  1878. Log3 $name, $level, "$type: [$name] $msg";
  1879. return $rc;
  1880. }
  1881. ######################################################################
  1882. # Set error state and write log file message
  1883. # Parameter text can be an error code (integer < 0) or an error text.
  1884. # Parameter addinfo is optional.
  1885. ######################################################################
  1886. sub HMCCU_SetError ($@)
  1887. {
  1888. my ($hash, $text, $addinfo) = @_;
  1889. my $name = $hash->{NAME};
  1890. my $type = $hash->{TYPE};
  1891. my $msg;
  1892. my %errlist = (
  1893. -1 => 'Invalid device/channel name or address',
  1894. -2 => 'Execution of CCU script or command failed',
  1895. -3 => 'Cannot detect IO device',
  1896. -4 => 'Device deleted in CCU',
  1897. -5 => 'No response from CCU',
  1898. -6 => 'Update of readings disabled. Set attribute ccureadings first',
  1899. -7 => 'Invalid channel number',
  1900. -8 => 'Invalid datapoint',
  1901. -9 => 'Interface does not support RPC calls',
  1902. -10 => 'No readable datapoints found',
  1903. -11 => 'No state channel defined',
  1904. -12 => 'No control channel defined',
  1905. -13 => 'No state datapoint defined',
  1906. -14 => 'No control datapoint defined',
  1907. -15 => 'No state values defined',
  1908. -16 => 'Cannot open file',
  1909. -17 => 'Cannot detect or create external RPC device',
  1910. -18 => 'Type of system variable not supported'
  1911. );
  1912. $msg = exists ($errlist{$text}) ? $errlist{$text} : $text;
  1913. $msg = $type.": ".$name." ". $msg;
  1914. if (defined ($addinfo) && $addinfo ne '') {
  1915. $msg .= ". $addinfo";
  1916. }
  1917. Log3 $name, 1, $msg;
  1918. return HMCCU_SetState ($hash, "Error", $msg);
  1919. }
  1920. ##################################################################
  1921. # Set state of device if attribute ccuflags = ackState
  1922. ##################################################################
  1923. sub HMCCU_SetState ($@)
  1924. {
  1925. my ($hash, $text, $retval) = @_;
  1926. my $name = $hash->{NAME};
  1927. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  1928. $ccuflags .= ',ackState' if ($hash->{TYPE} eq 'HMCCU' && $ccuflags !~ /ackState/);
  1929. if (defined ($hash) && defined ($text) && $ccuflags =~ /ackState/) {
  1930. readingsSingleUpdate ($hash, 'state', $text, 1)
  1931. if (ReadingsVal ($name, 'state', '') ne $text);
  1932. }
  1933. return $retval;
  1934. }
  1935. ######################################################################
  1936. # Set state of RPC server. Update all client devices if overall state
  1937. # is 'running'.
  1938. # Parameters iface and msg are optional. If iface is set function
  1939. # was called by HMCCURPCPROC device.
  1940. ######################################################################
  1941. sub HMCCU_SetRPCState ($@)
  1942. {
  1943. my ($hash, $state, $iface, $msg) = @_;
  1944. my $name = $hash->{NAME};
  1945. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  1946. my $filter;
  1947. my $rpcstate = $state;
  1948. if ($ccuflags =~ /(intrpc|extrpc)/ || $ccuflags !~ /(intrpc|extrpc|procrpc)/) {
  1949. if ($state ne $hash->{RPCState}) {
  1950. $hash->{RPCState} = $state;
  1951. readingsSingleUpdate ($hash, "rpcstate", $state, 1);
  1952. HMCCU_Log ($hash, 4, "Set rpcstate to $state", undef);
  1953. HMCCU_Log ($hash, 1, $msg, undef) if (defined ($msg));
  1954. HMCCU_Log ($hash, 1, "All RPC servers $state", undef);
  1955. DoTrigger ($name, "RPC server $state");
  1956. if ($state eq 'running') {
  1957. my ($c_ok, $c_err) = HMCCU_UpdateClients ($hash, '.*', 'Attr', 0, $filter);
  1958. HMCCU_Log ($hash, 2, "Updated devices. Success=$c_ok Failed=$c_err", undef);
  1959. }
  1960. }
  1961. }
  1962. elsif (defined ($iface) && $ccuflags =~ /procrpc/) {
  1963. # Set interface state
  1964. my $ifname = HMCCU_GetRPCServerInfo ($hash, $iface, 'name');
  1965. $hash->{hmccu}{interfaces}{$ifname}{state} = $state if (defined ($ifname));
  1966. # Count number of processes in state running, error or inactive
  1967. # Prepare filter for updating client devices
  1968. my %stc = ("running" => 0, "error" => 0, "inactive" => 0);
  1969. my @iflist = HMCCU_GetRPCInterfaceList ($hash);
  1970. foreach my $i (@iflist) {
  1971. my $st = $hash->{hmccu}{interfaces}{$i}{state};
  1972. $stc{$st}++ if (exists ($stc{$st}));
  1973. if ($hash->{hmccu}{interfaces}{$i}{manager} eq 'HMCCU') {
  1974. $filter = defined ($filter) ? "$filter|$i" : $i;
  1975. }
  1976. }
  1977. # Determine overall process state
  1978. my $rpcstate = 'null';
  1979. $rpcstate = "running" if ($stc{"running"} == scalar (@iflist));
  1980. $rpcstate = "inactive" if ($stc{"inactive"} == scalar (@iflist));
  1981. $rpcstate = "error" if ($stc{"error"} == scalar (@iflist));
  1982. if ($rpcstate =~ /^(running|inactive|error)$/) {
  1983. if ($rpcstate ne $hash->{RPCState}) {
  1984. $hash->{RPCState} = $rpcstate;
  1985. readingsSingleUpdate ($hash, "rpcstate", $rpcstate, 1);
  1986. HMCCU_Log ($hash, 4, "Set rpcstate to $rpcstate", undef);
  1987. HMCCU_Log ($hash, 1, $msg, undef) if (defined ($msg));
  1988. HMCCU_Log ($hash, 1, "All RPC servers $rpcstate", undef);
  1989. DoTrigger ($name, "RPC server $rpcstate");
  1990. if ($rpcstate eq 'running') {
  1991. my ($c_ok, $c_err) = HMCCU_UpdateClients ($hash, '.*', 'Attr', 0, $filter);
  1992. HMCCU_Log ($hash, 2, "Updated devices. Success=$c_ok Failed=$c_err", undef);
  1993. }
  1994. }
  1995. }
  1996. }
  1997. # Set I/O device state
  1998. if ($rpcstate eq 'running' || $rpcstate eq 'inactive') {
  1999. HMCCU_SetState ($hash, "OK");
  2000. }
  2001. elsif ($rpcstate eq 'error') {
  2002. HMCCU_SetState ($hash, "error");
  2003. }
  2004. else {
  2005. HMCCU_SetState ($hash, "busy");
  2006. }
  2007. return undef;
  2008. }
  2009. ######################################################################
  2010. # Substitute first occurrence of regular expression or fixed string.
  2011. # Floating point values are ignored without datapoint specification.
  2012. # Integer values are compared with complete value.
  2013. # mode: 0=Substitute regular expression, 1=Substitute text
  2014. ######################################################################
  2015. sub HMCCU_Substitute ($$$$$)
  2016. {
  2017. my ($value, $substrule, $mode, $chn, $dpt, $std) = @_;
  2018. my $rc = 0;
  2019. my $newvalue;
  2020. return $value if (!defined ($substrule) || $substrule eq '');
  2021. # Remove channel number from datapoint if specified
  2022. if ($dpt =~ /^([0-9]{1,2})\.(.+)$/) {
  2023. ($chn, $dpt) = ($1, $2);
  2024. }
  2025. my @rulelist = split (';', $substrule);
  2026. foreach my $rule (@rulelist) {
  2027. my @ruletoks = split ('!', $rule);
  2028. if (@ruletoks == 2 && $dpt ne '' && $mode == 0) {
  2029. my @dptlist = split (',', $ruletoks[0]);
  2030. foreach my $d (@dptlist) {
  2031. my $c = -1;
  2032. if ($d =~ /^([0-9]{1,2})\.(.+)$/) {
  2033. ($c, $d) = ($1, $2);
  2034. }
  2035. if ($d eq $dpt && ($c == -1 || !defined($chn) || $c == $chn)) {
  2036. ($rc, $newvalue) = HMCCU_SubstRule ($value, $ruletoks[1], $mode);
  2037. return $newvalue;
  2038. }
  2039. }
  2040. }
  2041. elsif (@ruletoks == 1) {
  2042. return $value if ($value !~ /^[+-]?\d+$/ && $value =~ /^[+-]?\d*\.?\d+(?:(?:e|E)\d+)?$/);
  2043. ($rc, $newvalue) = HMCCU_SubstRule ($value, $ruletoks[0], $mode);
  2044. return $newvalue if ($rc == 1);
  2045. }
  2046. }
  2047. return $value;
  2048. }
  2049. ######################################################################
  2050. # Execute substitution list.
  2051. # Syntax for single substitution: {#n-n|regexp|text}:newtext
  2052. # mode=0: Substitute regular expression
  2053. # mode=1: Substitute text (for setting statevals)
  2054. # newtext can contain ':'. Parameter ${value} in newtext is
  2055. # substituted by original value.
  2056. # Return (status, value)
  2057. # status=1: value = substituted value
  2058. # status=0: value = original value
  2059. ######################################################################
  2060. sub HMCCU_SubstRule ($$$)
  2061. {
  2062. my ($value, $substitutes, $mode ) = @_;
  2063. my $rc = 0;
  2064. $substitutes =~ s/\$\{value\}/$value/g;
  2065. my @sub_list = split /,/,$substitutes;
  2066. foreach my $s (@sub_list) {
  2067. my ($regexp, $text) = split /:/,$s,2;
  2068. next if (!defined ($regexp) || !defined($text));
  2069. if ($regexp =~ /^#([+-]?\d*\.?\d+?)\-([+-]?\d*\.?\d+?)$/) {
  2070. my ($mi, $ma) = ($1, $2);
  2071. if ($value =~ /^\d*\.?\d+?$/ && $value >= $mi && $value <= $ma) {
  2072. $value = $text;
  2073. $rc = 1;
  2074. }
  2075. }
  2076. if ($mode == 0 && $value =~ /$regexp/ && $value !~ /^[+-]?\d+$/) {
  2077. my $x = eval { $value =~ s/$regexp/$text/ };
  2078. $rc = 1 if (defined ($x));
  2079. last;
  2080. }
  2081. elsif (($mode == 1 || $value =~/^[+-]?\d+$/) && $value =~ /^$regexp$/) {
  2082. my $x = eval { $value =~ s/^$regexp$/$text/ };
  2083. $rc = 1 if (defined ($x));
  2084. last;
  2085. }
  2086. }
  2087. return ($rc, $value);
  2088. }
  2089. ######################################################################
  2090. # Substitute datapoint variables in string by datapoint value. The
  2091. # value depends on the character preceding the variable name. Syntax
  2092. # of variable names is:
  2093. # {$|$$|%|%%}{[cn.]Name}
  2094. # {$|$$|%|%%}[cn.]Name
  2095. # % = Original / raw value
  2096. # %% = Previous original / raw value
  2097. # $ = Converted / formatted value
  2098. # $$ = Previous converted / formatted value
  2099. ######################################################################
  2100. sub HMCCU_SubstVariables ($$$)
  2101. {
  2102. my ($clhash, $text, $dplist) = @_;
  2103. my @varlist;
  2104. if (defined ($dplist)) {
  2105. @varlist = split (',', $dplist);
  2106. }
  2107. else {
  2108. @varlist = keys %{$clhash->{hmccu}{dp}};
  2109. }
  2110. # Substitute datapoint variables by value
  2111. foreach my $dp (@varlist) {
  2112. my ($chn, $dpt) = split (/\./, $dp);
  2113. if (defined ($clhash->{hmccu}{dp}{$dp}{OSVAL})) {
  2114. $text =~ s/\$\$\{?$dp\}?/$clhash->{hmccu}{dp}{$dp}{OSVAL}/g;
  2115. $text =~ s/\$\$\{?$dpt\}?/$clhash->{hmccu}{dp}{$dp}{OSVAL}/g;
  2116. }
  2117. if (defined ($clhash->{hmccu}{dp}{$dp}{SVAL})) {
  2118. $text =~ s/\$\{?$dp\}?/$clhash->{hmccu}{dp}{$dp}{SVAL}/g;
  2119. $text =~ s/\$\{?$dpt\}?/$clhash->{hmccu}{dp}{$dp}{SVAL}/g;
  2120. }
  2121. if (defined ($clhash->{hmccu}{dp}{$dp}{OVAL})) {
  2122. $text =~ s/\%\%\{?$dp\}?/$clhash->{hmccu}{dp}{$dp}{OVAL}/g;
  2123. $text =~ s/\%\%\{?$dpt\}?/$clhash->{hmccu}{dp}{$dp}{OVAL}/g;
  2124. }
  2125. if (defined ($clhash->{hmccu}{dp}{$dp}{VAL})) {
  2126. $text =~ s/\%\{?$dp\}?/$clhash->{hmccu}{dp}{$dp}{VAL}/g;
  2127. $text =~ s/\%\{?$dpt\}?/$clhash->{hmccu}{dp}{$dp}{VAL}/g;
  2128. }
  2129. }
  2130. return $text;
  2131. }
  2132. ######################################################################
  2133. # Update all datapoint/readings of all client devices matching
  2134. # specified regular expression. Update will fail if device is deleted
  2135. # or disabled or if attribute ccureadings of a device is set to 0.
  2136. # If fromccu is 1 regular expression is compared to CCU device name.
  2137. # Otherwise it's compared to FHEM device name. If ifname is specified
  2138. # only devices belonging to interface ifname are updated.
  2139. ######################################################################
  2140. sub HMCCU_UpdateClients ($$$$$)
  2141. {
  2142. my ($hash, $devexp, $ccuget, $fromccu, $ifname) = @_;
  2143. my $fhname = $hash->{NAME};
  2144. my $c_ok = 0;
  2145. my $c_err = 0;
  2146. my $filter = "ccudevstate=active";
  2147. $filter .= ",ccuif=$ifname" if (defined ($ifname));
  2148. if ($fromccu) {
  2149. foreach my $name (sort keys %{$hash->{hmccu}{adr}}) {
  2150. next if ($name !~ /$devexp/ || !($hash->{hmccu}{adr}{$name}{valid}));
  2151. my @devlist = HMCCU_FindClientDevices ($hash, "(HMCCUDEV|HMCCUCHN)", undef, $filter);
  2152. foreach my $d (@devlist) {
  2153. my $ch = $defs{$d};
  2154. next if (!defined ($ch->{IODev}) || !defined ($ch->{ccuaddr}));
  2155. next if ($ch->{ccuaddr} ne $hash->{hmccu}{adr}{$name}{address});
  2156. my $rc = HMCCU_GetUpdate ($ch, $hash->{hmccu}{adr}{$name}{address}, $ccuget);
  2157. if ($rc <= 0) {
  2158. if ($rc == -10) {
  2159. Log3 $fhname, 3, "HMCCU: Device $name has no readable datapoints";
  2160. }
  2161. else {
  2162. Log3 $fhname, 2, "HMCCU: Update of device $name failed";
  2163. }
  2164. $c_err++;
  2165. }
  2166. else {
  2167. $c_ok++;
  2168. }
  2169. }
  2170. }
  2171. }
  2172. else {
  2173. my @devlist = HMCCU_FindClientDevices ($hash, "(HMCCUDEV|HMCCUCHN)", $devexp, $filter);
  2174. Log3 $fhname, 2, "HMCCU: No client devices matching $devexp" if (scalar (@devlist) == 0);
  2175. foreach my $d (@devlist) {
  2176. my $ch = $defs{$d};
  2177. next if (!defined ($ch->{IODev}) || !defined ($ch->{ccuaddr}));
  2178. my $rc = HMCCU_GetUpdate ($ch, $ch->{ccuaddr}, $ccuget);
  2179. if ($rc <= 0) {
  2180. if ($rc == -10) {
  2181. Log3 $fhname, 3, "HMCCU: Device ".$ch->{ccuaddr}." has no readable datapoints";
  2182. }
  2183. else {
  2184. Log3 $fhname, 2, "HMCCU: Update of device ".$ch->{ccuaddr}." failed"
  2185. if ($ch->{ccuif} ne 'VirtualDevices');
  2186. }
  2187. $c_err++;
  2188. }
  2189. else {
  2190. $c_ok++;
  2191. }
  2192. }
  2193. }
  2194. return ($c_ok, $c_err);
  2195. }
  2196. ##########################################################################
  2197. # Update parameters in internal device tables and client devices.
  2198. # Parameter devices is a hash reference with following keys:
  2199. # {address}
  2200. # {address}{flag} := [N, D, R] (N=New, D=Deleted, R=Renamed)
  2201. # {address}{addtype} := [chn, dev]
  2202. # {address}{channels} := Number of channels
  2203. # {address}{name} := Device or channel name
  2204. # {address}{type} := Homematic device type
  2205. # {address}{usetype} := Usage type
  2206. # {address}{interface} := Device interface ID
  2207. # {address}{firmware} := Firmware version of device
  2208. # {address}{version} := Version of RPC device description
  2209. # {address}{rxmode} := Transmit mode
  2210. # {address}{chndir} := Channel direction: 0=none, 1=sensor, 2=actor
  2211. # If flag is 'D' the hash must contain an entry for the device address
  2212. # and for each channel address.
  2213. ##########################################################################
  2214. sub HMCCU_UpdateDeviceTable ($$)
  2215. {
  2216. my ($hash, $devices) = @_;
  2217. my $name = $hash->{NAME};
  2218. my $devcount = 0;
  2219. my $chncount = 0;
  2220. # Update internal device table
  2221. foreach my $da (keys %{$devices}) {
  2222. my $nm = $hash->{hmccu}{dev}{$da}{name} if (defined ($hash->{hmccu}{dev}{$da}{name}));
  2223. $nm = $devices->{$da}{name} if (defined ($devices->{$da}{name}));
  2224. if ($devices->{$da}{flag} eq 'N' && defined ($nm)) {
  2225. my $at = '';
  2226. if (defined ($devices->{$da}{addtype})) {
  2227. $at = $devices->{$da}{addtype};
  2228. }
  2229. else {
  2230. $at = 'chn' if (HMCCU_IsChnAddr ($da, 0));
  2231. $at = 'dev' if (HMCCU_IsDevAddr ($da, 0));
  2232. }
  2233. if ($at eq '') {
  2234. Log3 $name, 2, "HMCCU: Cannot detect type of address $da";
  2235. next;
  2236. }
  2237. Log3 $name, 2, "HMCCU: Duplicate name for device/channel $nm address=$da in CCU."
  2238. if (exists ($hash->{hmccu}{adr}{$nm}) && $at ne $hash->{hmccu}{adr}{$nm}{addtype});
  2239. # Updated or new device/channel
  2240. $hash->{hmccu}{dev}{$da}{addtype} = $at;
  2241. $hash->{hmccu}{dev}{$da}{name} = $nm if (defined ($nm));
  2242. $hash->{hmccu}{dev}{$da}{valid} = 1;
  2243. $hash->{hmccu}{dev}{$da}{channels} = $devices->{$da}{channels}
  2244. if (defined ($devices->{$da}{channels}));
  2245. $hash->{hmccu}{dev}{$da}{type} = $devices->{$da}{type}
  2246. if (defined ($devices->{$da}{type}));
  2247. $hash->{hmccu}{dev}{$da}{usetype} = $devices->{$da}{usetype}
  2248. if (defined ($devices->{$da}{usetype}));
  2249. $hash->{hmccu}{dev}{$da}{interface} = $devices->{$da}{interface}
  2250. if (defined ($devices->{$da}{interface}));
  2251. $hash->{hmccu}{dev}{$da}{version} = $devices->{$da}{version}
  2252. if (defined ($devices->{$da}{version}));
  2253. $hash->{hmccu}{dev}{$da}{firmware} = $devices->{$da}{firmware}
  2254. if (defined ($devices->{$da}{firmware}));
  2255. $hash->{hmccu}{dev}{$da}{rxmode} = $devices->{$da}{rxmode}
  2256. if (defined ($devices->{$da}{rxmode}));
  2257. $hash->{hmccu}{dev}{$da}{chndir} = $devices->{$da}{chndir}
  2258. if (defined ($devices->{$da}{chndir}));
  2259. $hash->{hmccu}{adr}{$nm}{address} = $da;
  2260. $hash->{hmccu}{adr}{$nm}{addtype} = $hash->{hmccu}{dev}{$da}{addtype};
  2261. $hash->{hmccu}{adr}{$nm}{valid} = 1 if (defined ($nm));
  2262. }
  2263. elsif ($devices->{$da}{flag} eq 'D' && exists ($hash->{hmccu}{dev}{$da})) {
  2264. # Device deleted, mark as invalid
  2265. $hash->{hmccu}{dev}{$da}{valid} = 0;
  2266. $hash->{hmccu}{adr}{$nm}{valid} = 0 if (defined ($nm));
  2267. }
  2268. elsif ($devices->{$da}{flag} eq 'R' && exists ($hash->{hmccu}{dev}{$da})) {
  2269. # Device replaced, change address
  2270. my $na = $devices->{hmccu}{newaddr};
  2271. # Copy device entries and delete old device entries
  2272. foreach my $k (keys %{$hash->{hmccu}{dev}{$da}}) {
  2273. $hash->{hmccu}{dev}{$na}{$k} = $hash->{hmccu}{dev}{$da}{$k};
  2274. }
  2275. $hash->{hmccu}{adr}{$nm}{address} = $na;
  2276. delete $hash->{hmccu}{dev}{$da};
  2277. }
  2278. }
  2279. # Update client devices
  2280. my @devlist = HMCCU_FindClientDevices ($hash, "(HMCCUDEV|HMCCUCHN)", undef, undef);
  2281. foreach my $d (@devlist) {
  2282. my $ch = $defs{$d};
  2283. my $ct = $ch->{TYPE};
  2284. my $ca = $ch->{ccuaddr};
  2285. next if (!exists ($devices->{$ca}));
  2286. if ($devices->{$ca}{flag} eq 'N') {
  2287. # New device or new device information
  2288. $ch->{ccudevstate} = 'active';
  2289. if ($ct eq 'HMCCUDEV') {
  2290. $ch->{ccutype} = $hash->{hmccu}{dev}{$ca}{type}
  2291. if (defined ($hash->{hmccu}{dev}{$ca}{type}));
  2292. $ch->{firmware} = $devices->{$ca}{firmware}
  2293. if (defined ($devices->{$ca}{firmware}));
  2294. }
  2295. else {
  2296. $ch->{chntype} = $devices->{$ca}{usetype}
  2297. if (defined ($devices->{$ca}{usetype}));
  2298. my ($add, $chn) = HMCCU_SplitChnAddr ($ca);
  2299. $ch->{ccutype} = $devices->{$add}{type}
  2300. if (defined ($devices->{$add}{type}));
  2301. $ch->{firmware} = $devices->{$add}{firmware}
  2302. if (defined ($devices->{$add}{firmware}));
  2303. }
  2304. $ch->{ccuname} = $hash->{hmccu}{dev}{$ca}{name}
  2305. if (defined ($hash->{hmccu}{dev}{$ca}{name}));
  2306. $ch->{ccuif} = $hash->{hmccu}{dev}{$ca}{interface}
  2307. if (defined ($devices->{$ca}{interface}));
  2308. $ch->{channels} = $hash->{hmccu}{dev}{$ca}{channels}
  2309. if (defined ($hash->{hmccu}{dev}{$ca}{channels}));
  2310. }
  2311. elsif ($devices->{$ca}{flag} eq 'D') {
  2312. # Deleted device
  2313. $ch->{ccudevstate} = 'deleted';
  2314. }
  2315. elsif ($devices->{$ca}{flag} eq 'R') {
  2316. # Replaced device
  2317. $ch->{ccuaddr} = $devices->{$ca}{newaddr};
  2318. }
  2319. }
  2320. # Update internals of I/O device
  2321. foreach my $adr (keys %{$hash->{hmccu}{dev}}) {
  2322. if (exists ($hash->{hmccu}{dev}{$adr}{addtype})) {
  2323. $devcount++ if ($hash->{hmccu}{dev}{$adr}{addtype} eq 'dev');
  2324. $chncount++ if ($hash->{hmccu}{dev}{$adr}{addtype} eq 'chn');
  2325. }
  2326. }
  2327. $hash->{ccudevices} = $devcount;
  2328. $hash->{ccuchannels} = $chncount;
  2329. return ($devcount, $chncount);
  2330. }
  2331. ######################################################################
  2332. # Update a single client device datapoint considering scaling, reading
  2333. # format and value substitution.
  2334. # Return stored value.
  2335. ######################################################################
  2336. sub HMCCU_UpdateSingleDatapoint ($$$$)
  2337. {
  2338. my ($hash, $chn, $dpt, $value) = @_;
  2339. my $hmccu_hash = HMCCU_GetHash ($hash);
  2340. return $value if (!defined ($hmccu_hash));
  2341. my %objects;
  2342. my $ccuaddr = $hash->{ccuaddr};
  2343. my ($devaddr, $chnnum) = HMCCU_SplitChnAddr ($ccuaddr);
  2344. $objects{$devaddr}{$chn}{$dpt} = $value;
  2345. my $rc = HMCCU_UpdateSingleDevice ($hmccu_hash, $hash, \%objects);
  2346. return (ref ($rc)) ? $rc->{$devaddr}{$chn}{$dpt} : $value;
  2347. }
  2348. ######################################################################
  2349. # Update readings of client device.
  2350. # Parameter objects is a hash reference which contains updated data
  2351. # for any device:
  2352. # {devaddr}{channelno}{datapoint} = value
  2353. # If client device is virtual device group: check if group members are
  2354. # affected by updates and update readings in virtual group device.
  2355. # Return a hash reference with datapoints and new values:
  2356. # {devaddr}{datapoint} = value
  2357. ######################################################################
  2358. sub HMCCU_UpdateSingleDevice ($$$)
  2359. {
  2360. my ($ccuhash, $clthash, $objects) = @_;
  2361. my $ccuname = $ccuhash->{NAME};
  2362. my $cltname = $clthash->{NAME};
  2363. my $clttype = $clthash->{TYPE};
  2364. my $fnc = "UpdateSingleDevice";
  2365. return 0 if (!defined ($clthash->{IODev}) || !defined ($clthash->{ccuaddr}));
  2366. return 0 if ($clthash->{IODev} != $ccuhash);
  2367. # Check for updated data
  2368. my ($devaddr, $cnum) = HMCCU_SplitChnAddr ($clthash->{ccuaddr});
  2369. return 0 if (!exists ($objects->{$devaddr}));
  2370. return 0 if ($clttype eq 'HMCUCCHN' && !exists ($objects->{$devaddr}{$cnum}) &&
  2371. !exists ($objects->{$devaddr}{0}));
  2372. my $ccuflags = AttrVal ($ccuname, 'ccuflags', 'null');
  2373. # Build device list including virtual devices
  2374. my @grplist = ($cltname);
  2375. my @virlist = HMCCU_FindClientDevices ($ccuhash, "HMCCUDEV", undef, "ccuif=VirtualDevices");
  2376. foreach my $vd (@virlist) {
  2377. my $vh = $defs{$vd};
  2378. next if (!defined ($vh->{ccugroup}));
  2379. foreach my $gadd (split (",", $vh->{ccugroup})) {
  2380. if ("$gadd" eq "$devaddr") {
  2381. push @grplist, $vd;
  2382. last;
  2383. }
  2384. }
  2385. }
  2386. HMCCU_Trace ($clthash, 2, $fnc,
  2387. "$cltname Virlist = ".join(',', @virlist)."<br>".
  2388. "$cltname Grplist = ".join(',', @grplist)."<br>".
  2389. "$cltname Objects = ".join(',', keys %{$objects}));
  2390. # Store the resulting readings
  2391. my %results;
  2392. # Update device considering foreign device data assigned to group device
  2393. foreach my $cn (@grplist) {
  2394. my $ch = $defs{$cn};
  2395. my $ct = $ch->{TYPE};
  2396. my $disable = AttrVal ($cn, 'disable', 0);
  2397. my $update = AttrVal ($cn, 'ccureadings', 1);
  2398. next if ($update == 0 || $disable == 1);
  2399. my $cf = AttrVal ($cn, 'ccuflags', 'null');
  2400. my $peer = AttrVal ($cn, 'peer', 'null');
  2401. HMCCU_Trace ($ch, 2, $fnc, "Processing device $cn");
  2402. my $crf = HMCCU_GetAttrReadingFormat ($ch, $ccuhash);
  2403. my $substitute = HMCCU_GetAttrSubstitute ($ch, $ccuhash);
  2404. my ($sc, $st, $cc, $cd) = HMCCU_GetSpecialDatapoints ($ch, '', 'STATE', '', '');
  2405. my @devlist = ($ch->{ccuaddr});
  2406. push @devlist, split (",", $ch->{ccugroup})
  2407. if ($ch->{ccuif} eq 'VirtualDevices' && exists ($ch->{ccugroup}));
  2408. readingsBeginUpdate ($ch);
  2409. # Update devices
  2410. foreach my $dev (@devlist) {
  2411. my ($da, $cnum) = HMCCU_SplitChnAddr ($dev);
  2412. next if (!exists ($objects->{$da}));
  2413. next if ($clttype eq 'HMCUCCHN' && !exists ($objects->{$da}{$cnum}) &&
  2414. !exists ($objects->{$da}{0}));
  2415. # Update channels of device
  2416. foreach my $chnnum (keys (%{$objects->{$da}})) {
  2417. next if ($ct eq 'HMCCUCHN' && "$chnnum" ne "$cnum" && "$chnnum" ne "0");
  2418. next if ("$chnnum" eq "0" && $cf =~ /nochn0/);
  2419. my $chnadd = "$da:$chnnum";
  2420. # Update datapoints of channel
  2421. foreach my $dpt (keys (%{$objects->{$da}{$chnnum}})) {
  2422. my $value = $objects->{$da}{$chnnum}{$dpt};
  2423. next if (!defined ($value));
  2424. # Store datapoint raw value in device hash
  2425. if (exists ($clthash->{hmccu}{dp}{"$chnnum.$dpt"}{VAL})) {
  2426. $clthash->{hmccu}{dp}{"$chnnum.$dpt"}{OVAL} = $clthash->{hmccu}{dp}{"$chnnum.$dpt"}{VAL};
  2427. }
  2428. else {
  2429. $clthash->{hmccu}{dp}{"$chnnum.$dpt"}{OVAL} = $value;
  2430. }
  2431. $clthash->{hmccu}{dp}{"$chnnum.$dpt"}{VAL} = $value;
  2432. HMCCU_Trace ($ch, 2, $fnc, "dev=$cn, chnadd=$chnadd, dpt=$dpt, value=$value");
  2433. if (HMCCU_FilterReading ($ch, $chnadd, $dpt)) {
  2434. my @readings = HMCCU_GetReadingName ($ch, '', $da, $chnnum, $dpt, '', $crf);
  2435. my $svalue = HMCCU_ScaleValue ($ch, $dpt, $value, 0);
  2436. my $fvalue = HMCCU_FormatReadingValue ($ch, $svalue, $dpt);
  2437. my $cvalue = HMCCU_Substitute ($fvalue, $substitute, 0, $chnnum, $dpt);
  2438. my %calcs = HMCCU_CalculateReading ($ch, $chnnum, $dpt);
  2439. # Store the resulting value after scaling, formatting and substitution
  2440. if (exists ($clthash->{hmccu}{dp}{"$chnnum.$dpt"}{OSVAL})) {
  2441. $clthash->{hmccu}{dp}{"$chnnum.$dpt"}{OSVAL} = $clthash->{hmccu}{dp}{"$chnnum.$dpt"}{SVAL};
  2442. }
  2443. else {
  2444. $clthash->{hmccu}{dp}{"$chnnum.$dpt"}{OSVAL} = $cvalue;
  2445. }
  2446. $clthash->{hmccu}{dp}{"$chnnum.$dpt"}{SVAL} = $cvalue;
  2447. $results{$da}{$chnnum}{$dpt} = $cvalue;
  2448. HMCCU_Trace ($ch, 2, $fnc,
  2449. "device=$cltname, readings=".join(',', @readings).
  2450. ", orgvalue=$value value=$cvalue peer=$peer");
  2451. # Update readings
  2452. foreach my $rn (@readings) {
  2453. HMCCU_BulkUpdate ($ch, $rn, $fvalue, $cvalue) if ($rn ne '');
  2454. }
  2455. foreach my $clcr (keys %calcs) {
  2456. HMCCU_BulkUpdate ($ch, $clcr, $calcs{$clcr}, $calcs{$clcr});
  2457. }
  2458. HMCCU_BulkUpdate ($ch, 'control', $fvalue, $cvalue)
  2459. if ($cd ne '' && $dpt eq $cd && $chnnum eq $cc);
  2460. HMCCU_BulkUpdate ($ch, 'state', $fvalue, $cvalue)
  2461. if ($dpt eq $st && ($sc eq '' || $sc eq $chnnum));
  2462. # Update peers
  2463. HMCCU_UpdatePeers ($ch, "$chnnum.$dpt", $cvalue, $peer) if ($peer ne 'null');
  2464. }
  2465. }
  2466. }
  2467. }
  2468. # Calculate and update HomeMatic state
  2469. if ($ccuflags !~ /nohmstate/) {
  2470. my ($hms_read, $hms_chn, $hms_dpt, $hms_val) = HMCCU_GetHMState ($cn, $ccuname, undef);
  2471. HMCCU_BulkUpdate ($ch, $hms_read, $hms_val, $hms_val) if (defined ($hms_val));
  2472. }
  2473. readingsEndUpdate ($ch, 1);
  2474. }
  2475. return \%results;
  2476. }
  2477. ######################################################################
  2478. # Update readings of multiple client devices.
  2479. # Parameter objects is a hash reference:
  2480. # {devaddr}
  2481. # {devaddr}{channelno}
  2482. # {devaddr}{channelno}{datapoint} = value
  2483. # Return number of updated devices.
  2484. ######################################################################
  2485. sub HMCCU_UpdateMultipleDevices ($$)
  2486. {
  2487. my ($hash, $objects) = @_;
  2488. my $name = $hash->{NAME};
  2489. my $fnc = "UpdateMultipleDevices";
  2490. my $c = 0;
  2491. # Check syntax
  2492. return 0 if (!defined ($hash) || !defined ($objects));
  2493. # Update reading in matching client devices
  2494. my @devlist = HMCCU_FindClientDevices ($hash, "(HMCCUDEV|HMCCUCHN)", undef,
  2495. "ccudevstate=active");
  2496. foreach my $d (@devlist) {
  2497. my $ch = $defs{$d};
  2498. my $rc = HMCCU_UpdateSingleDevice ($hash, $ch, $objects);
  2499. $c++ if (ref ($rc));
  2500. }
  2501. return $c;
  2502. }
  2503. ######################################################################
  2504. # Update peer devices.
  2505. # Syntax of peer definitions is:
  2506. # channel.datapoint[,...]:condition:type:action
  2507. # condition := valid perl expression. Any channel.datapoint
  2508. # combination is substituted by the corresponding value. If channel
  2509. # is preceded by a % it's substituted by the raw value. If it's
  2510. # preceded by a $ it's substituted by the formated/converted value.
  2511. # If % or $ is doubled the old values are used.
  2512. # type := type of action. Valid types are ccu, hmccu and fhem.
  2513. # action := Action to be performed if result of condition is true.
  2514. # Depending on type action type this could be an assignment or a
  2515. # FHEM command. If action contains $value this parameter is
  2516. # substituted by the original value of the datapoint which has
  2517. # triggered the action.
  2518. # assignment := channel.datapoint=expression
  2519. ######################################################################
  2520. sub HMCCU_UpdatePeers ($$$$)
  2521. {
  2522. my ($clt_hash, $chndpt, $val, $peerattr) = @_;
  2523. my $fnc = "UpdatePeers";
  2524. HMCCU_Trace ($clt_hash, 2, $fnc, "chndpt=$chndpt val=$val peer=$peerattr");
  2525. my @rules = split (/[;\n]+/, $peerattr);
  2526. foreach my $r (@rules) {
  2527. HMCCU_Trace ($clt_hash, 2, $fnc, "rule=$r");
  2528. my ($vars, $cond, $type, $act) = split (/:/, $r, 4);
  2529. next if (!defined ($act));
  2530. HMCCU_Trace ($clt_hash, 2, $fnc, "vars=$vars, cond=$cond, type=$type, act=$act");
  2531. next if ($cond !~ /$chndpt/);
  2532. # Check if rule is affected by datapoint update
  2533. my $ex = 0;
  2534. foreach my $dpt (split (",", $vars)) {
  2535. HMCCU_Trace ($clt_hash, 2, $fnc, "dpt=$dpt");
  2536. $ex = 1 if ($ex == 0 && $dpt eq $chndpt);
  2537. if (!exists ($clt_hash->{hmccu}{dp}{$dpt})) {
  2538. HMCCU_Trace ($clt_hash, 2, $fnc, "Datapoint $dpt does not exist on hash");
  2539. }
  2540. last if ($ex == 1);
  2541. }
  2542. next if (! $ex);
  2543. # Substitute variables and evaluate condition
  2544. $cond = HMCCU_SubstVariables ($clt_hash, $cond, $vars);
  2545. my $e = eval "$cond";
  2546. HMCCU_Trace ($clt_hash, 2, $fnc, "eval $cond = $e") if (defined ($e));
  2547. HMCCU_Trace ($clt_hash, 2, $fnc, "Error in eval $cond") if (!defined ($e));
  2548. HMCCU_Trace ($clt_hash, 2, $fnc, "NoMatch in eval $cond") if (defined ($e) && $e eq '');
  2549. next if (!defined ($e) || $e eq '');
  2550. # Substitute variables and execute action
  2551. if ($type eq 'ccu' || $type eq 'hmccu') {
  2552. my ($aobj, $aexp) = split (/=/, $act);
  2553. $aexp =~ s/\$value/$val/g;
  2554. $aexp = HMCCU_SubstVariables ($clt_hash, $aexp, $vars);
  2555. HMCCU_Trace ($clt_hash, 2, $fnc, "set $aobj to $aexp");
  2556. HMCCU_SetDatapoint ($clt_hash, "$type:$aobj", $aexp);
  2557. }
  2558. elsif ($type eq 'fhem') {
  2559. $act =~ s/\$value/$val/g;
  2560. $act = HMCCU_SubstVariables ($clt_hash, $act, $vars);
  2561. HMCCU_Trace ($clt_hash, 2, $fnc, "Execute command $act");
  2562. AnalyzeCommandChain (undef, $act);
  2563. }
  2564. }
  2565. }
  2566. ######################################################################
  2567. # Get list of valid RPC interfaces.
  2568. # Binary interfaces are ignored if internal RPC server is used.
  2569. # Default interface is BidCos-RF.
  2570. ######################################################################
  2571. sub HMCCU_GetRPCInterfaceList ($)
  2572. {
  2573. my ($hash) = @_;
  2574. my $name = $hash->{NAME};
  2575. my @interfaces = ($HMCCU_RPC_INTERFACE_DEFAULT);
  2576. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  2577. if (defined ($hash->{hmccu}{rpcports})) {
  2578. foreach my $p (split (',', $hash->{hmccu}{rpcports})) {
  2579. my $ifname = HMCCU_GetRPCServerInfo ($hash, $p, 'name');
  2580. next if (!defined ($ifname));
  2581. my $iftype = HMCCU_GetRPCServerInfo ($hash, $ifname, 'type');
  2582. next if ($ifname eq $HMCCU_RPC_INTERFACE_DEFAULT ||
  2583. ($iftype eq 'B' && $ccuflags !~ /(extrpc|procrpc)/) ||
  2584. !exists ($hash->{hmccu}{interfaces}{$ifname}));
  2585. push (@interfaces, $ifname);
  2586. }
  2587. }
  2588. return @interfaces;
  2589. }
  2590. ######################################################################
  2591. # Get list of valid RPC ports.
  2592. # Binary interfaces are ignored if internal RPC server is used.
  2593. # Default port is 2001.
  2594. ######################################################################
  2595. sub HMCCU_GetRPCPortList ($)
  2596. {
  2597. my ($hash) = @_;
  2598. my $name = $hash->{NAME};
  2599. my @ports = ($HMCCU_RPC_PORT_DEFAULT);
  2600. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  2601. if (defined ($hash->{hmccu}{rpcports})) {
  2602. foreach my $p (split (',', $hash->{hmccu}{rpcports})) {
  2603. my $ifname = HMCCU_GetRPCServerInfo ($hash, $p, 'name');
  2604. next if (!defined ($ifname));
  2605. my $iftype = HMCCU_GetRPCServerInfo ($hash, $ifname, 'type');
  2606. next if ($p == $HMCCU_RPC_PORT_DEFAULT ||
  2607. ($iftype eq 'B' && $ccuflags !~ /(extrpc|procrpc)/) ||
  2608. !exists ($hash->{hmccu}{interfaces}{$ifname}));
  2609. push (@ports, $p);
  2610. }
  2611. }
  2612. return @ports;
  2613. }
  2614. ######################################################################
  2615. # Build RPC callback URL
  2616. # Parameter hash might be a HMCCU or a HMCCURPC hash.
  2617. ######################################################################
  2618. sub HMCCU_GetRPCCallbackURL ($$$$$)
  2619. {
  2620. my ($hash, $localaddr, $cbport, $clkey, $iface) = @_;
  2621. return undef if (!defined ($hash));
  2622. my $hmccu_hash = $hash->{TYPE} eq 'HMCCURPC' ? $hash->{IODev} : $hash;
  2623. return undef if (!exists ($hmccu_hash->{hmccu}{interfaces}{$iface}) &&
  2624. !exists ($hmccu_hash->{hmccu}{ifports}{$iface}));
  2625. my $ifname = $iface =~ /^[0-9]+$/ ? $hmccu_hash->{hmccu}{ifports}{$iface} : $iface;
  2626. return undef if (!exists ($hmccu_hash->{hmccu}{interfaces}{$ifname}));
  2627. return $hmccu_hash->{hmccu}{interfaces}{$ifname}{prot}."://$localaddr:$cbport/fh".
  2628. $hmccu_hash->{hmccu}{interfaces}{$ifname}{port};
  2629. }
  2630. ######################################################################
  2631. # Get RPC server information.
  2632. # Parameter iface can be a port number or an interface name.
  2633. # Valid values for info are:
  2634. # url, port, prot, host, type, name, flags, device.
  2635. ######################################################################
  2636. sub HMCCU_GetRPCServerInfo ($$$)
  2637. {
  2638. my ($hash, $iface, $info) = @_;
  2639. return undef if (!defined ($hash));
  2640. return undef if (!exists ($hash->{hmccu}{interfaces}{$iface}) &&
  2641. !exists ($hash->{hmccu}{ifports}{$iface}));
  2642. my $ifname = $iface =~ /^[0-9]+$/ ? $hash->{hmccu}{ifports}{$iface} : $iface;
  2643. return undef if (!exists ($hash->{hmccu}{interfaces}{$ifname}));
  2644. return $ifname if ($info eq 'name');
  2645. return $hash->{hmccu}{interfaces}{$ifname}{$info};
  2646. }
  2647. ######################################################################
  2648. # Check if RPC interface is of specified type.
  2649. # Parameter type is A for XML or B for binary.
  2650. ######################################################################
  2651. sub HMCCU_IsRPCType ($$$)
  2652. {
  2653. my ($hash, $iface, $type) = @_;
  2654. my $rpctype = HMCCU_GetRPCServerInfo ($hash, $iface, 'type');
  2655. return 0 if (!defined ($rpctype));
  2656. return $rpctype eq $type ? 1 : 0;
  2657. }
  2658. ######################################################################
  2659. # Register RPC callbacks at CCU if RPC-Server already in server loop
  2660. ######################################################################
  2661. sub HMCCU_RPCRegisterCallback ($)
  2662. {
  2663. my ($hash) = @_;
  2664. my $name = $hash->{NAME};
  2665. my $localaddr = $hash->{hmccu}{localaddr};
  2666. my $rpcinterval = AttrVal ($name, 'rpcinterval', $HMCCU_INIT_INTERVAL2);
  2667. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  2668. my @rpcports = HMCCU_GetRPCPortList ($hash);
  2669. foreach my $port (@rpcports) {
  2670. my $clkey = 'CB'.$port;
  2671. my $cburl = HMCCU_GetRPCCallbackURL ($hash, $localaddr, $hash->{hmccu}{rpc}{$clkey}{cbport},
  2672. $clkey, $port);
  2673. next if (!defined ($cburl));
  2674. my $url = HMCCU_GetRPCServerInfo ($hash, $port, 'url');
  2675. next if (!defined ($url));
  2676. my $rpcflags = HMCCU_GetRPCServerInfo ($hash, $port, 'flags');
  2677. if ($hash->{hmccu}{rpc}{$clkey}{loop} == 1 ||
  2678. $hash->{hmccu}{rpc}{$clkey}{state} eq "register") {
  2679. $hash->{hmccu}{rpc}{$clkey}{port} = $port;
  2680. $hash->{hmccu}{rpc}{$clkey}{clurl} = $url;
  2681. $hash->{hmccu}{rpc}{$clkey}{cburl} = $cburl;
  2682. $hash->{hmccu}{rpc}{$clkey}{loop} = 2;
  2683. $hash->{hmccu}{rpc}{$clkey}{state} = $rpcflags =~ /forceInit/ ? "running" : "registered";
  2684. Log3 $name, 1, "HMCCU: Registering callback $cburl with ID $clkey at $url";
  2685. my $rpcclient = RPC::XML::Client->new ($url);
  2686. $rpcclient->send_request ("init", $cburl, $clkey);
  2687. Log3 $name, 1, "HMCCU: RPC callback with URL $cburl initialized";
  2688. }
  2689. }
  2690. # Schedule reading of RPC queue
  2691. InternalTimer (gettimeofday()+$rpcinterval, 'HMCCU_ReadRPCQueue', $hash, 0);
  2692. }
  2693. ######################################################################
  2694. # Deregister RPC callbacks at CCU
  2695. ######################################################################
  2696. sub HMCCU_RPCDeRegisterCallback ($)
  2697. {
  2698. my ($hash) = @_;
  2699. my $name = $hash->{NAME};
  2700. foreach my $clkey (keys %{$hash->{hmccu}{rpc}}) {
  2701. my $rpchash = \%{$hash->{hmccu}{rpc}{$clkey}};
  2702. if (exists ($rpchash->{cburl}) && $rpchash->{cburl} ne '') {
  2703. my $port = $rpchash->{port};
  2704. my $rpcclient = RPC::XML::Client->new ($rpchash->{clurl});
  2705. Log3 $name, 1, "HMCCU: Deregistering RPC server ".$rpchash->{cburl}.
  2706. " at ".$rpchash->{clurl};
  2707. $rpcclient->send_request("init", $rpchash->{cburl});
  2708. $rpchash->{cburl} = '';
  2709. $rpchash->{clurl} = '';
  2710. $rpchash->{cbport} = 0;
  2711. }
  2712. }
  2713. }
  2714. ######################################################################
  2715. # Initialize statistic counters
  2716. ######################################################################
  2717. sub HMCCU_ResetCounters ($)
  2718. {
  2719. my ($hash) = @_;
  2720. my @counters = ('total', 'EV', 'ND', 'IN', 'DD', 'RA', 'RD', 'UD', 'EX', 'SL', 'ST');
  2721. foreach my $cnt (@counters) {
  2722. $hash->{hmccu}{ev}{$cnt} = 0;
  2723. }
  2724. delete $hash->{hmccu}{evs};
  2725. delete $hash->{hmccu}{evr};
  2726. $hash->{hmccu}{evtimeout} = 0;
  2727. $hash->{hmccu}{evtime} = 0;
  2728. }
  2729. ######################################################################
  2730. # Start external RPC server via RPC device.
  2731. # Return number of RPC servers or 0 on error.
  2732. ######################################################################
  2733. sub HMCCU_StartExtRPCServer ($)
  2734. {
  2735. my ($hash) = @_;
  2736. my $name = $hash->{NAME};
  2737. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  2738. if ($ccuflags =~ /extrpc/) {
  2739. # Search RPC device. Create one if none exists
  2740. my ($rpcdev, $save) = HMCCU_GetRPCDevice ($hash, 1, undef);
  2741. return HMCCU_Log ($hash, 0, "Can't find or create HMCCURPC device", 0) if ($rpcdev eq '');
  2742. CommandSave (undef, undef) if ($save);
  2743. my ($rc, $msg) = HMCCURPC_StartRPCServer ($defs{$rpcdev});
  2744. HMCCU_SetRPCState ($hash, 'starting') if ($rc);
  2745. Log3 $name, 0, "HMCCURPC: $msg" if (!$rc && defined ($msg));
  2746. return $rc;
  2747. }
  2748. elsif ($ccuflags =~ /procrpc/) {
  2749. my $c = 0;
  2750. my $d = 0;
  2751. my $s = 0;
  2752. my @iflist = HMCCU_GetRPCInterfaceList ($hash);
  2753. foreach my $ifname1 (@iflist) {
  2754. my ($rpcdev, $save) = HMCCU_GetRPCDevice ($hash, 1, $ifname1);
  2755. next if ($rpcdev eq '' || !defined ($hash->{hmccu}{interfaces}{$ifname1}{device}));
  2756. $d++;
  2757. $s++ if ($save);
  2758. }
  2759. CommandSave (undef, undef) if ($s > 0);
  2760. if ($d == scalar (@iflist)) {
  2761. foreach my $ifname2 (@iflist) {
  2762. my $dh = $defs{$hash->{hmccu}{interfaces}{$ifname2}{device}};
  2763. $hash->{hmccu}{interfaces}{$ifname2}{manager} = 'HMCCU';
  2764. my ($rc, $msg) = HMCCURPCPROC_StartRPCServer ($dh);
  2765. if (!$rc) {
  2766. HMCCU_SetRPCState ($hash, 'error', $ifname2, $msg);
  2767. }
  2768. else {
  2769. $c++;
  2770. }
  2771. }
  2772. HMCCU_SetRPCState ($hash, 'starting') if ($c > 0);
  2773. return $c;
  2774. }
  2775. else {
  2776. HMCCU_Log ($hash, 0, "Definition of some RPC devices failed", undef);
  2777. }
  2778. }
  2779. return 0;
  2780. }
  2781. ######################################################################
  2782. # Stop external RPC server via RPC device.
  2783. ######################################################################
  2784. sub HMCCU_StopExtRPCServer ($)
  2785. {
  2786. my ($hash) = @_;
  2787. my $name = $hash->{NAME};
  2788. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  2789. if ($ccuflags =~ /extrpc/) {
  2790. return HMCCU_Log ($hash, 0, "Module HMCCURPC not loaded", 0) if (!exists ($modules{'HMCCURPC'}));
  2791. my ($rpcdev, $save) = HMCCU_GetRPCDevice ($hash, 0, undef);
  2792. return HMCCU_Log ($hash, 0, "Can't find RPC device", 0) if ($rpcdev eq '');
  2793. HMCCU_SetRPCState ($hash, 'stopping');
  2794. return HMCCURPC_StopRPCServer ($defs{$rpcdev});
  2795. }
  2796. elsif ($ccuflags =~ /procrpc/) {
  2797. return HMCCU_Log ($hash, 0, "Module HMCCURPCPROC not loaded", 0) if (!exists ($modules{'HMCCURPCPROC'}));
  2798. HMCCU_SetRPCState ($hash, 'stopping');
  2799. my $rc = 1;
  2800. my @iflist = HMCCU_GetRPCInterfaceList ($hash);
  2801. foreach my $ifname (@iflist) {
  2802. my ($rpcdev, $save) = HMCCU_GetRPCDevice ($hash, 0, $ifname);
  2803. if ($rpcdev eq '') {
  2804. Log3 $name, 0, "HMCCU: Can't find RPC device";
  2805. next;
  2806. }
  2807. $hash->{hmccu}{interfaces}{$ifname}{manager} = 'HMCCU';
  2808. $rc &= HMCCURPCPROC_StopRPCServer ($defs{$rpcdev});
  2809. }
  2810. return $rc;
  2811. }
  2812. }
  2813. ######################################################################
  2814. # Start internal file queue based RPC server.
  2815. # Return number of RPC server processes or 0 on error.
  2816. ######################################################################
  2817. sub HMCCU_StartIntRPCServer ($)
  2818. {
  2819. my ($hash) = @_;
  2820. my $name = $hash->{NAME};
  2821. # Timeouts
  2822. my $timeout = AttrVal ($name, 'rpctimeout', '0.01,0.25');
  2823. my ($to_read, $to_write) = split (",", $timeout);
  2824. $to_write = $to_read if (!defined ($to_write));
  2825. # Address and ports
  2826. my $rpcqueue = AttrVal ($name, 'rpcqueue', '/tmp/ccuqueue');
  2827. my $localaddr = AttrVal ($name, 'rpcserveraddr', '');
  2828. my $rpcserverport = AttrVal ($name, 'rpcserverport', 5400);
  2829. my $rpcinterval = AttrVal ($name, 'rpcinterval', $HMCCU_INIT_INTERVAL1);
  2830. my @rpcportlist = HMCCU_GetRPCPortList ($hash);
  2831. my $serveraddr = HMCCU_GetRPCServerInfo ($hash, $rpcportlist[0], 'host');
  2832. my $fork_cnt = 0;
  2833. # Check for running RPC server processes
  2834. my @hm_pids;
  2835. my @hm_tids;
  2836. HMCCU_IsRPCServerRunning ($hash, \@hm_pids, \@hm_tids);
  2837. if (scalar (@hm_pids) > 0) {
  2838. return HMCCU_Log ($hash, 0, "RPC server(s) already running with PIDs ".join (',', @hm_pids),
  2839. scalar (@hm_pids));
  2840. }
  2841. elsif (scalar (@hm_tids) > 0) {
  2842. return HMCCU_Log ($hash, 1, "RPC server(s) already running with TIDs ".join (',', @hm_tids),
  2843. 0);
  2844. }
  2845. # Detect local IP address
  2846. if ($localaddr eq '') {
  2847. my $socket = IO::Socket::INET->new (PeerAddr => $serveraddr, PeerPort => $rpcportlist[0]);
  2848. return HMCCU_Log ($hash, 1, "Can't connect to RPC host $serveraddr port".$rpcportlist[0], 0) if (!$socket);
  2849. $localaddr = $socket->sockhost ();
  2850. close ($socket);
  2851. }
  2852. $hash->{hmccu}{localaddr} = $localaddr;
  2853. my $ccunum = $hash->{CCUNum};
  2854. # Fork child processes
  2855. foreach my $port (@rpcportlist) {
  2856. my $clkey = 'CB'.$port;
  2857. my $rpcqueueport = $rpcqueue."_".$port."_".$ccunum;
  2858. my $callbackport = $rpcserverport+$port+($ccunum*10);
  2859. # Clear event queue
  2860. HMCCU_ResetRPCQueue ($hash, $port);
  2861. # Create child process
  2862. Log3 $name, 2, "HMCCU: Create child process with timeouts $to_read and $to_write";
  2863. my $child = SubProcess->new ({ onRun => \&HMCCU_CCURPC_OnRun,
  2864. onExit => \&HMCCU_CCURPC_OnExit, timeoutread => $to_read, timeoutwrite => $to_write });
  2865. $child->{serveraddr} = $serveraddr;
  2866. $child->{serverport} = $port;
  2867. $child->{callbackport} = $callbackport;
  2868. $child->{devname} = $name;
  2869. $child->{queue} = $rpcqueueport;
  2870. # Start child process
  2871. my $pid = $child->run ();
  2872. if (!defined ($pid)) {
  2873. Log3 $name, 1, "HMCCU: No RPC process for server $clkey started";
  2874. next;
  2875. }
  2876. Log3 $name, 0, "HMCCU: Child process for server $clkey started with PID $pid";
  2877. $fork_cnt++;
  2878. # Store child process parameters
  2879. $hash->{hmccu}{rpc}{$clkey}{child} = $child;
  2880. $hash->{hmccu}{rpc}{$clkey}{cbport} = $callbackport;
  2881. $hash->{hmccu}{rpc}{$clkey}{loop} = 0;
  2882. $hash->{hmccu}{rpc}{$clkey}{pid} = $pid;
  2883. $hash->{hmccu}{rpc}{$clkey}{queue} = $rpcqueueport;
  2884. $hash->{hmccu}{rpc}{$clkey}{state} = "starting";
  2885. push (@hm_pids, $pid);
  2886. }
  2887. $hash->{hmccu}{rpccount} = $fork_cnt;
  2888. if ($fork_cnt > 0) {
  2889. # Set internals
  2890. $hash->{RPCPID} = join (',', @hm_pids);
  2891. $hash->{RPCPRC} = "internal";
  2892. HMCCU_SetRPCState ($hash, 'starting');
  2893. # Initialize statistic counters
  2894. HMCCU_ResetCounters ($hash);
  2895. Log3 $name, 0, "RPC server(s) starting";
  2896. DoTrigger ($name, "RPC server starting");
  2897. InternalTimer (gettimeofday()+$rpcinterval, 'HMCCU_ReadRPCQueue', $hash, 0);
  2898. }
  2899. return $fork_cnt;
  2900. }
  2901. ######################################################################
  2902. # Stop RPC server(s) by sending SIGINT to process(es)
  2903. ######################################################################
  2904. sub HMCCU_StopRPCServer ($)
  2905. {
  2906. my ($hash) = @_;
  2907. my $name = $hash->{NAME};
  2908. my $pid = 0;
  2909. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  2910. # Deregister callback URLs in CCU
  2911. HMCCU_RPCDeRegisterCallback ($hash);
  2912. # Send signal SIGINT to RPC server processes
  2913. foreach my $clkey (keys %{$hash->{hmccu}{rpc}}) {
  2914. my $rpchash = \%{$hash->{hmccu}{rpc}{$clkey}};
  2915. if (exists ($rpchash->{pid}) && $rpchash->{pid} != 0) {
  2916. Log3 $name, 0, "HMCCU: Stopping RPC server $clkey with PID ".$rpchash->{pid};
  2917. kill ('INT', $rpchash->{pid});
  2918. $rpchash->{state} = "stopping";
  2919. }
  2920. else {
  2921. $rpchash->{state} = "inactive";
  2922. }
  2923. }
  2924. # Update status
  2925. HMCCU_SetRPCState ($hash, 'stopping') if ($hash->{hmccu}{rpccount} > 0);
  2926. # Wait
  2927. sleep (1);
  2928. # Check if processes were terminated
  2929. my @hm_pids;
  2930. my @hm_tids;
  2931. HMCCU_IsRPCServerRunning ($hash, \@hm_pids, \@hm_tids);
  2932. if (scalar (@hm_pids) > 0) {
  2933. foreach my $pid (@hm_pids) {
  2934. Log3 $name, 0, "HMCCU: Stopping RPC server with PID $pid";
  2935. kill ('INT', $pid);
  2936. }
  2937. }
  2938. Log3 $name, 0, "HMCCU: Externally launched RPC server detected." if (scalar (@hm_tids) > 0);
  2939. # Wait
  2940. sleep (1);
  2941. # Kill the rest
  2942. @hm_pids = ();
  2943. @hm_tids = ();
  2944. if (HMCCU_IsRPCServerRunning ($hash, \@hm_pids, \@hm_tids)) {
  2945. foreach my $pid (@hm_pids) {
  2946. kill ('KILL', $pid);
  2947. }
  2948. }
  2949. # Store number of running RPC servers
  2950. $hash->{hmccu}{rpccount} = HMCCU_IsRPCServerRunning ($hash, undef, undef);
  2951. return $hash->{hmccu}{rpccount} > 0 ? 0 : 1;
  2952. }
  2953. ######################################################################
  2954. # Check status of RPC server depending on internal RPCState.
  2955. # Return 1 if RPC server is stopping, starting or restarting. During
  2956. # this phases CCU reacts very slowly so any get or set command from
  2957. # HMCCU devices are disabled.
  2958. ######################################################################
  2959. sub HMCCU_IsRPCStateBlocking ($)
  2960. {
  2961. my ($hash) = @_;
  2962. if ($hash->{RPCState} eq "starting" ||
  2963. $hash->{RPCState} eq "restarting" ||
  2964. $hash->{RPCState} eq "stopping") {
  2965. return 1;
  2966. }
  2967. else {
  2968. return 0;
  2969. }
  2970. }
  2971. ######################################################################
  2972. # Check if RPC servers are running.
  2973. # Return number of running RPC servers. If paramters pids or tids are
  2974. # defined also return process or thread IDs.
  2975. ######################################################################
  2976. sub HMCCU_IsRPCServerRunning ($$$)
  2977. {
  2978. my ($hash, $pids, $tids) = @_;
  2979. my $name = $hash->{NAME};
  2980. my $c = 0;
  2981. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  2982. if ($ccuflags =~ /extrpc/) {
  2983. @$tids = () if (defined ($tids));
  2984. my ($rpcdev, $save) = HMCCU_GetRPCDevice ($hash, 0, undef);
  2985. if ($rpcdev ne '') {
  2986. my ($r, $a) = HMCCURPC_CheckThreadState ($defs{$rpcdev}, 6, 'running', $tids);
  2987. $c = $r;
  2988. }
  2989. }
  2990. elsif ($ccuflags =~ /procrpc/) {
  2991. @$pids = () if (defined ($pids));
  2992. my @iflist = HMCCU_GetRPCInterfaceList ($hash);
  2993. foreach my $ifname (@iflist) {
  2994. my ($rpcdev, $save) = HMCCU_GetRPCDevice ($hash, 0, $ifname);
  2995. next if ($rpcdev eq '');
  2996. my $rc = HMCCURPCPROC_CheckProcessState ($defs{$rpcdev}, 'running');
  2997. if ($rc < 0 || $rc > 1) {
  2998. push (@$pids, $rc);
  2999. $c++;
  3000. }
  3001. }
  3002. }
  3003. else {
  3004. @$pids = () if (defined ($pids));
  3005. foreach my $clkey (keys %{$hash->{hmccu}{rpc}}) {
  3006. if (defined ($hash->{hmccu}{rpc}{$clkey}{pid})) {
  3007. my $pid = $hash->{hmccu}{rpc}{$clkey}{pid};
  3008. if ($pid != 0 && kill (0, $pid)) {
  3009. push (@$pids, $pid) if (defined ($pids));
  3010. $c++;
  3011. }
  3012. }
  3013. }
  3014. }
  3015. return $c;
  3016. }
  3017. ######################################################################
  3018. # Get channels and datapoints of CCU device
  3019. ######################################################################
  3020. sub HMCCU_GetDeviceInfo ($$$)
  3021. {
  3022. my ($hash, $device, $ccuget) = @_;
  3023. my $name = $hash->{NAME};
  3024. my $devname = '';
  3025. my $hmccu_hash = HMCCU_GetHash ($hash);
  3026. return '' if (!defined ($hmccu_hash));
  3027. $ccuget = HMCCU_GetAttribute ($hmccu_hash, $hash, 'ccuget', 'Value') if ($ccuget eq 'Attr');
  3028. my ($int, $add, $chn, $dpt, $nam, $flags) = HMCCU_ParseObject ($hmccu_hash, $device, 0);
  3029. if ($flags == $HMCCU_FLAG_ADDRESS) {
  3030. $devname = HMCCU_GetDeviceName ($hmccu_hash, $add, '');
  3031. return '' if ($devname eq '');
  3032. }
  3033. else {
  3034. $devname = $nam;
  3035. }
  3036. my $response = HMCCU_HMScriptExt ($hmccu_hash, "!GetDeviceInfo",
  3037. { devname => $devname, ccuget => $ccuget });
  3038. HMCCU_Trace ($hash, 2, undef,
  3039. "Device=$device Devname=$devname<br>".
  3040. "Script response = \n".$response."<br>".
  3041. "Script = GetDeviceInfo");
  3042. return $response;
  3043. }
  3044. ######################################################################
  3045. # Make device info readable
  3046. # n=number, b=bool, f=float, i=integer, s=string, a=alarm, p=presence
  3047. # e=enumeration
  3048. ######################################################################
  3049. sub HMCCU_FormatDeviceInfo ($)
  3050. {
  3051. my ($devinfo) = @_;
  3052. my %vtypes = (0, "n", 2, "b", 4, "f", 6, "a", 8, "n", 11, "s", 16, "i", 20, "s", 23, "p", 29, "e");
  3053. my $result = '';
  3054. my $c_oaddr = '';
  3055. foreach my $dpspec (split ("\n", $devinfo)) {
  3056. my ($c, $c_addr, $c_name, $d_name, $d_type, $d_value, $d_flags) = split (";", $dpspec);
  3057. if ($c_addr ne $c_oaddr) {
  3058. $result .= "CHN $c_addr $c_name\n";
  3059. $c_oaddr = $c_addr;
  3060. }
  3061. my $t = exists ($vtypes{$d_type}) ? $vtypes{$d_type} : $d_type;
  3062. $result .= " DPT {$t} $d_name = $d_value [$d_flags]\n";
  3063. }
  3064. return $result;
  3065. }
  3066. ######################################################################
  3067. # Get available firmware versions from EQ-3 server.
  3068. # Firmware version, date and download link are stored in hash
  3069. # {hmccu}{type}{$type} in elements {firmware}, {date} and {download}.
  3070. # Return number of available firmware downloads.
  3071. ######################################################################
  3072. sub HMCCU_GetFirmwareVersions ($)
  3073. {
  3074. my ($hash) = @_;
  3075. my $name = $hash->{NAME};
  3076. my $ccureqtimeout = AttrVal ($name, "ccuReqTimeout", $HMCCU_TIMEOUT_REQUEST);
  3077. my $url = "http://www.eq-3.de/service/downloads.html";
  3078. my $response = GetFileFromURL ($url, $ccureqtimeout, "suchtext=&suche_in=&downloadart=11");
  3079. # my @changebc = $response =~ m/href="(Downloads\/Software\/Firmware\/changelog_[^"]+)/g;
  3080. # my @changeip = $response =~ m/href="(Downloads\/Software\/Firmware\/Homematic IP\/changelog_[^"]+)/g;
  3081. my @download = $response =~ m/<a.href="(Downloads\/Software\/Firmware\/[^"]+)/g;
  3082. my $dc = 0;
  3083. foreach my $dl (@download) {
  3084. my $dd;
  3085. my $mm;
  3086. my $yy;
  3087. my $date = '?';
  3088. my $fw;
  3089. my @path = split (/\//, $dl);
  3090. my $file = pop @path;
  3091. next if ($file !~ /(\.tgz|\.tar\.gz)/);
  3092. # Log3 $name, 2, "HMCCU: $file";
  3093. $file =~ m/^(.+)_update_V([^.]+)/;
  3094. my ($dt, $rest) = ($1, $2);
  3095. $dt =~ s/_/-/g;
  3096. $dt = uc($dt);
  3097. if ($rest =~ /^([\d_]+)([0-9]{2})([0-9]{2})([0-9]{2})$/) {
  3098. ($fw, $yy, $mm, $dd) = ($1, $2, $3, $4);
  3099. $date = "$dd.$mm.20$yy";
  3100. $fw =~ s/_$//;
  3101. }
  3102. else {
  3103. $fw = $rest;
  3104. }
  3105. $fw =~ s/_/\./g;
  3106. $fw =~ s/^V//;
  3107. $dc++;
  3108. $hash->{hmccu}{type}{$dt}{firmware} = $fw;
  3109. $hash->{hmccu}{type}{$dt}{date} = $date;
  3110. $hash->{hmccu}{type}{$dt}{download} = $dl;
  3111. }
  3112. return $dc;
  3113. }
  3114. ######################################################################
  3115. # Read CCU device identified by device or channel name via Homematic
  3116. # Script.
  3117. # Return (device count, channel count) or (-1, -1) on error.
  3118. ######################################################################
  3119. sub HMCCU_GetDevice ($$)
  3120. {
  3121. my ($hash, $name) = @_;
  3122. my $devcount = 0;
  3123. my $chncount = 0;
  3124. my $devname;
  3125. my $devtype;
  3126. my %objects = ();
  3127. my $response = HMCCU_HMScriptExt ($hash, "!GetDevice", { name => $name });
  3128. return (-1, -1) if ($response eq '' || $response =~ /^ERROR:.*/);
  3129. my @scrlines = split /\n/,$response;
  3130. foreach my $hmdef (@scrlines) {
  3131. my @hmdata = split /;/,$hmdef;
  3132. next if (scalar (@hmdata) == 0);
  3133. my $typeprefix = '';
  3134. if ($hmdata[0] eq 'D') {
  3135. next if (scalar (@hmdata) != 6);
  3136. # 1=Interface 2=Device-Address 3=Device-Name 4=Device-Type 5=Channel-Count
  3137. $objects{$hmdata[2]}{addtype} = 'dev';
  3138. $objects{$hmdata[2]}{channels} = $hmdata[5];
  3139. $objects{$hmdata[2]}{flag} = 'N';
  3140. $objects{$hmdata[2]}{interface} = $hmdata[1];
  3141. $objects{$hmdata[2]}{name} = $hmdata[3];
  3142. $typeprefix = "CUX-" if ($hmdata[2] =~ /^CUX/);
  3143. $typeprefix = "HVL-" if ($hmdata[1] eq 'HVL');
  3144. $objects{$hmdata[2]}{type} = $typeprefix . $hmdata[4];
  3145. $objects{$hmdata[2]}{chndir} = 0;
  3146. $devname = $hmdata[3];
  3147. $devtype = $typeprefix . $hmdata[4];
  3148. }
  3149. elsif ($hmdata[0] eq 'C') {
  3150. next if (scalar (@hmdata) != 4);
  3151. # 1=Channel-Address 2=Channel-Name 3=Direction
  3152. $objects{$hmdata[1]}{addtype} = 'chn';
  3153. $objects{$hmdata[1]}{channels} = 1;
  3154. $objects{$hmdata[1]}{flag} = 'N';
  3155. $objects{$hmdata[1]}{name} = $hmdata[2];
  3156. $objects{$hmdata[1]}{valid} = 1;
  3157. $objects{$hmdata[1]}{chndir} = $hmdata[3];
  3158. }
  3159. }
  3160. if (scalar (keys %objects) > 0) {
  3161. # Update HMCCU device tables
  3162. ($devcount, $chncount) = HMCCU_UpdateDeviceTable ($hash, \%objects);
  3163. # Read available datapoints for device type
  3164. HMCCU_GetDatapointList ($hash, $devname, $devtype) if (defined ($devname) && defined ($devtype));
  3165. }
  3166. return ($devcount, $chncount);
  3167. }
  3168. ######################################################################
  3169. # Read list of CCU devices, channels and interfaces via Homematic
  3170. # Script.
  3171. # Update data of client devices if not current.
  3172. # Return (device count, channel count, interface count) or (-1, -1, -1)
  3173. # on error.
  3174. ######################################################################
  3175. sub HMCCU_GetDeviceList ($)
  3176. {
  3177. my ($hash) = @_;
  3178. my $devcount = 0;
  3179. my $chncount = 0;
  3180. my $ifcount = 0;
  3181. my %objects = ();
  3182. my $response = HMCCU_HMScriptExt ($hash, "!GetDeviceList", undef);
  3183. return (-1, -1, -1) if ($response eq '' || $response =~ /^ERROR:.*/);
  3184. # Delete old entries
  3185. %{$hash->{hmccu}{dev}} = ();
  3186. %{$hash->{hmccu}{adr}} = ();
  3187. $hash->{hmccu}{updatetime} = time ();
  3188. # Device hash elements for HMCCU_UpdateDeviceTable():
  3189. #
  3190. # {address}{flag} := [N, D, R]
  3191. # {address}{addtype} := [chn, dev]
  3192. # {address}{channels} := Number of channels
  3193. # {address}{name} := Device or channel name
  3194. # {address}{type} := Homematic device type
  3195. # {address}{usetype} := Usage type
  3196. # {address}{interface} := Device interface ID
  3197. # {address}{firmware} := Firmware version of device
  3198. # {address}{version} := Version of RPC device description
  3199. # {address}{rxmode} := Transmit mode
  3200. # {address}{chndir} := Channel direction: 1=sensor 2=actor 0=none
  3201. my @scrlines = split /\n/,$response;
  3202. foreach my $hmdef (@scrlines) {
  3203. my @hmdata = split /;/,$hmdef;
  3204. next if (scalar (@hmdata) == 0);
  3205. my $typeprefix = '';
  3206. if ($hmdata[0] eq 'D') {
  3207. next if (scalar (@hmdata) != 6);
  3208. # 1=Interface 2=Device-Address 3=Device-Name 4=Device-Type 5=Channel-Count
  3209. $objects{$hmdata[2]}{addtype} = 'dev';
  3210. $objects{$hmdata[2]}{channels} = $hmdata[5];
  3211. $objects{$hmdata[2]}{flag} = 'N';
  3212. $objects{$hmdata[2]}{interface} = $hmdata[1];
  3213. $objects{$hmdata[2]}{name} = $hmdata[3];
  3214. $typeprefix = "CUX-" if ($hmdata[2] =~ /^CUX/);
  3215. $typeprefix = "HVL-" if ($hmdata[1] eq 'HVL');
  3216. $objects{$hmdata[2]}{type} = $typeprefix . $hmdata[4];
  3217. $objects{$hmdata[2]}{chndir} = 0;
  3218. # CCU information (address = BidCoS-RF)
  3219. if ($hmdata[2] eq 'BidCoS-RF') {
  3220. $hash->{ccuname} = $hmdata[3];
  3221. $hash->{ccuaddr} = $hmdata[2];
  3222. $hash->{ccuif} = $hmdata[1];
  3223. }
  3224. }
  3225. elsif ($hmdata[0] eq 'C') {
  3226. next if (scalar (@hmdata) != 4);
  3227. # 1=Channel-Address 2=Channel-Name 3=Direction
  3228. $objects{$hmdata[1]}{addtype} = 'chn';
  3229. $objects{$hmdata[1]}{channels} = 1;
  3230. $objects{$hmdata[1]}{flag} = 'N';
  3231. $objects{$hmdata[1]}{name} = $hmdata[2];
  3232. $objects{$hmdata[1]}{valid} = 1;
  3233. $objects{$hmdata[1]}{chndir} = $hmdata[3];
  3234. }
  3235. elsif ($hmdata[0] eq 'I') {
  3236. next if (scalar (@hmdata) != 4);
  3237. # 1=Interface-Name 2=Interface Info 3=URL
  3238. my $ifurl = $hmdata[3];
  3239. if ($ifurl =~ /^([^:]+):\/\/([^:]+):([0-9]+)/) {
  3240. my ($prot, $ipaddr, $port) = ($1, $2, $3);
  3241. next if (!defined ($port) || $port eq '');
  3242. if ($hash->{ccuip} ne 'N/A') {
  3243. $ifurl =~ s/127\.0\.0\.1/$hash->{ccuip}/;
  3244. $ipaddr =~ s/127\.0\.0\.1/$hash->{ccuip}/;
  3245. }
  3246. else {
  3247. $ifurl =~ s/127\.0\.0\.1/$hash->{host}/;
  3248. $ipaddr =~ s/127\.0\.0\.1/$hash->{host}/;
  3249. }
  3250. if ($HMCCU_RPC_FLAG{$port} =~ /forceASCII/) {
  3251. $ifurl =~ s/xmlrpc_bin/xmlrpc/;
  3252. $prot = "xmlrpc";
  3253. }
  3254. # Perl RPC::XML::Client.pm does not support URLs starting with xmlrpc://
  3255. $ifurl =~ s/xmlrpc:/http:/;
  3256. $prot =~ s/^xmlrpc$/http/;
  3257. $hash->{hmccu}{interfaces}{$hmdata[1]}{url} = $ifurl;
  3258. $hash->{hmccu}{interfaces}{$hmdata[1]}{prot} = $prot;
  3259. $hash->{hmccu}{interfaces}{$hmdata[1]}{type} = $prot eq 'http' ? 'A' : 'B';
  3260. $hash->{hmccu}{interfaces}{$hmdata[1]}{port} = $port;
  3261. $hash->{hmccu}{interfaces}{$hmdata[1]}{host} = $ipaddr;
  3262. $hash->{hmccu}{interfaces}{$hmdata[1]}{state} = 'inactive';
  3263. $hash->{hmccu}{interfaces}{$hmdata[1]}{manager} = 'null';
  3264. $hash->{hmccu}{interfaces}{$hmdata[1]}{flags} = $HMCCU_RPC_FLAG{$port};
  3265. $hash->{hmccu}{ifports}{$port} = $hmdata[1];
  3266. $ifcount++;
  3267. }
  3268. }
  3269. }
  3270. if (scalar (keys %objects) > 0) {
  3271. # Update some CCU I/O device information
  3272. $hash->{ccuinterfaces} = join (',', keys %{$hash->{hmccu}{interfaces}});
  3273. # Update HMCCU device tables
  3274. ($devcount, $chncount) = HMCCU_UpdateDeviceTable ($hash, \%objects);
  3275. # Read available datapoints for each device type
  3276. HMCCU_GetDatapointList ($hash, undef, undef);
  3277. }
  3278. return ($devcount, $chncount, $ifcount);
  3279. }
  3280. ######################################################################
  3281. # Read list of datapoints for all or one CCU device type(s).
  3282. # Function must not be called before GetDeviceList.
  3283. # Return number of datapoints.
  3284. ######################################################################
  3285. sub HMCCU_GetDatapointList ($$$)
  3286. {
  3287. my ($hash, $devname, $devtype) = @_;
  3288. my $name = $hash->{NAME};
  3289. my @devunique;
  3290. if (defined ($devname) && defined ($devtype)) {
  3291. return 0 if (exists ($hash->{hmccu}{dp}{$devtype}));
  3292. push @devunique, $devname;
  3293. }
  3294. else {
  3295. if (exists ($hash->{hmccu}{dp})) {
  3296. delete $hash->{hmccu}{dp};
  3297. }
  3298. # Select one device for each device type
  3299. my %alltypes;
  3300. foreach my $add (sort keys %{$hash->{hmccu}{dev}}) {
  3301. next if ($hash->{hmccu}{dev}{$add}{addtype} ne 'dev');
  3302. my $dt = $hash->{hmccu}{dev}{$add}{type};
  3303. if (defined ($dt)) {
  3304. if ($dt ne '' && !exists ($alltypes{$dt})) {
  3305. $alltypes{$dt} = 1;
  3306. push @devunique, $hash->{hmccu}{dev}{$add}{name};
  3307. }
  3308. }
  3309. else {
  3310. Log3 $name, 2, "HMCCU: Corrupt or invalid entry in device table for device $add";
  3311. }
  3312. }
  3313. }
  3314. if (scalar (@devunique) == 0) {
  3315. Log3 $name, 2, "HMCCU: No device types found in device table. Cannot read datapoints.";
  3316. return 0;
  3317. }
  3318. my $devlist = join (',', @devunique);
  3319. my $response = HMCCU_HMScriptExt ($hash, "!GetDatapointList",
  3320. { list => $devlist });
  3321. if ($response eq '' || $response =~ /^ERROR:.*/) {
  3322. Log3 $name, 2, "HMCCU: Cannot get datapoint list";
  3323. return 0;
  3324. }
  3325. my $c = 0;
  3326. foreach my $dpspec (split /\n/,$response) {
  3327. my ($iface, $chna, $devt, $devc, $dptn, $dptt, $dpto) = split (";", $dpspec);
  3328. $devt = "CUX-".$devt if ($iface eq 'CUxD');
  3329. $devt = "HVL-".$devt if ($iface eq 'HVL');
  3330. $hash->{hmccu}{dp}{$devt}{spc}{ontime} = $devc.".".$dptn if ($dptn eq "ON_TIME");
  3331. $hash->{hmccu}{dp}{$devt}{spc}{ramptime} = $devc.".".$dptn if ($dptn eq "RAMP_TIME");
  3332. $hash->{hmccu}{dp}{$devt}{spc}{submit} = $devc.".".$dptn if ($dptn eq "SUBMIT");
  3333. $hash->{hmccu}{dp}{$devt}{spc}{level} = $devc.".".$dptn if ($dptn eq "LEVEL");
  3334. $hash->{hmccu}{dp}{$devt}{ch}{$devc}{$dptn}{type} = $dptt;
  3335. $hash->{hmccu}{dp}{$devt}{ch}{$devc}{$dptn}{oper} = $dpto;
  3336. if (exists ($hash->{hmccu}{dp}{$devt}{cnt}{$dptn})) {
  3337. $hash->{hmccu}{dp}{$devt}{cnt}{$dptn}++;
  3338. }
  3339. else {
  3340. $hash->{hmccu}{dp}{$devt}{cnt}{$dptn} = 1;
  3341. }
  3342. $c++;
  3343. }
  3344. return $c;
  3345. }
  3346. ######################################################################
  3347. # Check if device/channel name or address is valid and refers to an
  3348. # existing device or channel.
  3349. ######################################################################
  3350. sub HMCCU_IsValidDeviceOrChannel ($$)
  3351. {
  3352. my ($hash, $param) = @_;
  3353. if (HMCCU_IsDevAddr ($param, 1) || HMCCU_IsChnAddr ($param, 1)) {
  3354. my ($i, $a) = split (/\./, $param);
  3355. return 0 if (! exists ($hash->{hmccu}{dev}{$a}));
  3356. return $hash->{hmccu}{dev}{$a}{valid};
  3357. }
  3358. if (HMCCU_IsDevAddr ($param, 0) || HMCCU_IsChnAddr ($param, 0)) {
  3359. return 0 if (! exists ($hash->{hmccu}{dev}{$param}));
  3360. return $hash->{hmccu}{dev}{$param}{valid};
  3361. }
  3362. else {
  3363. if (exists ($hash->{hmccu}{adr}{$param})) {
  3364. return $hash->{hmccu}{adr}{$param}{valid};
  3365. }
  3366. elsif (exists ($hash->{hmccu}{dev}{$param})) {
  3367. return $hash->{hmccu}{dev}{$param}{valid};
  3368. }
  3369. else {
  3370. return 0;
  3371. }
  3372. }
  3373. }
  3374. ######################################################################
  3375. # Check if device name or address is valid and refers to an existing
  3376. # device.
  3377. ######################################################################
  3378. sub HMCCU_IsValidDevice ($$)
  3379. {
  3380. my ($hash, $param) = @_;
  3381. if (HMCCU_IsDevAddr ($param, 1)) {
  3382. my ($i, $a) = split (/\./, $param);
  3383. return 0 if (! exists ($hash->{hmccu}{dev}{$a}));
  3384. return $hash->{hmccu}{dev}{$a}{valid};
  3385. }
  3386. if (HMCCU_IsDevAddr ($param, 0)) {
  3387. return 0 if (! exists ($hash->{hmccu}{dev}{$param}));
  3388. return $hash->{hmccu}{dev}{$param}{valid};
  3389. }
  3390. else {
  3391. if (exists ($hash->{hmccu}{adr}{$param})) {
  3392. return $hash->{hmccu}{adr}{$param}{valid} && $hash->{hmccu}{adr}{$param}{addtype} eq 'dev' ? 1 : 0;
  3393. }
  3394. elsif (exists ($hash->{hmccu}{dev}{$param})) {
  3395. return $hash->{hmccu}{dev}{$param}{valid} && $hash->{hmccu}{dev}{$param}{addtype} eq 'dev' ? 1 : 0;
  3396. }
  3397. else {
  3398. return 0;
  3399. }
  3400. }
  3401. }
  3402. ######################################################################
  3403. # Check if channel name or address is valid and refers to an existing
  3404. # channel.
  3405. ######################################################################
  3406. sub HMCCU_IsValidChannel ($$)
  3407. {
  3408. my ($hash, $param) = @_;
  3409. if (HMCCU_IsChnAddr ($param, 1)) {
  3410. my ($i, $a) = split (/\./, $param);
  3411. return 0 if (! exists ($hash->{hmccu}{dev}{$a}));
  3412. return $hash->{hmccu}{dev}{$a}{valid};
  3413. }
  3414. if (HMCCU_IsChnAddr ($param, 0)) {
  3415. return 0 if (! exists ($hash->{hmccu}{dev}{$param}));
  3416. return $hash->{hmccu}{dev}{$param}{valid};
  3417. }
  3418. else {
  3419. if (exists ($hash->{hmccu}{adr}{$param})) {
  3420. return $hash->{hmccu}{adr}{$param}{valid} && $hash->{hmccu}{adr}{$param}{addtype} eq 'chn' ? 1 : 0;
  3421. }
  3422. elsif (exists ($hash->{hmccu}{dev}{$param})) {
  3423. return $hash->{hmccu}{dev}{$param}{valid} && $hash->{hmccu}{dev}{$param}{addtype} eq 'chn' ? 1 : 0;
  3424. }
  3425. else {
  3426. return 0;
  3427. }
  3428. }
  3429. }
  3430. ######################################################################
  3431. # Get CCU parameters of device or channel.
  3432. # Returns list containing interface, deviceaddress, name, type and
  3433. # channels.
  3434. ######################################################################
  3435. sub HMCCU_GetCCUDeviceParam ($$)
  3436. {
  3437. my ($hash, $param) = @_;
  3438. my $name = $hash->{NAME};
  3439. my $devadd;
  3440. my $add = undef;
  3441. my $chn = undef;
  3442. if (HMCCU_IsDevAddr ($param, 1) || HMCCU_IsChnAddr ($param, 1)) {
  3443. my $i;
  3444. ($i, $add) = split (/\./, $param);
  3445. }
  3446. else {
  3447. if (HMCCU_IsDevAddr ($param, 0) || HMCCU_IsChnAddr ($param, 0)) {
  3448. $add = $param;
  3449. }
  3450. else {
  3451. if (exists ($hash->{hmccu}{adr}{$param})) {
  3452. $add = $hash->{hmccu}{adr}{$param}{address};
  3453. }
  3454. }
  3455. }
  3456. return (undef, undef, undef, undef) if (!defined ($add));
  3457. ($devadd, $chn) = split (':', $add);
  3458. return (undef, undef, undef, undef) if (!defined ($devadd) ||
  3459. !exists ($hash->{hmccu}{dev}{$devadd}) || $hash->{hmccu}{dev}{$devadd}{valid} == 0);
  3460. return ($hash->{hmccu}{dev}{$devadd}{interface}, $add, $hash->{hmccu}{dev}{$add}{name},
  3461. $hash->{hmccu}{dev}{$devadd}{type}, $hash->{hmccu}{dev}{$add}{channels});
  3462. }
  3463. ######################################################################
  3464. # Get list of valid datapoints for device type.
  3465. # hash = hash of client or IO device
  3466. # devtype = Homematic device type
  3467. # chn = Channel number, -1=all channels
  3468. # oper = Valid operation: 1=Read, 2=Write, 4=Event
  3469. # dplistref = Reference for array with datapoints.
  3470. # Return number of datapoints.
  3471. ######################################################################
  3472. sub HMCCU_GetValidDatapoints ($$$$$)
  3473. {
  3474. my ($hash, $devtype, $chn, $oper, $dplistref) = @_;
  3475. my $hmccu_hash = HMCCU_GetHash ($hash);
  3476. my $ccuflags = AttrVal ($hmccu_hash->{NAME}, 'ccuflags', 'null');
  3477. return 0 if ($ccuflags =~ /dptnocheck/);
  3478. return 0 if (!exists ($hmccu_hash->{hmccu}{dp}));
  3479. return HMCCU_Log ($hash, 2, "chn undefined", 0) if (!defined ($chn));
  3480. if ($chn >= 0) {
  3481. if (exists ($hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$chn})) {
  3482. foreach my $dp (sort keys %{$hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$chn}}) {
  3483. if ($hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$chn}{$dp}{oper} & $oper) {
  3484. push @$dplistref, $dp;
  3485. }
  3486. }
  3487. }
  3488. }
  3489. else {
  3490. if (exists ($hmccu_hash->{hmccu}{dp}{$devtype})) {
  3491. foreach my $ch (sort keys %{$hmccu_hash->{hmccu}{dp}{$devtype}{ch}}) {
  3492. foreach my $dp (sort keys %{$hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$ch}}) {
  3493. if ($hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$ch}{$dp}{oper} & $oper) {
  3494. push @$dplistref, $ch.".".$dp;
  3495. }
  3496. }
  3497. }
  3498. }
  3499. }
  3500. return scalar (@$dplistref);
  3501. }
  3502. ######################################################################
  3503. # Get datapoint attribute.
  3504. # Valid attributes are 'oper' or 'type'.
  3505. ######################################################################
  3506. sub HMCCU_GetDatapointAttr ($$$$$)
  3507. {
  3508. my ($hash, $devtype, $chnno, $dpt, $attr) = @_;
  3509. return undef if ($attr ne 'oper' && $attr ne 'type');
  3510. return undef if (!exists ($hash->{hmccu}{dp}{$devtype}));
  3511. return undef if (!exists ($hash->{hmccu}{dp}{$devtype}{ch}{$chnno}));
  3512. return undef if (!exists ($hash->{hmccu}{dp}{$devtype}{ch}{$chnno}{$dpt}));
  3513. return $hash->{hmccu}{dp}{$devtype}{ch}{$chnno}{$dpt}{$attr};
  3514. }
  3515. ######################################################################
  3516. # Find a datapoint for device type.
  3517. # hash = hash of client or IO device
  3518. # devtype = Homematic device type
  3519. # chn = Channel number, -1=all channels
  3520. # oper = Valid operation: 1=Read, 2=Write, 4=Event
  3521. # Return channel of first match or -1.
  3522. ######################################################################
  3523. sub HMCCU_FindDatapoint ($$$$$)
  3524. {
  3525. my ($hash, $devtype, $chn, $dpt, $oper) = @_;
  3526. my $hmccu_hash = HMCCU_GetHash ($hash);
  3527. return -1 if (!exists ($hmccu_hash->{hmccu}{dp}));
  3528. if ($chn >= 0) {
  3529. if (exists ($hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$chn})) {
  3530. foreach my $dp (sort keys %{$hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$chn}}) {
  3531. return $chn if ($dp eq $dpt &&
  3532. $hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$chn}{$dp}{oper} & $oper);
  3533. }
  3534. }
  3535. }
  3536. else {
  3537. if (exists ($hmccu_hash->{hmccu}{dp}{$devtype})) {
  3538. foreach my $ch (sort keys %{$hmccu_hash->{hmccu}{dp}{$devtype}{ch}}) {
  3539. foreach my $dp (sort keys %{$hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$ch}}) {
  3540. return $ch if ($dp eq $dpt &&
  3541. $hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$ch}{$dp}{oper} & $oper);
  3542. }
  3543. }
  3544. }
  3545. }
  3546. return -1;
  3547. }
  3548. ######################################################################
  3549. # Get channel number and datapoint name for special datapoint.
  3550. # Valid modes are ontime, ramptime, submit, level
  3551. ######################################################################
  3552. sub HMCCU_GetSwitchDatapoint ($$$)
  3553. {
  3554. my ($hash, $devtype, $mode) = @_;
  3555. my $hmccu_hash = HMCCU_GetHash ($hash);
  3556. if (exists ($hmccu_hash->{hmccu}{dp}{$devtype}{spc}{$mode})) {
  3557. return $hmccu_hash->{hmccu}{dp}{$devtype}{spc}{$mode};
  3558. }
  3559. else {
  3560. return '';
  3561. }
  3562. }
  3563. ######################################################################
  3564. # Check if datapoint is valid.
  3565. # Parameter chn can be a channel address or a channel number. If dpt
  3566. # contains a channel number parameter chn should be set to undef.
  3567. # Parameter dpt can contain a channel number.
  3568. # Parameter oper specifies access flag:
  3569. # 1 = datapoint readable
  3570. # 2 = datapoint writeable
  3571. # Return 1 if ccuflags is set to dptnocheck or datapoint is valid.
  3572. # Otherwise 0.
  3573. ######################################################################
  3574. sub HMCCU_IsValidDatapoint ($$$$$)
  3575. {
  3576. my ($hash, $devtype, $chn, $dpt, $oper) = @_;
  3577. my $fnc = "IsValidDatapoint";
  3578. my $hmccu_hash = HMCCU_GetHash ($hash);
  3579. return 0 if (!defined ($hmccu_hash));
  3580. if ($hash->{TYPE} eq 'HMCCU' && !defined ($devtype)) {
  3581. $devtype = HMCCU_GetDeviceType ($hmccu_hash, $chn, 'null');
  3582. }
  3583. my $ccuflags = AttrVal ($hmccu_hash->{NAME}, 'ccuflags', 'null');
  3584. return 1 if ($ccuflags =~ /dptnocheck/);
  3585. return 1 if (!exists ($hmccu_hash->{hmccu}{dp}));
  3586. my $chnno = $chn;
  3587. if (HMCCU_IsValidChannel ($hmccu_hash, $chn)) {
  3588. HMCCU_Trace ($hash, 2, $fnc, "$chn is a valid channel address");
  3589. my ($a, $c) = split(":",$chn);
  3590. $chnno = $c;
  3591. }
  3592. else {
  3593. HMCCU_Trace ($hash, 2, $fnc, "$chn is not a valid channel address");
  3594. }
  3595. if ($dpt =~ /^([0-9]{1,2})\.(.+)$/) {
  3596. $chnno = $1;
  3597. $dpt = $2;
  3598. HMCCU_Trace ($hash, 2, $fnc, "$dpt contains channel number");
  3599. }
  3600. HMCCU_Trace ($hash, 2, $fnc, "devtype=$devtype, chnno=$chnno, dpt=$dpt");
  3601. return (exists ($hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$chnno}{$dpt}) &&
  3602. ($hmccu_hash->{hmccu}{dp}{$devtype}{ch}{$chnno}{$dpt}{oper} & $oper)) ? 1 : 0;
  3603. }
  3604. ######################################################################
  3605. # Get list of device or channel addresses for which device or channel
  3606. # name matches regular expression.
  3607. # Parameter mode can be 'dev' or 'chn'.
  3608. # Return number of matching entries.
  3609. ######################################################################
  3610. sub HMCCU_GetMatchingDevices ($$$$)
  3611. {
  3612. my ($hash, $regexp, $mode, $listref) = @_;
  3613. my $c = 0;
  3614. foreach my $name (sort keys %{$hash->{hmccu}{adr}}) {
  3615. next if ($name !~/$regexp/ || $hash->{hmccu}{adr}{$name}{addtype} ne $mode ||
  3616. $hash->{hmccu}{adr}{$name}{valid} == 0);
  3617. push (@$listref, $hash->{hmccu}{adr}{$name}{address});
  3618. $c++;
  3619. }
  3620. return $c;
  3621. }
  3622. ######################################################################
  3623. # Get name of a CCU device by address.
  3624. # Channel number will be removed if specified.
  3625. ######################################################################
  3626. sub HMCCU_GetDeviceName ($$$)
  3627. {
  3628. my ($hash, $addr, $default) = @_;
  3629. if (HMCCU_IsValidDeviceOrChannel ($hash, $addr)) {
  3630. $addr =~ s/:[0-9]+$//;
  3631. return $hash->{hmccu}{dev}{$addr}{name};
  3632. }
  3633. return $default;
  3634. }
  3635. ######################################################################
  3636. # Get name of a CCU device channel by address.
  3637. ######################################################################
  3638. sub HMCCU_GetChannelName ($$$)
  3639. {
  3640. my ($hash, $addr, $default) = @_;
  3641. if (HMCCU_IsValidChannel ($hash, $addr)) {
  3642. return $hash->{hmccu}{dev}{$addr}{name};
  3643. }
  3644. return $default;
  3645. }
  3646. ######################################################################
  3647. # Get type of a CCU device by address.
  3648. # Channel number will be removed if specified.
  3649. ######################################################################
  3650. sub HMCCU_GetDeviceType ($$$)
  3651. {
  3652. my ($hash, $addr, $default) = @_;
  3653. if (HMCCU_IsValidDeviceOrChannel ($hash, $addr)) {
  3654. $addr =~ s/:[0-9]+$//;
  3655. return $hash->{hmccu}{dev}{$addr}{type};
  3656. }
  3657. return $default;
  3658. }
  3659. ######################################################################
  3660. # Get number of channels of a CCU device.
  3661. # Channel number will be removed if specified.
  3662. ######################################################################
  3663. sub HMCCU_GetDeviceChannels ($$$)
  3664. {
  3665. my ($hash, $addr, $default) = @_;
  3666. if (HMCCU_IsValidDeviceOrChannel ($hash, $addr)) {
  3667. $addr =~ s/:[0-9]+$//;
  3668. return $hash->{hmccu}{dev}{$addr}{channels};
  3669. }
  3670. return 0;
  3671. }
  3672. ######################################################################
  3673. # Get interface of a CCU device by address.
  3674. # Channel number will be removed if specified.
  3675. ######################################################################
  3676. sub HMCCU_GetDeviceInterface ($$$)
  3677. {
  3678. my ($hash, $addr, $default) = @_;
  3679. if (HMCCU_IsValidDeviceOrChannel ($hash, $addr)) {
  3680. $addr =~ s/:[0-9]+$//;
  3681. return $hash->{hmccu}{dev}{$addr}{interface};
  3682. }
  3683. return $default;
  3684. }
  3685. ######################################################################
  3686. # Get address of a CCU device or channel by CCU name or FHEM device
  3687. # name defined via HMCCUCHN or HMCCUDEV. FHEM device names must be
  3688. # preceded by "hmccu:". CCU names can be preceded by "ccu:".
  3689. # Return array with device address and channel no. If name is not
  3690. # found or refers to a device the specified default values will be
  3691. # returned.
  3692. ######################################################################
  3693. sub HMCCU_GetAddress ($$$$)
  3694. {
  3695. my ($hash, $name, $defadd, $defchn) = @_;
  3696. my $add = $defadd;
  3697. my $chn = $defchn;
  3698. my $chnno = $defchn;
  3699. my $addr = '';
  3700. my $type = '';
  3701. if ($name =~ /^hmccu:.+$/) {
  3702. $name =~ s/^hmccu://;
  3703. if ($name =~ /^([^:]+):([0-9]{1,2})$/) {
  3704. $name = $1;
  3705. $chnno = $2;
  3706. }
  3707. return ($defadd, $defchn) if (!exists ($defs{$name}));
  3708. my $dh = $defs{$name};
  3709. return ($defadd, $defchn) if ($dh->{TYPE} ne 'HMCCUCHN' && $dh->{TYPE} ne 'HMCCUDEV');
  3710. ($add, $chn) = HMCCU_SplitChnAddr ($dh->{ccuaddr});
  3711. $chn = $chnno if ($chn eq '');
  3712. return ($add, $chn);
  3713. }
  3714. elsif ($name =~ /^ccu:.+$/) {
  3715. $name =~ s/^ccu://;
  3716. }
  3717. if (exists ($hash->{hmccu}{adr}{$name})) {
  3718. # Name known by HMCCU
  3719. $addr = $hash->{hmccu}{adr}{$name}{address};
  3720. $type = $hash->{hmccu}{adr}{$name}{addtype};
  3721. }
  3722. elsif (exists ($hash->{hmccu}{dev}{$name})) {
  3723. # Address known by HMCCU
  3724. $addr = $name;
  3725. $type = $hash->{hmccu}{dev}{$name}{addtype};
  3726. }
  3727. else {
  3728. # Address not known. Query CCU
  3729. my ($dc, $cc) = HMCCU_GetDevice ($hash, $name);
  3730. if ($dc > 0 && $cc > 0 && exists ($hash->{hmccu}{adr}{$name})) {
  3731. $addr = $hash->{hmccu}{adr}{$name}{address};
  3732. $type = $hash->{hmccu}{adr}{$name}{addtype};
  3733. }
  3734. }
  3735. if ($addr ne '') {
  3736. if ($type eq 'chn') {
  3737. ($add, $chn) = split (":", $addr);
  3738. }
  3739. else {
  3740. $add = $addr;
  3741. }
  3742. }
  3743. return ($add, $chn);
  3744. }
  3745. ######################################################################
  3746. # Check if parameter is a channel address (syntax)
  3747. # f=1: Interface required.
  3748. ######################################################################
  3749. sub HMCCU_IsChnAddr ($$)
  3750. {
  3751. my ($id, $f) = @_;
  3752. if ($f) {
  3753. return ($id =~ /^.+\.[\*]*[A-Z]{3}[0-9]{7}:[0-9]{1,2}$/ ||
  3754. $id =~ /^.+\.[0-9A-F]{12,14}:[0-9]{1,2}$/ ||
  3755. $id =~ /^.+\.OL-.+:[0-9]{1,2}$/ ||
  3756. $id =~ /^.+\.BidCoS-RF:[0-9]{1,2}$/) ? 1 : 0;
  3757. }
  3758. else {
  3759. return ($id =~ /^[\*]*[A-Z]{3}[0-9]{7}:[0-9]{1,2}$/ ||
  3760. $id =~ /^[0-9A-F]{12,14}:[0-9]{1,2}$/ ||
  3761. $id =~ /^OL-.+:[0-9]{1,2}$/ ||
  3762. $id =~ /^BidCoS-RF:[0-9]{1,2}$/) ? 1 : 0;
  3763. }
  3764. }
  3765. ######################################################################
  3766. # Check if parameter is a device address (syntax)
  3767. # f=1: Interface required.
  3768. ######################################################################
  3769. sub HMCCU_IsDevAddr ($$)
  3770. {
  3771. my ($id, $f) = @_;
  3772. if ($f) {
  3773. return ($id =~ /^.+\.[\*]*[A-Z]{3}[0-9]{7}$/ ||
  3774. $id =~ /^.+\.[0-9A-F]{12,14}$/ ||
  3775. $id =~ /^.+\.OL-.+$/ ||
  3776. $id =~ /^.+\.BidCoS-RF$/) ? 1 : 0;
  3777. }
  3778. else {
  3779. return ($id =~ /^[\*]*[A-Z]{3}[0-9]{7}$/ ||
  3780. $id =~ /^[0-9A-F]{12,14}$/ ||
  3781. $id =~ /^OL-.+$/ ||
  3782. $id eq 'BidCoS-RF') ? 1 : 0;
  3783. }
  3784. }
  3785. ######################################################################
  3786. # Split channel address into device address and channel number.
  3787. # Returns device address only if parameter is already a device address.
  3788. ######################################################################
  3789. sub HMCCU_SplitChnAddr ($)
  3790. {
  3791. my ($addr) = @_;
  3792. my ($dev, $chn) = split (':', $addr);
  3793. $chn = '' if (!defined ($chn));
  3794. return ($dev, $chn);
  3795. }
  3796. ######################################################################
  3797. # Query object attribute from CCU. Attribute must be a valid method
  3798. # for specified object, i.e. Address()
  3799. ######################################################################
  3800. sub HMCCU_GetCCUObjectAttribute ($$$)
  3801. {
  3802. my ($hash, $object, $attr) = @_;
  3803. my $name = $hash->{NAME};
  3804. my $ccureqtimeout = AttrVal ($name, "ccuReqTimeout", $HMCCU_TIMEOUT_REQUEST);
  3805. my $url = 'http://'.$hash->{host}.':8181/do.exe?r1=dom.GetObject("'.$object.'").'.$attr;
  3806. my $response = GetFileFromURL ($url, $ccureqtimeout);
  3807. if (defined ($response) && $response !~ /<r1>null</) {
  3808. if ($response =~ /<r1>(.+)<\/r1>/) {
  3809. return $1;
  3810. }
  3811. }
  3812. return undef;
  3813. }
  3814. ######################################################################
  3815. # Get list of client devices matching the specified criteria.
  3816. # If no criteria is specified all device names will be returned.
  3817. # Parameters modexp and namexp are regular expressions for module
  3818. # name and device name. Parameter internal contains a comma separated
  3819. # list of expressions like internal=valueexp.
  3820. # All parameters can be undefined. In this case all devices will be
  3821. # returned.
  3822. ######################################################################
  3823. sub HMCCU_FindClientDevices ($$$$)
  3824. {
  3825. my ($hash, $modexp, $namexp, $internal) = @_;
  3826. my @devlist = ();
  3827. foreach my $d (keys %defs) {
  3828. my $ch = $defs{$d};
  3829. my $m = 1;
  3830. next if (!defined ($ch->{TYPE}) || !defined ($ch->{NAME}));
  3831. next if (defined ($modexp) && $ch->{TYPE} !~ /$modexp/);
  3832. next if (defined ($namexp) && $ch->{NAME} !~ /$namexp/);
  3833. next if (defined ($hash) && exists ($ch->{IODev}) && $ch->{IODev} != $hash);
  3834. if (defined ($internal)) {
  3835. foreach my $intspec (split (',', $internal)) {
  3836. my ($i, $v) = split ('=', $intspec);
  3837. if (defined ($v) && exists ($ch->{$i}) && $ch->{$i} !~ /$v/) {
  3838. $m = 0;
  3839. last;
  3840. }
  3841. }
  3842. }
  3843. push @devlist, $ch->{NAME} if ($m == 1);
  3844. }
  3845. return @devlist;
  3846. }
  3847. ######################################################################
  3848. # Get name of assigned client device of type HMCCURPC or HMCCURPCPROC.
  3849. # Create a RPC device of type HMCCURPC or HMCCURPCPROC if none is
  3850. # found and parameter create is set to 1.
  3851. # Return (devname, create).
  3852. # Return empty string for devname if RPC device cannot be identified
  3853. # or created. Return create = 1 if device has been created and
  3854. # configuration should be saved.
  3855. ######################################################################
  3856. sub HMCCU_GetRPCDevice ($$$)
  3857. {
  3858. my ($hash, $create, $ifname) = @_;
  3859. my $name = $hash->{NAME};
  3860. my $rpcdevname;
  3861. my $rpcdevtype = 'HMCCURPC';
  3862. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  3863. if ($ccuflags =~ /procrpc/) {
  3864. return (HMCCU_Log ($hash, 1, "Interface not defined for RPC server of type HMCCURPCPROC", ''), 0)
  3865. if (!defined ($ifname));
  3866. $rpcdevname = HMCCU_GetRPCServerInfo ($hash, $ifname, 'device');
  3867. return ($rpcdevname, 0) if (defined ($rpcdevname));
  3868. $rpcdevtype = 'HMCCURPCPROC';
  3869. }
  3870. elsif ($ccuflags =~ /extrpc/) {
  3871. if (defined ($hash->{RPCDEV})) {
  3872. if (exists ($defs{$hash->{RPCDEV}})) {
  3873. my $rpchash = $defs{$hash->{RPCDEV}};
  3874. return (HMCCU_Log ($hash, 1, "RPC device ".$hash->{RPCDEV}." is not assigned to $name", ''), 0)
  3875. if (!defined ($rpchash->{IODev}) || $rpchash->{IODev} != $hash);
  3876. }
  3877. else {
  3878. return (HMCCU_Log ($hash, 1, "RPC device ".$hash->{RPCDEV}." not found", ''), 0);
  3879. }
  3880. return $hash->{RPCDEV};
  3881. }
  3882. }
  3883. else {
  3884. return (HMCCU_Log ($hash, 1, "No need for RPC device when using internal RPC server", ''), 0);
  3885. }
  3886. # Search for RPC devices associated with I/O device
  3887. my @devlist;
  3888. foreach my $dev (keys %defs) {
  3889. my $devhash = $defs{$dev};
  3890. next if ($devhash->{TYPE} ne $rpcdevtype || $devhash->{host} ne $hash->{host});
  3891. next if ($rpcdevtype eq 'HMCCURPCPROC' && $devhash->{rpcinterface} ne $ifname);
  3892. push @devlist, $devhash->{NAME};
  3893. }
  3894. my $devcnt = scalar (@devlist);
  3895. if ($devcnt == 1) {
  3896. if ($ccuflags =~ /extrpc/) {
  3897. $hash->{RPCDEV} = $devlist[0];
  3898. }
  3899. else {
  3900. $hash->{hmccu}{interfaces}{$ifname}{device} = $devlist[0];
  3901. }
  3902. return ($devlist[0], 0);
  3903. }
  3904. elsif ($devcnt > 1) {
  3905. return (HMCCU_Log ($hash, 2, "Found more than one RPC device", ''), 0);
  3906. }
  3907. HMCCU_Log ($hash, 1, "No RPC device defined", undef);
  3908. # Create RPC device
  3909. if ($create) {
  3910. my $alias = "CCU RPC";
  3911. my $rpccreate = "d_rpc $rpcdevtype ".$hash->{host};
  3912. $rpcdevname = "d_rpc";
  3913. if (defined ($ifname)) {
  3914. $rpcdevname = makeDeviceName ("d_rpc".$ifname);
  3915. $alias .= " $ifname";
  3916. $rpccreate = "$rpcdevname $rpcdevtype ".$hash->{host}. " $ifname";
  3917. }
  3918. HMCCU_Log ($hash, 1, "Creating new RPC device $rpcdevname", undef);
  3919. my $ret = CommandDefine (undef, $rpccreate);
  3920. if (!defined ($ret)) {
  3921. # HMCCURPC device created. Set/copy some attributes from HMCCU device
  3922. my %rpcdevattr = ('room' => 'copy', 'group' => 'copy', 'icon' => 'copy',
  3923. 'stateFormat' => 'rpcstate/state', 'eventMap' => '/rpcserver on:on/rpcserver off:off/',
  3924. 'verbose' => 2, 'alias' => $alias );
  3925. foreach my $a (keys %rpcdevattr) {
  3926. my $v = $rpcdevattr{$a} eq 'copy' ? AttrVal ($name, $a, '') : $rpcdevattr{$a};
  3927. CommandAttr (undef, "$rpcdevname $a $v") if ($v ne '');
  3928. }
  3929. $hash->{RPCDEV} = $rpcdevname if ($ccuflags =~ /extrpc/);
  3930. return ($rpcdevname, 1);
  3931. }
  3932. else {
  3933. Log3 $name, 1, "HMCCU: [$name] Definition of RPC device failed.";
  3934. Log3 $name, 1, "HMCCU: [$name] $ret";
  3935. }
  3936. }
  3937. return ('', 0);
  3938. }
  3939. ######################################################################
  3940. # Get hash of HMCCU IO device which is responsible for device or
  3941. # channel specified by parameter
  3942. ######################################################################
  3943. sub HMCCU_FindIODevice ($)
  3944. {
  3945. my ($param) = @_;
  3946. foreach my $dn (sort keys %defs) {
  3947. my $ch = $defs{$dn};
  3948. next if (!exists ($ch->{TYPE}));
  3949. next if ($ch->{TYPE} ne 'HMCCU');
  3950. return $ch if (HMCCU_IsValidDeviceOrChannel ($ch, $param));
  3951. }
  3952. return undef;
  3953. }
  3954. ######################################################################
  3955. # Get hash of HMCCU IO device. Useful for client devices. Accepts hash
  3956. # of HMCCU, HMCCUDEV or HMCCUCHN device as parameter.
  3957. ######################################################################
  3958. sub HMCCU_GetHash ($@)
  3959. {
  3960. my ($hash) = @_;
  3961. if (defined ($hash) && $hash != 0) {
  3962. if ($hash->{TYPE} eq 'HMCCUDEV' || $hash->{TYPE} eq 'HMCCUCHN') {
  3963. return $hash->{IODev} if (exists ($hash->{IODev}));
  3964. return HMCCU_FindIODevice ($hash->{ccuaddr}) if (exists ($hash->{ccuaddr}));
  3965. }
  3966. elsif ($hash->{TYPE} eq 'HMCCU') {
  3967. return $hash;
  3968. }
  3969. }
  3970. # Search for first HMCCU device
  3971. foreach my $dn (sort keys %defs) {
  3972. my $ch = $defs{$dn};
  3973. next if (!exists ($ch->{TYPE}));
  3974. return $ch if ($ch->{TYPE} eq 'HMCCU');
  3975. }
  3976. return undef;
  3977. }
  3978. ######################################################################
  3979. # Get attribute of client device. Fallback to attribute of IO device.
  3980. ######################################################################
  3981. sub HMCCU_GetAttribute ($$$$)
  3982. {
  3983. my ($hmccu_hash, $cl_hash, $attr_name, $attr_def) = @_;
  3984. my $value = AttrVal ($cl_hash->{NAME}, $attr_name, '');
  3985. $value = AttrVal ($hmccu_hash->{NAME}, $attr_name, $attr_def) if ($value eq '');
  3986. return $value;
  3987. }
  3988. ######################################################################
  3989. # Get number of occurrences of datapoint.
  3990. # Return 0 if datapoint does not exist.
  3991. ######################################################################
  3992. sub HMCCU_GetDatapointCount ($$$)
  3993. {
  3994. my ($hash, $devtype, $dpt) = @_;
  3995. if (exists ($hash->{hmccu}{dp}{$devtype}{cnt}{$dpt})) {
  3996. return $hash->{hmccu}{dp}{$devtype}{cnt}{$dpt};
  3997. }
  3998. else {
  3999. return 0;
  4000. }
  4001. }
  4002. ######################################################################
  4003. # Get channels and datapoints from attributes statechannel,
  4004. # statedatapoint and controldatapoint.
  4005. # Return attribute values. Attribute controldatapoint is splitted into
  4006. # controlchannel and datapoint name. If attribute statedatapoint
  4007. # contains channel number it is splitted into statechannel and
  4008. # datapoint name.
  4009. # If controldatapoint is not specified it will synchronized with
  4010. # statedatapoint.
  4011. ######################################################################
  4012. sub HMCCU_GetSpecialDatapoints ($$$$$)
  4013. {
  4014. # my ($hash, $defsc, $defsd, $defcc, $defcd) = @_;
  4015. my ($hash, $sc, $sd, $cc, $cd) = @_;
  4016. my $name = $hash->{NAME};
  4017. my $type = $hash->{TYPE};
  4018. my $statedatapoint = AttrVal ($name, 'statedatapoint', '');
  4019. my $statechannel = AttrVal ($name, 'statechannel', '');
  4020. my $controldatapoint = AttrVal ($name, 'controldatapoint', $statedatapoint);
  4021. if ($statedatapoint ne '') {
  4022. if ($statedatapoint =~ /^([0-9]+)\.(.+)$/) {
  4023. ($sc, $sd) = ($1, $2);
  4024. }
  4025. else {
  4026. $sd = $statedatapoint;
  4027. }
  4028. }
  4029. $sc = $statechannel if ($statechannel ne '' && $sc eq '');
  4030. if ($controldatapoint ne '') {
  4031. if ($controldatapoint =~ /^([0-9]+)\.(.+)$/) {
  4032. ($cc, $cd) = ($1, $2);
  4033. }
  4034. else {
  4035. $cd = $controldatapoint;
  4036. }
  4037. }
  4038. # For devices of type HMCCUCHN extract channel numbers from CCU device address
  4039. if ($type eq 'HMCCUCHN') {
  4040. $sc = $hash->{ccuaddr};
  4041. $sc =~ s/^[\*]*[0-9A-Z]+://;
  4042. $cc = $sc;
  4043. }
  4044. # Try to find state channel
  4045. my $c = -1;
  4046. if ($sc eq '' && $sd ne '') {
  4047. $c = HMCCU_FindDatapoint ($hash, $hash->{ccutype}, -1, $sd, 3);
  4048. $sc = $c if ($c >= 0);
  4049. }
  4050. # Try to find control channel
  4051. if ($cc eq '' && $cd ne '') {
  4052. $c = HMCCU_FindDatapoint ($hash, $hash->{ccutype}, -1, $cd, 3);
  4053. $cc = $c if ($c >= 0);
  4054. }
  4055. # By default set control channel and datapoint to state channel and datapoint
  4056. $cc = $sc if ($cc eq '');
  4057. $cd = $sd if ($cd eq '');
  4058. return ($sc, $sd, $cc, $cd);
  4059. }
  4060. ######################################################################
  4061. # Get reading format considering default attribute
  4062. # ccudef-readingformat defined in I/O device.
  4063. # Default reading format for virtual groups is always 'name'.
  4064. ######################################################################
  4065. sub HMCCU_GetAttrReadingFormat ($$)
  4066. {
  4067. my ($clhash, $iohash) = @_;
  4068. my $clname = $clhash->{NAME};
  4069. my $ioname = $iohash->{NAME};
  4070. my $rfdef = '';
  4071. if (exists ($clhash->{ccutype}) && $clhash->{ccutype} =~ /^HM-CC-VG/) {
  4072. $rfdef = 'name';
  4073. }
  4074. else {
  4075. $rfdef = AttrVal ($ioname, 'ccudef-readingformat', 'datapoint');
  4076. }
  4077. return AttrVal ($clname, 'ccureadingformat', $rfdef);
  4078. }
  4079. ######################################################################
  4080. # Get attributes substitute and substexcl considering default
  4081. # attribute ccudef-substitute defined in I/O device.
  4082. # Substitute ${xxx} by datapoint value.
  4083. ######################################################################
  4084. sub HMCCU_GetAttrSubstitute ($$)
  4085. {
  4086. my ($clhash, $iohash) = @_;
  4087. my $fnc = "GetAttrSubstitute";
  4088. my $clname = $clhash->{NAME};
  4089. my $ioname = $iohash->{NAME};
  4090. # my $ccuflags = AttrVal ($clname, 'ccuflags', 'null');
  4091. my $substdef = AttrVal ($ioname, 'ccudef-substitute', '');
  4092. my $subst = AttrVal ($clname, 'substitute', $substdef);
  4093. $subst .= ";$substdef" if ($subst ne $substdef && $substdef ne '');
  4094. HMCCU_Trace ($clhash, 2, $fnc, "subst = $subst");
  4095. return $subst if ($subst !~ /\$\{.+\}/);
  4096. $subst = HMCCU_SubstVariables ($clhash, $subst, undef);
  4097. HMCCU_Trace ($clhash, 2, $fnc, "subst_vars = $subst");
  4098. return $subst;
  4099. }
  4100. ######################################################################
  4101. # Clear RPC queue
  4102. ######################################################################
  4103. sub HMCCU_ResetRPCQueue ($$)
  4104. {
  4105. my ($hash, $port) = @_;
  4106. my $name = $hash->{NAME};
  4107. my $rpcqueue = AttrVal ($name, 'rpcqueue', '/tmp/ccuqueue');
  4108. my $clkey = 'CB'.$port;
  4109. if (HMCCU_QueueOpen ($hash, $rpcqueue."_".$port."_".$hash->{CCUNum})) {
  4110. HMCCU_QueueReset ($hash);
  4111. while (defined (HMCCU_QueueDeq ($hash))) { }
  4112. HMCCU_QueueClose ($hash);
  4113. }
  4114. $hash->{hmccu}{rpc}{$clkey}{queue} = '' if (exists ($hash->{hmccu}{rpc}{$clkey}{queue}));
  4115. }
  4116. ######################################################################
  4117. # Process RPC server event
  4118. ######################################################################
  4119. sub HMCCU_ProcessEvent ($$)
  4120. {
  4121. my ($hash, $event) = @_;
  4122. my $name = $hash->{NAME};
  4123. my $rh = \%{$hash->{hmccu}{rpc}};
  4124. return undef if (!defined ($event) || $event eq '');
  4125. my @t = split (/\|/, $event);
  4126. my $tc = scalar (@t);
  4127. # Update statistic counters
  4128. if (exists ($hash->{hmccu}{ev}{$t[0]})) {
  4129. $hash->{hmccu}{evtime} = time ();
  4130. $hash->{hmccu}{ev}{total}++;
  4131. $hash->{hmccu}{ev}{$t[0]}++;
  4132. $hash->{hmccu}{evtimeout} = 0 if ($hash->{hmccu}{evtimeout} == 1);
  4133. }
  4134. else {
  4135. my $errtok = $t[0];
  4136. $errtok =~ s/([\x00-\xFF])/sprintf("0x%X ",ord($1))/eg;
  4137. return HMCCU_Log ($hash, 2, "Received unknown event from CCU: ".$errtok, undef);
  4138. }
  4139. # Check event syntax
  4140. return HMCCU_Log ($hash, 2, "Wrong number of parameters in event $event", undef)
  4141. if (exists ($rpceventargs{$t[0]}) && ($tc-1) != $rpceventargs{$t[0]});
  4142. if ($t[0] eq 'EV') {
  4143. #
  4144. # Update of datapoint
  4145. # Input: EV|Adress|Datapoint|Value
  4146. # Output: EV, DevAdd, ChnNo, Reading='', Value
  4147. #
  4148. return HMCCU_Log ($hash, 2, "Invalid channel ".$t[1], undef)
  4149. if (!HMCCU_IsValidChannel ($hash, $t[1]));
  4150. my ($add, $chn) = split (/:/, $t[1]);
  4151. return ($t[0], $add, $chn, $t[2], $t[3]);
  4152. }
  4153. elsif ($t[0] eq 'SL') {
  4154. #
  4155. # RPC server enters server loop
  4156. # Input: SL|Pid|Servername
  4157. # Output: SL, Servername, Pid
  4158. #
  4159. my $clkey = $t[2];
  4160. return HMCCU_Log ($hash, 0, "Received SL event for unknown RPC server $clkey", undef)
  4161. if (!exists ($rh->{$clkey}));
  4162. Log3 $name, 0, "HMCCU: Received SL event. RPC server $clkey enters server loop";
  4163. $rh->{$clkey}{loop} = 1 if ($rh->{$clkey}{pid} == $t[1]);
  4164. return ($t[0], $clkey, $t[1]);
  4165. }
  4166. elsif ($t[0] eq 'IN') {
  4167. #
  4168. # RPC server initialized
  4169. # Input: IN|INIT|State|Servername
  4170. # Output: IN, Servername, Running, NotRunning, ClientsUpdated, UpdateErrors
  4171. #
  4172. my $clkey = $t[3];
  4173. my $norun = 0;
  4174. my $run = 0;
  4175. return HMCCU_Log ($hash, 0, "Received IN event for unknown RPC server $clkey", undef)
  4176. if (!exists ($rh->{$clkey}));
  4177. Log3 $name, 0, "HMCCU: Received IN event. RPC server $clkey initialized.";
  4178. $rh->{$clkey}{state} = $rh->{$clkey}{pid} != 0 ? "running" : "initialized";
  4179. # Check if all RPC servers were initialized. Set overall status
  4180. foreach my $ser (keys %{$rh}) {
  4181. $norun++ if ($rh->{$ser}{state} ne "running" && $rh->{$ser}{pid} != 0);
  4182. $norun++ if ($rh->{$ser}{state} ne "initialized" && $rh->{$ser}{pid} == 0);
  4183. $run++ if ($rh->{$ser}{state} eq "running");
  4184. }
  4185. HMCCU_SetRPCState ($hash, 'running') if ($norun == 0);
  4186. $hash->{hmccu}{rpcinit} = $run;
  4187. return ($t[0], $clkey, $run, $norun);
  4188. }
  4189. elsif ($t[0] eq 'EX') {
  4190. #
  4191. # RPC server shutdown
  4192. # Input: EX|SHUTDOWN|Pid|Servername
  4193. # Output: EX, Servername, Pid, Flag, Run
  4194. #
  4195. my $clkey = $t[3];
  4196. my $run = 0;
  4197. return HMCCU_Log ($hash, 0, "Received EX event for unknown RPC server $clkey", undef)
  4198. if (!exists ($rh->{$clkey}));
  4199. Log3 $name, 0, "HMCCU: Received EX event. RPC server $clkey terminated.";
  4200. my $f = $hash->{RPCState} eq "restarting" ? 2 : 1;
  4201. delete $rh->{$clkey};
  4202. # Check if all RPC servers were terminated. Set overall status
  4203. foreach my $ser (keys %{$rh}) {
  4204. $run++ if ($rh->{$ser}{state} ne "inactive");
  4205. }
  4206. if ($run == 0) {
  4207. HMCCU_SetRPCState ($hash, 'inactive') if ($f == 1);
  4208. $hash->{RPCPID} = '0';
  4209. }
  4210. $hash->{hmccu}{rpccount} = $run;
  4211. $hash->{hmccu}{rpcinit} = $run;
  4212. return ($t[0], $clkey, $t[2], $f, $run);
  4213. }
  4214. elsif ($t[0] eq 'ND') {
  4215. #
  4216. # CCU device added
  4217. # Input: ND|C/D|Address|Type|Version|Firmware|RxMode
  4218. # Output: ND, DevAdd, C/D, Type, Version, Firmware, RxMode
  4219. #
  4220. return ($t[0], $t[2], $t[1], $t[3], $t[4], $t[5], $t[6]);
  4221. }
  4222. elsif ($t[0] eq 'DD' || $t[0] eq 'RA') {
  4223. #
  4224. # CCU device added, deleted or readded
  4225. # Input: {DD,RA}|Address
  4226. # Output: {DD,RA}, DevAdd
  4227. #
  4228. return ($t[0], $t[1]);
  4229. }
  4230. elsif ($t[0] eq 'UD') {
  4231. #
  4232. # CCU device updated
  4233. # Input: UD|Address|Hint
  4234. # Output: UD, DevAdd, Hint
  4235. #
  4236. return ($t[0], $t[1], $t[2]);
  4237. }
  4238. elsif ($t[0] eq 'RD') {
  4239. #
  4240. # CCU device replaced
  4241. # Input: RD|Address1|Address2
  4242. # Output: RD, Address1, Address2
  4243. #
  4244. return ($t[0], $t[1], $t[2]);
  4245. }
  4246. elsif ($t[0] eq 'ST') {
  4247. #
  4248. # Statistic data. Store snapshots of sent and received events.
  4249. # Input: ST|nTotal|nEV|nND|nDD|nRD|nRA|nUD|nIN|nSL|nEX
  4250. # Output: ST, ...
  4251. #
  4252. my @stkeys = ('total', 'EV', 'ND', 'DD', 'RD', 'RA', 'UD', 'IN', 'SL', 'EX');
  4253. for (my $i=0; $i<10; $i++) {
  4254. $hash->{hmccu}{evs}{$stkeys[$i]} = $t[$i+1];
  4255. $hash->{hmccu}{evr}{$stkeys[$i]} = $hash->{hmccu}{ev}{$stkeys[$i]};
  4256. }
  4257. return @t;
  4258. }
  4259. else {
  4260. my $errtok = $t[0];
  4261. $errtok =~ s/([\x00-\xFF])/sprintf("0x%X ",ord($1))/eg;
  4262. Log3 $name, 2, "HMCCU: Received unknown event from CCU: ".$errtok;
  4263. }
  4264. return undef;
  4265. }
  4266. ######################################################################
  4267. # Timer function for reading RPC queue
  4268. ######################################################################
  4269. sub HMCCU_ReadRPCQueue ($)
  4270. {
  4271. my ($hash) = @_;
  4272. my $name = $hash->{NAME};
  4273. my $eventno = 0;
  4274. my $f = 0;
  4275. my @newdevices;
  4276. my @deldevices;
  4277. my @termpids;
  4278. my $newcount = 0;
  4279. my $devcount = 0;
  4280. my %events = ();
  4281. my %devices = ();
  4282. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  4283. my $rpcinterval = AttrVal ($name, 'rpcinterval', 5);
  4284. my $rpcqueue = AttrVal ($name, 'rpcqueue', '/tmp/ccuqueue');
  4285. my $rpcevtimeout = AttrVal ($name, 'rpcevtimeout', $HMCCU_TIMEOUT_EVENT);
  4286. my $maxevents = $rpcinterval*10;
  4287. $maxevents = 50 if ($maxevents > 50);
  4288. $maxevents = 10 if ($maxevents < 10);
  4289. my @portlist = HMCCU_GetRPCPortList ($hash);
  4290. foreach my $port (@portlist) {
  4291. my $clkey = 'CB'.$port;
  4292. next if (!exists ($hash->{hmccu}{rpc}{$clkey}{queue}));
  4293. my $queuename = $hash->{hmccu}{rpc}{$clkey}{queue};
  4294. next if ($queuename eq '');
  4295. if (!HMCCU_QueueOpen ($hash, $queuename)) {
  4296. Log3 $name, 1, "HMCCU: Can't open file queue $queuename";
  4297. next;
  4298. }
  4299. my $element = HMCCU_QueueDeq ($hash);
  4300. while (defined ($element)) {
  4301. Log3 $name, 2, "HMCCU: Event = $element" if ($ccuflags =~ /logEvents/);
  4302. my ($et, @par) = HMCCU_ProcessEvent ($hash, $element);
  4303. if (defined ($et)) {
  4304. if ($et eq 'EV') {
  4305. $events{$par[0]}{$par[1]}{$par[2]} = $par[3];
  4306. $eventno++;
  4307. last if ($eventno == $maxevents);
  4308. }
  4309. elsif ($et eq 'ND') {
  4310. # push (@newdevices, $par[1]);
  4311. $newcount++ if (!exists ($hash->{hmccu}{dev}{$par[0]}));
  4312. # $hash->{hmccu}{dev}{$par[1]}{chntype} = $par[3];
  4313. $devices{$par[0]}{flag} = 'N';
  4314. $devices{$par[0]}{version} = $par[3];
  4315. if ($par[1] eq 'D') {
  4316. $devices{$par[0]}{addtype} = 'dev';
  4317. $devices{$par[0]}{type} = $par[2];
  4318. $devices{$par[0]}{firmware} = $par[4];
  4319. $devices{$par[0]}{rxmode} = $par[5];
  4320. }
  4321. else {
  4322. $devices{$par[0]}{addtype} = 'chn';
  4323. $devices{$par[0]}{usetype} = $par[2];
  4324. }
  4325. $devcount++;
  4326. }
  4327. elsif ($et eq 'DD') {
  4328. # push (@deldevices, $par[0]);
  4329. $devices{$par[0]}{flag} = 'D';
  4330. $devcount++;
  4331. # $delcount++;
  4332. }
  4333. elsif ($et eq 'RD') {
  4334. $devices{$par[0]}{flag} = 'R';
  4335. $devices{$par[0]}{newaddr} = $par[1];
  4336. $devcount++;
  4337. }
  4338. elsif ($et eq 'SL') {
  4339. InternalTimer (gettimeofday()+$HMCCU_INIT_INTERVAL1,
  4340. 'HMCCU_RPCRegisterCallback', $hash, 0);
  4341. $f = -1;
  4342. last;
  4343. }
  4344. elsif ($et eq 'EX') {
  4345. push (@termpids, $par[1]);
  4346. $f = $par[2];
  4347. last;
  4348. }
  4349. }
  4350. last if ($f == -1);
  4351. # Read next element from queue
  4352. $element = HMCCU_QueueDeq ($hash);
  4353. }
  4354. HMCCU_QueueClose ($hash);
  4355. }
  4356. # Update readings
  4357. HMCCU_UpdateMultipleDevices ($hash, \%events) if ($eventno > 0);
  4358. # Update device table and client device parameter
  4359. HMCCU_UpdateDeviceTable ($hash, \%devices) if ($devcount > 0);
  4360. return if ($f == -1);
  4361. # Check if events from CCU timed out
  4362. if ($hash->{hmccu}{evtime} > 0 && time()-$hash->{hmccu}{evtime} > $rpcevtimeout &&
  4363. $hash->{hmccu}{evtimeout} == 0) {
  4364. $hash->{hmccu}{evtimeout} = 1;
  4365. $hash->{ccustate} = HMCCU_TCPConnect ($hash->{host}, 8181) ? 'timeout' : 'unreachable';
  4366. Log3 $name, 2, "HMCCU: Received no events from CCU since $rpcevtimeout seconds";
  4367. DoTrigger ($name, "No events from CCU since $rpcevtimeout seconds");
  4368. }
  4369. else {
  4370. $hash->{ccustate} = 'active' if ($hash->{ccustate} ne 'active');
  4371. }
  4372. my @hm_pids;
  4373. my @hm_tids;
  4374. HMCCU_IsRPCServerRunning ($hash, \@hm_pids, \@hm_tids);
  4375. my $nhm_pids = scalar (@hm_pids);
  4376. my $nhm_tids = scalar (@hm_tids);
  4377. Log3 $name, 1, "HMCCU: Externally launched RPC server(s) detected. f=$f" if ($nhm_tids > 0);
  4378. if ($f > 0) {
  4379. # At least one RPC server has been stopped. Update PID list
  4380. $hash->{RPCPID} = $nhm_pids > 0 ? join(',',@hm_pids) : '0';
  4381. Log3 $name, 0, "HMCCU: RPC server(s) with PID(s) ".join(',',@termpids)." shut down. f=$f";
  4382. # Output statistic counters
  4383. foreach my $cnt (sort keys %{$hash->{hmccu}{ev}}) {
  4384. Log3 $name, 3, "HMCCU: Eventcount $cnt = ".$hash->{hmccu}{ev}{$cnt};
  4385. }
  4386. }
  4387. if ($f == 2 && $nhm_pids == 0) {
  4388. # All RPC servers terminated and restart flag set
  4389. if ($ccuflags !~ /(extrpc|procrpc)/) {
  4390. return if (HMCCU_StartIntRPCServer ($hash));
  4391. }
  4392. Log3 $name, 0, "HMCCU: Restart of RPC server failed";
  4393. }
  4394. if ($nhm_pids > 0) {
  4395. # Reschedule reading of RPC queues if at least one RPC server is running
  4396. InternalTimer (gettimeofday()+$rpcinterval, 'HMCCU_ReadRPCQueue', $hash, 0);
  4397. }
  4398. else {
  4399. # No more RPC servers active
  4400. Log3 $name, 0, "HMCCU: Periodical check found no RPC Servers";
  4401. # Deregister existing callbacks
  4402. HMCCU_RPCDeRegisterCallback ($hash);
  4403. # Cleanup hash variables
  4404. my @clkeylist = keys %{$hash->{hmccu}{rpc}};
  4405. foreach my $clkey (@clkeylist) {
  4406. delete $hash->{hmccu}{rpc}{$clkey};
  4407. }
  4408. $hash->{hmccu}{rpccount} = 0;
  4409. $hash->{hmccu}{rpcinit} = 0;
  4410. $hash->{RPCPID} = '0';
  4411. $hash->{RPCPRC} = 'none';
  4412. HMCCU_SetRPCState ($hash, 'inactive');
  4413. Log3 $name, 0, "HMCCU: All RPC servers stopped";
  4414. DoTrigger ($name, "All RPC servers stopped");
  4415. }
  4416. }
  4417. ######################################################################
  4418. # Execute Homematic script on CCU.
  4419. # Parameters: device-hash, script-code or script-name, parameter-hash
  4420. # If content of hmscript starts with a ! the following text is treated
  4421. # as name of an internal HomeMatic script function.
  4422. # If content of hmscript is enclosed in [] the content is treated as
  4423. # HomeMatic script code.
  4424. # Otherwise hmscript is the name of a file containing Homematic script
  4425. # code.
  4426. # Return script output or error message starting with "ERROR:".
  4427. ######################################################################
  4428. sub HMCCU_HMScriptExt ($$$)
  4429. {
  4430. my ($hash, $hmscript, $params) = @_;
  4431. my $name = $hash->{NAME};
  4432. my $host = $hash->{host};
  4433. my $code = $hmscript;
  4434. my $scrname = '';
  4435. # Check for internal script
  4436. if ($hmscript =~ /^!(.*)$/) {
  4437. $scrname = $1;
  4438. return "ERROR: Can't find internal script $scrname" if (!exists ($HMCCU_SCRIPTS->{$scrname}));
  4439. $code = $HMCCU_SCRIPTS->{$scrname}{code};
  4440. }
  4441. elsif ($hmscript =~ /^\[(.*)\]$/) {
  4442. $code = $1;
  4443. }
  4444. else {
  4445. if (open (SCRFILE, "<$hmscript")) {
  4446. my @lines = <SCRFILE>;
  4447. $code = join ("\n", @lines);
  4448. close (SCRFILE);
  4449. }
  4450. else {
  4451. return "ERROR: Can't open script file";
  4452. }
  4453. }
  4454. # Check and replace variables
  4455. if (defined ($params)) {
  4456. my @parnames = keys %{$params};
  4457. if ($scrname ne '') {
  4458. if (scalar (@parnames) != $HMCCU_SCRIPTS->{$scrname}{parameters}) {
  4459. return "ERROR: Wrong number of parameters. Usage: $scrname ".
  4460. $HMCCU_SCRIPTS->{$scrname}{syntax};
  4461. }
  4462. foreach my $p (split (/[, ]+/, $HMCCU_SCRIPTS->{$scrname}{syntax})) {
  4463. return "ERROR: Missing definition of parameter $p" if (!exists ($params->{$p}));
  4464. }
  4465. }
  4466. foreach my $svar (keys %{$params}) {
  4467. next if ($code !~ /\$$svar/);
  4468. $code =~ s/\$$svar/$params->{$svar}/g;
  4469. }
  4470. }
  4471. else {
  4472. if ($scrname ne '' && $HMCCU_SCRIPTS->{$scrname}{parameters} > 0) {
  4473. return "ERROR: Wrong number of parameters. Usage: $scrname ".
  4474. $HMCCU_SCRIPTS->{$scrname}{syntax};
  4475. }
  4476. }
  4477. # Execute script on CCU
  4478. my $url = "http://".$host.":8181/tclrega.exe";
  4479. my $ua = new LWP::UserAgent ();
  4480. my $response = $ua->post($url, Content => $code);
  4481. if ($response->is_success ()) {
  4482. my $output = $response->content;
  4483. $output =~ s/<xml>.*<\/xml>//;
  4484. $output =~ s/\r//g;
  4485. return $output;
  4486. }
  4487. else {
  4488. my $msg = $response->status_line();
  4489. Log3 $name, 2, "HMCCU: HMScript failed. $msg";
  4490. return "ERROR: HMScript failed. $msg";
  4491. }
  4492. }
  4493. ######################################################################
  4494. # Bulk update of reading considering attribute substexcl.
  4495. ######################################################################
  4496. sub HMCCU_BulkUpdate ($$$$)
  4497. {
  4498. my ($hash, $reading, $orgval, $subval) = @_;
  4499. my $excl = AttrVal ($hash->{NAME}, 'substexcl', '');
  4500. readingsBulkUpdate ($hash, $reading, ($excl ne '' && $reading =~ /$excl/ ? $orgval : $subval));
  4501. }
  4502. ######################################################################
  4503. # Get datapoint value from CCU and update reading.
  4504. ######################################################################
  4505. sub HMCCU_GetDatapoint ($@)
  4506. {
  4507. my ($hash, $param) = @_;
  4508. my $name = $hash->{NAME};
  4509. my $type = $hash->{TYPE};
  4510. my $fnc = "GetDatapoint";
  4511. my $hmccu_hash;
  4512. my $value = '';
  4513. $hmccu_hash = HMCCU_GetHash ($hash);
  4514. return (-3, $value) if (!defined ($hmccu_hash));
  4515. return (-4, $value) if ($type ne 'HMCCU' && $hash->{ccudevstate} eq 'deleted');
  4516. my $readingformat = HMCCU_GetAttrReadingFormat ($hash, $hmccu_hash);
  4517. my ($statechn, $statedpt, $controlchn, $controldpt) = HMCCU_GetSpecialDatapoints (
  4518. $hash, '', 'STATE', '', '');
  4519. my $ccuget = HMCCU_GetAttribute ($hmccu_hash, $hash, 'ccuget', 'Value');
  4520. my $ccureqtimeout = AttrVal ($hmccu_hash->{NAME}, "ccuReqTimeout", $HMCCU_TIMEOUT_REQUEST);
  4521. my $url = 'http://'.$hmccu_hash->{host}.':8181/do.exe?r1=dom.GetObject("';
  4522. my ($int, $add, $chn, $dpt, $nam, $flags) = HMCCU_ParseObject ($hmccu_hash, $param,
  4523. $HMCCU_FLAG_INTERFACE);
  4524. if ($flags == $HMCCU_FLAGS_IACD) {
  4525. $url .= $int.'.'.$add.':'.$chn.'.'.$dpt.'").'.$ccuget.'()';
  4526. }
  4527. elsif ($flags == $HMCCU_FLAGS_NCD) {
  4528. $url .= $nam.'").DPByHssDP("'.$dpt.'").'.$ccuget.'()';
  4529. ($add, $chn) = HMCCU_GetAddress ($hmccu_hash, $nam, '', '');
  4530. }
  4531. else {
  4532. return (-1, $value);
  4533. }
  4534. HMCCU_Trace ($hash, 2, $fnc, "URL=$url, param=$param, ccuget=$ccuget");
  4535. my $rawresponse = GetFileFromURL ($url, $ccureqtimeout);
  4536. my $response = $rawresponse;
  4537. $response =~ m/<r1>(.*)<\/r1>/;
  4538. $value = $1;
  4539. HMCCU_Trace ($hash, 2, $fnc, "Response = ".$rawresponse);
  4540. if (defined ($value) && $value ne '' && $value ne 'null') {
  4541. $value = HMCCU_UpdateSingleDatapoint ($hash, $chn, $dpt, $value);
  4542. HMCCU_Trace ($hash, 2, $fnc, "Value of $chn.$dpt = $value");
  4543. return (1, $value);
  4544. }
  4545. else {
  4546. Log3 $name, 1, "$type: Error URL = ".$url;
  4547. return (-2, '');
  4548. }
  4549. }
  4550. ######################################################################
  4551. # Set datapoint on CCU.
  4552. # Parameter param is a valid CCU or FHEM datapoint specification:
  4553. # [ccu:]address:channelnumber.datapoint
  4554. # [ccu:]channelname.datapoint
  4555. # hmccu:hmccudev_name.channelnumber.datapoint
  4556. # hmccu:hmccuchn_name.datapoint
  4557. ######################################################################
  4558. sub HMCCU_SetDatapoint ($$$)
  4559. {
  4560. my ($hash, $param, $value) = @_;
  4561. my $fnc = "SetDatapoint";
  4562. my $type = $hash->{TYPE};
  4563. my $hmccu_hash = HMCCU_GetHash ($hash);
  4564. return -3 if (!defined ($hmccu_hash));
  4565. return -4 if (exists ($hash->{ccudevstate}) && $hash->{ccudevstate} eq 'deleted');
  4566. my $name = $hmccu_hash->{NAME};
  4567. my $cdname = $hash->{NAME};
  4568. my $ccureqtimeout = AttrVal ($name, "ccuReqTimeout", $HMCCU_TIMEOUT_REQUEST);
  4569. my $readingformat = HMCCU_GetAttrReadingFormat ($hash, $hmccu_hash);
  4570. my $ccuverify = AttrVal ($cdname, 'ccuverify', 0);
  4571. HMCCU_Trace ($hash, 2, $fnc, "param=$param, value=$value");
  4572. if ($param =~ /^hmccu:.+$/) {
  4573. my @t = split (/\./, $param);
  4574. return -1 if (scalar (@t) < 2 || scalar (@t) > 3);
  4575. my $fhdpt = pop @t;
  4576. my ($fhadd, $fhchn) = HMCCU_GetAddress ($hmccu_hash, $t[0], '', '');
  4577. $fhchn = $t[1] if (scalar (@t) == 2);
  4578. return -1 if ($fhadd eq '' || $fhchn eq '');
  4579. $param = "$fhadd:$fhchn.$fhdpt";
  4580. }
  4581. elsif ($param =~ /^ccu:(.+)$/) {
  4582. $param = $1;
  4583. }
  4584. my $url = 'http://'.$hmccu_hash->{host}.':8181/do.exe?r1=dom.GetObject("';
  4585. my ($int, $add, $chn, $dpt, $nam, $flags) = HMCCU_ParseObject ($hmccu_hash, $param,
  4586. $HMCCU_FLAG_INTERFACE);
  4587. return -1 if ($flags != $HMCCU_FLAGS_IACD && $flags != $HMCCU_FLAGS_NCD);
  4588. if ($hash->{ccutype} eq 'HM-Dis-EP-WM55' && $dpt eq 'SUBMIT') {
  4589. $value = HMCCU_EncodeEPDisplay ($value);
  4590. }
  4591. else {
  4592. $value = HMCCU_ScaleValue ($hash, $dpt, $value, 1);
  4593. }
  4594. my $dpttype = HMCCU_GetDatapointAttr ($hmccu_hash, $hash->{ccutype}, $chn, $dpt, 'type');
  4595. if (defined ($dpttype) && $dpttype == $HMCCU_TYPE_STRING) {
  4596. $value = "'".$value."'";
  4597. }
  4598. if ($flags == $HMCCU_FLAGS_IACD) {
  4599. $url .= $int.'.'.$add.':'.$chn.'.'.$dpt.'").State('.$value.')';
  4600. $nam = HMCCU_GetChannelName ($hmccu_hash, $add.":".$chn, '');
  4601. }
  4602. elsif ($flags == $HMCCU_FLAGS_NCD) {
  4603. $url .= $nam.'").DPByHssDP("'.$dpt.'").State('.$value.')';
  4604. ($add, $chn) = HMCCU_GetAddress ($hmccu_hash, $nam, '', '');
  4605. }
  4606. my $addr = $add.":".$chn;
  4607. my $response = GetFileFromURL ($url, $ccureqtimeout);
  4608. HMCCU_Trace ($hash, 2, $fnc,
  4609. "Addr=$addr Name=$nam<br>".
  4610. "Script response = \n".(defined ($response) ? $response: 'undef')."<br>".
  4611. "Script = \n".$url);
  4612. return -2 if (!defined ($response) || $response =~ /<r1>null</);
  4613. # Verify setting of datapoint value or update reading with new datapoint value
  4614. if (HMCCU_IsValidDatapoint ($hash, $hash->{ccutype}, $addr, $dpt, 1)) {
  4615. if ($ccuverify == 1) {
  4616. # usleep (100000);
  4617. my ($rc, $result) = HMCCU_GetDatapoint ($hash, $param);
  4618. return $rc;
  4619. }
  4620. elsif ($ccuverify == 2) {
  4621. HMCCU_UpdateSingleDatapoint ($hash, $chn, $dpt, $value);
  4622. }
  4623. }
  4624. return 0;
  4625. }
  4626. ######################################################################
  4627. # Scale, spread and/or shift datapoint value.
  4628. # Mode: 0 = Get/Divide, 1 = Set/Multiply
  4629. # Supports reversing of value if value range is specified. Syntax for
  4630. # Rule is:
  4631. # Datapoint:Factor
  4632. # [!]Datapoint:Min:Max:Range1:Range2
  4633. # If Datapoint name starts with a ! the value is reversed. In case of
  4634. # an error original value is returned.
  4635. ######################################################################
  4636. sub HMCCU_ScaleValue ($$$$)
  4637. {
  4638. my ($hash, $dpt, $value, $mode) = @_;
  4639. my $name = $hash->{NAME};
  4640. my $ccuscaleval = AttrVal ($name, 'ccuscaleval', '');
  4641. return $value if ($ccuscaleval eq '');
  4642. my @sl = split (',', $ccuscaleval);
  4643. foreach my $sr (@sl) {
  4644. my $f = 1.0;
  4645. my @a = split (':', $sr);
  4646. my $n = scalar (@a);
  4647. next if ($n != 2 && $n != 5);
  4648. my $rev = 0;
  4649. my $dn = $a[0];
  4650. if ($dn =~ /^\!(.+)$/) {
  4651. $dn = $1;
  4652. $rev = 1;
  4653. }
  4654. next if ($dpt ne $dn);
  4655. if ($n == 2) {
  4656. $f = ($a[1] == 0.0) ? 1.0 : $a[1];
  4657. return ($mode == 0) ? $value/$f : $value*$f;
  4658. }
  4659. else {
  4660. # Do not scale if value out of range or interval wrong
  4661. return $value if ($a[1] > $a[2] || $a[3] > $a[4]);
  4662. return $value if ($mode == 0 && ($value < $a[1] || $value > $a[2]));
  4663. # return $value if ($mode == 1 && ($value >= $a[1] && $value <= $a[2]));
  4664. return $value if ($mode == 1 && ($value < $a[3] || $value > $a[4]));
  4665. # Reverse value
  4666. if ($rev) {
  4667. my $dr = ($mode == 0) ? $a[1]+$a[2] : $a[3]+$a[4];
  4668. $value = $dr-$value;
  4669. }
  4670. my $d1 = $a[2]-$a[1];
  4671. my $d2 = $a[4]-$a[3];
  4672. return $value if ($d1 == 0.0 || $d2 == 0.0);
  4673. $f = $d1/$d2;
  4674. return ($mode == 0) ? $value/$f+$a[3] : ($value-$a[3])*$f;
  4675. }
  4676. }
  4677. return $value;
  4678. }
  4679. ######################################################################
  4680. # Get CCU system variables and update readings.
  4681. # System variable readings are stored in I/O device. Unsupported
  4682. # characters in variable names are substituted.
  4683. ######################################################################
  4684. sub HMCCU_GetVariables ($$)
  4685. {
  4686. my ($hash, $pattern) = @_;
  4687. my $name = $hash->{NAME};
  4688. my $count = 0;
  4689. my $result = '';
  4690. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  4691. my $ccureadings = AttrVal ($name, 'ccureadings', $ccuflags =~ /noReadings/ ? 0 : 1);
  4692. my $response = HMCCU_HMScriptExt ($hash, "!GetVariables", undef);
  4693. return (-2, $response) if ($response eq '' || $response =~ /^ERROR:.*/);
  4694. readingsBeginUpdate ($hash) if ($ccureadings);
  4695. foreach my $vardef (split /\n/, $response) {
  4696. my @vardata = split /=/, $vardef;
  4697. next if (@vardata != 3);
  4698. next if ($vardata[0] !~ /$pattern/);
  4699. my $rn = HMCCU_CorrectName ($vardata[0]);
  4700. my $value = HMCCU_FormatReadingValue ($hash, $vardata[2], $vardata[0]);
  4701. readingsBulkUpdate ($hash, $rn, $value) if ($ccureadings);
  4702. $result .= $vardata[0].'='.$vardata[2]."\n";
  4703. $count++;
  4704. }
  4705. readingsEndUpdate ($hash, 1) if ($ccureadings);
  4706. return ($count, $result);
  4707. }
  4708. ######################################################################
  4709. # Set CCU system variable. If parameter vartype is undefined system
  4710. # variable must exist in CCU. Following variable types are supported:
  4711. # bool, list, number, text. Parameter params is a hash reference of
  4712. # script parameters.
  4713. # Return 0 on success, error code on error.
  4714. ######################################################################
  4715. sub HMCCU_SetVariable ($$$$$)
  4716. {
  4717. my ($hash, $varname, $value, $vartype, $params) = @_;
  4718. my $name = $hash->{NAME};
  4719. my $ccureqtimeout = AttrVal ($name, "ccuReqTimeout", $HMCCU_TIMEOUT_REQUEST);
  4720. my %varfnc = (
  4721. "bool" => "!CreateBoolVariable", "list", "!CreateListVariable",
  4722. "number" => "!CreateNumericVariable", "text", "!CreateStringVariable"
  4723. );
  4724. if (!defined ($vartype)) {
  4725. my $url = 'http://'.$hash->{host}.':8181/do.exe?r1=dom.GetObject("'.$varname.
  4726. '").State("'.$value.'")';
  4727. my $response = GetFileFromURL ($url, $ccureqtimeout);
  4728. return HMCCU_Log ($hash, 1, "URL=$url", -2)
  4729. if (!defined ($response) || $response =~ /<r1>null</);
  4730. }
  4731. else {
  4732. return -18 if (!exists ($varfnc{$vartype}));
  4733. # Set default values for variable attributes
  4734. $params->{name} = $varname if (!exists ($params->{name}));
  4735. $params->{init} = $value if (!exists ($params->{init}));
  4736. $params->{unit} = "" if (!exists ($params->{unit}));
  4737. $params->{desc} = "" if (!exists ($params->{desc}));
  4738. $params->{min} = "0" if ($vartype eq 'number' && !exists ($params->{min}));
  4739. $params->{max} = "65000" if ($vartype eq 'number' && !exists ($params->{max}));
  4740. $params->{list} = $value if ($vartype eq 'list' && !exists ($params->{list}));
  4741. $params->{valtrue} = "ist wahr" if ($vartype eq 'bool' && !exists ($params->{valtrue}));
  4742. $params->{valfalse} = "ist falsch" if ($vartype eq 'bool' && !exists ($params->{valfalse}));
  4743. my $rc = HMCCU_HMScriptExt ($hash, $varfnc{$vartype}, $params);
  4744. return HMCCU_Log ($hash, 1, $rc, -2) if ($rc =~ /^ERROR:.*/);
  4745. }
  4746. return 0;
  4747. }
  4748. ######################################################################
  4749. # Update all datapoints / readings of device or channel considering
  4750. # attribute ccureadingfilter.
  4751. # Parameter $ccuget can be 'State', 'Value' or 'Attr'.
  4752. ######################################################################
  4753. sub HMCCU_GetUpdate ($$$)
  4754. {
  4755. my ($cl_hash, $addr, $ccuget) = @_;
  4756. my $name = $cl_hash->{NAME};
  4757. my $type = $cl_hash->{TYPE};
  4758. my $fnc = "GetUpdate";
  4759. my $disable = AttrVal ($name, 'disable', 0);
  4760. return 1 if ($disable == 1);
  4761. my $hmccu_hash = HMCCU_GetHash ($cl_hash);
  4762. return -3 if (!defined ($hmccu_hash));
  4763. return -4 if ($type ne 'HMCCU' && $cl_hash->{ccudevstate} eq 'deleted');
  4764. my $nam = '';
  4765. my $list = '';
  4766. my $script = '';
  4767. $ccuget = HMCCU_GetAttribute ($hmccu_hash, $cl_hash, 'ccuget', 'Value') if ($ccuget eq 'Attr');
  4768. if (HMCCU_IsValidChannel ($hmccu_hash, $addr)) {
  4769. $nam = HMCCU_GetChannelName ($hmccu_hash, $addr, '');
  4770. return -1 if ($nam eq '');
  4771. my ($stadd, $stchn) = split (':', $addr);
  4772. my $stnam = HMCCU_GetChannelName ($hmccu_hash, "$stadd:0", '');
  4773. $list = $stnam eq '' ? $nam : $stnam . "," . $nam;
  4774. $script = "!GetDatapointsByChannel";
  4775. }
  4776. elsif (HMCCU_IsValidDevice ($hmccu_hash, $addr)) {
  4777. $nam = HMCCU_GetDeviceName ($hmccu_hash, $addr, '');
  4778. return -1 if ($nam eq '');
  4779. $list = $nam;
  4780. $script = "!GetDatapointsByDevice";
  4781. # Consider members of group device
  4782. if ($type eq 'HMCCUDEV' && $cl_hash->{ccuif} eq 'VirtualDevices' &&
  4783. exists ($cl_hash->{ccugroup})) {
  4784. foreach my $gd (split (",", $cl_hash->{ccugroup})) {
  4785. $nam = HMCCU_GetDeviceName ($hmccu_hash, $gd, '');
  4786. $list .= ','.$nam if ($nam ne '');
  4787. }
  4788. }
  4789. }
  4790. else {
  4791. return -1;
  4792. }
  4793. my $response = HMCCU_HMScriptExt ($hmccu_hash, $script,
  4794. { list => $list, ccuget => $ccuget });
  4795. HMCCU_Trace ($cl_hash, 2, $fnc, "Addr=$addr Name=$nam Script=$script<br>".
  4796. "Script response = \n".$response);
  4797. return -2 if ($response eq '' || $response =~ /^ERROR:.*/);
  4798. my @dpdef = split /\n/, $response;
  4799. my $count = pop (@dpdef);
  4800. return -10 if (!defined ($count) || $count == 0);
  4801. my %events = ();
  4802. foreach my $dp (@dpdef) {
  4803. my ($chnname, $dpspec, $value) = split /=/, $dp;
  4804. next if (!defined ($value));
  4805. my ($iface, $chnadd, $dpt) = split /\./, $dpspec;
  4806. next if (!defined ($dpt));
  4807. my ($add, $chn) = HMCCU_SplitChnAddr ($chnadd);
  4808. next if ($chn eq '');
  4809. $events{$add}{$chn}{$dpt} = $value;
  4810. }
  4811. HMCCU_UpdateSingleDevice ($hmccu_hash, $cl_hash, \%events);
  4812. return 1;
  4813. }
  4814. ######################################################################
  4815. # Get multiple datapoints of channels and update readings of client
  4816. # devices.
  4817. # Returncodes: -1 = Invalid channel/datapoint in list
  4818. # -2 = CCU script execution failed
  4819. # -3 = Cannot detect IO device
  4820. # On success number of updated readings is returned.
  4821. ######################################################################
  4822. sub HMCCU_GetChannel ($$)
  4823. {
  4824. my ($hash, $chnref) = @_;
  4825. my $name = $hash->{NAME};
  4826. my $type = $hash->{TYPE};
  4827. my $count = 0;
  4828. my $chnlist = '';
  4829. my $result = '';
  4830. my %chnpars;
  4831. my %objects = ();
  4832. my $objcount = 0;
  4833. my $hmccuflags = AttrVal ($name, 'ccuflags', 'null');
  4834. my $ccuget = AttrVal ($name, 'ccuget', 'Value');
  4835. # Build channel list. Datapoints and substitution rules are ignored.
  4836. foreach my $chndef (@$chnref) {
  4837. my ($channel, $substitute) = split /\s+/, $chndef;
  4838. next if (!defined ($channel) || $channel =~ /^#/ || $channel eq '');
  4839. my ($int, $add, $chn, $dpt, $nam, $flags) = HMCCU_ParseObject ($hash, $channel,
  4840. $HMCCU_FLAG_INTERFACE | $HMCCU_FLAG_DATAPOINT);
  4841. if ($flags == $HMCCU_FLAGS_IACD || $flags == $HMCCU_FLAGS_NCD) {
  4842. $nam = HMCCU_GetChannelName ($hash, $add.':'.$chn, '') if ($flags == $HMCCU_FLAGS_IACD);
  4843. $chnlist = $chnlist eq '' ? $nam : $chnlist.','.$nam;
  4844. $chnpars{$nam}{sub} = $substitute;
  4845. $chnpars{$nam}{dpt} = $dpt;
  4846. }
  4847. else {
  4848. return (-1, $result);
  4849. }
  4850. }
  4851. return (0, $result) if ($chnlist eq '');
  4852. my $response = HMCCU_HMScriptExt ($hash, "!GetChannel",
  4853. { list => $chnlist, ccuget => $ccuget });
  4854. return (-2, $result) if ($response eq '' || $response =~ /^ERROR:.*/);
  4855. # Output format is Channelname=Interface.Channeladdress.Datapoint=Value
  4856. foreach my $dpdef (split /\n/, $response) {
  4857. my ($chnname, $dptaddr, $value) = split /=/, $dpdef;
  4858. next if (!defined ($value));
  4859. my ($iface, $chnaddr, $dpt) = split /\./, $dptaddr;
  4860. next if (!defined ($dpt));
  4861. my ($add, $chn) = HMCCU_SplitChnAddr ($chnaddr);
  4862. next if ($chn eq '');
  4863. if (defined ($chnpars{$chnname}{dpt}) && $chnpars{$chnname}{dpt} ne '') {
  4864. next if ($dpt !~ $chnpars{$chnname}{dpt});
  4865. }
  4866. $value = HMCCU_Substitute ($value, $chnpars{$chnname}{sub}, 0, $chn, $dpt);
  4867. $objects{$add}{$chn}{$dpt} = $value;
  4868. $objcount++;
  4869. }
  4870. $count = HMCCU_UpdateMultipleDevices ($hash, \%objects) if ($objcount > 0);
  4871. return ($count, $result);
  4872. }
  4873. ######################################################################
  4874. # Get RPC paramSet or paramSetDescription
  4875. ######################################################################
  4876. sub HMCCU_RPCGetConfig ($$$$)
  4877. {
  4878. my ($hash, $param, $mode, $filter) = @_;
  4879. my $name = $hash->{NAME};
  4880. my $type = $hash->{TYPE};
  4881. my $fnc = "RPCGetConfig";
  4882. my $method = $mode eq 'listParamset' ? 'getParamset' : $mode;
  4883. my $addr;
  4884. my $result = '';
  4885. my $res = '';
  4886. my $hmccu_hash = HMCCU_GetHash ($hash);
  4887. return (-3, $result) if (!defined ($hmccu_hash));
  4888. return (-4, $result) if ($type ne 'HMCCU' && $hash->{ccudevstate} eq 'deleted');
  4889. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  4890. my $ccureadings = AttrVal ($name, 'ccureadings', $ccuflags =~ /noReadings/ ? 0 : 1);
  4891. my $readingformat = HMCCU_GetAttrReadingFormat ($hash, $hmccu_hash);
  4892. my $substitute = HMCCU_GetAttrSubstitute ($hash, $hmccu_hash);
  4893. my ($int, $add, $chn, $dpt, $nam, $flags) = HMCCU_ParseObject ($hmccu_hash, $param,
  4894. $HMCCU_FLAG_FULLADDR);
  4895. return (-1, '') if (!($flags & $HMCCU_FLAG_ADDRESS));
  4896. $addr = $add;
  4897. $addr .= ':'.$chn if ($flags & $HMCCU_FLAG_CHANNEL);
  4898. my $rpctype = HMCCU_GetRPCServerInfo ($hmccu_hash, $int, 'type');
  4899. my $port = HMCCU_GetRPCServerInfo ($hmccu_hash, $int, 'port');
  4900. return (-9, '') if (!defined ($rpctype) || !defined ($port));
  4901. if ($rpctype eq 'B') {
  4902. # Search RPC device
  4903. my $rpcdev = HMCCU_GetRPCDevice ($hmccu_hash, 0, $int);
  4904. return (-17, '') if ($rpcdev eq '');
  4905. HMCCU_Trace ($hash, 2, $fnc, "Method=$method Addr=$addr Port=$port");
  4906. if ($ccuflags =~ /extrpc/) {
  4907. $res = HMCCURPC_SendBinRequest ($defs{$rpcdev}, $port, $method, $BINRPC_STRING, $addr,
  4908. $BINRPC_STRING, "MASTER");
  4909. }
  4910. elsif ($ccuflags =~ /procrpc/) {
  4911. $res = HMCCURPCPROC_SendRequest ($defs{$rpcdev}, $method, $BINRPC_STRING, $addr,
  4912. $BINRPC_STRING, "MASTER");
  4913. }
  4914. }
  4915. else {
  4916. my $url = HMCCU_GetRPCServerInfo ($hmccu_hash, $int, 'url');
  4917. return (-9, '') if (!defined ($url));
  4918. HMCCU_Trace ($hash, 2, $fnc, "Method=$method Addr=$addr Port=$port");
  4919. my $client = RPC::XML::Client->new ($url);
  4920. $res = $client->simple_request ($method, $addr, "MASTER");
  4921. }
  4922. return (-5, "Function not available") if (!defined ($res));
  4923. if (defined ($res)) {
  4924. HMCCU_Trace ($hash, 2, $fnc,
  4925. "Dump of RPC request $method $addr. Result type=".ref($res)."<br>".
  4926. HMCCU_RefToString ($res));
  4927. }
  4928. if (ref ($res) eq 'HASH') {
  4929. my $parcount = scalar (keys %$res);
  4930. if (exists ($res->{faultString})) {
  4931. Log3 $name, 1, "HMCCU: ".$res->{faultString};
  4932. return (-2, $res->{faultString});
  4933. }
  4934. elsif ($parcount == 0) {
  4935. return (-5, "CCU returned no data");
  4936. }
  4937. }
  4938. else {
  4939. return (-2, defined ($RPC::XML::ERROR) ? $RPC::XML::ERROR : '');
  4940. }
  4941. if ($mode eq 'getParamsetDescription') {
  4942. foreach my $key (sort keys %$res) {
  4943. my $oper = '';
  4944. $oper .= 'R' if ($res->{$key}->{OPERATIONS} & 1);
  4945. $oper .= 'W' if ($res->{$key}->{OPERATIONS} & 2);
  4946. $oper .= 'E' if ($res->{$key}->{OPERATIONS} & 4);
  4947. $result .= $key.": ".$res->{$key}->{TYPE}." [".$oper."]\n";
  4948. }
  4949. }
  4950. elsif ($mode eq 'listParamset') {
  4951. foreach my $key (sort keys %$res) {
  4952. next if ($key !~ /$filter/);
  4953. my $value = $res->{$key};
  4954. $result .= "$key=$value\n";
  4955. }
  4956. }
  4957. else {
  4958. readingsBeginUpdate ($hash) if ($ccureadings);
  4959. foreach my $key (sort keys %$res) {
  4960. next if ($key !~ /$filter/);
  4961. my $value = $res->{$key};
  4962. $result .= "$key=$value\n";
  4963. next if (!$ccureadings);
  4964. $value = HMCCU_FormatReadingValue ($hash, $value, $key);
  4965. $value = HMCCU_Substitute ($value, $substitute, 0, $chn, $key);
  4966. my @readings = HMCCU_GetReadingName ($hash, $int, $add, $chn, $key, $nam, $readingformat);
  4967. foreach my $rn (@readings) {
  4968. next if ($rn eq '');
  4969. $rn = "R-".$rn;
  4970. readingsBulkUpdate ($hash, $rn, $value);
  4971. }
  4972. }
  4973. readingsEndUpdate ($hash, 1) if ($ccureadings);
  4974. }
  4975. return (0, $result);
  4976. }
  4977. ######################################################################
  4978. # Set RPC paramSet
  4979. ######################################################################
  4980. sub HMCCU_RPCSetConfig ($$$)
  4981. {
  4982. my ($hash, $param, $parref) = @_;
  4983. my $name = $hash->{NAME};
  4984. my $type = $hash->{TYPE};
  4985. my $ccuflags = AttrVal ($name, 'ccuflags', 'null');
  4986. my $addr;
  4987. my $res;
  4988. my $hmccu_hash = HMCCU_GetHash ($hash);
  4989. return -3 if (!defined ($hmccu_hash));
  4990. return -4 if ($type ne 'HMCCU' && $hash->{ccudevstate} eq 'deleted');
  4991. my ($int, $add, $chn, $dpt, $nam, $flags) = HMCCU_ParseObject ($hmccu_hash, $param,
  4992. $HMCCU_FLAG_FULLADDR);
  4993. return -1 if (!($flags & $HMCCU_FLAG_ADDRESS));
  4994. $addr = $add;
  4995. $addr .= ':'.$chn if ($flags & $HMCCU_FLAG_CHANNEL);
  4996. my $rpctype = HMCCU_GetRPCServerInfo ($hmccu_hash, $int, 'type');
  4997. return -9 if (!defined ($rpctype));
  4998. my $port = HMCCU_GetRPCServerInfo ($hmccu_hash, $int, 'port');
  4999. return -9 if (!defined ($port));
  5000. if ($ccuflags =~ /trace/) {
  5001. my $ps = '';
  5002. foreach my $p (keys %$parref) {
  5003. $ps .= ", ".$p."=".$parref->{$p};
  5004. }
  5005. Log3 $name, 2, "HMCCU: RPCSetConfig: addr=$addr".$ps;
  5006. }
  5007. if ($rpctype eq 'B') {
  5008. # Search RPC device
  5009. my $rpcdev = HMCCU_GetRPCDevice ($hmccu_hash, 0, $int);
  5010. return -17 if ($rpcdev eq '');
  5011. # Rebuild parameter hash for binary encoding
  5012. my %binpar;
  5013. foreach my $e (keys %$parref) {
  5014. $binpar{$e}{T} = $BINRPC_STRING;
  5015. $binpar{$e}{V} = $parref->{$e};
  5016. }
  5017. if ($ccuflags =~ /extrpc/) {
  5018. $res = HMCCURPC_SendBinRequest ($defs{$rpcdev}, $port, "putParamset", $BINRPC_STRING, $addr,
  5019. $BINRPC_STRING, "MASTER", $BINRPC_STRUCT, \%binpar);
  5020. }
  5021. elsif ($ccuflags =~ /procrpc/) {
  5022. $res = HMCCURPCPROC_SendRequest ($defs{$rpcdev}, "putParamset", $BINRPC_STRING, $addr,
  5023. $BINRPC_STRING, "MASTER", $BINRPC_STRUCT, \%binpar);
  5024. }
  5025. }
  5026. else {
  5027. my $url = HMCCU_GetRPCServerInfo ($hmccu_hash, $int, 'url');
  5028. return -9 if (!defined ($url));
  5029. my $client = RPC::XML::Client->new ($url);
  5030. $res = $client->simple_request ("putParamset", $addr, "MASTER", $parref);
  5031. }
  5032. return -5 if (! defined ($res));
  5033. return HMCCU_Log ($hash, 1, "HMCCU: RPC request failed. ".$res->{faultString}, -2)
  5034. if (ref ($res) && exists ($res->{faultString}));
  5035. return 0;
  5036. }
  5037. ######################################################################
  5038. # *** FILEQUEUE FUNCTIONS ***
  5039. ######################################################################
  5040. ######################################################################
  5041. # Open file queue
  5042. ######################################################################
  5043. sub HMCCU_QueueOpen ($$)
  5044. {
  5045. my ($hash, $queue_file) = @_;
  5046. my $idx_file = $queue_file . '.idx';
  5047. $queue_file .= '.dat';
  5048. my $mode = '0666';
  5049. umask (0);
  5050. $hash->{hmccu}{queue}{block_size} = 64;
  5051. $hash->{hmccu}{queue}{seperator} = "\n";
  5052. $hash->{hmccu}{queue}{sep_length} = length $hash->{hmccu}{queue}{seperator};
  5053. $hash->{hmccu}{queue}{queue_file} = $queue_file;
  5054. $hash->{hmccu}{queue}{idx_file} = $idx_file;
  5055. $hash->{hmccu}{queue}{queue} = new IO::File $queue_file, O_CREAT | O_RDWR, oct($mode) or return 0;
  5056. $hash->{hmccu}{queue}{idx} = new IO::File $idx_file, O_CREAT | O_RDWR, oct($mode) or return 0;
  5057. ### Default ptr to 0, replace it with value in idx file if one exists
  5058. $hash->{hmccu}{queue}{idx}->sysseek(0, SEEK_SET);
  5059. $hash->{hmccu}{queue}{idx}->sysread($hash->{hmccu}{queue}{ptr}, 1024);
  5060. $hash->{hmccu}{queue}{ptr} = '0' unless $hash->{hmccu}{queue}{ptr};
  5061. if($hash->{hmccu}{queue}{ptr} > -s $queue_file)
  5062. {
  5063. $hash->{hmccu}{queue}{idx}->truncate(0) or return 0;
  5064. $hash->{hmccu}{queue}{idx}->sysseek(0, SEEK_SET);
  5065. $hash->{hmccu}{queue}{idx}->syswrite('0') or return 0;
  5066. }
  5067. return 1;
  5068. }
  5069. ######################################################################
  5070. # Close file queue
  5071. ######################################################################
  5072. sub HMCCU_QueueClose ($)
  5073. {
  5074. my ($hash) = @_;
  5075. if (exists ($hash->{hmccu}{queue})) {
  5076. $hash->{hmccu}{queue}{idx}->close();
  5077. $hash->{hmccu}{queue}{queue}->close();
  5078. delete $hash->{hmccu}{queue};
  5079. }
  5080. }
  5081. sub HMCCU_QueueReset ($)
  5082. {
  5083. my ($hash) = @_;
  5084. $hash->{hmccu}{queue}{idx}->truncate(0) or return 0;
  5085. $hash->{hmccu}{queue}{idx}->sysseek(0, SEEK_SET);
  5086. $hash->{hmccu}{queue}{idx}->syswrite('0') or return 0;
  5087. $hash->{hmccu}{queue}{queue}->sysseek($hash->{hmccu}{queue}{ptr} = 0, SEEK_SET);
  5088. return 1;
  5089. }
  5090. ######################################################################
  5091. # Put value in file queue
  5092. ######################################################################
  5093. sub HMCCU_QueueEnq ($$)
  5094. {
  5095. my ($hash, $element) = @_;
  5096. return 0 if (!exists ($hash->{hmccu}{queue}));
  5097. $hash->{hmccu}{queue}{queue}->sysseek(0, SEEK_END);
  5098. $element =~ s/$hash->{hmccu}{queue}{seperator}//g;
  5099. $hash->{hmccu}{queue}{queue}->syswrite($element.$hash->{hmccu}{queue}{seperator}) or return 0;
  5100. return 1;
  5101. }
  5102. ######################################################################
  5103. # Return next value in file queue
  5104. ######################################################################
  5105. sub HMCCU_QueueDeq ($)
  5106. {
  5107. my ($hash) = @_;
  5108. my $name = $hash->{NAME};
  5109. my $sep_length = $hash->{hmccu}{queue}{sep_length};
  5110. my $element = '';
  5111. return undef if (!exists ($hash->{hmccu}{queue}));
  5112. $hash->{hmccu}{queue}{queue}->sysseek($hash->{hmccu}{queue}{ptr}, SEEK_SET);
  5113. my $i;
  5114. while($hash->{hmccu}{queue}{queue}->sysread($_, $hash->{hmccu}{queue}{block_size})) {
  5115. $i = index($_, $hash->{hmccu}{queue}{seperator});
  5116. if($i != -1) {
  5117. $element .= substr($_, 0, $i);
  5118. $hash->{hmccu}{queue}{ptr} += $i + $sep_length;
  5119. $hash->{hmccu}{queue}{queue}->sysseek($hash->{hmccu}{queue}{ptr}, SEEK_SET);
  5120. last;
  5121. }
  5122. else {
  5123. # Seperator not found, go back 'sep_length' spaces to ensure we don't miss it between reads
  5124. Log3 $name, 2, "HMCCU: HMCCU_QueueDeq seperator not found";
  5125. $element .= substr($_, 0, -$sep_length, '');
  5126. $hash->{hmccu}{queue}{ptr} += $hash->{hmccu}{queue}{block_size} - $sep_length;
  5127. $hash->{hmccu}{queue}{queue}->sysseek($hash->{hmccu}{queue}{ptr}, SEEK_SET);
  5128. }
  5129. }
  5130. ## If queue seek pointer is at the EOF, truncate the queue file
  5131. if($hash->{hmccu}{queue}{queue}->sysread($_, 1) == 0)
  5132. {
  5133. $hash->{hmccu}{queue}{queue}->truncate(0) or return undef;
  5134. $hash->{hmccu}{queue}{queue}->sysseek($hash->{hmccu}{queue}{ptr} = 0, SEEK_SET);
  5135. }
  5136. ## Set idx file contents to point to the current seek position in queue file
  5137. $hash->{hmccu}{queue}{idx}->truncate(0) or return undef;
  5138. $hash->{hmccu}{queue}{idx}->sysseek(0, SEEK_SET);
  5139. $hash->{hmccu}{queue}{idx}->syswrite($hash->{hmccu}{queue}{ptr}) or return undef;
  5140. return ($element ne '') ? $element : undef;
  5141. }
  5142. ######################################################################
  5143. # *** HELPER FUNCTIONS ***
  5144. ######################################################################
  5145. ######################################################################
  5146. # Determine HomeMatic state considering datapoint values specified
  5147. # in attributes ccudef-hmstatevals and hmstatevals.
  5148. # Return (reading, channel, datapoint, value)
  5149. ######################################################################
  5150. sub HMCCU_GetHMState ($$$)
  5151. {
  5152. my ($name, $ioname, $defval) = @_;
  5153. my @hmstate = ('hmstate', undef, undef, $defval);
  5154. my $fnc = "GetHMState";
  5155. my $clhash = $defs{$name};
  5156. my $cltype = $clhash->{TYPE};
  5157. return @hmstate if ($cltype ne 'HMCCUDEV' && $cltype ne 'HMCCUCHN');
  5158. my $ghmstatevals = AttrVal ($ioname, 'ccudef-hmstatevals', $HMCCU_DEF_HMSTATE);
  5159. my $hmstatevals = AttrVal ($name, 'hmstatevals', $ghmstatevals);
  5160. $hmstatevals .= ";".$ghmstatevals if ($hmstatevals ne $ghmstatevals);
  5161. # Get reading name
  5162. if ($hmstatevals =~ /^=([^;]*);/) {
  5163. $hmstate[0] = $1;
  5164. $hmstatevals =~ s/^=[^;]*;//;
  5165. }
  5166. HMCCU_Trace ($clhash, 2, $fnc, "hmstatevals=$hmstatevals");
  5167. # Default hmstate is equal to state
  5168. $hmstate[3] = ReadingsVal ($name, 'state', undef) if (!defined ($defval));
  5169. # Substitute variables
  5170. $hmstatevals = HMCCU_SubstVariables ($clhash, $hmstatevals, undef);
  5171. my @rulelist = split (";", $hmstatevals);
  5172. foreach my $rule (@rulelist) {
  5173. my ($dptexpr, $subst) = split ('!', $rule, 2);
  5174. my $dp = '';
  5175. next if (!defined ($dptexpr) || !defined ($subst));
  5176. HMCCU_Trace ($clhash, 2, $fnc, "dptexpr=$dptexpr, subst=$subst");
  5177. foreach my $d (keys %{$clhash->{hmccu}{dp}}) {
  5178. HMCCU_Trace ($clhash, 2, $fnc, "Check $d match $dptexpr");
  5179. if ($d =~ /$dptexpr/) {
  5180. $dp = $d;
  5181. last;
  5182. }
  5183. }
  5184. next if ($dp eq '');
  5185. my ($chn, $dpt) = split (/\./, $dp);
  5186. my $value = HMCCU_FormatReadingValue ($clhash, $clhash->{hmccu}{dp}{$dp}{VAL}, $hmstate[0]);
  5187. my ($rc, $newvalue) = HMCCU_SubstRule ($value, $subst, 0);
  5188. return ($hmstate[0], $chn, $dpt, $newvalue) if ($rc);
  5189. }
  5190. return @hmstate;
  5191. }
  5192. ######################################################################
  5193. # Calculate time difference in seconds between current time and
  5194. # specified timestamp
  5195. ######################################################################
  5196. sub HMCCU_GetTimeSpec ($)
  5197. {
  5198. my ($ts) = @_;
  5199. return -1 if ($ts !~ /^[0-9]{2}:[0-9]{2}$/ && $ts !~ /^[0-9]{2}:[0-9]{2}:[0-9]{2}$/);
  5200. my (undef, $h, $m, $s) = GetTimeSpec ($ts);
  5201. return -1 if (!defined ($h));
  5202. $s += $h*3600+$m*60;
  5203. my @lt = localtime;
  5204. my $cs = $lt[2]*3600+$lt[1]*60+$lt[0];
  5205. $s += 86400 if ($cs > $s);
  5206. return ($s-$cs);
  5207. }
  5208. ######################################################################
  5209. # Calculate special readings. Requires hash of client device, channel
  5210. # number and datapoint. Supported functions:
  5211. # dewpoint, absolute humidity, increasing/decreasing counters,
  5212. # minimum/maximum, average, sum.
  5213. # Return readings array with reading/value pairs.
  5214. ######################################################################
  5215. sub HMCCU_CalculateReading ($$$)
  5216. {
  5217. my ($cl_hash, $chnno, $dpt) = @_;
  5218. my $name = $cl_hash->{NAME};
  5219. my @result = ();
  5220. my $ccucalculate = AttrVal ($name, 'ccucalculate', '');
  5221. return @result if ($ccucalculate eq '');
  5222. my @calclist = split (/[;\n]+/, $ccucalculate);
  5223. foreach my $calculation (@calclist) {
  5224. my ($vt, $rn, $dpts) = split (':', $calculation);
  5225. next if (!defined ($rn));
  5226. # Get parameters values stored in device hash
  5227. my @dplist = defined ($dpts) ? split (',', $dpts) : ();
  5228. next if (@dplist > 0 && !(grep { $_ eq "$chnno.$dpt"} @dplist));
  5229. my @pars = ();
  5230. foreach my $dp (@dplist) {
  5231. if (exists ($cl_hash->{hmccu}{dp}{$dp}{VAL})) {
  5232. push @pars, $cl_hash->{hmccu}{dp}{$dp}{VAL};
  5233. }
  5234. }
  5235. if ($vt eq 'dewpoint' || $vt eq 'abshumidity') {
  5236. # Dewpoint and absolute humidity
  5237. next if (scalar (@pars) < 2);
  5238. my ($tmp, $hum) = @pars;
  5239. if ($tmp >= 0.0) {
  5240. $a = 7.5;
  5241. $b = 237.3;
  5242. }
  5243. else {
  5244. $a = 7.6;
  5245. $b = 240.7;
  5246. }
  5247. my $sdd = 6.1078*(10.0**(($a*$tmp)/($b+$tmp)));
  5248. my $dd = $hum/100.0*$sdd;
  5249. if ($vt eq 'dewpoint') {
  5250. my $v = log($dd/6.1078)/log(10.0);
  5251. my $td = $b*$v/($a-$v);
  5252. push (@result, $rn, (sprintf "%.1f", $td));
  5253. }
  5254. else {
  5255. my $af = 100000.0*18.016/8314.3*$dd/($tmp+273.15);
  5256. push (@result, $rn, (sprintf "%.1f", $af));
  5257. }
  5258. }
  5259. elsif ($vt eq 'min' || $vt eq 'max') {
  5260. # Minimum or maximum values
  5261. next if (scalar (@pars) < 1);
  5262. my $newval = shift @pars;
  5263. my $curval = ReadingsVal ($name, $rn, 0);
  5264. $curval = $newval if ($vt eq 'min' && $newval < $curval);
  5265. $curval = $newval if ($vt eq 'max' && $newval > $curval);
  5266. push (@result, $rn, $curval);
  5267. }
  5268. elsif ($vt eq 'inc' || $vt eq 'dec') {
  5269. # Increasing or decreasing values without reset
  5270. next if (scalar (@pars) < 1);
  5271. my $newval = shift @pars;
  5272. my $oldval = ReadingsVal ($name, $rn."_old", 0);
  5273. my $curval = ReadingsVal ($name, $rn, 0);
  5274. if (($vt eq 'inc' && $newval < $curval) || ($vt eq 'dec' && $newval > $curval)) {
  5275. $oldval = $curval;
  5276. push (@result, $rn."_old", $oldval);
  5277. }
  5278. $curval = $newval+$oldval;
  5279. push (@result, $rn, $curval);
  5280. }
  5281. elsif ($vt eq 'avg') {
  5282. # Average value
  5283. next if (scalar (@pars) < 1);
  5284. my $newval = shift @pars;
  5285. my $cnt = ReadingsVal ($name, $rn."_cnt", 0);
  5286. my $sum = ReadingsVal ($name, $rn."_sum", 0);
  5287. $cnt++;
  5288. $sum += $newval;
  5289. my $curval = $sum/$cnt;
  5290. push (@result, $rn."_cnt", $cnt, $rn."_sum", $sum, $rn, $curval);
  5291. }
  5292. elsif ($vt eq 'sum') {
  5293. # Sum of values
  5294. next if (scalar (@pars) < 1);
  5295. my $newval = shift @pars;
  5296. my $curval = ReadingsVal ($name, $rn, 0);
  5297. $curval += $newval;
  5298. push (@result, $rn, $curval);
  5299. }
  5300. }
  5301. return @result;
  5302. }
  5303. ######################################################################
  5304. # Encode command string for e-paper display
  5305. #
  5306. # Parameters:
  5307. #
  5308. # msg := parameter=value[,...]
  5309. #
  5310. # text1-3=Text
  5311. # icon1-3=IconName
  5312. # sound=SoundName
  5313. # signal=SignalName
  5314. # pause=1-160
  5315. # repeat=0-15
  5316. #
  5317. # Returns undef on error or encoded string on success
  5318. ######################################################################
  5319. sub HMCCU_EncodeEPDisplay ($)
  5320. {
  5321. my ($msg) = @_;
  5322. # set defaults
  5323. $msg = '' if (!defined ($msg));
  5324. my %disp_icons = (
  5325. ico_off => '0x80', ico_on => '0x81', ico_open => '0x82', ico_closed => '0x83',
  5326. ico_error => '0x84', ico_ok => '0x85', ico_info => '0x86', ico_newmsg => '0x87',
  5327. ico_svcmsg => '0x88'
  5328. );
  5329. my %disp_sounds = (
  5330. snd_off => '0xC0', snd_longlong => '0xC1', snd_longshort => '0xC2',
  5331. snd_long2short => '0xC3', snd_short => '0xC4', snd_shortshort => '0xC5',
  5332. snd_long => '0xC6'
  5333. );
  5334. my %disp_signals = (
  5335. sig_off => '0xF0', sig_red => '0xF1', sig_green => '0xF2', sig_orange => '0xF3'
  5336. );
  5337. # Parse command string
  5338. my @text = ('', '', '');
  5339. my @icon = ('', '', '');
  5340. my %conf = (sound => 'snd_off', signal => 'sig_off', repeat => 1, pause => 10);
  5341. foreach my $tok (split (',', $msg)) {
  5342. my ($par, $val) = split ('=', $tok);
  5343. next if (!defined ($val));
  5344. if ($par =~ /^text([1-3])$/) {
  5345. $text[$1-1] = substr ($val, 0, 12);
  5346. }
  5347. elsif ($par =~ /^icon([1-3])$/) {
  5348. $icon[$1-1] = $val;
  5349. }
  5350. elsif ($par =~ /^(sound|pause|repeat|signal)$/) {
  5351. $conf{$1} = $val;
  5352. }
  5353. }
  5354. my $cmd = '0x02,0x0A';
  5355. for (my $c=0; $c<3; $c++) {
  5356. if ($text[$c] ne '' || $icon[$c] ne '') {
  5357. $cmd .= ',0x12';
  5358. # Hex code
  5359. if ($text[$c] =~ /^0x[0-9A-F]{2}$/) {
  5360. $cmd .= ','.$text[$c];
  5361. }
  5362. # Predefined text code #0-9
  5363. elsif ($text[$c] =~ /^#([0-9])$/) {
  5364. $cmd .= sprintf (",0x8%1X", $1);
  5365. }
  5366. # Convert string to hex codes
  5367. else {
  5368. $text[$c] =~ s/\\_/ /g;
  5369. foreach my $ch (split ('', $text[$c])) {
  5370. $cmd .= sprintf (",0x%02X", ord ($ch));
  5371. }
  5372. }
  5373. # Icon
  5374. if ($icon[$c] ne '' && exists ($disp_icons{$icon[$c]})) {
  5375. $cmd .= ',0x13,'.$disp_icons{$icon[$c]};
  5376. }
  5377. }
  5378. $cmd .= ',0x0A';
  5379. }
  5380. # Sound
  5381. my $snd = $disp_sounds{snd_off};
  5382. $snd = $disp_sounds{$conf{sound}} if (exists ($disp_sounds{$conf{sound}}));
  5383. $cmd .= ',0x14,'.$snd.',0x1C';
  5384. # Repeat
  5385. my $rep = $conf{repeat} if ($conf{repeat} >= 0 && $conf{repeat} <= 15);
  5386. $rep = 1 if ($rep < 0);
  5387. $rep = 15 if ($rep > 15);
  5388. if ($rep == 0) {
  5389. $cmd .= ',0xDF';
  5390. }
  5391. else {
  5392. $cmd .= sprintf (",0x%02X", 0xD0+$rep-1);
  5393. }
  5394. $cmd .= ',0x1D';
  5395. # Pause
  5396. my $pause = $conf{pause};
  5397. $pause = 1 if ($pause < 1);
  5398. $pause = 160 if ($pause > 160);
  5399. $cmd .= sprintf (",0xE%1X,0x16", int(($pause-1)/10));
  5400. # Signal
  5401. my $sig = $disp_signals{sig_off};
  5402. $sig = $disp_signals{$conf{signal}} if (exists ($disp_signals{$conf{signal}}));
  5403. $cmd .= ','.$sig.',0x03';
  5404. return $cmd;
  5405. }
  5406. ######################################################################
  5407. # Convert reference to string recursively
  5408. # Supports reference to ARRAY, HASH and SCALAR and scalar values.
  5409. ######################################################################
  5410. sub HMCCU_RefToString ($)
  5411. {
  5412. my ($r) = @_;
  5413. my $result = '';
  5414. if (ref ($r) eq 'ARRAY') {
  5415. $result .= "[\n";
  5416. foreach my $e (@$r) {
  5417. $result .= "," if ($result ne '[');
  5418. $result .= HMCCU_RefToString ($e);
  5419. }
  5420. $result .= "\n]";
  5421. }
  5422. elsif (ref ($r) eq 'HASH') {
  5423. $result .= "{\n";
  5424. foreach my $k (sort keys %$r) {
  5425. $result .= "," if ($result ne '{');
  5426. $result .= "$k=".HMCCU_RefToString ($r->{$k});
  5427. }
  5428. $result .= "\n}";
  5429. }
  5430. elsif (ref ($r) eq 'SCALAR') {
  5431. $result .= $$r;
  5432. }
  5433. else {
  5434. $result .= $r;
  5435. }
  5436. return $result;
  5437. }
  5438. ######################################################################
  5439. # Match string with regular expression considering illegal regular
  5440. # expressions. Return parameter e if regular expression is incorrect.
  5441. ######################################################################
  5442. sub HMCCU_ExprMatch ($$$)
  5443. {
  5444. my ($t, $r, $e) = @_;
  5445. my $x = eval { $t =~ /$r/ };
  5446. return $e if (!defined ($x));
  5447. return "$x" eq '' ? 0 : 1;
  5448. }
  5449. sub HMCCU_ExprNotMatch ($$$)
  5450. {
  5451. my ($t, $r, $e) = @_;
  5452. my $x = eval { $t !~ /$r/ };
  5453. return $e if (!defined ($x));
  5454. return "$x" eq '' ? 0 : 1;
  5455. }
  5456. ######################################################################
  5457. # Read duty cycles of interfaces 2001 and 2010 and update readings.
  5458. ######################################################################
  5459. sub HMCCU_GetDutyCycle ($)
  5460. {
  5461. my ($hash) = @_;
  5462. my $name = $hash->{NAME};
  5463. my $dc = 0;
  5464. my @rpcports = HMCCU_GetRPCPortList ($hash);
  5465. readingsBeginUpdate ($hash);
  5466. foreach my $port (@rpcports) {
  5467. next if ($port != 2001 && $port != 2010);
  5468. my $url = HMCCU_GetRPCServerInfo ($hash, $port, 'url');
  5469. next if (!defined ($url));
  5470. my $rpcclient = RPC::XML::Client->new ($url);
  5471. my $response = $rpcclient->simple_request ("listBidcosInterfaces");
  5472. next if (!defined ($response) || ref($response) ne 'ARRAY');
  5473. foreach my $iface (@$response) {
  5474. next if (ref ($iface) ne 'HASH');
  5475. next if (!exists ($iface->{DUTY_CYCLE}));
  5476. $dc++;
  5477. my $type = exists ($iface->{TYPE}) ? $iface->{TYPE} : HMCCU_GetRPCServerInfo ($hash, $port, 'name');
  5478. readingsBulkUpdate ($hash, "iface_addr_$dc", $iface->{ADDRESS});
  5479. readingsBulkUpdate ($hash, "iface_conn_$dc", $iface->{CONNECTED});
  5480. readingsBulkUpdate ($hash, "iface_type_$dc", $type);
  5481. readingsBulkUpdate ($hash, "iface_ducy_$dc", $iface->{DUTY_CYCLE});
  5482. }
  5483. }
  5484. readingsEndUpdate ($hash, 1);
  5485. return $dc;
  5486. }
  5487. ######################################################################
  5488. # Check if TCP port is reachable.
  5489. # Parameter timeout should be a multiple of 20 plus 5.
  5490. ######################################################################
  5491. sub HMCCU_TCPPing ($$$)
  5492. {
  5493. my ($addr, $port, $timeout) = @_;
  5494. if ($timeout > 0) {
  5495. my $t = time ();
  5496. while (time () < $t+$timeout) {
  5497. return 1 if (HMCCU_TCPConnect ($addr, $port));
  5498. sleep (20);
  5499. }
  5500. return 0;
  5501. }
  5502. else {
  5503. return HMCCU_TCPConnect ($addr, $port);
  5504. }
  5505. }
  5506. ######################################################################
  5507. # Check if TCP connection to specified host and port is possible.
  5508. ######################################################################
  5509. sub HMCCU_TCPConnect ($$)
  5510. {
  5511. my ($addr, $port) = @_;
  5512. my $socket = IO::Socket::INET->new (PeerAddr => $addr, PeerPort => $port);
  5513. if ($socket) {
  5514. close ($socket);
  5515. return 1;
  5516. }
  5517. return 0;
  5518. }
  5519. ######################################################################
  5520. # Substitute invalid characters in reading name.
  5521. # Substitution rules: ':' => '.', any other illegal character => '_'
  5522. ######################################################################
  5523. sub HMCCU_CorrectName ($)
  5524. {
  5525. my ($rn) = @_;
  5526. $rn =~ s/\:/\./g;
  5527. $rn =~ s/[^A-Za-z\d_\.-]+/_/g;
  5528. return $rn;
  5529. }
  5530. ######################################################################
  5531. # *** SUBPROCESS PART ***
  5532. ######################################################################
  5533. # Child process. Must be global to allow access by RPC callbacks
  5534. my $hmccu_child;
  5535. # Queue file
  5536. my %child_queue;
  5537. my $cpqueue = \%child_queue;
  5538. # Statistic data of child process
  5539. my %child_hash = (
  5540. "total", 0,
  5541. "writeerror", 0,
  5542. "EV", 0,
  5543. "ND", 0,
  5544. "DD", 0,
  5545. "RD", 0,
  5546. "RA", 0,
  5547. "UD", 0,
  5548. "IN", 0,
  5549. "EX", 0,
  5550. "SL", 0
  5551. );
  5552. my $cphash = \%child_hash;
  5553. ######################################################################
  5554. # Subprocess: Write event to parent process
  5555. ######################################################################
  5556. sub HMCCU_CCURPC_Write ($$)
  5557. {
  5558. my ($et, $msg) = @_;
  5559. my $name = $hmccu_child->{devname};
  5560. $cphash->{total}++;
  5561. $cphash->{$et}++;
  5562. HMCCU_QueueEnq ($cpqueue, $et."|".$msg);
  5563. }
  5564. ######################################################################
  5565. # Subprocess: Initialize RPC server. Return 1 on success.
  5566. ######################################################################
  5567. sub HMCCU_CCURPC_OnRun ($)
  5568. {
  5569. $hmccu_child = shift;
  5570. my $name = $hmccu_child->{devname};
  5571. my $serveraddr = $hmccu_child->{serveraddr};
  5572. my $serverport = $hmccu_child->{serverport};
  5573. my $callbackport = $hmccu_child->{callbackport};
  5574. my $queuefile = $hmccu_child->{queue};
  5575. my $clkey = "CB".$serverport;
  5576. my $ccurpc_server;
  5577. # Create, open and reset queue file
  5578. Log3 $name, 0, "CCURPC: $clkey Creating file queue $queuefile";
  5579. if (!HMCCU_QueueOpen ($cpqueue, $queuefile)) {
  5580. Log3 $name, 0, "CCURPC: $clkey Can't create queue";
  5581. return 0;
  5582. }
  5583. # Reset event queue
  5584. HMCCU_QueueReset ($cpqueue);
  5585. while (defined (HMCCU_QueueDeq ($cpqueue))) { }
  5586. # Create RPC server
  5587. Log3 $name, 0, "CCURPC: Initializing RPC server $clkey";
  5588. $ccurpc_server = RPC::XML::Server->new (port=>$callbackport);
  5589. if (!ref($ccurpc_server))
  5590. {
  5591. Log3 $name, 0, "CCURPC: Can't create RPC callback server on port $callbackport. Port in use?";
  5592. return 0;
  5593. }
  5594. else {
  5595. Log3 $name, 0, "CCURPC: Callback server created listening on port $callbackport";
  5596. }
  5597. # Format of signature:
  5598. # string par1 ... parN
  5599. # Callback for events
  5600. # Parameters: Server, InterfaceId, Address, ValueKey, Value
  5601. Log3 $name, 1, "CCURPC: $clkey Adding callback for events";
  5602. $ccurpc_server->add_method (
  5603. { name=>"event",
  5604. 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"],
  5605. code=>\&HMCCU_CCURPC_EventCB
  5606. }
  5607. );
  5608. # Callback for new devices
  5609. # Parameters: Server, InterfaceId, DeviceDescriptions[]
  5610. Log3 $name, 1, "CCURPC: $clkey Adding callback for new devices";
  5611. $ccurpc_server->add_method (
  5612. { name=>"newDevices",
  5613. signature=>["string string array"],
  5614. code=>\&HMCCU_CCURPC_NewDevicesCB
  5615. }
  5616. );
  5617. # Callback for deleted devices
  5618. # Parameters: Server, InterfaceId, Addresses[]
  5619. Log3 $name, 1, "CCURPC: $clkey Adding callback for deleted devices";
  5620. $ccurpc_server->add_method (
  5621. { name=>"deleteDevices",
  5622. signature=>["string string array"],
  5623. code=>\&HMCCU_CCURPC_DeleteDevicesCB
  5624. }
  5625. );
  5626. # Callback for modified devices
  5627. # Parameters: Server, InterfaceId, Address, Hint
  5628. Log3 $name, 1, "CCURPC: $clkey Adding callback for modified devices";
  5629. $ccurpc_server->add_method (
  5630. { name=>"updateDevice",
  5631. signature=>["string string string int"],
  5632. code=>\&HMCCU_CCURPC_UpdateDeviceCB
  5633. }
  5634. );
  5635. # Callback for replaced devices
  5636. # Parameters: Server, InterfaceId, OldAddress, NewAddress
  5637. Log3 $name, 1, "CCURPC: $clkey Adding callback for replaced devices";
  5638. $ccurpc_server->add_method (
  5639. { name=>"replaceDevice",
  5640. signature=>["string string string string"],
  5641. code=>\&HMCCU_CCURPC_ReplaceDeviceCB
  5642. }
  5643. );
  5644. # Callback for readded devices
  5645. # Parameters: Server, InterfaceId, Addresses[]
  5646. Log3 $name, 1, "CCURPC: $clkey Adding callback for readded devices";
  5647. $ccurpc_server->add_method (
  5648. { name=>"replaceDevice",
  5649. signature=>["string string array"],
  5650. code=>\&HMCCU_CCURPC_ReaddDeviceCB
  5651. }
  5652. );
  5653. # Dummy implementation, always return an empty array
  5654. # Parameters: Server, InterfaceId
  5655. Log3 $name, 1, "CCURPC: $clkey Adding callback for list devices";
  5656. $ccurpc_server->add_method (
  5657. { name=>"listDevices",
  5658. signature=>["string string"],
  5659. code=>\&HMCCU_CCURPC_ListDevicesCB
  5660. }
  5661. );
  5662. # Enter server loop
  5663. HMCCU_CCURPC_Write ("SL", "$$|$clkey");
  5664. Log3 $name, 0, "CCURPC: $clkey Entering server loop";
  5665. $ccurpc_server->server_loop;
  5666. Log3 $name, 0, "CCURPC: $clkey Server loop terminated";
  5667. # Server loop exited by SIGINT
  5668. HMCCU_CCURPC_Write ("EX", "SHUTDOWN|$$|$clkey");
  5669. return 1;
  5670. }
  5671. ######################################################################
  5672. # Subprocess: Called when RPC server loop is terminated
  5673. ######################################################################
  5674. sub HMCCU_CCURPC_OnExit ()
  5675. {
  5676. # Output statistics
  5677. foreach my $et (sort keys %child_hash) {
  5678. Log3 $hmccu_child->{devname}, 2, "CCURPC: Eventcount $et = ".$cphash->{$et};
  5679. }
  5680. }
  5681. ######################################################################
  5682. # Subprocess: Callback for new devices
  5683. ######################################################################
  5684. sub HMCCU_CCURPC_NewDevicesCB ($$$)
  5685. {
  5686. my ($server, $cb, $a) = @_;
  5687. my $devcount = scalar (@$a);
  5688. my $name = $hmccu_child->{devname};
  5689. my $c = 0;
  5690. my $msg = '';
  5691. Log3 $name, 2, "CCURPC: $cb NewDevice received $devcount device specifications";
  5692. for my $dev (@$a) {
  5693. my $msg = '';
  5694. if ($dev->{ADDRESS} =~ /:[0-9]{1,2}$/) {
  5695. $msg = "C|".$dev->{ADDRESS}."|".$dev->{TYPE}."|".$dev->{VERSION}."|null|null";
  5696. }
  5697. else {
  5698. # Wired devices do not have a RX_MODE attribute
  5699. my $rx = exists ($dev->{RX_MODE}) ? $dev->{RX_MODE} : 'null';
  5700. $msg = "D|".$dev->{ADDRESS}."|".$dev->{TYPE}."|".$dev->{VERSION}."|".
  5701. $dev->{FIRMWARE}."|".$rx;
  5702. }
  5703. HMCCU_CCURPC_Write ("ND", $msg);
  5704. }
  5705. return;
  5706. }
  5707. ######################################################################
  5708. # Subprocess: Callback for deleted devices
  5709. ######################################################################
  5710. sub HMCCU_CCURPC_DeleteDevicesCB ($$$)
  5711. {
  5712. my ($server, $cb, $a) = @_;
  5713. my $name = $hmccu_child->{devname};
  5714. my $devcount = scalar (@$a);
  5715. Log3 $name, 2, "CCURPC: $cb DeleteDevice received $devcount device addresses";
  5716. for my $dev (@$a) {
  5717. HMCCU_CCURPC_Write ("DD", $dev);
  5718. }
  5719. return;
  5720. }
  5721. ######################################################################
  5722. # Subprocess: Callback for modified devices
  5723. ######################################################################
  5724. sub HMCCU_CCURPC_UpdateDeviceCB ($$$$)
  5725. {
  5726. my ($server, $cb, $devid, $hint) = @_;
  5727. HMCCU_CCURPC_Write ("UD", $devid."|".$hint);
  5728. return;
  5729. }
  5730. ######################################################################
  5731. # Subprocess: Callback for replaced devices
  5732. ######################################################################
  5733. sub HMCCU_CCURPC_ReplaceDeviceCB ($$$$)
  5734. {
  5735. my ($server, $cb, $devid1, $devid2) = @_;
  5736. HMCCU_CCURPC_Write ("RD", $devid1."|".$devid2);
  5737. return;
  5738. }
  5739. ######################################################################
  5740. # Subprocess: Callback for readded devices
  5741. ######################################################################
  5742. sub HMCCU_CCURPC_ReaddDevicesCB ($$$)
  5743. {
  5744. my ($server, $cb, $a) = @_;
  5745. my $name = $hmccu_child->{devname};
  5746. my $devcount = scalar (@$a);
  5747. Log3 $name, 2, "CCURPC: $cb ReaddDevice received $devcount device addresses";
  5748. for my $dev (@$a) {
  5749. HMCCU_CCURPC_Write ("RA", $dev);
  5750. }
  5751. return;
  5752. }
  5753. ######################################################################
  5754. # Subprocess: Callback for handling CCU events
  5755. ######################################################################
  5756. sub HMCCU_CCURPC_EventCB ($$$$$)
  5757. {
  5758. my ($server, $cb, $devid, $attr, $val) = @_;
  5759. my $name = $hmccu_child->{devname};
  5760. HMCCU_CCURPC_Write ("EV", $devid."|".$attr."|".$val);
  5761. if (($cphash->{EV} % 500) == 0) {
  5762. Log3 $name, 3, "CCURPC: $cb Received 500 events from CCU since last check";
  5763. my @stkeys = ('total', 'EV', 'ND', 'DD', 'RD', 'RA', 'UD', 'IN', 'SL', 'EX');
  5764. my $msg = '';
  5765. foreach my $stkey (@stkeys) {
  5766. $msg .= '|' if ($msg ne '');
  5767. $msg .= $cphash->{$stkey};
  5768. }
  5769. HMCCU_CCURPC_Write ("ST", $msg);
  5770. }
  5771. # Never remove this statement!
  5772. return;
  5773. }
  5774. ######################################################################
  5775. # Subprocess: Callback for list devices
  5776. ######################################################################
  5777. sub HMCCU_CCURPC_ListDevicesCB ($$)
  5778. {
  5779. my ($server, $cb) = @_;
  5780. my $name = $hmccu_child->{devname};
  5781. $cb = "unknown" if (!defined ($cb));
  5782. Log3 $name, 1, "CCURPC: $cb ListDevices. Sending init to HMCCU";
  5783. HMCCU_CCURPC_Write ("IN", "INIT|1|$cb");
  5784. return RPC::XML::array->new();
  5785. }
  5786. 1;
  5787. =pod
  5788. =item device
  5789. =item summary provides interface between FHEM and Homematic CCU2
  5790. =begin html
  5791. <a name="HMCCU"></a>
  5792. <h3>HMCCU</h3>
  5793. <ul>
  5794. The module provides an interface between FHEM and a Homematic CCU2. HMCCU is the
  5795. I/O device for the client devices HMCCUDEV and HMCCUCHN. The module requires the
  5796. additional Perl modules IO::File, RPC::XML::Client, RPC::XML::Server and SubProcess
  5797. (part of FHEM).
  5798. </br></br>
  5799. <a name="HMCCUdefine"></a>
  5800. <b>Define</b><br/><br/>
  5801. <ul>
  5802. <code>define &lt;name&gt; HMCCU &lt;HostOrIP&gt; [&lt;ccu-number&gt;] [waitforccu=&lt;timeout&gt;]</code>
  5803. <br/><br/>
  5804. Example:<br/>
  5805. <code>define myccu HMCCU 192.168.1.10</code>
  5806. <br/><br/>
  5807. The parameter <i>HostOrIP</i> is the hostname or IP address of a Homematic CCU2. If you have
  5808. more than one CCU you can specifiy a unique CCU number with parameter <i>ccu-number</i>. With
  5809. option <i>waitforccu</i> HMCCU will wait for the specified time if CCU is not reachable.
  5810. Parameter <i>timeout</i> should be a multiple of 20 in seconds. Warning: This option could
  5811. block the start of FHEM for <i>timeout</i> seconds.
  5812. <br/>
  5813. For automatic update of Homematic device datapoints and FHEM readings one have to:
  5814. <br/><br/>
  5815. <ul>
  5816. <li>Define used RPC interfaces with attribute 'rpcinterfaces'</li>
  5817. <li>Start RPC servers with command 'set rpcserver on'</li>
  5818. <li>Optionally enable automatic start of RPC servers with attribute 'rpcserver'</li>
  5819. </ul><br/>
  5820. Than start with the definition of client devices using modules HMCCUDEV (CCU devices)
  5821. and HMCCUCHN (CCU channels) or with command 'get devicelist create'.<br/>
  5822. Maybe it's helpful to set the following FHEM standard attributes for the HMCCU I/O
  5823. device:<br/><br/>
  5824. <ul>
  5825. <li>Shortcut for RPC server control: eventMap /rpcserver on:on/rpcserver off:off/</li>
  5826. </ul>
  5827. </ul>
  5828. <br/>
  5829. <a name="HMCCUset"></a>
  5830. <b>Set</b><br/><br/>
  5831. <ul>
  5832. <li><b>set &lt;name&gt; ackmessages</b><br/>
  5833. Acknowledge device was unreachable messages in CCU.
  5834. </li><br/>
  5835. <li><b>set &lt;name&gt; cleardefaults</b><br/>
  5836. Clear default attributes imported from file.
  5837. </li><br/>
  5838. <li><b>set &lt;name&gt; datapoint {&lt;[ccu:]ccuobject&gt;|&lt;hmccu:fhemobject&gt;}.
  5839. &lt;datapoint&gt; &lt;value&gt;</b><br/>
  5840. Set datapoint of CCU channel in "raw" mode. The value is not scaled or substituted. If
  5841. target object is preceded by string "hmccu:" the following parameter <i>fhemobject</i>
  5842. must be a FHEM device of type HMCCUDEV or HMCCUCHN. If device type is HMCCUDEV the device
  5843. name must be followed by a ':' and a valid channel number.<br/><br/>
  5844. Examples:<br/>
  5845. <code>set d_ccu datapoint ABC1234567:1.STATE true</code><br/>
  5846. <code>set d_ccu datapoint hmccu:mychndevice.STATE true</code><br/>
  5847. <code>set d_ccu datapoint hmccu:mydevdevice:1.STATE true</code>
  5848. </li><br/>
  5849. <li><b>set &lt;name&gt; defaults</b><br/>
  5850. Set default attributes for I/O device.
  5851. </li><br/>
  5852. <li><b>set &lt;name&gt; delete &lt;ccuobject&gt; [&lt;objecttype&gt;]</b><br/>
  5853. Delete object in CCU. Default object type is OT_VARDP. Valid object types are<br/>
  5854. OT_DEVICE=device, OT_VARDP=variable.
  5855. </li><br/>
  5856. <li><b>set &lt;name&gt; execute &lt;program&gt;</b><br/>
  5857. Execute a CCU program.
  5858. <br/><br/>
  5859. Example:<br/>
  5860. <code>set d_ccu execute PR-TEST</code>
  5861. </li><br/>
  5862. <li><b>set &lt;name&gt; hmscript {&lt;script-file&gt;|'!'&lt;function&gt;|'['&lt;code&gt;']'} [dump]
  5863. [&lt;parname&gt;=&lt;value&gt; [...]]</b><br/>
  5864. Execute Homematic script on CCU. If script code contains parameter in format $parname
  5865. they are substituted by corresponding command line parameters <i>parname</i>.<br/>
  5866. If output of script contains lines in format Object=Value readings in existing
  5867. corresponding FHEM devices will be set. <i>Object</i> can be the name of a CCU system
  5868. variable or a valid channel and datapoint specification. Readings for system variables
  5869. are set in the I/O device. Datapoint related readings are set in client devices. If option
  5870. 'dump' is specified the result of script execution is displayed in FHEM web interface.
  5871. Execute command without parameters will list available script functions.
  5872. </li><br/>
  5873. <li><b>set &lt;name&gt; importdefaults &lt;filename&gt;</b><br/>
  5874. Import default attributes from file.
  5875. </li><br/>
  5876. <li><b>set &lt;name&gt; rpcserver {on | off | restart}</b><br/>
  5877. Start, stop or restart RPC server(s). This command executed with option 'on'
  5878. will fork a RPC server process for each RPC interface defined in attribute 'rpcinterfaces'.
  5879. Until operation is completed only a few set/get commands are available and you
  5880. may get the error message 'CCU busy'.
  5881. </li><br/>
  5882. <li><b>set &lt;name&gt; var &lt;variable&gt; &lt;Value&gt;</b><br/>
  5883. Set CCU system variable value. Special characters \_ in <i>value</i> are
  5884. substituted by blanks.
  5885. </li>
  5886. </ul>
  5887. <br/>
  5888. <a name="HMCCUget"></a>
  5889. <b>Get</b><br/><br/>
  5890. <ul>
  5891. <li><b>get &lt;name&gt; aggregation {&lt;rule&gt;|all}</b><br/>
  5892. Process aggregation rule defined with attribute ccuaggregate.
  5893. </li><br/>
  5894. <li><b>get &lt;name&gt; configdesc {&lt;device&gt;|&lt;channel&gt;}</b><br/>
  5895. Get configuration parameter description of CCU device or channel (similar
  5896. to device settings in CCU). Not every CCU device or channel provides a configuration
  5897. parameter description. So result may be empty.
  5898. </li><br/>
  5899. <li><b>get &lt;name&gt; defaults</b><br/>
  5900. List device types and channels with default attributes available.
  5901. </li><br/>
  5902. <li><b>get &lt;name&gt; deviceinfo &lt;device-name&gt; [{State | <u>Value</u>}]</b><br/>
  5903. List device channels and datapoints. If option 'State' is specified the device is
  5904. queried directly. Otherwise device information from CCU is listed.
  5905. </li><br/>
  5906. <li><b>get &lt;name&gt; devicelist [dump]</b><br/>
  5907. Read list of devices and channels from CCU. This command is executed automatically
  5908. after the definition of an I/O device. It must be executed manually after
  5909. module HMCCU is reloaded or after devices have changed in CCU (added, removed or
  5910. renamed). With option 'dump' devices are displayed in browser window. If a RPC
  5911. server is running HMCCU will raise events "<i>count</i> devices added in CCU" or
  5912. "<i>count</i> devices deleted in CCU". It's recommended to set up a notification
  5913. which reacts with execution of command 'get devicelist' on these events.
  5914. </li><br/>
  5915. <li><b>get &lt;name&gt; devicelist create &lt;devexp&gt; [t={chn|<u>dev</u>|all}]
  5916. [p=&lt;prefix&gt;] [s=&lt;suffix&gt;] [f=&lt;format&gt;] [defattr] [duplicates]
  5917. [save] [&lt;attr&gt;=&lt;value&gt; [...]]</b><br/>
  5918. With option 'create' HMCCU will automatically create client devices for all CCU devices
  5919. and channels matching specified regular expression. With option t=chn or t=dev (default)
  5920. the creation of devices is limited to CCU channels or devices.<br/>
  5921. Optionally a <i>prefix</i> and/or a
  5922. <i>suffix</i> for the FHEM device name can be specified. The parameter <i>format</i>
  5923. defines a template for the FHEM device names. Prefix, suffix and format can contain
  5924. format identifiers which are substituted by corresponding values of the CCU device or
  5925. channel: %n = CCU object name (channel or device), %d = CCU device name, %a = CCU address.
  5926. In addition a list of default attributes for the created client devices can be specified.
  5927. If option 'defattr' is specified HMCCU tries to set default attributes for device.
  5928. With option 'duplicates' HMCCU will overwrite existing devices and/or create devices
  5929. for existing device addresses. Option 'save' will save FHEM config after device definition.
  5930. </li><br/>
  5931. <li><b>get &lt;name&gt; dump {datapoints|devtypes} [&lt;filter&gt;]</b><br/>
  5932. Dump all Homematic devicetypes or all devices including datapoints currently
  5933. defined in FHEM.
  5934. </li><br/>
  5935. <li><b>get &lt;name&gt; dutycycle</b><br/>
  5936. Read CCU interface and gateway information. For each interface/gateway the following
  5937. information is stored in readings:<br/>
  5938. iface_addr_n = interface address<br/>
  5939. iface_type_n = interface type<br/>
  5940. iface_conn_n = interface connection state (1=connected, 0=disconnected)<br/>
  5941. iface_ducy_n = duty cycle of interface (0-100)
  5942. </li><br/>
  5943. <li><b>get &lt;name&gt; exportdefaults &lt;filename&gt;</b><br/>
  5944. Export default attributes into file.
  5945. </li><br/>
  5946. <li><b>get &lt;name&gt; firmware</b><br/>
  5947. Get available firmware downloads from eq-3.de. List FHEM devices with current and available
  5948. firmware version. Firmware versions are only displayed after RPC server has been started.
  5949. </li><br/>
  5950. <li><b>get &lt;name&gt; parfile [&lt;parfile&gt;]</b><br/>
  5951. Get values of all channels / datapoints specified in <i>parfile</i>. The parameter
  5952. <i>parfile</i> can also be defined as an attribute. The file must contain one channel /
  5953. definition per line.
  5954. <br/><br/>
  5955. The syntax of Parfile entries is:
  5956. <br/><br/>
  5957. {[&lt;interface&gt;.]&lt;channel-address&gt; | &lt;channel-name&gt;}
  5958. [.&lt;datapoint-expr&gt;] [&lt;subst-rules&gt;]
  5959. <br/><br/>
  5960. Empty lines or lines starting with a # are ignored.
  5961. </li><br/>
  5962. <li><b>get &lt;name&gt; rpcstate</b><br/>
  5963. Check if RPC server process is running.
  5964. </li><br/>
  5965. <li><b>get &lt;name&gt; update [&lt;devexp&gt; [{State | <u>Value</u>}]]</b><br/>
  5966. Update all datapoints / readings of client devices with <u>FHEM device name</u>(!) matching
  5967. <i>devexp</i>. With option 'State' all CCU devices are queried directly. This can be
  5968. time consuming.
  5969. </li><br/>
  5970. <li><b>get &lt;name&gt; updateccu [&lt;devexp&gt; [{State | <u>Value</u>}]]</b><br/>
  5971. Update all datapoints / readings of client devices with <u>CCU device name</u>(!) matching
  5972. <i>devexp</i>. With option 'State' all CCU devices are queried directly. This can be
  5973. time consuming.
  5974. </li><br/>
  5975. <li><b>get &lt;name&gt; vars &lt;regexp&gt;</b><br/>
  5976. Get CCU system variables matching <i>regexp</i> and store them as readings.
  5977. </li>
  5978. </ul>
  5979. <br/>
  5980. <a name="HMCCUattr"></a>
  5981. <b>Attributes</b><br/>
  5982. <br/>
  5983. <ul>
  5984. <li><b>ccuaggregate &lt;rule&gt;[;...]</b><br/>
  5985. Define aggregation rules for client device readings. With an aggregation rule
  5986. it's easy to detect if some or all client device readings are set to a specific
  5987. value, i.e. detect all devices with low battery or detect all open windows.<br/>
  5988. Aggregation rules are automatically executed as a reaction on reading events of
  5989. HMCCU client devices. An aggregation rule consists of several parameters separated
  5990. by comma:<br/><br/>
  5991. <ul>
  5992. <li><b>name:&lt;rule-name&gt;</b><br/>
  5993. Name of aggregation rule</li>
  5994. <li><b>filter:{name|alias|group|room|type}=&lt;incl-expr&gt;[!&lt;excl-expr&gt;]</b><br/>
  5995. Filter criteria, i.e. "type=^HM-Sec-SC.*"</li>
  5996. <li><b>read:&lt;read-expr&gt;</b><br/>
  5997. Expression for reading names, i.e. "STATE"</li>
  5998. <li><b>if:{any|all|min|max|sum|avg|lt|gt|le|ge}=&lt;value&gt;</b><br/>
  5999. Condition, i.e. "any=open" or initial value, i.e. max=0</li>
  6000. <li><b>else:&lt;value&gt;</b><br/>
  6001. Complementary value, i.e. "closed"</li>
  6002. <li><b>prefix:{&lt;text&gt;|RULE}</b><br/>
  6003. Prefix for reading names with aggregation results</li>
  6004. <li><b>coll:{&lt;attribute&gt;|NAME}[!&lt;default-text&gt;]</b><br/>
  6005. Attribute of matching devices stored in aggregation results. Default text in case
  6006. of no matching devices found is optional.</li>
  6007. <li><b>html:&lt;template-file&gt;</b><br/>
  6008. Create HTML code with matching devices.</li>
  6009. </ul><br/>
  6010. Aggregation results will be stored in readings <i>prefix</i>count, <i>prefix</i>list,
  6011. <i>prefix</i>match, <i>prefix</i>state and <i>prefix</i>table.<br/><br/>
  6012. Format of a line in <i>template-file</i> is &lt;keyword&gt;:&lt;html-code&gt;. See
  6013. FHEM Wiki for an example. Valid keywords are:<br/><br/>
  6014. <ul>
  6015. <li><b>begin-html</b>: Start of html code.</li>
  6016. <li><b>begin-table</b>: Start of table (i.e. the table header)</li>
  6017. <li><b>row-odd</b>: HTML code for odd lines. A tag &lt;reading/&gt is replaced by a matching device.</li>
  6018. <li><b>row-even</b>: HTML code for event lines.</li>
  6019. <li><b>end-table</b>: End of table.</li>
  6020. <li><b>default</b>: HTML code for no matches.</li>
  6021. <li><b>end-html</b>: End of html code.</li>
  6022. </ul><br/>
  6023. Example: Find open windows<br/>
  6024. name=lock,filter:type=^HM-Sec-SC.*,read:STATE,if:any=open,else:closed,prefix:lock_,coll:NAME!All windows closed<br/><br/>
  6025. Example: Find devices with low batteries. Generate reading in HTML format.<br/>
  6026. 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/>
  6027. </li><br/>
  6028. <li><b>ccudef-hmstatevals &lt;subst-rule[;...]&gt;</b><br/>
  6029. Set global rules for calculation of reading hmstate.
  6030. </li><br/>
  6031. <li><b>ccudef-readingfilter &lt;filter-rule[;...]&gt;</b><br/>
  6032. Set global reading/datapoint filter. This filter is added to the filter specified by
  6033. client device attribute 'ccureadingfilter'.
  6034. </li><br/>
  6035. <li><b>ccudef-readingformat {name | address | <u>datapoint</u> | namelc | addresslc |
  6036. datapointlc}</b><br/>
  6037. Set global reading format. This format is the default for all readings except readings
  6038. of virtual device groups.
  6039. </li><br/>
  6040. <li><b>ccudef-readingname &lt;old-readingname-expr&gt;:[+]&lt;new-readingname&gt;
  6041. [;...]</b><br/>
  6042. Set global rules for reading name substitution. These rules are added to the rules
  6043. specified by client device attribute 'ccureadingname'.
  6044. </li><br/>
  6045. <li><b>ccudef-substitute &lt;subst-rule&gt;[;...]</b><br/>
  6046. Set global substitution rules for datapoint value. These rules are added to the rules
  6047. specified by client device attribute 'substitute'.
  6048. </li><br/>
  6049. <li><b>ccudefaults &lt;filename&gt;</b><br/>
  6050. Load default attributes for HMCCUCHN and HMCCUDEV devices from specified file. Best
  6051. practice for creating a custom default attribute file is by exporting predefined default
  6052. attributes from HMCCU with command 'get exportdefaults'.
  6053. </li><br/>
  6054. <li><b>ccuflags {extrpc, procrpc, <u>intrpc</u>}</b><br/>
  6055. Control behaviour of several HMCCU functions:<br/>
  6056. ackState - Acknowledge command execution by setting STATE to error or success.<br/>
  6057. dptnocheck - Do not check within set or get commands if datapoint is valid<br/>
  6058. intrpc - Use internal RPC server. This is the default.<br/>
  6059. extrpc - Use external RPC server provided by module HMCCURPC. If no HMCCURPC device
  6060. exists HMCCU will create one after command 'set rpcserver on'.<br/>
  6061. logEvents - Write events from CCU into FHEM logfile<br/>
  6062. noReadings - Do not write readings<br/>
  6063. </li><br/>
  6064. <li><b>ccuget {State | <u>Value</u>}</b><br/>
  6065. Set read access method for CCU channel datapoints. Method 'State' is slower than
  6066. 'Value' because each request is sent to the device. With method 'Value' only CCU
  6067. is queried. Default is 'Value'.
  6068. </li><br/>
  6069. <li><b>ccuReqTimeout &lt;Seconds&gt;</b><br/>
  6070. Set timeout for CCU request. Default is 4 seconds. This timeout affects several
  6071. set and get commands, i.e. "set datapoint" or "set var". If a command runs into
  6072. a timeout FHEM will block for <i>Seconds</i>.
  6073. </li>
  6074. <li><b>ccureadings {0 | <u>1</u>}</b><br/>
  6075. Deprecated. Readings are written by default. To deactivate readings set flag noReadings
  6076. in attribute ccuflags.
  6077. </li><br/>
  6078. <li><b>parfile &lt;filename&gt;</b><br/>
  6079. Define parameter file for command 'get parfile'.
  6080. </li><br/>
  6081. <li><b>rpcdevice &lt;devicename&gt;</b><br/>
  6082. Specify name of external RPC device of type HMCCURPC.
  6083. </li><br/>
  6084. <li><b>rpcinterfaces &lt;interface&gt;[,...]</b><br/>
  6085. Specify list of CCU RPC interfaces. HMCCU will register a RPC server for each interface.
  6086. Interface BidCos-RF is default and always active. Valid interfaces are:<br/><br/>
  6087. <ul>
  6088. <li>BidCos-Wired (Port 2000)</li>
  6089. <li>BidCos-RF (Port 2001)</li>
  6090. <li>Homegear (Port 2003)</li>
  6091. <li>HmIP-RF (Port 2010)</li>
  6092. <li>HVL (Port 7000)</li>
  6093. <li>CUxD (Port 8701)</li>
  6094. <li>VirtualDevice (Port 9292)</li>
  6095. </ul>
  6096. </li><br/>
  6097. <li><b>rpcinterval &lt;Seconds&gt;</b><br/>
  6098. Specifiy how often RPC queue is read. Default is 5 seconds.
  6099. </li><br/>
  6100. <li><b>rpcport &lt;value[,...]&gt;</b><br/>
  6101. Deprecated, use 'rpcinterfaces' instead. Specify list of RPC ports on CCU. Default is
  6102. 2001. Valid RPC ports are:<br/><br/>
  6103. <ul>
  6104. <li>2000 = Wired components</li>
  6105. <li>2001 = BidCos-RF (wireless 868 MHz components with BidCos protocol)</li>
  6106. <li>2003 = Homegear (experimental)</li>
  6107. <li>2010 = HM-IP (wireless 868 MHz components with IPv6 protocol)</li>
  6108. <li>7000 = HVL (Homematic Virtual Layer devices)</li>
  6109. <li>8701 = CUxD (only supported with external RPC server HMCCURPC)</li>
  6110. <li>9292 = CCU group devices (especially heating groups)</li>
  6111. </ul>
  6112. </li><br/>
  6113. <li><b>rpcqueue &lt;queue-file&gt;</b><br/>
  6114. Specify name of RPC queue file. This parameter is only a prefix (including the
  6115. pathname) for the queue files with extension .idx and .dat. Default is
  6116. /tmp/ccuqueue. If FHEM is running on a SD card it's recommended that the queue
  6117. files are placed on a RAM disk.
  6118. </li><br/>
  6119. <li><b>rpcserver {on | <u>off</u>}</b><br/>
  6120. Specify if RPC server is automatically started on FHEM startup.
  6121. </li><br/>
  6122. <li><b>rpcserveraddr &lt;ip-or-name&gt;</b><br/>
  6123. Specify network interface by IP address or DNS name where RPC server should listen
  6124. on. By default HMCCU automatically detects the IP address. This attribute should be used
  6125. if the FHEM server has more than one network interface.
  6126. </li><br/>
  6127. <li><b>rpcserverport &lt;base-port&gt;</b><br/>
  6128. Specify base port for RPC server. The real listening port of an RPC server is
  6129. calculated by the formula: base-port + rpc-port + (10 * ccu-number). Default
  6130. value for <i>base-port</i> is 5400.<br/>
  6131. The value ccu-number is only relevant if more than one CCU is connected to FHEM.
  6132. Example: If <i>base-port</i> is 5000, protocol is BidCos (rpc-port 2001) and only
  6133. one CCU is connected the resulting RPC server port is 5000+2001+(10*0) = 7001.
  6134. </li><br/>
  6135. <li><b>substitute &lt;subst-rule&gt;:&lt;substext&gt;[,...]</b><br/>
  6136. Define substitions for datapoint values. Syntax of <i>subst-rule</i> is<br/><br/>
  6137. [[&lt;channelno.&gt;]&lt;datapoint&gt;[,...]!]&lt;{#n1-m1|regexp1}&gt;:&lt;text1&gt;[,...]
  6138. <br/>
  6139. Substitutions for parfile values must be specified in parfiles.
  6140. </li><br/>
  6141. <li><b>stripchar &lt;character&gt;</b><br/>
  6142. Strip the specified character from variable or device name in set commands. This
  6143. is useful if a variable should be set in CCU using the reading with trailing colon.
  6144. </li>
  6145. </ul>
  6146. </ul>
  6147. =end html
  6148. =cut