93_DbLog.pm 323 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074
  1. ############################################################################################################################################
  2. # $Id: 93_DbLog.pm 16369 2018-03-10 08:15:06Z DS_Starter $
  3. #
  4. # 93_DbLog.pm
  5. # written by Dr. Boris Neubert 2007-12-30
  6. # e-mail: omega at online dot de
  7. #
  8. # modified and maintained by Tobias Faust since 2012-06-26
  9. # e-mail: tobias dot faust at online dot de
  10. #
  11. # reduceLog() created by Claudiu Schuster (rapster)
  12. #
  13. # redesigned 2016-2018 by DS_Starter with credits by
  14. # JoeAllb, DeeSpe
  15. #
  16. ############################################################################################################################################
  17. # Versions History done by DS_Starter & DeeSPe:
  18. #
  19. # 3.8.9 10.03.2018 commandref revised
  20. # 3.8.8 05.03.2018 fix device doesn't exit if configuration couldn't be read
  21. # 3.8.7 28.02.2018 changed DbLog_sampleDataFn - no change limits got fron SVG, commandref revised
  22. # 3.8.6 25.02.2018 commandref revised (forum:#84953)
  23. # 3.8.5 16.02.2018 changed ParseEvent for Zwave
  24. # 3.8.4 07.02.2018 minor fixes of "$@", code review, eval for userCommand, DbLog_ExecSQL1 (forum:#83973)
  25. # 3.8.3 03.02.2018 call execmemcache only syncInterval/2 if cacheLimit reached and DB is not reachable, fix handling of
  26. # "$@" in DbLog_PushAsync
  27. # 3.8.2 31.01.2018 RaiseError => 1 in DbLog_ConnectPush, DbLog_ConnectNewDBH, configCheck improved
  28. # 3.8.1 29.01.2018 Use of uninitialized value $txt if addlog has no value
  29. # 3.8.0 26.01.2018 escape "|" in events to log events containing it
  30. # 3.7.1 25.01.2018 fix typo in commandref
  31. # 3.7.0 21.01.2018 parsed event with Log 5 added, configCheck enhanced by configuration read check
  32. # 3.6.5 19.01.2018 fix lot of logentries if disabled and db not available
  33. # 3.6.4 17.01.2018 improve DbLog_Shutdown, extend configCheck by shutdown preparation check
  34. # 3.6.3 14.01.2018 change verbose level of addlog "no Reading of device ..." message from 2 to 4
  35. # 3.6.2 07.01.2018 new attribute "exportCacheAppend", change function exportCache to respect attr exportCacheAppend,
  36. # fix DbLog_execmemcache verbose 5 message
  37. # 3.6.1 04.01.2018 change SQLite PRAGMA from NORMAL to FULL (Default Value of SQLite)
  38. # 3.6.0 20.12.2017 check global blockingCallMax in configCheck, configCheck now available for SQLITE
  39. # 3.5.0 18.12.2017 importCacheFile, addCacheLine uses useCharfilter option, filter only $event by charfilter
  40. # 3.4.0 10.12.2017 avoid print out {RUNNING_PID} by "list device"
  41. # 3.3.0 07.12.2017 avoid print out the content of cache by "list device"
  42. # 3.2.0 06.12.2017 change attribute "autocommit" to "commitMode", activate choice of autocommit/transaction in logging
  43. # Addlog/addCacheLine change $TIMESTAMP check,
  44. # rebuild DbLog_Push/DbLog_PushAsync due to bugfix in update current (Forum:#80519),
  45. # new attribute "useCharfilter" for Characterfilter usage
  46. # 3.1.1 05.12.2017 Characterfilter added to avoid unwanted characters what may destroy transaction
  47. # 3.1.0 05.12.2017 new set command addCacheLine
  48. # 3.0.0 03.12.2017 set begin_work depending of AutoCommit value, new attribute "autocommit", some minor corrections,
  49. # report working progress of reduceLog,reduceLogNbl in logfile (verbose 3), enhanced log output
  50. # (e.g. of execute_array)
  51. # 2.22.15 28.11.2017 some Log3 verbose level adapted
  52. # 2.22.14 18.11.2017 create state-events if state has been changed (Forum:#78867)
  53. # 2.22.13 20.10.2017 output of reopen command improved
  54. # 2.22.12 19.10.2017 avoid illegible messages in "state"
  55. # 2.22.11 13.10.2017 DbLogType expanded by SampleFill, DbLog_sampleDataFn adapted to sort case insensitive, commandref revised
  56. # 2.22.10 04.10.2017 Encode::encode_utf8 of $error, DbLog_PushAsyncAborted adapted to use abortArg (Forum:77472)
  57. # 2.22.9 04.10.2017 added hint to SVG/DbRep in commandref
  58. # 2.22.8 29.09.2017 avoid multiple entries in Dopdown-list when creating SVG by group Device:Reading in DbLog_sampleDataFn
  59. # 2.22.7 24.09.2017 minor fixes in configcheck
  60. # 2.22.6 22.09.2017 commandref revised
  61. # 2.22.5 05.09.2017 fix Internal MODE isn't set correctly after DEF is edited, nextsynch is not renewed if reopen is
  62. # set manually after reopen was set with a delay Forum:#76213, Link to 98_FileLogConvert.pm added
  63. # 2.22.4 27.08.2017 fhem chrashes if database DBD driver is not installed (Forum:#75894)
  64. # 2.22.3 11.08.2017 Forum:#74690, bug unitialized in row 4322 -> $ret .= SVG_txt("par_${r}_0", "", "$f0:$f1:$f2:$f3", 20);
  65. # 2.22.2 08.08.2017 Forum:#74690, bug unitialized in row 737 -> $ret .= ($fld[0]?$fld[0]:" ").'.'.($fld[1]?$fld[1]:" ");
  66. # 2.22.1 07.08.2017 attribute "suppressAddLogV3" to suppress verbose3-logentries created by DbLog_AddLog
  67. # 2.22.0 25.07.2017 attribute "addStateEvent" added
  68. # 2.21.3 24.07.2017 commandref revised
  69. # 2.21.2 19.07.2017 changed readCfg to report more error-messages
  70. # 2.21.1 18.07.2017 change configCheck for DbRep Report_Idx
  71. # 2.21.0 17.07.2017 standard timeout increased to 86400, enhanced explaination in configCheck
  72. # 2.20.0 15.07.2017 state-Events complemented with state by using $events = deviceEvents($dev_hash,1)
  73. # 2.19.0 11.07.2017 replace {DBMODEL} by {MODEL} completely
  74. # 2.18.3 04.07.2017 bugfix (links with $FW_ME deleted), MODEL as Internal (for statistic)
  75. # 2.18.2 29.06.2017 check of index for DbRep added
  76. # 2.18.1 25.06.2017 DbLog_configCheck/ DbLog_sqlget some changes, commandref revised
  77. # 2.18.0 24.06.2017 configCheck added (MySQL, PostgreSQL)
  78. # 2.17.1 17.06.2017 fix log-entries "utf8 enabled" if SVG's called, commandref revised, enable UTF8 for DbLog_get
  79. # 2.17.0 15.06.2017 enable UTF8 for MySQL (entry in configuration file necessary)
  80. # 2.16.11 03.06.2017 execmemcache changed for SQLite avoid logging if deleteOldDaysNbl or reduceLogNbL is running
  81. # 2.16.10 15.05.2017 commandref revised
  82. # 2.16.9.1 11.05.2017 set userCommand changed -
  83. # Forum: https://forum.fhem.de/index.php/topic,71808.msg633607.html#msg633607
  84. # 2.16.9 07.05.2017 addlog syntax changed to "addLog devspec:Reading [Value]"
  85. # 2.16.8 06.05.2017 in valueFN $VALUE and $UNIT can now be set to '' or 0
  86. # 2.16.7 20.04.2017 fix $now at addLog
  87. # 2.16.6 18.04.2017 AddLog set lasttime, lastvalue of dev_name, dev_reading
  88. # 2.16.5 16.04.2017 DbLog_checkUsePK changed again, new attribute noSupportPK
  89. # 2.16.4 15.04.2017 commandref completed, DbLog_checkUsePK changed (@usepkh = "", @usepkc = "")
  90. # 2.16.3 07.04.2017 evaluate reading in DbLog_AddLog as regular expression
  91. # 2.16.2 06.04.2017 sub DbLog_cutCol for cutting fields to maximum length, return to "$lv = "" if(!$lv);" because
  92. # of problems with MinIntervall, DbLogType-Logging in database cycle verbose 5, make $TIMESTAMP
  93. # changable by valueFn
  94. # 2.16.1 04.04.2017 changed regexp $exc =~ s/(\s|\s*\n)/,/g; , DbLog_AddLog changed, enhanced sort of listCache
  95. # 2.16.0 03.04.2017 new set-command addLog
  96. # 2.15.0 03.04.2017 new attr valueFn using for perl expression which may change variables and skip logging
  97. # unwanted datasets, change DbLog_ParseEvent for ZWAVE,
  98. # change DbLogExclude / DbLogInclude in DbLog_Log to "$lv = "" if(!defined($lv));"
  99. # 2.14.4 28.03.2017 pre-connection check in DbLog_execmemcache deleted (avoid possible blocking), attr excludeDevs
  100. # can be specified as devspec
  101. # 2.14.3 24.03.2017 DbLog_Get, DbLog_Push changed for better plotfork-support
  102. # 2.14.2 23.03.2017 new reading "lastCachefile"
  103. # 2.14.1 22.03.2017 cacheFile will be renamed after successful import by set importCachefile
  104. # 2.14.0 19.03.2017 new set-commands exportCache, importCachefile, new attr expimpdir, all cache relevant set-commands
  105. # only in drop-down list when asynch mode is used, minor fixes
  106. # 2.13.6 13.03.2017 plausibility check in set reduceLog(Nbl) enhanced, minor fixes
  107. # 2.13.5 20.02.2017 check presence of table current in DbLog_sampleDataFn
  108. # 2.13.4 18.02.2017 DbLog_Push & DbLog_PushAsync: separate eval-routines for history & current table execution
  109. # to decouple commit or rollback transactions, DbLog_sampleDataFn changed to avoid fhem from crash if table
  110. # current is not present and DbLogType isn't set
  111. # 2.13.3 18.02.2017 default timeout of DbLog_PushAsync increased to 1800,
  112. # delete {HELPER}{xx_PID} in reopen function
  113. # 2.13.2 16.02.2017 deleteOldDaysNbl added (non-blocking implementation of deleteOldDays)
  114. # 2.13.1 15.02.2017 clearReadings limited to readings which won't be recreated periodicly in asynch mode and set readings only blank,
  115. # eraseReadings added to delete readings except reading "state",
  116. # countNbl non-blocking by DeeSPe,
  117. # rename reduceLog non-blocking to reduceLogNbl and implement the old reduceLog too
  118. # 2.13.0 13.02.2017 made reduceLog non-blocking by DeeSPe
  119. # 2.12.5 11.02.2017 add support for primary key of PostgreSQL DB (Rel. 9.5) in both modes for current table
  120. # 2.12.4 09.02.2017 support for primary key of PostgreSQL DB (Rel. 9.5) in both modes only history table
  121. # 2.12.3 07.02.2017 set command clearReadings added
  122. # 2.12.2 07.02.2017 support for primary key of SQLITE DB in both modes
  123. # 2.12.1 05.02.2017 support for primary key of MySQL DB in synch mode
  124. # 2.12 04.02.2017 support for primary key of MySQL DB in asynch mode
  125. # 2.11.4 03.02.2017 check of missing modules added
  126. # 2.11.3 01.02.2017 make errorlogging of DbLog_PushAsync more identical to DbLog_Push
  127. # 2.11.2 31.01.2017 if attr colEvent, colReading, colValue is set, the limitation of fieldlength is also valid
  128. # for SQLite databases
  129. # 2.11.1 30.01.2017 output to central logfile enhanced for DbLog_Push
  130. # 2.11 28.01.2017 DbLog_connect substituted by DbLog_connectPush completely
  131. # 2.10.8 27.01.2017 DbLog_setinternalcols delayed at fhem start
  132. # 2.10.7 25.01.2017 $hash->{HELPER}{COLSET} in DbLog_setinternalcols, DbLog_Push changed due to
  133. # issue Turning on AutoCommit failed
  134. # 2.10.6 24.01.2017 DbLog_connect changed "connect_cashed" to "connect", DbLog_Get, chartQuery now uses
  135. # DbLog_ConnectNewDBH, Attr asyncMode changed -> delete reading cacheusage reliable if mode was switched
  136. # 2.10.5 23.01.2017 count, userCommand, deleteOldDays now uses DbLog_ConnectNewDBH
  137. # DbLog_Push line 1107 changed
  138. # 2.10.4 22.01.2017 new sub DbLog_setinternalcols, new attributes colEvent, colReading, colValue
  139. # 2.10.3 21.01.2017 query of cacheEvents changed, attr timeout adjustable
  140. # 2.10.2 19.01.2017 ReduceLog now uses DbLog_ConnectNewDBH -> makes start of ReduceLog stable
  141. # 2.10.1 19.01.2017 commandref edited, cache events don't get lost even if other errors than "db not available" occure
  142. # 2.10 18.10.2017 new attribute cacheLimit, showNotifyTime
  143. # 2.9.3 17.01.2017 new sub DbLog_ConnectNewDBH (own new dbh for separate use in functions except logging functions),
  144. # DbLog_sampleDataFn, dbReadings now use DbLog_ConnectNewDBH
  145. # 2.9.2 16.01.2017 new bugfix for SQLite issue SVGs, DbLog_Log changed to $dev_hash->{CHANGETIME}, DbLog_Push
  146. # changed (db handle new separated)
  147. # 2.9.1 14.01.2017 changed DbLog_ParseEvent to CallInstanceFn, renamed flushCache to purgeCache,
  148. # renamed syncCache to commitCache, attr cacheEvents changed to 0,1,2
  149. # 2.9 11.01.2017 changed DbLog_ParseEvent to CallFn
  150. # 2.8.9 11.01.2017 own $dbhp (new DbLog_ConnectPush) for synchronous logging, delete $hash->{HELPER}{RUNNING_PID}
  151. # if DEAD, add func flushCache, syncCache
  152. # 2.8.8 10.01.2017 connection check in Get added, avoid warning "commit/rollback ineffective with AutoCommit enabled"
  153. # 2.8.7 10.01.2017 bugfix no dropdown list in SVG if asynchronous mode activated (func DbLog_sampleDataFn)
  154. # 2.8.6 09.01.2017 Workaround for Warning begin_work failed: Turning off AutoCommit failed, start new timer of
  155. # DbLog_execmemcache after reducelog
  156. # 2.8.5 08.01.2017 attr syncEvents, cacheEvents added to minimize events
  157. # 2.8.4 08.01.2017 $readingFnAttributes added
  158. # 2.8.3 08.01.2017 set NOTIFYDEV changed to use notifyRegexpChanged (Forum msg555619), attr noNotifyDev added
  159. # 2.8.2 06.01.2017 commandref maintained to cover new functions
  160. # 2.8.1 05.01.2017 use Time::HiRes qw(gettimeofday tv_interval), bugfix $hash->{HELPER}{RUNNING_PID}
  161. # 2.8 03.01.2017 attr asyncMode, you have a choice to use blocking (as V2.5) or non-blocking asynchronous
  162. # with caching, attr showproctime
  163. # 2.7 02.01.2017 initial release non-blocking using BlockingCall
  164. # 2.6 02.01.2017 asynchron writing to DB using cache, attr syncInterval, set listCache
  165. # 2.5 29.12.2016 commandref maintained to cover new attributes, attr "excludeDevs" and "verbose4Devs" now
  166. # accepting Regex
  167. # 2.4.4 28.12.2016 Attribut "excludeDevs" to exclude devices from db-logging (only if $hash->{NOTIFYDEV} eq ".*")
  168. # 2.4.3 28.12.2016 function DbLog_Log: changed separators of @row_array -> better splitting
  169. # 2.4.2 28.12.2016 Attribut "verbose4Devs" to restrict verbose4 loggings of specific devices
  170. # 2.4.1 27.12.2016 DbLog_Push: improved update/insert into current, analyze execute_array -> ArrayTupleStatus
  171. # 2.4 24.12.2016 some improvements of verbose 4 logging
  172. # 2.3.1 23.12.2016 fix due to https://forum.fhem.de/index.php/topic,62998.msg545541.html#msg545541
  173. # 2.3 22.12.2016 fix eval{} in DbLog_Log
  174. # 2.2 21.12.2016 set DbLogType only to "History" if attr DbLogType not set
  175. # 2.1 21.12.2016 use execute_array in DbLog_Push
  176. # 2.0 19.12.2016 some improvements DbLog_Log
  177. # 1.9.3 17.12.2016 $hash->{NOTIFYDEV} added to process only events from devices are in Regex
  178. # 1.9.2 17.12.2016 some improvemnts DbLog_Log, DbLog_Push
  179. # 1.9.1 16.12.2016 DbLog_Log no using encode_base64
  180. # 1.9 16.12.2016 DbLog_Push changed to use deviceEvents
  181. # 1.8.1 16.12.2016 DbLog_Push changed
  182. # 1.8 15.12.2016 bugfix of don't logging all received events
  183. # 1.7.1 15.12.2016 attr procedure of "disabled" changed
  184. package main;
  185. use strict;
  186. use warnings;
  187. eval "use DBI;1" or my $DbLogMMDBI = "DBI";
  188. use Data::Dumper;
  189. use Blocking;
  190. use Time::HiRes qw(gettimeofday tv_interval);
  191. use Encode qw(encode_utf8);
  192. my $DbLogVersion = "3.8.9";
  193. my %columns = ("DEVICE" => 64,
  194. "TYPE" => 64,
  195. "EVENT" => 512,
  196. "READING" => 64,
  197. "VALUE" => 128,
  198. "UNIT" => 32
  199. );
  200. sub dbReadings($@);
  201. ################################################################
  202. sub DbLog_Initialize($)
  203. {
  204. my ($hash) = @_;
  205. $hash->{DefFn} = "DbLog_Define";
  206. $hash->{UndefFn} = "DbLog_Undef";
  207. $hash->{NotifyFn} = "DbLog_Log";
  208. $hash->{SetFn} = "DbLog_Set";
  209. $hash->{GetFn} = "DbLog_Get";
  210. $hash->{AttrFn} = "DbLog_Attr";
  211. $hash->{SVG_regexpFn} = "DbLog_regexpFn";
  212. $hash->{ShutdownFn} = "DbLog_Shutdown";
  213. $hash->{AttrList} = "addStateEvent:0,1 ".
  214. "commitMode:basic_ta:on,basic_ta:off,ac:on_ta:on,ac:on_ta:off,ac:off_ta:on ".
  215. "colEvent ".
  216. "colReading ".
  217. "colValue ".
  218. "disable:1,0 ".
  219. "DbLogType:Current,History,Current/History,SampleFill/History ".
  220. "shutdownWait ".
  221. "suppressUndef:0,1 ".
  222. "verbose4Devs ".
  223. "excludeDevs ".
  224. "expimpdir ".
  225. "exportCacheAppend:1,0 ".
  226. "syncInterval ".
  227. "noNotifyDev:1,0 ".
  228. "showproctime:1,0 ".
  229. "suppressAddLogV3:1,0 ".
  230. "asyncMode:1,0 ".
  231. "cacheEvents:2,1,0 ".
  232. "cacheLimit ".
  233. "noSupportPK:1,0 ".
  234. "syncEvents:1,0 ".
  235. "showNotifyTime:1,0 ".
  236. "timeout ".
  237. "useCharfilter:0,1 ".
  238. "valueFn:textField-long ".
  239. "DbLogSelectionMode:Exclude,Include,Exclude/Include ".
  240. $readingFnAttributes;
  241. # Das Attribut DbLogSelectionMode legt fest, wie die Device-Spezifischen Atrribute
  242. # DbLogExclude und DbLogInclude behandelt werden sollen.
  243. # - Exclude: Es wird nur das Device-spezifische Attribut Exclude beruecksichtigt,
  244. # d.h. generell wird alles geloggt, was nicht per DBLogExclude ausgeschlossen wird
  245. # - Include: Es wird nur das Device-spezifische Attribut Include beruecksichtigt,
  246. # d.h. generell wird nichts geloggt, ausßer dem was per DBLogInclude eingeschlossen wird
  247. # - Exclude/Include: Es wird zunaechst Exclude geprueft und bei Ausschluß wird ggf. noch zusaetzlich Include geprueft,
  248. # d.h. generell wird alles geloggt, es sei denn es wird per DBLogExclude ausgeschlossen.
  249. # Wird es von DBLogExclude ausgeschlossen, kann es trotzdem wieder per DBLogInclude
  250. # eingeschlossen werden.
  251. addToAttrList("DbLogInclude");
  252. addToAttrList("DbLogExclude");
  253. $hash->{FW_detailFn} = "DbLog_fhemwebFn";
  254. $hash->{SVG_sampleDataFn} = "DbLog_sampleDataFn";
  255. }
  256. ###############################################################
  257. sub DbLog_Define($@)
  258. {
  259. my ($hash, $def) = @_;
  260. my @a = split("[ \t][ \t]*", $def);
  261. return "Error: Perl module ".$DbLogMMDBI." is missing.
  262. Install it on Debian with: sudo apt-get install libdbi-perl" if($DbLogMMDBI);
  263. return "wrong syntax: define <name> DbLog configuration regexp"
  264. if(int(@a) != 4);
  265. $hash->{CONFIGURATION} = $a[2];
  266. my $regexp = $a[3];
  267. eval { "Hallo" =~ m/^$regexp$/ };
  268. return "Bad regexp: $@" if($@);
  269. $hash->{REGEXP} = $regexp;
  270. $hash->{VERSION} = $DbLogVersion;
  271. $hash->{MODE} = AttrVal($hash->{NAME}, "asyncMode", undef)?"asynchronous":"synchronous"; # Mode setzen Forum:#76213
  272. $hash->{HELPER}{OLDSTATE} = "initialized";
  273. # nur Events dieser Devices an NotifyFn weiterleiten, NOTIFYDEV wird gesetzt wenn möglich
  274. notifyRegexpChanged($hash, $regexp);
  275. #remember PID for plotfork
  276. $hash->{PID} = $$;
  277. # CacheIndex für Events zum asynchronen Schreiben in DB
  278. $hash->{cache}{index} = 0;
  279. # read configuration data
  280. my $ret = DbLog_readCfg($hash);
  281. if ($ret) {
  282. # return on error while reading configuration
  283. Log3($hash->{NAME}, 1, "DbLog $hash->{NAME} - Error while reading $hash->{CONFIGURATION}: '$ret' ");
  284. return $ret;
  285. }
  286. # set used COLUMNS
  287. InternalTimer(gettimeofday()+2, "DbLog_setinternalcols", $hash, 0);
  288. readingsSingleUpdate($hash, 'state', 'waiting for connection', 1);
  289. DbLog_ConnectPush($hash);
  290. # initial execution of DbLog_execmemcache
  291. DbLog_execmemcache($hash);
  292. return undef;
  293. }
  294. ################################################################
  295. sub DbLog_Undef($$) {
  296. my ($hash, $name) = @_;
  297. my $dbh= $hash->{DBHP};
  298. BlockingKill($hash->{HELPER}{".RUNNING_PID"}) if($hash->{HELPER}{".RUNNING_PID"});
  299. BlockingKill($hash->{HELPER}{REDUCELOG_PID}) if($hash->{HELPER}{REDUCELOG_PID});
  300. BlockingKill($hash->{HELPER}{COUNT_PID}) if($hash->{HELPER}{COUNT_PID});
  301. BlockingKill($hash->{HELPER}{DELDAYS_PID}) if($hash->{HELPER}{DELDAYS_PID});
  302. $dbh->disconnect() if(defined($dbh));
  303. RemoveInternalTimer($hash);
  304. return undef;
  305. }
  306. ################################################################
  307. sub DbLog_Shutdown($) {
  308. my ($hash) = @_;
  309. my $name = $hash->{NAME};
  310. $hash->{HELPER}{SHUTDOWNSEQ} = 1;
  311. DbLog_execmemcache($hash);
  312. my $shutdownWait = AttrVal($name,"shutdownWait",undef);
  313. if(defined($shutdownWait)) {
  314. Log3($name, 2, "DbLog $name - waiting for shutdown $shutdownWait seconds ...");
  315. sleep($shutdownWait);
  316. Log3($name, 2, "DbLog $name - continuing shutdown sequence");
  317. }
  318. if($hash->{HELPER}{".RUNNING_PID"}) {
  319. BlockingKill($hash->{HELPER}{".RUNNING_PID"});
  320. }
  321. return undef;
  322. }
  323. ################################################################
  324. #
  325. # Wird bei jeder Aenderung eines Attributes dieser
  326. # DbLog-Instanz aufgerufen
  327. #
  328. ################################################################
  329. sub DbLog_Attr(@) {
  330. my($cmd,$name,$aName,$aVal) = @_;
  331. # my @a = @_;
  332. my $hash = $defs{$name};
  333. my $dbh = $hash->{DBHP};
  334. my $do = 0;
  335. if($cmd eq "set") {
  336. if ($aName eq "syncInterval" || $aName eq "cacheLimit" || $aName eq "timeout") {
  337. unless ($aVal =~ /^[0-9]+$/) { return " The Value of $aName is not valid. Use only figures 0-9 !";}
  338. }
  339. if( $aName eq 'valueFn' ) {
  340. my %specials= (
  341. "%TIMESTAMP" => $name,
  342. "%DEVICE" => $name,
  343. "%DEVICETYPE" => $name,
  344. "%EVENT" => $name,
  345. "%READING" => $name,
  346. "%VALUE" => $name,
  347. "%UNIT" => $name,
  348. "%IGNORE" => $name,
  349. );
  350. my $err = perlSyntaxCheck($aVal, %specials);
  351. return $err if($err);
  352. }
  353. }
  354. if($aName eq "colEvent" || $aName eq "colReading" || $aName eq "colValue") {
  355. if ($cmd eq "set" && $aVal) {
  356. unless ($aVal =~ /^[0-9]+$/) { return " The Value of $aName is not valid. Use only figures 0-9 !";}
  357. }
  358. InternalTimer(gettimeofday()+0.5, "DbLog_setinternalcols", $hash, 0);
  359. }
  360. if($aName eq "asyncMode") {
  361. if ($cmd eq "set" && $aVal) {
  362. $hash->{MODE} = "asynchronous";
  363. InternalTimer(gettimeofday()+2, "DbLog_execmemcache", $hash, 0);
  364. } else {
  365. $hash->{MODE} = "synchronous";
  366. delete($defs{$name}{READINGS}{NextSync});
  367. delete($defs{$name}{READINGS}{CacheUsage});
  368. InternalTimer(gettimeofday()+5, "DbLog_execmemcache", $hash, 0);
  369. }
  370. }
  371. if($aName eq "commitMode") {
  372. if ($dbh) {
  373. $dbh->commit() if(!$dbh->{AutoCommit});
  374. $dbh->disconnect();
  375. }
  376. }
  377. if($aName eq "showproctime") {
  378. if ($cmd ne "set" || !$aVal) {
  379. delete($defs{$name}{READINGS}{background_processing_time});
  380. delete($defs{$name}{READINGS}{sql_processing_time});
  381. }
  382. }
  383. if($aName eq "showNotifyTime") {
  384. if ($cmd ne "set" || !$aVal) {
  385. delete($defs{$name}{READINGS}{notify_processing_time});
  386. }
  387. }
  388. if($aName eq "noNotifyDev") {
  389. my $regexp = $hash->{REGEXP};
  390. if ($cmd eq "set" && $aVal) {
  391. delete($hash->{NOTIFYDEV});
  392. } else {
  393. notifyRegexpChanged($hash, $regexp);
  394. }
  395. }
  396. if ($aName eq "disable") {
  397. my $async = AttrVal($name, "asyncMode", 0);
  398. if($cmd eq "set") {
  399. $do = ($aVal) ? 1 : 0;
  400. }
  401. $do = 0 if($cmd eq "del");
  402. my $val = ($do == 1 ? "disabled" : "active");
  403. # letzter CacheSync vor disablen
  404. DbLog_execmemcache($hash) if($do == 1);
  405. readingsSingleUpdate($hash, "state", $val, 1);
  406. $hash->{HELPER}{OLDSTATE} = $val;
  407. if ($do == 0) {
  408. InternalTimer(gettimeofday()+2, "DbLog_execmemcache", $hash, 0) if($async);
  409. InternalTimer(gettimeofday()+2, "DbLog_ConnectPush", $hash, 0) if(!$async);
  410. }
  411. }
  412. return undef;
  413. }
  414. ################################################################
  415. sub DbLog_Set($@) {
  416. my ($hash, @a) = @_;
  417. my $name = $hash->{NAME};
  418. my $async = AttrVal($name, "asyncMode", undef);
  419. my $usage = "Unknown argument, choose one of reduceLog reduceLogNbl reopen rereadcfg:noArg count:noArg countNbl:noArg
  420. deleteOldDays deleteOldDaysNbl userCommand clearReadings:noArg
  421. eraseReadings:noArg addLog ";
  422. $usage .= "listCache:noArg addCacheLine purgeCache:noArg commitCache:noArg exportCache:nopurge,purgecache " if (AttrVal($name, "asyncMode", undef));
  423. $usage .= "configCheck:noArg ";
  424. my (@logs,$dir);
  425. if (!AttrVal($name,"expimpdir",undef)) {
  426. $dir = $attr{global}{modpath}."/log/";
  427. } else {
  428. $dir = AttrVal($name,"expimpdir",undef);
  429. }
  430. opendir(DIR,$dir);
  431. my $sd = "cache_".$name."_";
  432. while (my $file = readdir(DIR)) {
  433. next unless (-f "$dir/$file");
  434. next unless ($file =~ /^$sd/);
  435. push @logs,$file;
  436. }
  437. closedir(DIR);
  438. my $cj = join(",",reverse(sort @logs)) if (@logs);
  439. if (@logs) {
  440. $usage .= "importCachefile:".$cj." ";
  441. } else {
  442. $usage .= "importCachefile ";
  443. }
  444. return $usage if(int(@a) < 2);
  445. my $dbh = $hash->{DBHP};
  446. my $db = (split(/;|=/, $hash->{dbconn}))[1];
  447. my $ret;
  448. if ($a[1] eq 'reduceLog') {
  449. if (defined($a[3]) && $a[3] !~ /^average$|^average=.+|^EXCLUDE=.+$|^INCLUDE=.+$/i) {
  450. return "ReduceLog syntax error in set command. Please see commandref for help.";
  451. }
  452. if (defined $a[2] && $a[2] =~ /^\d+$/) {
  453. $ret = DbLog_reduceLog($hash,@a);
  454. InternalTimer(gettimeofday()+5, "DbLog_execmemcache", $hash, 0);
  455. } else {
  456. Log3($name, 1, "DbLog $name: reduceLog error, no <days> given.");
  457. $ret = "reduceLog error, no <days> given.";
  458. }
  459. }
  460. elsif ($a[1] eq 'reduceLogNbl') {
  461. if (defined($a[3]) && $a[3] !~ /^average$|^average=.+|^EXCLUDE=.+$|^INCLUDE=.+$/i) {
  462. return "ReduceLogNbl syntax error in set command. Please see commandref for help.";
  463. }
  464. if (defined $a[2] && $a[2] =~ /^\d+$/) {
  465. if ($hash->{HELPER}{REDUCELOG_PID} && $hash->{HELPER}{REDUCELOG_PID}{pid} !~ m/DEAD/) {
  466. $ret = "reduceLogNbl already in progress. Please wait for the current process to finish.";
  467. } else {
  468. delete $hash->{HELPER}{REDUCELOG_PID};
  469. my @b = @a;
  470. shift(@b);
  471. readingsSingleUpdate($hash,"reduceLogState","@b started",1);
  472. $hash->{HELPER}{REDUCELOG} = \@a;
  473. $hash->{HELPER}{REDUCELOG_PID} = BlockingCall("DbLog_reduceLogNbl","$name","DbLog_reduceLogNbl_finished");
  474. return;
  475. }
  476. } else {
  477. Log3($name, 1, "DbLog $name: reduceLogNbl error, no <days> given.");
  478. $ret = "reduceLogNbl error, no <days> given.";
  479. }
  480. }
  481. elsif ($a[1] eq 'clearReadings') {
  482. my @allrds = keys%{$defs{$name}{READINGS}};
  483. foreach my $key(@allrds) {
  484. next if($key =~ m/state/ || $key =~ m/CacheUsage/ || $key =~ m/NextSync/);
  485. readingsSingleUpdate($hash,$key," ",0);
  486. }
  487. }
  488. elsif ($a[1] eq 'eraseReadings') {
  489. my @allrds = keys%{$defs{$name}{READINGS}};
  490. foreach my $key(@allrds) {
  491. delete($defs{$name}{READINGS}{$key}) if($key !~ m/^state$/);
  492. }
  493. }
  494. elsif ($a[1] eq 'addLog') {
  495. unless ($a[2]) { return " The argument of $a[1] is not valid. Use a pair of <devicespec>,reading [value] you want to create a log entry from";}
  496. DbLog_AddLog($hash,$a[2],$a[3]);
  497. }
  498. elsif ($a[1] eq 'reopen') {
  499. if ($dbh) {
  500. $dbh->commit() if(!$dbh->{AutoCommit});
  501. $dbh->disconnect();
  502. }
  503. if (!$a[2]) {
  504. Log3($name, 3, "DbLog $name: Reopen requested.");
  505. DbLog_ConnectPush($hash);
  506. if($hash->{HELPER}{REOPEN_RUNS}) {
  507. delete $hash->{HELPER}{REOPEN_RUNS};
  508. RemoveInternalTimer($hash, "reopen");
  509. }
  510. DbLog_execmemcache($hash) if($async);
  511. $ret = "Reopen executed.";
  512. } else {
  513. unless ($a[2] =~ /^[0-9]+$/) { return " The Value of $a[1]-time is not valid. Use only figures 0-9 !";}
  514. # Statusbit "Kein Schreiben in DB erlauben" wenn reopen mit Zeitangabe
  515. $hash->{HELPER}{REOPEN_RUNS} = $a[2];
  516. # falls ein hängender Prozess vorhanden ist -> löschen
  517. BlockingKill($hash->{HELPER}{".RUNNING_PID"}) if($hash->{HELPER}{".RUNNING_PID"});
  518. BlockingKill($hash->{HELPER}{REDUCELOG_PID}) if($hash->{HELPER}{REDUCELOG_PID});
  519. BlockingKill($hash->{HELPER}{COUNT_PID}) if($hash->{HELPER}{COUNT_PID});
  520. BlockingKill($hash->{HELPER}{DELDAYS_PID}) if($hash->{HELPER}{DELDAYS_PID});
  521. delete $hash->{HELPER}{".RUNNING_PID"};
  522. delete $hash->{HELPER}{COUNT_PID};
  523. delete $hash->{HELPER}{DELDAYS_PID};
  524. delete $hash->{HELPER}{REDUCELOG_PID};
  525. my $ts = (split(" ",FmtDateTime(gettimeofday()+$a[2])))[1];
  526. Log3($name, 2, "DbLog $name: Connection closed until $ts ($a[2] seconds).");
  527. readingsSingleUpdate($hash, "state", "closed until $ts ($a[2] seconds)", 1);
  528. InternalTimer(gettimeofday()+$a[2], "DbLog_reopen", $hash, 0);
  529. }
  530. }
  531. elsif ($a[1] eq 'rereadcfg') {
  532. Log3($name, 3, "DbLog $name: Rereadcfg requested.");
  533. if ($dbh) {
  534. $dbh->commit() if(!$dbh->{AutoCommit});
  535. $dbh->disconnect();
  536. }
  537. $ret = DbLog_readCfg($hash);
  538. return $ret if $ret;
  539. DbLog_ConnectPush($hash);
  540. $ret = "Rereadcfg executed.";
  541. }
  542. elsif ($a[1] eq 'purgeCache') {
  543. delete $hash->{cache};
  544. readingsSingleUpdate($hash, 'CacheUsage', 0, 1);
  545. }
  546. elsif ($a[1] eq 'commitCache') {
  547. DbLog_execmemcache($hash);
  548. }
  549. elsif ($a[1] eq 'listCache') {
  550. my $cache;
  551. foreach my $key (sort{$a <=>$b}keys%{$hash->{cache}{".memcache"}}) {
  552. $cache .= $key." => ".$hash->{cache}{".memcache"}{$key}."\n";
  553. }
  554. return $cache;
  555. }
  556. elsif ($a[1] eq 'addCacheLine') {
  557. if(!$a[2]) {
  558. return "Syntax error in set $a[1] command. Use this line format: YYYY-MM-DD HH:MM:SS|<device>|<type>|<event>|<reading>|<value>|[<unit>] ";
  559. }
  560. my @b = @a;
  561. shift @b;
  562. shift @b;
  563. my $aa;
  564. foreach my $k (@b) {
  565. $aa .= "$k ";
  566. }
  567. chop($aa); #letztes Leerzeichen entfernen
  568. $aa = DbLog_charfilter($aa) if(AttrVal($name, "useCharfilter",0));
  569. my ($i_timestamp, $i_dev, $i_type, $i_evt, $i_reading, $i_val, $i_unit) = split("\\|",$aa);
  570. if($i_timestamp !~ /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/ || !$i_dev || !$i_reading) {
  571. return "Syntax error in set $a[1] command. Use this line format: YYYY-MM-DD HH:MM:SS|<device>|<type>|<event>|<reading>|<value>|[<unit>] ";
  572. }
  573. my ($yyyy, $mm, $dd, $hh, $min, $sec) = ($i_timestamp =~ /(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)/);
  574. eval { my $ts = timelocal($sec, $min, $hh, $dd, $mm-1, $yyyy-1900); };
  575. if ($@) {
  576. my @l = split (/at/, $@);
  577. return " Timestamp is out of range - $l[0]";
  578. }
  579. DbLog_addCacheLine($hash,$i_timestamp,$i_dev,$i_type,$i_evt,$i_reading,$i_val,$i_unit);
  580. }
  581. elsif ($a[1] eq 'configCheck') {
  582. my $check = DbLog_configcheck($hash);
  583. return $check;
  584. }
  585. elsif ($a[1] eq 'exportCache') {
  586. my $cln;
  587. my $crows = 0;
  588. my ($out,$outfile,$error);
  589. my $now = strftime('%Y-%m-%d_%H-%M-%S',localtime);
  590. # return wenn "reopen" mit Ablaufzeit gestartet ist oder disabled, nicht im asynch-Mode
  591. return if(IsDisabled($name) || $hash->{HELPER}{REOPEN_RUNS});
  592. return if(!AttrVal($name, "asyncMode", undef));
  593. if(@logs && AttrVal($name, "exportCacheAppend", 0)) {
  594. # exportiertes Cachefile existiert und es soll an das neueste angehängt werden
  595. $outfile = $dir.pop(@logs);
  596. $out = ">>$outfile";
  597. } else {
  598. $outfile = $dir."cache_".$name."_".$now;
  599. $out = ">$outfile";
  600. }
  601. if(open(FH, $out)) {
  602. binmode (FH);
  603. } else {
  604. readingsSingleUpdate($hash, "lastCachefile", $outfile." - Error - ".$!, 1);
  605. $error = "could not open ".$outfile.": ".$!;
  606. }
  607. if(!$error) {
  608. foreach my $key (sort(keys%{$hash->{cache}{".memcache"}})) {
  609. $cln = $hash->{cache}{".memcache"}{$key}."\n";
  610. print FH $cln ;
  611. $crows++;
  612. }
  613. close(FH);
  614. readingsSingleUpdate($hash, "lastCachefile", $outfile." (".$crows." cache rows exported)", 1);
  615. }
  616. # readingsSingleUpdate($hash, "state", $crows." cache rows exported to ".$outfile, 1);
  617. my $state = $error?$error:(IsDisabled($name))?"disabled":"connected";
  618. my $evt = ($state eq $hash->{HELPER}{OLDSTATE})?0:1;
  619. readingsSingleUpdate($hash, "state", $state, $evt);
  620. $hash->{HELPER}{OLDSTATE} = $state;
  621. Log3($name, 3, "DbLog $name: $crows cache rows exported to $outfile.");
  622. if (lc($a[-1]) =~ m/^purgecache/i) {
  623. delete $hash->{cache};
  624. readingsSingleUpdate($hash, 'CacheUsage', 0, 1);
  625. Log3($name, 3, "DbLog $name: Cache purged after exporting rows to $outfile.");
  626. }
  627. return;
  628. }
  629. elsif ($a[1] eq 'importCachefile') {
  630. my $cln;
  631. my $crows = 0;
  632. my $infile;
  633. my @row_array;
  634. readingsSingleUpdate($hash, "lastCachefile", "", 0);
  635. # return wenn "reopen" mit Ablaufzeit gestartet ist oder disabled
  636. return if(IsDisabled($name) || $hash->{HELPER}{REOPEN_RUNS});
  637. if (!$a[2]) {
  638. return "Wrong function-call. Use set <name> importCachefile <file> without directory (see attr expimpdir)." ;
  639. } else {
  640. $infile = $dir.$a[2];
  641. }
  642. if (open(FH, "$infile")) {
  643. binmode (FH);
  644. } else {
  645. return "could not open ".$infile.": ".$!;
  646. }
  647. while (<FH>) {
  648. my $row = $_;
  649. $row = DbLog_charfilter($row) if(AttrVal($name, "useCharfilter",0));
  650. push(@row_array, $row);
  651. $crows++;
  652. }
  653. close(FH);
  654. if(@row_array) {
  655. my $error = DbLog_Push($hash, 1, @row_array);
  656. if($error) {
  657. readingsSingleUpdate($hash, "lastCachefile", $infile." - Error - ".$!, 1);
  658. readingsSingleUpdate($hash, "state", $error, 1);
  659. Log3 $name, 5, "DbLog $name -> DbLog_Push Returncode: $error";
  660. } else {
  661. unless(rename($dir.$a[2], $dir."impdone_".$a[2])) {
  662. Log3($name, 2, "DbLog $name: cachefile $infile couldn't be renamed after import !");
  663. }
  664. readingsSingleUpdate($hash, "lastCachefile", $infile." import successful", 1);
  665. readingsSingleUpdate($hash, "state", $crows." cache rows processed from ".$infile, 1);
  666. Log3($name, 3, "DbLog $name: $crows cache rows processed from $infile.");
  667. }
  668. } else {
  669. readingsSingleUpdate($hash, "state", "no rows in ".$infile, 1);
  670. Log3($name, 3, "DbLog $name: $infile doesn't contain any rows - no imports done.");
  671. }
  672. return;
  673. }
  674. elsif ($a[1] eq 'count') {
  675. $dbh = DbLog_ConnectNewDBH($hash);
  676. if(!$dbh) {
  677. Log3($name, 1, "DbLog $name: DBLog_Set - count - DB connect not possible");
  678. return;
  679. } else {
  680. Log3($name, 4, "DbLog $name: Records count requested.");
  681. my $c = $dbh->selectrow_array('SELECT count(*) FROM history');
  682. readingsSingleUpdate($hash, 'countHistory', $c ,1);
  683. $c = $dbh->selectrow_array('SELECT count(*) FROM current');
  684. readingsSingleUpdate($hash, 'countCurrent', $c ,1);
  685. $dbh->disconnect();
  686. InternalTimer(gettimeofday()+5, "DbLog_execmemcache", $hash, 0);
  687. }
  688. }
  689. elsif ($a[1] eq 'countNbl') {
  690. if ($hash->{HELPER}{COUNT_PID} && $hash->{HELPER}{COUNT_PID}{pid} !~ m/DEAD/){
  691. $ret = "DbLog count already in progress. Please wait for the current process to finish.";
  692. } else {
  693. delete $hash->{HELPER}{COUNT_PID};
  694. $hash->{HELPER}{COUNT_PID} = BlockingCall("DbLog_countNbl","$name","DbLog_countNbl_finished");
  695. return;
  696. }
  697. }
  698. elsif ($a[1] eq 'deleteOldDays') {
  699. Log3 ($name, 3, "DbLog $name -> Deletion of records older than $a[2] days in database $db requested");
  700. my ($c, $cmd);
  701. $dbh = DbLog_ConnectNewDBH($hash);
  702. if(!$dbh) {
  703. Log3($name, 1, "DbLog $name: DBLog_Set - deleteOldDays - DB connect not possible");
  704. return;
  705. } else {
  706. $cmd = "delete from history where TIMESTAMP < ";
  707. if ($hash->{MODEL} eq 'SQLITE') { $cmd .= "datetime('now', '-$a[2] days')"; }
  708. elsif ($hash->{MODEL} eq 'MYSQL') { $cmd .= "DATE_SUB(CURDATE(),INTERVAL $a[2] DAY)"; }
  709. elsif ($hash->{MODEL} eq 'POSTGRESQL') { $cmd .= "NOW() - INTERVAL '$a[2]' DAY"; }
  710. else { $cmd = undef; $ret = 'Unknown database type. Maybe you can try userCommand anyway.'; }
  711. if(defined($cmd)) {
  712. $c = $dbh->do($cmd);
  713. $c = 0 if($c == 0E0);
  714. eval {$dbh->commit() if(!$dbh->{AutoCommit});};
  715. $dbh->disconnect();
  716. Log3 ($name, 3, "DbLog $name -> deleteOldDays finished. $c entries of database $db deleted.");
  717. readingsSingleUpdate($hash, 'lastRowsDeleted', $c ,1);
  718. }
  719. InternalTimer(gettimeofday()+5, "DbLog_execmemcache", $hash, 0);
  720. }
  721. }
  722. elsif ($a[1] eq 'deleteOldDaysNbl') {
  723. if (defined $a[2] && $a[2] =~ /^\d+$/) {
  724. if ($hash->{HELPER}{DELDAYS_PID} && $hash->{HELPER}{DELDAYS_PID}{pid} !~ m/DEAD/) {
  725. $ret = "deleteOldDaysNbl already in progress. Please wait for the current process to finish.";
  726. } else {
  727. delete $hash->{HELPER}{DELDAYS_PID};
  728. $hash->{HELPER}{DELDAYS} = $a[2];
  729. Log3 ($name, 3, "DbLog $name -> Deletion of records older than $a[2] days in database $db requested");
  730. $hash->{HELPER}{DELDAYS_PID} = BlockingCall("DbLog_deldaysNbl","$name","DbLog_deldaysNbl_done");
  731. return;
  732. }
  733. } else {
  734. Log3($name, 1, "DbLog $name: deleteOldDaysNbl error, no <days> given.");
  735. $ret = "deleteOldDaysNbl error, no <days> given.";
  736. }
  737. }
  738. elsif ($a[1] eq 'userCommand') {
  739. $dbh = DbLog_ConnectNewDBH($hash);
  740. if(!$dbh) {
  741. Log3($name, 1, "DbLog $name: DBLog_Set - userCommand - DB connect not possible");
  742. return;
  743. } else {
  744. Log3($name, 4, "DbLog $name: userCommand execution requested.");
  745. my ($c, @cmd, $sql);
  746. @cmd = @a;
  747. shift(@cmd); shift(@cmd);
  748. $sql = join(" ",@cmd);
  749. readingsSingleUpdate($hash, 'userCommand', $sql, 1);
  750. $dbh->{RaiseError} = 1;
  751. $dbh->{PrintError} = 0;
  752. my $error;
  753. eval { $c = $dbh->selectrow_array($sql); };
  754. if($@) {
  755. $error = $@;
  756. Log3($name, 1, "DbLog $name: DBLog_Set - $error");
  757. }
  758. my $res = $error?$error:(defined($c))?$c:"no result";
  759. Log3($name, 4, "DbLog $name: DBLog_Set - userCommand - result: $res");
  760. readingsSingleUpdate($hash, 'userCommandResult', $res ,1);
  761. $dbh->disconnect();
  762. InternalTimer(gettimeofday()+5, "DbLog_execmemcache", $hash, 0);
  763. }
  764. }
  765. else { $ret = $usage; }
  766. return $ret;
  767. }
  768. ###############################################################################################
  769. #
  770. # Exrahieren des Filters aus der ColumnsSpec (gplot-Datei)
  771. #
  772. # Die grundlegend idee ist das jeder svg plot einen filter hat der angibt
  773. # welches device und reading dargestellt wird so das der plot sich neu
  774. # lädt wenn es ein entsprechendes event gibt.
  775. #
  776. # Parameter: Quell-Instanz-Name, und alle FileLog-Parameter, die diese Instanz betreffen.
  777. # Quelle: http://forum.fhem.de/index.php/topic,40176.msg325200.html#msg325200
  778. ###############################################################################################
  779. sub DbLog_regexpFn($$) {
  780. my ($name, $filter) = @_;
  781. my $ret;
  782. my @a = split( ' ', $filter );
  783. for(my $i = 0; $i < int(@a); $i++) {
  784. my @fld = split(":", $a[$i]);
  785. $ret .= '|' if( $ret );
  786. no warnings 'uninitialized'; # Forum:74690, bug unitialized
  787. $ret .= $fld[0] .'.'. $fld[1];
  788. use warnings;
  789. }
  790. return $ret;
  791. }
  792. ################################################################
  793. #
  794. # Parsefunktion, abhaengig vom Devicetyp
  795. #
  796. ################################################################
  797. sub DbLog_ParseEvent($$$)
  798. {
  799. my ($device, $type, $event)= @_;
  800. my @result;
  801. my $reading;
  802. my $value;
  803. my $unit;
  804. # Splitfunktion der Eventquelle aufrufen (ab 2.9.1)
  805. ($reading, $value, $unit) = CallInstanceFn($device, "DbLog_splitFn", $event, $device);
  806. # undef bedeutet, Modul stellt keine DbLog_splitFn bereit
  807. if($reading) {
  808. return ($reading, $value, $unit);
  809. }
  810. # split the event into reading, value and unit
  811. # "day-temp: 22.0 (Celsius)" -> "day-temp", "22.0 (Celsius)"
  812. my @parts = split(/: /,$event);
  813. $reading = shift @parts;
  814. if(@parts == 2) {
  815. $value = $parts[0];
  816. $unit = $parts[1];
  817. } else {
  818. $value = join(": ", @parts);
  819. $unit = "";
  820. }
  821. #default
  822. if(!defined($reading)) { $reading = ""; }
  823. if(!defined($value)) { $value = ""; }
  824. if( $value eq "" ) {
  825. $reading= "state";
  826. $value= $event;
  827. }
  828. #globales Abfangen von
  829. # - temperature
  830. # - humidity
  831. if ($reading =~ m(^temperature)) { $unit= "°C"; } # wenn reading mit temperature beginnt
  832. elsif($reading =~ m(^humidity)) { $unit= "%"; }
  833. # the interpretation of the argument depends on the device type
  834. # EMEM, M232Counter, M232Voltage return plain numbers
  835. if(($type eq "M232Voltage") ||
  836. ($type eq "M232Counter") ||
  837. ($type eq "EMEM")) {
  838. }
  839. #OneWire
  840. elsif(($type eq "OWMULTI")) {
  841. if(int(@parts)>1) {
  842. $reading = "data";
  843. $value = $event;
  844. } else {
  845. @parts = split(/\|/, AttrVal($device, $reading."VUnit", ""));
  846. $unit = $parts[1] if($parts[1]);
  847. if(lc($reading) =~ m/temp/) {
  848. $value=~ s/ \(Celsius\)//;
  849. $value=~ s/([-\.\d]+).*/$1/;
  850. $unit= "°C";
  851. }
  852. elsif(lc($reading) =~ m/(humidity|vwc)/) {
  853. $value=~ s/ \(\%\)//;
  854. $unit= "%";
  855. }
  856. }
  857. }
  858. # Onewire
  859. elsif(($type eq "OWAD") ||
  860. ($type eq "OWSWITCH")) {
  861. if(int(@parts)>1) {
  862. $reading = "data";
  863. $value = $event;
  864. } else {
  865. @parts = split(/\|/, AttrVal($device, $reading."Unit", ""));
  866. $unit = $parts[1] if($parts[1]);
  867. }
  868. }
  869. # ZWAVE
  870. elsif ($type eq "ZWAVE") {
  871. if ( $value=~/([-\.\d]+)\s([a-z].*)/i ) {
  872. $value = $1;
  873. $unit = $2;
  874. }
  875. }
  876. # FBDECT
  877. elsif ($type eq "FBDECT") {
  878. if ( $value=~/([\.\d]+)\s([a-z].*)/i ) {
  879. $value = $1;
  880. $unit = $2;
  881. }
  882. }
  883. # MAX
  884. elsif(($type eq "MAX")) {
  885. $unit= "°C" if(lc($reading) =~ m/temp/);
  886. $unit= "%" if(lc($reading) eq "valveposition");
  887. }
  888. # FS20
  889. elsif(($type eq "FS20") || ($type eq "X10")) {
  890. if($reading =~ m/^dim(\d+).*/o) {
  891. $value = $1;
  892. $reading= "dim";
  893. $unit= "%";
  894. }
  895. elsif(!defined($value) || $value eq "") {
  896. $value= $reading;
  897. $reading= "data";
  898. }
  899. }
  900. # FHT
  901. elsif($type eq "FHT") {
  902. if($reading =~ m(-from[12]\ ) || $reading =~ m(-to[12]\ )) {
  903. @parts= split(/ /,$event);
  904. $reading= $parts[0];
  905. $value= $parts[1];
  906. $unit= "";
  907. }
  908. elsif($reading =~ m(-temp)) { $value=~ s/ \(Celsius\)//; $unit= "°C"; }
  909. elsif($reading =~ m(temp-offset)) { $value=~ s/ \(Celsius\)//; $unit= "°C"; }
  910. elsif($reading =~ m(^actuator[0-9]*)) {
  911. if($value eq "lime-protection") {
  912. $reading= "actuator-lime-protection";
  913. undef $value;
  914. }
  915. elsif($value =~ m(^offset:)) {
  916. $reading= "actuator-offset";
  917. @parts= split(/: /,$value);
  918. $value= $parts[1];
  919. if(defined $value) {
  920. $value=~ s/%//; $value= $value*1.; $unit= "%";
  921. }
  922. }
  923. elsif($value =~ m(^unknown_)) {
  924. @parts= split(/: /,$value);
  925. $reading= "actuator-" . $parts[0];
  926. $value= $parts[1];
  927. if(defined $value) {
  928. $value=~ s/%//; $value= $value*1.; $unit= "%";
  929. }
  930. }
  931. elsif($value =~ m(^synctime)) {
  932. $reading= "actuator-synctime";
  933. undef $value;
  934. }
  935. elsif($value eq "test") {
  936. $reading= "actuator-test";
  937. undef $value;
  938. }
  939. elsif($value eq "pair") {
  940. $reading= "actuator-pair";
  941. undef $value;
  942. }
  943. else {
  944. $value=~ s/%//; $value= $value*1.; $unit= "%";
  945. }
  946. }
  947. }
  948. # KS300
  949. elsif($type eq "KS300") {
  950. if($event =~ m(T:.*)) { $reading= "data"; $value= $event; }
  951. elsif($event =~ m(avg_day)) { $reading= "data"; $value= $event; }
  952. elsif($event =~ m(avg_month)) { $reading= "data"; $value= $event; }
  953. elsif($reading eq "temperature") { $value=~ s/ \(Celsius\)//; $unit= "°C"; }
  954. elsif($reading eq "wind") { $value=~ s/ \(km\/h\)//; $unit= "km/h"; }
  955. elsif($reading eq "rain") { $value=~ s/ \(l\/m2\)//; $unit= "l/m2"; }
  956. elsif($reading eq "rain_raw") { $value=~ s/ \(counter\)//; $unit= ""; }
  957. elsif($reading eq "humidity") { $value=~ s/ \(\%\)//; $unit= "%"; }
  958. elsif($reading eq "israining") {
  959. $value=~ s/ \(yes\/no\)//;
  960. $value=~ s/no/0/;
  961. $value=~ s/yes/1/;
  962. }
  963. }
  964. # HMS
  965. elsif($type eq "HMS" ||
  966. $type eq "CUL_WS" ||
  967. $type eq "OWTHERM") {
  968. if($event =~ m(T:.*)) { $reading= "data"; $value= $event; }
  969. elsif($reading eq "temperature") {
  970. $value=~ s/ \(Celsius\)//;
  971. $value=~ s/([-\.\d]+).*/$1/; #OWTHERM
  972. $unit= "°C";
  973. }
  974. elsif($reading eq "humidity") { $value=~ s/ \(\%\)//; $unit= "%"; }
  975. elsif($reading eq "battery") {
  976. $value=~ s/ok/1/;
  977. $value=~ s/replaced/1/;
  978. $value=~ s/empty/0/;
  979. }
  980. }
  981. # CUL_HM
  982. elsif ($type eq "CUL_HM") {
  983. # remove trailing %
  984. $value=~ s/ \%$//;
  985. }
  986. # BS
  987. elsif($type eq "BS") {
  988. if($event =~ m(brightness:.*)) {
  989. @parts= split(/ /,$event);
  990. $reading= "lux";
  991. $value= $parts[4]*1.;
  992. $unit= "lux";
  993. }
  994. }
  995. # RFXTRX Lighting
  996. elsif($type eq "TRX_LIGHT") {
  997. if($reading =~ m/^level (\d+)/) {
  998. $value = $1;
  999. $reading= "level";
  1000. }
  1001. }
  1002. # RFXTRX Sensors
  1003. elsif($type eq "TRX_WEATHER") {
  1004. if($reading eq "energy_current") { $value=~ s/ W//; }
  1005. elsif($reading eq "energy_total") { $value=~ s/ kWh//; }
  1006. # elsif($reading eq "temperature") {TODO}
  1007. # elsif($reading eq "temperature") {TODO
  1008. elsif($reading eq "battery") {
  1009. if ($value=~ m/(\d+)\%/) {
  1010. $value= $1;
  1011. }
  1012. else {
  1013. $value= ($value eq "ok");
  1014. }
  1015. }
  1016. }
  1017. # Weather
  1018. elsif($type eq "WEATHER") {
  1019. if($event =~ m(^wind_condition)) {
  1020. @parts= split(/ /,$event); # extract wind direction from event
  1021. if(defined $parts[0]) {
  1022. $reading = "wind_direction";
  1023. $value= $parts[2];
  1024. }
  1025. }
  1026. elsif($reading eq "wind_chill") { $unit= "°C"; }
  1027. elsif($reading eq "wind_direction") { $unit= ""; }
  1028. elsif($reading =~ m(^wind)) { $unit= "km/h"; } # wind, wind_speed
  1029. elsif($reading =~ m(^temperature)) { $unit= "°C"; } # wenn reading mit temperature beginnt
  1030. elsif($reading =~ m(^humidity)) { $unit= "%"; }
  1031. elsif($reading =~ m(^pressure)) { $unit= "hPa"; }
  1032. elsif($reading =~ m(^pressure_trend)) { $unit= ""; }
  1033. }
  1034. # FHT8V
  1035. elsif($type eq "FHT8V") {
  1036. if($reading =~ m(valve)) {
  1037. @parts= split(/ /,$event);
  1038. $reading= $parts[0];
  1039. $value= $parts[1];
  1040. $unit= "%";
  1041. }
  1042. }
  1043. # Dummy
  1044. elsif($type eq "DUMMY") {
  1045. if( $value eq "" ) {
  1046. $reading= "data";
  1047. $value= $event;
  1048. }
  1049. $unit= "";
  1050. }
  1051. @result= ($reading,$value,$unit);
  1052. return @result;
  1053. }
  1054. ##################################################################################################################
  1055. #
  1056. # Hauptroutine zum Loggen. Wird bei jedem Eventchange
  1057. # aufgerufen
  1058. #
  1059. ##################################################################################################################
  1060. # Es werden nur die Events von Geräten verarbeitet die im Hash $hash->{NOTIFYDEV} gelistet sind (wenn definiert).
  1061. # Dadurch kann die Menge der Events verringert werden. In sub DbRep_Define angeben.
  1062. # Beispiele:
  1063. # $hash->{NOTIFYDEV} = "global";
  1064. # $hash->{NOTIFYDEV} = "global,Definition_A,Definition_B";
  1065. sub DbLog_Log($$) {
  1066. # $hash is my entry, $dev_hash is the entry of the changed device
  1067. my ($hash, $dev_hash) = @_;
  1068. my $name = $hash->{NAME};
  1069. my $dev_name = $dev_hash->{NAME};
  1070. my $dev_type = uc($dev_hash->{TYPE});
  1071. my $async = AttrVal($name, "asyncMode", undef);
  1072. my $clim = AttrVal($name, "cacheLimit", 500);
  1073. my $ce = AttrVal($name, "cacheEvents", 0);
  1074. my $net;
  1075. return if(IsDisabled($name) || !$hash->{HELPER}{COLSET} || $init_done != 1);
  1076. # Notify-Routine Startzeit
  1077. my $nst = [gettimeofday];
  1078. my $events = deviceEvents($dev_hash, AttrVal($name, "addStateEvent", 1));
  1079. return if(!$events);
  1080. my $max = int(@{$events});
  1081. my $lcdev = lc($dev_name);
  1082. # verbose4 Logs nur für Devices in Attr "verbose4Devs"
  1083. my $vb4show = 0;
  1084. my @vb4devs = split(",", AttrVal($name, "verbose4Devs", ""));
  1085. if (!@vb4devs) {
  1086. $vb4show = 1;
  1087. } else {
  1088. foreach (@vb4devs) {
  1089. if($dev_name =~ m/$_/i) {
  1090. $vb4show = 1;
  1091. last;
  1092. }
  1093. }
  1094. # Log3 $name, 5, "DbLog $name -> verbose 4 output of device $dev_name skipped due to attribute \"verbose4Devs\" restrictions" if(!$vb4show);
  1095. }
  1096. if($vb4show && !$hash->{HELPER}{".RUNNING_PID"}) {
  1097. Log3 $name, 4, "DbLog $name -> ################################################################";
  1098. Log3 $name, 4, "DbLog $name -> ### start of new Logcycle ###";
  1099. Log3 $name, 4, "DbLog $name -> ################################################################";
  1100. Log3 $name, 4, "DbLog $name -> number of events received: $max for device: $dev_name";
  1101. }
  1102. # Devices ausschließen durch Attribut "excludeDevs" (nur wenn kein $hash->{NOTIFYDEV})
  1103. if(!$hash->{NOTIFYDEV}) {
  1104. my $exc = AttrVal($name, "excludeDevs", "");
  1105. $exc =~ s/\s/,/g;
  1106. my @exdvs = devspec2array($exc);
  1107. if(@exdvs) {
  1108. # Log3 $name, 3, "DbLog $name -> excludeDevs: @exdvs";
  1109. foreach (@exdvs) {
  1110. if(lc($dev_name) eq lc($_)) {
  1111. Log3 $name, 4, "DbLog $name -> Device: $dev_name excluded from database logging due to attribute \"excludeDevs\" restrictions" if($vb4show);
  1112. return;
  1113. }
  1114. }
  1115. }
  1116. }
  1117. my $re = $hash->{REGEXP};
  1118. my @row_array;
  1119. my ($event,$reading,$value,$unit);
  1120. my $ts_0 = TimeNow(); # timestamp in SQL format YYYY-MM-DD hh:mm:ss
  1121. my $now = gettimeofday(); # get timestamp in seconds since epoch
  1122. my $DbLogExclude = AttrVal($dev_name, "DbLogExclude", undef);
  1123. my $DbLogInclude = AttrVal($dev_name, "DbLogInclude",undef);
  1124. my $DbLogSelectionMode = AttrVal($name, "DbLogSelectionMode","Exclude");
  1125. my $value_fn = AttrVal( $name, "valueFn", "" );
  1126. # Funktion aus Attr valueFn validieren
  1127. if( $value_fn =~ m/^\s*(\{.*\})\s*$/s ) {
  1128. $value_fn = $1;
  1129. } else {
  1130. $value_fn = '';
  1131. }
  1132. #one Transaction
  1133. eval {
  1134. for (my $i = 0; $i < $max; $i++) {
  1135. my $event = $events->[$i];
  1136. $event = "" if(!defined($event));
  1137. $event = DbLog_charfilter($event) if(AttrVal($name, "useCharfilter",0));
  1138. Log3 $name, 4, "DbLog $name -> check Device: $dev_name , Event: $event" if($vb4show && !$hash->{HELPER}{".RUNNING_PID"});
  1139. if($dev_name =~ m/^$re$/ || "$dev_name:$event" =~ m/^$re$/ || $DbLogSelectionMode eq 'Include') {
  1140. my $timestamp = $ts_0;
  1141. $timestamp = $dev_hash->{CHANGETIME}[$i] if(defined($dev_hash->{CHANGETIME}[$i]));
  1142. $event =~ s/\|/_ESC_/g; # escape Pipe "|"
  1143. my @r = DbLog_ParseEvent($dev_name, $dev_type, $event);
  1144. $reading = $r[0];
  1145. $value = $r[1];
  1146. $unit = $r[2];
  1147. if(!defined $reading) {$reading = "";}
  1148. if(!defined $value) {$value = "";}
  1149. if(!defined $unit || $unit eq "") {$unit = AttrVal("$dev_name", "unit", "");}
  1150. Log3 $name, 5, "DbLog $name -> parsed Event: $dev_name , Event: $event" if($vb4show && !$hash->{HELPER}{".RUNNING_PID"});
  1151. #Je nach DBLogSelectionMode muss das vorgegebene Ergebnis der Include-, bzw. Exclude-Pruefung
  1152. #entsprechend unterschiedlich vorbelegt sein.
  1153. #keine Readings loggen die in DbLogExclude explizit ausgeschlossen sind
  1154. my $DoIt = 0;
  1155. $DoIt = 1 if($DbLogSelectionMode =~ m/Exclude/ );
  1156. if($DbLogExclude && $DbLogSelectionMode =~ m/Exclude/) {
  1157. # Bsp: "(temperature|humidity):300 battery:3600"
  1158. my @v1 = split(/,/, $DbLogExclude);
  1159. for (my $i=0; $i<int(@v1); $i++) {
  1160. my @v2 = split(/:/, $v1[$i]);
  1161. $DoIt = 0 if(!$v2[1] && $reading =~ m/^$v2[0]$/); #Reading matcht auf Regexp, kein MinIntervall angegeben
  1162. if(($v2[1] && $reading =~ m/^$v2[0]$/) && ($v2[1] =~ m/^(\d+)$/)) {
  1163. #Regexp matcht und MinIntervall ist angegeben
  1164. my $lt = $defs{$dev_hash->{NAME}}{Helper}{DBLOG}{$reading}{$hash->{NAME}}{TIME};
  1165. my $lv = $defs{$dev_hash->{NAME}}{Helper}{DBLOG}{$reading}{$hash->{NAME}}{VALUE};
  1166. $lt = 0 if(!$lt);
  1167. $lv = "" if(!$lv);
  1168. if(($now-$lt < $v2[1]) && ($lv eq $value)) {
  1169. # innerhalb MinIntervall und LastValue=Value
  1170. $DoIt = 0;
  1171. }
  1172. }
  1173. }
  1174. }
  1175. #Hier ggf. zusätzlich noch dbLogInclude pruefen, falls bereits durch DbLogExclude ausgeschlossen
  1176. #Im Endeffekt genau die gleiche Pruefung, wie fuer DBLogExclude, lediglich mit umgegkehrtem Ergebnis.
  1177. if($DoIt == 0) {
  1178. if($DbLogInclude && ($DbLogSelectionMode =~ m/Include/)) {
  1179. my @v1 = split(/,/, $DbLogInclude);
  1180. for (my $i=0; $i<int(@v1); $i++) {
  1181. my @v2 = split(/:/, $v1[$i]);
  1182. $DoIt = 1 if($reading =~ m/^$v2[0]$/); #Reading matcht auf Regexp
  1183. if(($v2[1] && $reading =~ m/^$v2[0]$/) && ($v2[1] =~ m/^(\d+)$/)) {
  1184. #Regexp matcht und MinIntervall ist angegeben
  1185. my $lt = $defs{$dev_hash->{NAME}}{Helper}{DBLOG}{$reading}{$hash->{NAME}}{TIME};
  1186. my $lv = $defs{$dev_hash->{NAME}}{Helper}{DBLOG}{$reading}{$hash->{NAME}}{VALUE};
  1187. $lt = 0 if(!$lt);
  1188. $lv = "" if(!$lv);
  1189. if(($now-$lt < $v2[1]) && ($lv eq $value)) {
  1190. # innerhalb MinIntervall und LastValue=Value
  1191. $DoIt = 0;
  1192. }
  1193. }
  1194. }
  1195. }
  1196. }
  1197. next if($DoIt == 0);
  1198. if ($DoIt) {
  1199. $defs{$dev_name}{Helper}{DBLOG}{$reading}{$hash->{NAME}}{TIME} = $now;
  1200. $defs{$dev_name}{Helper}{DBLOG}{$reading}{$hash->{NAME}}{VALUE} = $value;
  1201. # Anwender kann Feldwerte mit Funktion aus Attr valueFn verändern oder Datensatz-Log überspringen
  1202. if($value_fn ne '') {
  1203. my $TIMESTAMP = $timestamp;
  1204. my $DEVICE = $dev_name;
  1205. my $DEVICETYPE = $dev_type;
  1206. my $EVENT = $event;
  1207. my $READING = $reading;
  1208. my $VALUE = $value;
  1209. my $UNIT = $unit;
  1210. my $IGNORE = 0;
  1211. eval $value_fn;
  1212. Log3 $name, 2, "DbLog $name -> error valueFn: ".$@ if($@);
  1213. if($IGNORE) {
  1214. # aktueller Event wird nicht geloggt wenn $IGNORE=1 gesetzt in $value_fn
  1215. Log3 $hash->{NAME}, 4, "DbLog $name -> Event ignored by valueFn - TS: $timestamp, Device: $dev_name, Type: $dev_type, Event: $event, Reading: $reading, Value: $value, Unit: $unit"
  1216. if($vb4show && !$hash->{HELPER}{".RUNNING_PID"});
  1217. next;
  1218. }
  1219. $timestamp = $TIMESTAMP if($TIMESTAMP =~ /(19[0-9][0-9]|2[0-9][0-9][0-9])-(0[1-9]|1[1-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1]) (0[0-9]|1[1-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])/);
  1220. $dev_name = $DEVICE if($DEVICE ne '');
  1221. $dev_type = $DEVICETYPE if($DEVICETYPE ne '');
  1222. $reading = $READING if($READING ne '');
  1223. $value = $VALUE if(defined $VALUE);
  1224. $unit = $UNIT if(defined $UNIT);
  1225. }
  1226. # Daten auf maximale Länge beschneiden
  1227. ($dev_name,$dev_type,$event,$reading,$value,$unit) = DbLog_cutCol($hash,$dev_name,$dev_type,$event,$reading,$value,$unit);
  1228. my $row = ($timestamp."|".$dev_name."|".$dev_type."|".$event."|".$reading."|".$value."|".$unit);
  1229. Log3 $hash->{NAME}, 4, "DbLog $name -> added event - Timestamp: $timestamp, Device: $dev_name, Type: $dev_type, Event: $event, Reading: $reading, Value: $value, Unit: $unit"
  1230. if($vb4show && !$hash->{HELPER}{".RUNNING_PID"});
  1231. if($async) {
  1232. # asynchoner non-blocking Mode
  1233. # Cache & CacheIndex für Events zum asynchronen Schreiben in DB
  1234. $hash->{cache}{index}++;
  1235. my $index = $hash->{cache}{index};
  1236. $hash->{cache}{".memcache"}{$index} = $row;
  1237. my $memcount = $hash->{cache}{".memcache"}?scalar(keys%{$hash->{cache}{".memcache"}}):0;
  1238. if($ce == 1) {
  1239. readingsSingleUpdate($hash, "CacheUsage", $memcount, 1);
  1240. } else {
  1241. readingsSingleUpdate($hash, 'CacheUsage', $memcount, 0);
  1242. }
  1243. # asynchrone Schreibroutine aufrufen wenn Füllstand des Cache erreicht ist
  1244. if($memcount >= $clim) {
  1245. my $lmlr = $hash->{HELPER}{LASTLIMITRUNTIME};
  1246. my $syncival = AttrVal($name, "syncInterval", 30);
  1247. if(!$lmlr || gettimeofday() > $lmlr+($syncival/2)) {
  1248. Log3 $hash->{NAME}, 4, "DbLog $name -> Number of cache entries reached cachelimit $clim - start database sync.";
  1249. DbLog_execmemcache($hash);
  1250. $hash->{HELPER}{LASTLIMITRUNTIME} = gettimeofday();
  1251. }
  1252. }
  1253. # Notify-Routine Laufzeit ermitteln
  1254. $net = tv_interval($nst);
  1255. } else {
  1256. # synchoner Mode
  1257. push(@row_array, $row);
  1258. }
  1259. }
  1260. }
  1261. }
  1262. };
  1263. if(!$async) {
  1264. if(@row_array) {
  1265. # synchoner Mode
  1266. # return wenn "reopen" mit Ablaufzeit gestartet ist
  1267. return if($hash->{HELPER}{REOPEN_RUNS});
  1268. my $error = DbLog_Push($hash, $vb4show, @row_array);
  1269. Log3 $name, 5, "DbLog $name -> DbLog_Push Returncode: $error" if($vb4show);
  1270. my $state = $error?$error:(IsDisabled($name))?"disabled":"connected";
  1271. my $evt = ($state eq $hash->{HELPER}{OLDSTATE})?0:1;
  1272. readingsSingleUpdate($hash, "state", $state, $evt);
  1273. $hash->{HELPER}{OLDSTATE} = $state;
  1274. # Notify-Routine Laufzeit ermitteln
  1275. $net = tv_interval($nst);
  1276. }
  1277. }
  1278. if($net && AttrVal($name, "showNotifyTime", undef)) {
  1279. readingsSingleUpdate($hash, "notify_processing_time", sprintf("%.4f",$net), 1);
  1280. }
  1281. return;
  1282. }
  1283. #################################################################################################
  1284. #
  1285. # Schreibroutine Einfügen Werte in DB im Synchronmode
  1286. #
  1287. #################################################################################################
  1288. sub DbLog_Push(@) {
  1289. my ($hash, $vb4show, @row_array) = @_;
  1290. my $name = $hash->{NAME};
  1291. my $DbLogType = AttrVal($name, "DbLogType", "History");
  1292. my $supk = AttrVal($name, "noSupportPK", 0);
  1293. my $errorh = 0;
  1294. my $error = 0;
  1295. my $doins = 0; # Hilfsvariable, wenn "1" sollen inserts in Tabele current erfolgen (updates schlugen fehl)
  1296. my $dbh;
  1297. my $nh = ($hash->{MODEL} ne 'SQLITE')?1:0;
  1298. # Unterscheidung $dbh um Abbrüche in Plots (SQLite) zu vermeiden und
  1299. # andererseite kein "MySQL-Server has gone away" Fehler
  1300. if ($nh) {
  1301. $dbh = DbLog_ConnectNewDBH($hash);
  1302. return if(!$dbh);
  1303. } else {
  1304. $dbh = $hash->{DBHP};
  1305. eval {
  1306. if ( !$dbh || not $dbh->ping ) {
  1307. # DB Session dead, try to reopen now !
  1308. DbLog_ConnectPush($hash,1);
  1309. }
  1310. };
  1311. if ($@) {
  1312. Log3($name, 1, "DbLog $name: DBLog_Push - DB Session dead! - $@");
  1313. return $@;
  1314. } else {
  1315. $dbh = $hash->{DBHP};
  1316. }
  1317. }
  1318. $dbh->{RaiseError} = 1;
  1319. $dbh->{PrintError} = 0;
  1320. my ($useac,$useta) = DbLog_commitMode($hash);
  1321. my $ac = ($dbh->{AutoCommit})?"ON":"OFF";
  1322. my $tm = ($useta)?"ON":"OFF";
  1323. Log3 $name, 4, "DbLog $name -> ################################################################";
  1324. Log3 $name, 4, "DbLog $name -> ### New database processing cycle - synchronous ###";
  1325. Log3 $name, 4, "DbLog $name -> ################################################################";
  1326. Log3 $name, 4, "DbLog $name -> DbLogType is: $DbLogType";
  1327. Log3 $name, 4, "DbLog $name -> AutoCommit mode: $ac, Transaction mode: $tm";
  1328. # check ob PK verwendet wird, @usepkx?Anzahl der Felder im PK:0 wenn kein PK, $pkx?Namen der Felder:none wenn kein PK
  1329. my ($usepkh,$usepkc,$pkh,$pkc);
  1330. if (!$supk) {
  1331. ($usepkh,$usepkc,$pkh,$pkc) = DbLog_checkUsePK($hash,$dbh);
  1332. } else {
  1333. Log3 $hash->{NAME}, 5, "DbLog $name -> Primary Key usage suppressed by attribute noSupportPK";
  1334. }
  1335. my (@timestamp,@device,@type,@event,@reading,@value,@unit);
  1336. my (@timestamp_cur,@device_cur,@type_cur,@event_cur,@reading_cur,@value_cur,@unit_cur);
  1337. my ($sth_ih,$sth_ic,$sth_uc);
  1338. no warnings 'uninitialized';
  1339. my $ceti = $#row_array+1;
  1340. foreach my $row (@row_array) {
  1341. my @a = split("\\|",$row);
  1342. s/_ESC_/\|/g for @a; # escaped Pipe return to "|"
  1343. push(@timestamp, "$a[0]");
  1344. push(@device, "$a[1]");
  1345. push(@type, "$a[2]");
  1346. push(@event, "$a[3]");
  1347. push(@reading, "$a[4]");
  1348. push(@value, "$a[5]");
  1349. push(@unit, "$a[6]");
  1350. Log3 $hash->{NAME}, 4, "DbLog $name -> processing event Timestamp: $a[0], Device: $a[1], Type: $a[2], Event: $a[3], Reading: $a[4], Value: $a[5], Unit: $a[6]"
  1351. if($vb4show);
  1352. }
  1353. use warnings;
  1354. if (lc($DbLogType) =~ m(history)) {
  1355. # insert history mit/ohne primary key
  1356. if ($usepkh && $hash->{MODEL} eq 'MYSQL') {
  1357. eval { $sth_ih = $dbh->prepare("INSERT IGNORE INTO history (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?)"); };
  1358. } elsif ($usepkh && $hash->{MODEL} eq 'SQLITE') {
  1359. eval { $sth_ih = $dbh->prepare("INSERT OR IGNORE INTO history (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?)"); };
  1360. } elsif ($usepkh && $hash->{MODEL} eq 'POSTGRESQL') {
  1361. eval { $sth_ih = $dbh->prepare("INSERT INTO history (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?) ON CONFLICT DO NOTHING"); };
  1362. } else {
  1363. # old behavior
  1364. eval { $sth_ih = $dbh->prepare("INSERT INTO history (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?)"); };
  1365. }
  1366. if ($@) {
  1367. return $@;
  1368. }
  1369. $sth_ih->bind_param_array(1, [@timestamp]);
  1370. $sth_ih->bind_param_array(2, [@device]);
  1371. $sth_ih->bind_param_array(3, [@type]);
  1372. $sth_ih->bind_param_array(4, [@event]);
  1373. $sth_ih->bind_param_array(5, [@reading]);
  1374. $sth_ih->bind_param_array(6, [@value]);
  1375. $sth_ih->bind_param_array(7, [@unit]);
  1376. }
  1377. if (lc($DbLogType) =~ m(current) ) {
  1378. # insert current mit/ohne primary key, insert-values für current werden generiert
  1379. if ($usepkc && $hash->{MODEL} eq 'MYSQL') {
  1380. eval { $sth_ic = $dbh->prepare("INSERT IGNORE INTO current (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?)"); };
  1381. } elsif ($usepkc && $hash->{MODEL} eq 'SQLITE') {
  1382. eval { $sth_ic = $dbh->prepare("INSERT OR IGNORE INTO current (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?)"); };
  1383. } elsif ($usepkc && $hash->{MODEL} eq 'POSTGRESQL') {
  1384. eval { $sth_ic = $dbh->prepare("INSERT INTO current (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?) ON CONFLICT DO NOTHING"); };
  1385. } else {
  1386. # old behavior
  1387. eval { $sth_ic = $dbh->prepare("INSERT INTO current (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?)"); };
  1388. }
  1389. if ($@) {
  1390. return $@;
  1391. }
  1392. if ($usepkc && $hash->{MODEL} eq 'MYSQL') {
  1393. # update current (mit PK), insert-values für current wird generiert
  1394. $sth_uc = $dbh->prepare("REPLACE INTO current (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?)");
  1395. $sth_uc->bind_param_array(1, [@timestamp]);
  1396. $sth_uc->bind_param_array(2, [@device]);
  1397. $sth_uc->bind_param_array(3, [@type]);
  1398. $sth_uc->bind_param_array(4, [@event]);
  1399. $sth_uc->bind_param_array(5, [@reading]);
  1400. $sth_uc->bind_param_array(6, [@value]);
  1401. $sth_uc->bind_param_array(7, [@unit]);
  1402. } elsif ($usepkc && $hash->{MODEL} eq 'SQLITE') {
  1403. # update current (mit PK), insert-values für current wird generiert
  1404. $sth_uc = $dbh->prepare("INSERT OR REPLACE INTO current (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?)");
  1405. $sth_uc->bind_param_array(1, [@timestamp]);
  1406. $sth_uc->bind_param_array(2, [@device]);
  1407. $sth_uc->bind_param_array(3, [@type]);
  1408. $sth_uc->bind_param_array(4, [@event]);
  1409. $sth_uc->bind_param_array(5, [@reading]);
  1410. $sth_uc->bind_param_array(6, [@value]);
  1411. $sth_uc->bind_param_array(7, [@unit]);
  1412. } elsif ($usepkc && $hash->{MODEL} eq 'POSTGRESQL') {
  1413. # update current (mit PK), insert-values für current wird generiert
  1414. $sth_uc = $dbh->prepare("INSERT INTO current (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?) ON CONFLICT ($pkc)
  1415. DO UPDATE SET TIMESTAMP=EXCLUDED.TIMESTAMP, DEVICE=EXCLUDED.DEVICE, TYPE=EXCLUDED.TYPE, EVENT=EXCLUDED.EVENT, READING=EXCLUDED.READING,
  1416. VALUE=EXCLUDED.VALUE, UNIT=EXCLUDED.UNIT");
  1417. $sth_uc->bind_param_array(1, [@timestamp]);
  1418. $sth_uc->bind_param_array(2, [@device]);
  1419. $sth_uc->bind_param_array(3, [@type]);
  1420. $sth_uc->bind_param_array(4, [@event]);
  1421. $sth_uc->bind_param_array(5, [@reading]);
  1422. $sth_uc->bind_param_array(6, [@value]);
  1423. $sth_uc->bind_param_array(7, [@unit]);
  1424. } else {
  1425. # for update current (ohne PK), insert-values für current wird generiert
  1426. $sth_uc = $dbh->prepare("UPDATE current SET TIMESTAMP=?, TYPE=?, EVENT=?, VALUE=?, UNIT=? WHERE (DEVICE=?) AND (READING=?)");
  1427. $sth_uc->bind_param_array(1, [@timestamp]);
  1428. $sth_uc->bind_param_array(2, [@type]);
  1429. $sth_uc->bind_param_array(3, [@event]);
  1430. $sth_uc->bind_param_array(4, [@value]);
  1431. $sth_uc->bind_param_array(5, [@unit]);
  1432. $sth_uc->bind_param_array(6, [@device]);
  1433. $sth_uc->bind_param_array(7, [@reading]);
  1434. }
  1435. }
  1436. my ($tuples, $rows);
  1437. # insert into history-Tabelle
  1438. eval { $dbh->begin_work() if($useta && $dbh->{AutoCommit}); }; # Transaktion wenn gewünscht und autocommit ein
  1439. if ($@) {
  1440. Log3($name, 2, "DbLog $name -> Error start transaction for history - $@");
  1441. }
  1442. eval {
  1443. if (lc($DbLogType) =~ m(history) ) {
  1444. ($tuples, $rows) = $sth_ih->execute_array( { ArrayTupleStatus => \my @tuple_status } );
  1445. my $nins_hist = 0;
  1446. for my $tuple (0..$#row_array) {
  1447. my $status = $tuple_status[$tuple];
  1448. $status = 0 if($status eq "0E0");
  1449. next if($status); # $status ist "1" wenn insert ok
  1450. Log3 $hash->{NAME}, 3, "DbLog $name -> Insert into history rejected".($usepkh?" (possible PK violation) ":" ")."- TS: $timestamp[$tuple], Device: $device[$tuple], Event: $event[$tuple]";
  1451. $nins_hist++;
  1452. }
  1453. if(!$nins_hist) {
  1454. Log3 $hash->{NAME}, 4, "DbLog $name -> $ceti of $ceti events inserted into table history".($usepkh?" using PK on columns $pkh":"");
  1455. } else {
  1456. Log3 $hash->{NAME}, 4, "DbLog $name -> ".($ceti-$nins_hist)." of $ceti events inserted into table history".($usepkh?" using PK on columns $pkh":"");
  1457. }
  1458. eval {$dbh->commit() if(!$dbh->{AutoCommit});}; # issue Turning on AutoCommit failed
  1459. if ($@) {
  1460. Log3($name, 2, "DbLog $name -> Error commit history - $@");
  1461. } else {
  1462. if(!$dbh->{AutoCommit}) {
  1463. Log3($name, 4, "DbLog $name -> insert table history committed");
  1464. } else {
  1465. Log3($name, 4, "DbLog $name -> insert table history committed by autocommit");
  1466. }
  1467. }
  1468. }
  1469. };
  1470. if ($@) {
  1471. Log3 $hash->{NAME}, 2, "DbLog $name -> Error table history - $@";
  1472. $errorh = $@;
  1473. eval {$dbh->rollback() if(!$dbh->{AutoCommit});}; # issue Turning on AutoCommit failed
  1474. if ($@) {
  1475. Log3($name, 2, "DbLog $name -> Error rollback history - $@");
  1476. } else {
  1477. Log3($name, 4, "DbLog $name -> insert history rolled back");
  1478. }
  1479. }
  1480. # update or insert current
  1481. eval { $dbh->begin_work() if($useta && $dbh->{AutoCommit}); }; # Transaktion wenn gewünscht und autocommit ein
  1482. if ($@) {
  1483. Log3($name, 2, "DbLog $name -> Error start transaction for history - $@");
  1484. }
  1485. eval {
  1486. if (lc($DbLogType) =~ m(current) ) {
  1487. ($tuples, $rows) = $sth_uc->execute_array( { ArrayTupleStatus => \my @tuple_status } );
  1488. # Log3 $hash->{NAME}, 2, "DbLog $name -> Rows: $rows, Ceti: $ceti";
  1489. my $nupd_cur = 0;
  1490. for my $tuple (0..$#row_array) {
  1491. my $status = $tuple_status[$tuple];
  1492. $status = 0 if($status eq "0E0");
  1493. next if($status); # $status ist "1" wenn update ok
  1494. Log3 $hash->{NAME}, 4, "DbLog $name -> Failed to update in current, try to insert - TS: $timestamp[$tuple], Device: $device[$tuple], Reading: $reading[$tuple], Status = $status";
  1495. push(@timestamp_cur, "$timestamp[$tuple]");
  1496. push(@device_cur, "$device[$tuple]");
  1497. push(@type_cur, "$type[$tuple]");
  1498. push(@event_cur, "$event[$tuple]");
  1499. push(@reading_cur, "$reading[$tuple]");
  1500. push(@value_cur, "$value[$tuple]");
  1501. push(@unit_cur, "$unit[$tuple]");
  1502. $nupd_cur++;
  1503. }
  1504. if(!$nupd_cur) {
  1505. Log3 $hash->{NAME}, 4, "DbLog $name -> $ceti of $ceti events updated in table current".($usepkc?" using PK on columns $pkc":"");
  1506. } else {
  1507. Log3 $hash->{NAME}, 4, "DbLog $name -> $nupd_cur of $ceti events not updated and try to insert into table current".($usepkc?" using PK on columns $pkc":"");
  1508. $doins = 1;
  1509. }
  1510. if ($doins) {
  1511. # events die nicht in Tabelle current updated wurden, werden in current neu eingefügt
  1512. $sth_ic->bind_param_array(1, [@timestamp_cur]);
  1513. $sth_ic->bind_param_array(2, [@device_cur]);
  1514. $sth_ic->bind_param_array(3, [@type_cur]);
  1515. $sth_ic->bind_param_array(4, [@event_cur]);
  1516. $sth_ic->bind_param_array(5, [@reading_cur]);
  1517. $sth_ic->bind_param_array(6, [@value_cur]);
  1518. $sth_ic->bind_param_array(7, [@unit_cur]);
  1519. ($tuples, $rows) = $sth_ic->execute_array( { ArrayTupleStatus => \my @tuple_status } );
  1520. my $nins_cur = 0;
  1521. for my $tuple (0..$#device_cur) {
  1522. my $status = $tuple_status[$tuple];
  1523. $status = 0 if($status eq "0E0");
  1524. next if($status); # $status ist "1" wenn insert ok
  1525. Log3 $hash->{NAME}, 3, "DbLog $name -> Insert into current rejected - TS: $timestamp[$tuple], Device: $device_cur[$tuple], Reading: $reading_cur[$tuple], Status = $status";
  1526. $nins_cur++;
  1527. }
  1528. if(!$nins_cur) {
  1529. Log3 $hash->{NAME}, 4, "DbLog $name -> ".($#device_cur+1)." of ".($#device_cur+1)." events inserted into table current ".($usepkc?" using PK on columns $pkc":"");
  1530. } else {
  1531. Log3 $hash->{NAME}, 4, "DbLog $name -> ".($#device_cur+1-$nins_cur)." of ".($#device_cur+1)." events inserted into table current".($usepkc?" using PK on columns $pkc":"");
  1532. }
  1533. }
  1534. eval {$dbh->commit() if(!$dbh->{AutoCommit});}; # issue Turning on AutoCommit failed
  1535. if ($@) {
  1536. Log3($name, 2, "DbLog $name -> Error commit table current - $@");
  1537. } else {
  1538. if(!$dbh->{AutoCommit}) {
  1539. Log3($name, 4, "DbLog $name -> insert / update table current committed");
  1540. } else {
  1541. Log3($name, 4, "DbLog $name -> insert / update table current committed by autocommit");
  1542. }
  1543. }
  1544. }
  1545. };
  1546. if ($errorh) {
  1547. $error = $errorh;
  1548. }
  1549. $dbh->{RaiseError} = 0;
  1550. $dbh->{PrintError} = 1;
  1551. $dbh->disconnect if ($nh);
  1552. return Encode::encode_utf8($error);
  1553. }
  1554. #################################################################################################
  1555. #
  1556. # MemCache auswerten und Schreibroutine asynchron und non-blocking aufrufen
  1557. #
  1558. #################################################################################################
  1559. sub DbLog_execmemcache ($) {
  1560. my ($hash) = @_;
  1561. my $name = $hash->{NAME};
  1562. my $syncival = AttrVal($name, "syncInterval", 30);
  1563. my $clim = AttrVal($name, "cacheLimit", 500);
  1564. my $async = AttrVal($name, "asyncMode", undef);
  1565. my $ce = AttrVal($name, "cacheEvents", 0);
  1566. my $timeout = AttrVal($name, "timeout", 86400);
  1567. my $DbLogType = AttrVal($name, "DbLogType", "History");
  1568. my $dbconn = $hash->{dbconn};
  1569. my $dbuser = $hash->{dbuser};
  1570. my $dbpassword = $attr{"sec$name"}{secret};
  1571. my $dolog = 1;
  1572. my $error = 0;
  1573. my (@row_array,$memcount,$dbh);
  1574. RemoveInternalTimer($hash, "DbLog_execmemcache");
  1575. if($init_done != 1) {
  1576. InternalTimer(gettimeofday()+5, "DbLog_execmemcache", $hash, 0);
  1577. return;
  1578. }
  1579. # return wenn "reopen" mit Zeitangabe läuft, oder kein asynchroner Mode oder wenn disabled
  1580. if(!$async || IsDisabled($name) || $hash->{HELPER}{REOPEN_RUNS}) {
  1581. return;
  1582. }
  1583. # tote PID's löschen
  1584. if($hash->{HELPER}{".RUNNING_PID"} && $hash->{HELPER}{".RUNNING_PID"}{pid} =~ m/DEAD/) {
  1585. delete $hash->{HELPER}{".RUNNING_PID"};
  1586. }
  1587. if($hash->{HELPER}{REDUCELOG_PID} && $hash->{HELPER}{REDUCELOG_PID}{pid} =~ m/DEAD/) {
  1588. delete $hash->{HELPER}{REDUCELOG_PID};
  1589. }
  1590. if($hash->{HELPER}{DELDAYS_PID} && $hash->{HELPER}{DELDAYS_PID}{pid} =~ m/DEAD/) {
  1591. delete $hash->{HELPER}{DELDAYS_PID};
  1592. }
  1593. # bei SQLite Sperrverwaltung Logging wenn andere schreibende Zugriffe laufen
  1594. if($hash->{MODEL} eq "SQLITE") {
  1595. if($hash->{HELPER}{DELDAYS_PID}) {
  1596. $error = "deleteOldDaysNbl is running - resync at NextSync";
  1597. $dolog = 0;
  1598. }
  1599. if($hash->{HELPER}{REDUCELOG_PID}) {
  1600. $error = "reduceLogNbl is running - resync at NextSync";
  1601. $dolog = 0;
  1602. }
  1603. if($hash->{HELPER}{".RUNNING_PID"}) {
  1604. $error = "Commit already running - resync at NextSync";
  1605. $dolog = 0;
  1606. }
  1607. }
  1608. $memcount = $hash->{cache}{".memcache"}?scalar(keys%{$hash->{cache}{".memcache"}}):0;
  1609. if($ce == 2) {
  1610. readingsSingleUpdate($hash, "CacheUsage", $memcount, 1);
  1611. } else {
  1612. readingsSingleUpdate($hash, 'CacheUsage', $memcount, 0);
  1613. }
  1614. if($memcount && $dolog && !$hash->{HELPER}{".RUNNING_PID"}) {
  1615. Log3 $name, 4, "DbLog $name -> ################################################################";
  1616. Log3 $name, 4, "DbLog $name -> ### New database processing cycle - asynchronous ###";
  1617. Log3 $name, 4, "DbLog $name -> ################################################################";
  1618. Log3 $name, 4, "DbLog $name -> MemCache contains $memcount entries to process";
  1619. Log3 $name, 4, "DbLog $name -> DbLogType is: $DbLogType";
  1620. foreach my $key (sort(keys%{$hash->{cache}{".memcache"}})) {
  1621. Log3 $hash->{NAME}, 5, "DbLog $name -> MemCache contains: ".$hash->{cache}{".memcache"}{$key};
  1622. push(@row_array, delete($hash->{cache}{".memcache"}{$key}));
  1623. }
  1624. my $rowlist = join('§', @row_array);
  1625. $rowlist = encode_base64($rowlist,"");
  1626. $hash->{HELPER}{".RUNNING_PID"} = BlockingCall (
  1627. "DbLog_PushAsync",
  1628. "$name|$rowlist",
  1629. "DbLog_PushAsyncDone",
  1630. $timeout,
  1631. "DbLog_PushAsyncAborted",
  1632. $hash );
  1633. $hash->{HELPER}{".RUNNING_PID"}{loglevel} = 4;
  1634. Log3 $hash->{NAME}, 5, "DbLog $name -> DbLog_PushAsync called with timeout: $timeout";
  1635. } else {
  1636. if($dolog && $hash->{HELPER}{".RUNNING_PID"}) {
  1637. $error = "Commit already running - resync at NextSync";
  1638. }
  1639. }
  1640. # $memcount = scalar(keys%{$hash->{cache}{".memcache"}});
  1641. my $nextsync = gettimeofday()+$syncival;
  1642. my $nsdt = FmtDateTime($nextsync);
  1643. if(AttrVal($name, "syncEvents", undef)) {
  1644. readingsSingleUpdate($hash, "NextSync", $nsdt. " or if CacheUsage ".$clim." reached", 1);
  1645. } else {
  1646. readingsSingleUpdate($hash, "NextSync", $nsdt. " or if CacheUsage ".$clim." reached", 0);
  1647. }
  1648. my $state = $error?$error:$hash->{HELPER}{OLDSTATE};
  1649. my $evt = ($state eq $hash->{HELPER}{OLDSTATE})?0:1;
  1650. readingsSingleUpdate($hash, "state", $state, $evt);
  1651. $hash->{HELPER}{OLDSTATE} = $state;
  1652. InternalTimer($nextsync, "DbLog_execmemcache", $hash, 0);
  1653. return;
  1654. }
  1655. #################################################################################################
  1656. #
  1657. # Schreibroutine Einfügen Werte in DB asynchron non-blocking
  1658. #
  1659. #################################################################################################
  1660. sub DbLog_PushAsync(@) {
  1661. my ($string) = @_;
  1662. my ($name,$rowlist) = split("\\|", $string);
  1663. my $hash = $defs{$name};
  1664. my $dbconn = $hash->{dbconn};
  1665. my $dbuser = $hash->{dbuser};
  1666. my $dbpassword = $attr{"sec$name"}{secret};
  1667. my $DbLogType = AttrVal($name, "DbLogType", "History");
  1668. my $supk = AttrVal($name, "noSupportPK", 0);
  1669. my $utf8 = defined($hash->{UTF8})?$hash->{UTF8}:0;
  1670. my $errorh = 0;
  1671. my $error = 0;
  1672. my $doins = 0; # Hilfsvariable, wenn "1" sollen inserts in Tabelle current erfolgen (updates schlugen fehl)
  1673. my $dbh;
  1674. my $rowlback = 0; # Eventliste für Rückgabe wenn Fehler
  1675. Log3 ($name, 5, "DbLog $name -> Start DbLog_PushAsync");
  1676. Log3 ($name, 5, "DbLog $name -> DbLogType is: $DbLogType");
  1677. # Background-Startzeit
  1678. my $bst = [gettimeofday];
  1679. my ($useac,$useta) = DbLog_commitMode($hash);
  1680. if(!$useac) {
  1681. eval {$dbh = DBI->connect("dbi:$dbconn", $dbuser, $dbpassword, { PrintError => 0, RaiseError => 1, AutoCommit => 0, mysql_enable_utf8 => $utf8 });};
  1682. } elsif($useac == 1) {
  1683. eval {$dbh = DBI->connect("dbi:$dbconn", $dbuser, $dbpassword, { PrintError => 0, RaiseError => 1, AutoCommit => 1, mysql_enable_utf8 => $utf8 });};
  1684. } else {
  1685. # Server default
  1686. eval {$dbh = DBI->connect("dbi:$dbconn", $dbuser, $dbpassword, { PrintError => 0, RaiseError => 1, mysql_enable_utf8 => $utf8 });};
  1687. }
  1688. if ($@) {
  1689. $error = encode_base64($@,"");
  1690. Log3 ($name, 2, "DbLog $name - Error: $@");
  1691. Log3 ($name, 5, "DbLog $name -> DbLog_PushAsync finished");
  1692. return "$name|$error|0|$rowlist";
  1693. }
  1694. my $ac = ($dbh->{AutoCommit})?"ON":"OFF";
  1695. my $tm = ($useta)?"ON":"OFF";
  1696. Log3 $hash->{NAME}, 4, "DbLog $name -> AutoCommit mode: $ac, Transaction mode: $tm";
  1697. # check ob PK verwendet wird, @usepkx?Anzahl der Felder im PK:0 wenn kein PK, $pkx?Namen der Felder:none wenn kein PK
  1698. my ($usepkh,$usepkc,$pkh,$pkc);
  1699. if (!$supk) {
  1700. ($usepkh,$usepkc,$pkh,$pkc) = DbLog_checkUsePK($hash,$dbh);
  1701. } else {
  1702. Log3 $hash->{NAME}, 5, "DbLog $name -> Primary Key usage suppressed by attribute noSupportPK";
  1703. }
  1704. my $rowldec = decode_base64($rowlist);
  1705. my @row_array = split('§', $rowldec);
  1706. my (@timestamp,@device,@type,@event,@reading,@value,@unit);
  1707. my (@timestamp_cur,@device_cur,@type_cur,@event_cur,@reading_cur,@value_cur,@unit_cur);
  1708. my ($sth_ih,$sth_ic,$sth_uc);
  1709. no warnings 'uninitialized';
  1710. my $ceti = $#row_array+1;
  1711. foreach my $row (@row_array) {
  1712. my @a = split("\\|",$row);
  1713. s/_ESC_/\|/g for @a; # escaped Pipe return to "|"
  1714. push(@timestamp, "$a[0]");
  1715. push(@device, "$a[1]");
  1716. push(@type, "$a[2]");
  1717. push(@event, "$a[3]");
  1718. push(@reading, "$a[4]");
  1719. push(@value, "$a[5]");
  1720. push(@unit, "$a[6]");
  1721. Log3 $hash->{NAME}, 5, "DbLog $name -> processing event Timestamp: $a[0], Device: $a[1], Type: $a[2], Event: $a[3], Reading: $a[4], Value: $a[5], Unit: $a[6]";
  1722. }
  1723. use warnings;
  1724. if (lc($DbLogType) =~ m(history)) {
  1725. # insert history mit/ohne primary key
  1726. if ($usepkh && $hash->{MODEL} eq 'MYSQL') {
  1727. eval { $sth_ih = $dbh->prepare("INSERT IGNORE INTO history (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?)"); };
  1728. } elsif ($usepkh && $hash->{MODEL} eq 'SQLITE') {
  1729. eval { $sth_ih = $dbh->prepare("INSERT OR IGNORE INTO history (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?)"); };
  1730. } elsif ($usepkh && $hash->{MODEL} eq 'POSTGRESQL') {
  1731. eval { $sth_ih = $dbh->prepare("INSERT INTO history (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?) ON CONFLICT DO NOTHING"); };
  1732. } else {
  1733. # old behavior
  1734. eval { $sth_ih = $dbh->prepare("INSERT INTO history (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?)"); };
  1735. }
  1736. if ($@) {
  1737. # Eventliste zurückgeben wenn z.B. disk I/O error bei SQLITE
  1738. $error = encode_base64($@,"");
  1739. Log3 ($name, 2, "DbLog $name - Error: $@");
  1740. Log3 ($name, 5, "DbLog $name -> DbLog_PushAsync finished");
  1741. $dbh->disconnect();
  1742. return "$name|$error|0|$rowlist";
  1743. }
  1744. $sth_ih->bind_param_array(1, [@timestamp]);
  1745. $sth_ih->bind_param_array(2, [@device]);
  1746. $sth_ih->bind_param_array(3, [@type]);
  1747. $sth_ih->bind_param_array(4, [@event]);
  1748. $sth_ih->bind_param_array(5, [@reading]);
  1749. $sth_ih->bind_param_array(6, [@value]);
  1750. $sth_ih->bind_param_array(7, [@unit]);
  1751. }
  1752. if (lc($DbLogType) =~ m(current) ) {
  1753. # insert current mit/ohne primary key, insert-values für current werden generiert
  1754. if ($usepkc && $hash->{MODEL} eq 'MYSQL') {
  1755. eval { $sth_ic = $dbh->prepare("INSERT IGNORE INTO current (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?)"); };
  1756. } elsif ($usepkc && $hash->{MODEL} eq 'SQLITE') {
  1757. eval { $sth_ic = $dbh->prepare("INSERT OR IGNORE INTO current (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?)"); };
  1758. } elsif ($usepkc && $hash->{MODEL} eq 'POSTGRESQL') {
  1759. eval { $sth_ic = $dbh->prepare("INSERT INTO current (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?) ON CONFLICT DO NOTHING"); };
  1760. } else {
  1761. # old behavior
  1762. eval { $sth_ic = $dbh->prepare("INSERT INTO current (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?)"); };
  1763. }
  1764. if ($@) {
  1765. # Eventliste zurückgeben wenn z.B. Disk I/O error bei SQLITE
  1766. $error = encode_base64($@,"");
  1767. Log3 ($name, 2, "DbLog $name - Error: $@");
  1768. Log3 ($name, 5, "DbLog $name -> DbLog_PushAsync finished");
  1769. $dbh->disconnect();
  1770. return "$name|$error|0|$rowlist";
  1771. }
  1772. if ($usepkc && $hash->{MODEL} eq 'MYSQL') {
  1773. # update current (mit PK), insert-values für current wird generiert
  1774. $sth_uc = $dbh->prepare("REPLACE INTO current (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?)");
  1775. $sth_uc->bind_param_array(1, [@timestamp]);
  1776. $sth_uc->bind_param_array(2, [@device]);
  1777. $sth_uc->bind_param_array(3, [@type]);
  1778. $sth_uc->bind_param_array(4, [@event]);
  1779. $sth_uc->bind_param_array(5, [@reading]);
  1780. $sth_uc->bind_param_array(6, [@value]);
  1781. $sth_uc->bind_param_array(7, [@unit]);
  1782. } elsif ($usepkc && $hash->{MODEL} eq 'SQLITE') {
  1783. # update current (mit PK), insert-values für current wird generiert
  1784. $sth_uc = $dbh->prepare("INSERT OR REPLACE INTO current (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?)");
  1785. $sth_uc->bind_param_array(1, [@timestamp]);
  1786. $sth_uc->bind_param_array(2, [@device]);
  1787. $sth_uc->bind_param_array(3, [@type]);
  1788. $sth_uc->bind_param_array(4, [@event]);
  1789. $sth_uc->bind_param_array(5, [@reading]);
  1790. $sth_uc->bind_param_array(6, [@value]);
  1791. $sth_uc->bind_param_array(7, [@unit]);
  1792. } elsif ($usepkc && $hash->{MODEL} eq 'POSTGRESQL') {
  1793. # update current (mit PK), insert-values für current wird generiert
  1794. $sth_uc = $dbh->prepare("INSERT INTO current (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES (?,?,?,?,?,?,?) ON CONFLICT ($pkc)
  1795. DO UPDATE SET TIMESTAMP=EXCLUDED.TIMESTAMP, DEVICE=EXCLUDED.DEVICE, TYPE=EXCLUDED.TYPE, EVENT=EXCLUDED.EVENT, READING=EXCLUDED.READING,
  1796. VALUE=EXCLUDED.VALUE, UNIT=EXCLUDED.UNIT");
  1797. $sth_uc->bind_param_array(1, [@timestamp]);
  1798. $sth_uc->bind_param_array(2, [@device]);
  1799. $sth_uc->bind_param_array(3, [@type]);
  1800. $sth_uc->bind_param_array(4, [@event]);
  1801. $sth_uc->bind_param_array(5, [@reading]);
  1802. $sth_uc->bind_param_array(6, [@value]);
  1803. $sth_uc->bind_param_array(7, [@unit]);
  1804. } else {
  1805. # update current (ohne PK), insert-values für current wird generiert
  1806. $sth_uc = $dbh->prepare("UPDATE current SET TIMESTAMP=?, TYPE=?, EVENT=?, VALUE=?, UNIT=? WHERE (DEVICE=?) AND (READING=?)");
  1807. $sth_uc->bind_param_array(1, [@timestamp]);
  1808. $sth_uc->bind_param_array(2, [@type]);
  1809. $sth_uc->bind_param_array(3, [@event]);
  1810. $sth_uc->bind_param_array(4, [@value]);
  1811. $sth_uc->bind_param_array(5, [@unit]);
  1812. $sth_uc->bind_param_array(6, [@device]);
  1813. $sth_uc->bind_param_array(7, [@reading]);
  1814. }
  1815. }
  1816. # SQL-Startzeit
  1817. my $st = [gettimeofday];
  1818. my ($tuples, $rows);
  1819. # insert into history
  1820. eval { $dbh->begin_work() if($useta && $dbh->{AutoCommit}); }; # Transaktion wenn gewünscht und autocommit ein
  1821. if ($@) {
  1822. Log3($name, 2, "DbLog $name -> Error start transaction for history - $@");
  1823. }
  1824. eval {
  1825. if (lc($DbLogType) =~ m(history) ) {
  1826. ($tuples, $rows) = $sth_ih->execute_array( { ArrayTupleStatus => \my @tuple_status } );
  1827. my $nins_hist = 0;
  1828. my @n2hist;
  1829. for my $tuple (0..$#row_array) {
  1830. my $status = $tuple_status[$tuple];
  1831. $status = 0 if($status eq "0E0");
  1832. next if($status); # $status ist "1" wenn insert ok
  1833. Log3 $hash->{NAME}, 3, "DbLog $name -> Insert into history rejected".($usepkh?" (possible PK violation) ":" ")."- TS: $timestamp[$tuple], Device: $device[$tuple], Event: $event[$tuple]";
  1834. my $nlh = ($timestamp[$tuple]."|".$device[$tuple]."|".$type[$tuple]."|".$event[$tuple]."|".$reading[$tuple]."|".$value[$tuple]."|".$unit[$tuple]);
  1835. push(@n2hist, "$nlh");
  1836. $nins_hist++;
  1837. }
  1838. if(!$nins_hist) {
  1839. Log3 $hash->{NAME}, 4, "DbLog $name -> $ceti of $ceti events inserted into table history".($usepkh?" using PK on columns $pkh":"");
  1840. } else {
  1841. Log3 $hash->{NAME}, 4, "DbLog $name -> ".($ceti-$nins_hist)." of $ceti events inserted into table history".($usepkh?" using PK on columns $pkh":"");
  1842. s/\|/_ESC_/g for @n2hist; # escape Pipe "|"
  1843. $rowlist = join('§', @n2hist);
  1844. $rowlist = encode_base64($rowlist,"");
  1845. }
  1846. eval {$dbh->commit() if(!$dbh->{AutoCommit});}; # issue Turning on AutoCommit failed
  1847. if ($@) {
  1848. Log3($name, 2, "DbLog $name -> Error commit history - $@");
  1849. } else {
  1850. if(!$dbh->{AutoCommit}) {
  1851. Log3($name, 4, "DbLog $name -> insert table history committed");
  1852. } else {
  1853. Log3($name, 4, "DbLog $name -> insert table history committed by autocommit");
  1854. }
  1855. }
  1856. }
  1857. };
  1858. if ($@) {
  1859. $errorh = $@;
  1860. Log3 $hash->{NAME}, 2, "DbLog $name -> Error table history - $errorh";
  1861. $error = encode_base64($errorh,"");
  1862. $rowlback = $rowlist;
  1863. }
  1864. # update or insert current
  1865. eval { $dbh->begin_work() if($useta && $dbh->{AutoCommit}); }; # Transaktion wenn gewünscht und autocommit ein
  1866. if ($@) {
  1867. Log3($name, 2, "DbLog $name -> Error start transaction for current - $@");
  1868. }
  1869. eval {
  1870. if (lc($DbLogType) =~ m(current) ) {
  1871. ($tuples, $rows) = $sth_uc->execute_array( { ArrayTupleStatus => \my @tuple_status } );
  1872. my $nupd_cur = 0;
  1873. for my $tuple (0..$#row_array) {
  1874. my $status = $tuple_status[$tuple];
  1875. $status = 0 if($status eq "0E0");
  1876. next if($status); # $status ist "1" wenn update ok
  1877. Log3 $hash->{NAME}, 4, "DbLog $name -> Failed to update in current, try to insert - TS: $timestamp[$tuple], Device: $device[$tuple], Reading: $reading[$tuple], Status = $status";
  1878. push(@timestamp_cur, "$timestamp[$tuple]");
  1879. push(@device_cur, "$device[$tuple]");
  1880. push(@type_cur, "$type[$tuple]");
  1881. push(@event_cur, "$event[$tuple]");
  1882. push(@reading_cur, "$reading[$tuple]");
  1883. push(@value_cur, "$value[$tuple]");
  1884. push(@unit_cur, "$unit[$tuple]");
  1885. $nupd_cur++;
  1886. }
  1887. if(!$nupd_cur) {
  1888. Log3 $hash->{NAME}, 4, "DbLog $name -> $ceti of $ceti events updated in table current".($usepkc?" using PK on columns $pkc":"");
  1889. } else {
  1890. Log3 $hash->{NAME}, 4, "DbLog $name -> $nupd_cur of $ceti events not updated and try to insert into table current".($usepkc?" using PK on columns $pkc":"");
  1891. $doins = 1;
  1892. }
  1893. if ($doins) {
  1894. # events die nicht in Tabelle current updated wurden, werden in current neu eingefügt
  1895. $sth_ic->bind_param_array(1, [@timestamp_cur]);
  1896. $sth_ic->bind_param_array(2, [@device_cur]);
  1897. $sth_ic->bind_param_array(3, [@type_cur]);
  1898. $sth_ic->bind_param_array(4, [@event_cur]);
  1899. $sth_ic->bind_param_array(5, [@reading_cur]);
  1900. $sth_ic->bind_param_array(6, [@value_cur]);
  1901. $sth_ic->bind_param_array(7, [@unit_cur]);
  1902. ($tuples, $rows) = $sth_ic->execute_array( { ArrayTupleStatus => \my @tuple_status } );
  1903. my $nins_cur = 0;
  1904. for my $tuple (0..$#device_cur) {
  1905. my $status = $tuple_status[$tuple];
  1906. $status = 0 if($status eq "0E0");
  1907. next if($status); # $status ist "1" wenn insert ok
  1908. Log3 $hash->{NAME}, 3, "DbLog $name -> Insert into current rejected - TS: $timestamp[$tuple], Device: $device_cur[$tuple], Reading: $reading_cur[$tuple], Status = $status";
  1909. $nins_cur++;
  1910. }
  1911. if(!$nins_cur) {
  1912. Log3 $hash->{NAME}, 4, "DbLog $name -> ".($#device_cur+1)." of ".($#device_cur+1)." events inserted into table current ".($usepkc?" using PK on columns $pkc":"");
  1913. } else {
  1914. Log3 $hash->{NAME}, 4, "DbLog $name -> ".($#device_cur+1-$nins_cur)." of ".($#device_cur+1)." events inserted into table current".($usepkc?" using PK on columns $pkc":"");
  1915. }
  1916. }
  1917. eval {$dbh->commit() if(!$dbh->{AutoCommit});}; # issue Turning on AutoCommit failed
  1918. if ($@) {
  1919. Log3($name, 2, "DbLog $name -> Error commit table current - $@");
  1920. } else {
  1921. if(!$dbh->{AutoCommit}) {
  1922. Log3($name, 4, "DbLog $name -> insert / update table current committed");
  1923. } else {
  1924. Log3($name, 4, "DbLog $name -> insert / update table current committed by autocommit");
  1925. }
  1926. }
  1927. }
  1928. };
  1929. $dbh->disconnect();
  1930. # SQL-Laufzeit ermitteln
  1931. my $rt = tv_interval($st);
  1932. Log3 ($name, 5, "DbLog $name -> DbLog_PushAsync finished");
  1933. # Background-Laufzeit ermitteln
  1934. my $brt = tv_interval($bst);
  1935. $rt = $rt.",".$brt;
  1936. return "$name|$error|$rt|$rowlback";
  1937. }
  1938. #############################################################################################
  1939. # Auswertung non-blocking asynchron DbLog_PushAsync
  1940. #############################################################################################
  1941. sub DbLog_PushAsyncDone ($) {
  1942. my ($string) = @_;
  1943. my @a = split("\\|",$string);
  1944. my $name = $a[0];
  1945. my $hash = $defs{$name};
  1946. my $error = $a[1]?decode_base64($a[1]):0;
  1947. my $bt = $a[2];
  1948. my $rowlist = $a[3];
  1949. my $asyncmode = AttrVal($name, "asyncMode", undef);
  1950. my $memcount;
  1951. Log3 ($name, 5, "DbLog $name -> Start DbLog_PushAsyncDone");
  1952. if($rowlist) {
  1953. $rowlist = decode_base64($rowlist);
  1954. my @row_array = split('§', $rowlist);
  1955. #one Transaction
  1956. eval {
  1957. foreach my $row (@row_array) {
  1958. # Cache & CacheIndex für Events zum asynchronen Schreiben in DB
  1959. $hash->{cache}{index}++;
  1960. my $index = $hash->{cache}{index};
  1961. $hash->{cache}{".memcache"}{$index} = $row;
  1962. }
  1963. $memcount = scalar(keys%{$hash->{cache}{".memcache"}});
  1964. };
  1965. }
  1966. $memcount = $hash->{cache}{".memcache"}?scalar(keys%{$hash->{cache}{".memcache"}}):0;
  1967. readingsSingleUpdate($hash, 'CacheUsage', $memcount, 0);
  1968. if(AttrVal($name, "showproctime", undef) && $bt) {
  1969. my ($rt,$brt) = split(",", $bt);
  1970. readingsBeginUpdate($hash);
  1971. readingsBulkUpdate($hash, "background_processing_time", sprintf("%.4f",$brt));
  1972. readingsBulkUpdate($hash, "sql_processing_time", sprintf("%.4f",$rt));
  1973. readingsEndUpdate($hash, 1);
  1974. }
  1975. my $state = $error?$error:(IsDisabled($name))?"disabled":"connected";
  1976. my $evt = ($state eq $hash->{HELPER}{OLDSTATE})?0:1;
  1977. readingsSingleUpdate($hash, "state", $state, $evt);
  1978. $hash->{HELPER}{OLDSTATE} = $state;
  1979. if(!$asyncmode) {
  1980. delete($defs{$name}{READINGS}{NextSync});
  1981. delete($defs{$name}{READINGS}{background_processing_time});
  1982. delete($defs{$name}{READINGS}{sql_processing_time});
  1983. delete($defs{$name}{READINGS}{CacheUsage});
  1984. }
  1985. delete $hash->{HELPER}{".RUNNING_PID"};
  1986. delete $hash->{HELPER}{LASTLIMITRUNTIME} if(!$error);
  1987. Log3 ($name, 5, "DbLog $name -> DbLog_PushAsyncDone finished");
  1988. return;
  1989. }
  1990. #############################################################################################
  1991. # Abbruchroutine Timeout non-blocking asynchron DbLog_PushAsync
  1992. #############################################################################################
  1993. sub DbLog_PushAsyncAborted(@) {
  1994. my ($hash,$cause) = @_;
  1995. my $name = $hash->{NAME};
  1996. $cause = $cause?$cause:"Timeout: process terminated";
  1997. Log3 ($name, 2, "DbLog $name -> ".$hash->{HELPER}{".RUNNING_PID"}{fn}." ".$cause) if(!$hash->{HELPER}{SHUTDOWNSEQ});
  1998. readingsSingleUpdate($hash,"state",$cause, 1);
  1999. delete $hash->{HELPER}{".RUNNING_PID"};
  2000. delete $hash->{HELPER}{LASTLIMITRUNTIME};
  2001. }
  2002. ################################################################
  2003. #
  2004. # zerlegt uebergebenes FHEM-Datum in die einzelnen Bestandteile
  2005. # und fuegt noch Defaultwerte ein
  2006. # uebergebenes SQL-Format: YYYY-MM-DD HH24:MI:SS
  2007. #
  2008. ################################################################
  2009. sub DbLog_explode_datetime($%) {
  2010. my ($t, %def) = @_;
  2011. my %retv;
  2012. my (@datetime, @date, @time);
  2013. @datetime = split(" ", $t); #Datum und Zeit auftrennen
  2014. @date = split("-", $datetime[0]);
  2015. @time = split(":", $datetime[1]) if ($datetime[1]);
  2016. if ($date[0]) {$retv{year} = $date[0];} else {$retv{year} = $def{year};}
  2017. if ($date[1]) {$retv{month} = $date[1];} else {$retv{month} = $def{month};}
  2018. if ($date[2]) {$retv{day} = $date[2];} else {$retv{day} = $def{day};}
  2019. if ($time[0]) {$retv{hour} = $time[0];} else {$retv{hour} = $def{hour};}
  2020. if ($time[1]) {$retv{minute}= $time[1];} else {$retv{minute}= $def{minute};}
  2021. if ($time[2]) {$retv{second}= $time[2];} else {$retv{second}= $def{second};}
  2022. $retv{datetime}=DbLog_implode_datetime($retv{year}, $retv{month}, $retv{day}, $retv{hour}, $retv{minute}, $retv{second});
  2023. #Log 1, Dumper(%retv);
  2024. return %retv
  2025. }
  2026. sub DbLog_implode_datetime($$$$$$) {
  2027. my ($year, $month, $day, $hour, $minute, $second) = @_;
  2028. my $retv = $year."-".$month."-".$day." ".$hour.":".$minute.":".$second;
  2029. return $retv;
  2030. }
  2031. ###################################################################################
  2032. # Verbindungen zur DB aufbauen
  2033. ###################################################################################
  2034. sub DbLog_readCfg($){
  2035. my ($hash)= @_;
  2036. my $name = $hash->{NAME};
  2037. my $configfilename= $hash->{CONFIGURATION};
  2038. my %dbconfig;
  2039. # use generic fileRead to get configuration data
  2040. my ($err, @config) = FileRead($configfilename);
  2041. return $err if($err);
  2042. eval join("\n", @config);
  2043. return "could not read connection" if (!defined $dbconfig{connection});
  2044. $hash->{dbconn} = $dbconfig{connection};
  2045. return "could not read user" if (!defined $dbconfig{user});
  2046. $hash->{dbuser} = $dbconfig{user};
  2047. return "could not read password" if (!defined $dbconfig{password});
  2048. $attr{"sec$name"}{secret} = $dbconfig{password};
  2049. #check the database model
  2050. if($hash->{dbconn} =~ m/pg:/i) {
  2051. $hash->{MODEL}="POSTGRESQL";
  2052. } elsif ($hash->{dbconn} =~ m/mysql:/i) {
  2053. $hash->{MODEL}="MYSQL";
  2054. } elsif ($hash->{dbconn} =~ m/oracle:/i) {
  2055. $hash->{MODEL}="ORACLE";
  2056. } elsif ($hash->{dbconn} =~ m/sqlite:/i) {
  2057. $hash->{MODEL}="SQLITE";
  2058. } else {
  2059. $hash->{MODEL}="unknown";
  2060. Log3 $hash->{NAME}, 1, "Unknown database model found in configuration file $configfilename.";
  2061. Log3 $hash->{NAME}, 1, "Only MySQL/MariaDB, PostgreSQL, Oracle, SQLite are fully supported.";
  2062. return "unknown database type";
  2063. }
  2064. if($hash->{MODEL} eq "MYSQL") {
  2065. $hash->{UTF8} = defined($dbconfig{utf8})?$dbconfig{utf8}:0;
  2066. }
  2067. return;
  2068. }
  2069. sub DbLog_ConnectPush($;$$) {
  2070. # own $dbhp for synchronous logging and dblog_get
  2071. my ($hash,$get)= @_;
  2072. my $name = $hash->{NAME};
  2073. my $dbconn = $hash->{dbconn};
  2074. my $dbuser = $hash->{dbuser};
  2075. my $dbpassword = $attr{"sec$name"}{secret};
  2076. my $utf8 = defined($hash->{UTF8})?$hash->{UTF8}:0;
  2077. my $dbhp;
  2078. return 0 if(IsDisabled($name));
  2079. if($init_done != 1) {
  2080. InternalTimer(gettimeofday()+5, "DbLog_ConnectPush", $hash, 0);
  2081. return;
  2082. }
  2083. Log3 $hash->{NAME}, 3, "DbLog $name - Creating Push-Handle to database $dbconn with user $dbuser" if(!$get);
  2084. my ($useac,$useta) = DbLog_commitMode($hash);
  2085. if(!$useac) {
  2086. eval {$dbhp = DBI->connect("dbi:$dbconn", $dbuser, $dbpassword, { PrintError => 0, RaiseError => 1, AutoCommit => 0, mysql_enable_utf8 => $utf8 });};
  2087. } elsif($useac == 1) {
  2088. eval {$dbhp = DBI->connect("dbi:$dbconn", $dbuser, $dbpassword, { PrintError => 0, RaiseError => 1, AutoCommit => 1, mysql_enable_utf8 => $utf8 });};
  2089. } else {
  2090. # Server default
  2091. eval {$dbhp = DBI->connect("dbi:$dbconn", $dbuser, $dbpassword, { PrintError => 0, RaiseError => 1, mysql_enable_utf8 => $utf8 });};
  2092. }
  2093. if($@) {
  2094. Log3 $hash->{NAME}, 2, "DbLog $name - Error: $@";
  2095. }
  2096. if(!$dbhp) {
  2097. RemoveInternalTimer($hash, "DbLog_ConnectPush");
  2098. Log3 $hash->{NAME}, 4, "DbLog $name - Trying to connect to database";
  2099. my $state = $@?$@:(IsDisabled($name))?"disabled":"disconnected";
  2100. my $evt = ($state eq $hash->{HELPER}{OLDSTATE})?0:1;
  2101. readingsSingleUpdate($hash, "state", $state, $evt);
  2102. $hash->{HELPER}{OLDSTATE} = $state;
  2103. InternalTimer(gettimeofday()+5, 'DbLog_ConnectPush', $hash, 0);
  2104. Log3 $hash->{NAME}, 4, "DbLog $name - Waiting for database connection";
  2105. return 0;
  2106. }
  2107. $dbhp->{RaiseError} = 0;
  2108. $dbhp->{PrintError} = 1;
  2109. Log3 $hash->{NAME}, 3, "DbLog $name - Push-Handle to db $dbconn created" if(!$get);
  2110. Log3 $hash->{NAME}, 3, "DbLog $name - UTF8 support enabled" if($utf8 && $hash->{MODEL} eq "MYSQL" && !$get);
  2111. readingsSingleUpdate($hash, 'state', 'connected', 1) if(!$get);
  2112. $hash->{DBHP}= $dbhp;
  2113. if ($hash->{MODEL} eq "SQLITE") {
  2114. $dbhp->do("PRAGMA temp_store=MEMORY");
  2115. $dbhp->do("PRAGMA synchronous=FULL"); # For maximum reliability and for robustness against database corruption,
  2116. # SQLite should always be run with its default synchronous setting of FULL.
  2117. # https://sqlite.org/howtocorrupt.html
  2118. $dbhp->do("PRAGMA journal_mode=WAL");
  2119. $dbhp->do("PRAGMA cache_size=4000");
  2120. }
  2121. return 1;
  2122. }
  2123. sub DbLog_ConnectNewDBH($) {
  2124. # new dbh for common use (except DbLog_Push and get-function)
  2125. my ($hash)= @_;
  2126. my $name = $hash->{NAME};
  2127. my $dbconn = $hash->{dbconn};
  2128. my $dbuser = $hash->{dbuser};
  2129. my $dbpassword = $attr{"sec$name"}{secret};
  2130. my $utf8 = defined($hash->{UTF8})?$hash->{UTF8}:0;
  2131. my $dbh;
  2132. my ($useac,$useta) = DbLog_commitMode($hash);
  2133. if(!$useac) {
  2134. eval {$dbh = DBI->connect("dbi:$dbconn", $dbuser, $dbpassword, { PrintError => 0, RaiseError => 1, AutoCommit => 0, mysql_enable_utf8 => $utf8 });};
  2135. } elsif($useac == 1) {
  2136. eval {$dbh = DBI->connect("dbi:$dbconn", $dbuser, $dbpassword, { PrintError => 0, RaiseError => 1, AutoCommit => 1, mysql_enable_utf8 => $utf8 });};
  2137. } else {
  2138. # Server default
  2139. eval {$dbh = DBI->connect("dbi:$dbconn", $dbuser, $dbpassword, { PrintError => 0, RaiseError => 1, mysql_enable_utf8 => $utf8 });};
  2140. }
  2141. if($@) {
  2142. Log3($name, 2, "DbLog $name - $@");
  2143. my $state = $@?$@:(IsDisabled($name))?"disabled":"disconnected";
  2144. my $evt = ($state eq $hash->{HELPER}{OLDSTATE})?0:1;
  2145. readingsSingleUpdate($hash, "state", $state, $evt);
  2146. $hash->{HELPER}{OLDSTATE} = $state;
  2147. }
  2148. if($dbh) {
  2149. $dbh->{RaiseError} = 0;
  2150. $dbh->{PrintError} = 1;
  2151. return $dbh;
  2152. } else {
  2153. return 0;
  2154. }
  2155. }
  2156. ##########################################################################
  2157. #
  2158. # Prozedur zum Ausfuehren von SQL-Statements durch externe Module
  2159. #
  2160. # param1: DbLog-hash
  2161. # param2: SQL-Statement
  2162. ##########################################################################
  2163. sub DbLog_ExecSQL($$)
  2164. {
  2165. my ($hash,$sql)= @_;
  2166. Log3 $hash->{NAME}, 4, "Executing $sql";
  2167. my $dbh = DbLog_ConnectNewDBH($hash);
  2168. return if(!$dbh);
  2169. my $sth = DbLog_ExecSQL1($hash,$dbh,$sql);
  2170. if(!$sth) {
  2171. #retry
  2172. $dbh->disconnect();
  2173. $dbh = DbLog_ConnectNewDBH($hash);
  2174. return if(!$dbh);
  2175. $sth = DbLog_ExecSQL1($hash,$dbh,$sql);
  2176. if(!$sth) {
  2177. Log3 $hash->{NAME}, 2, "DBLog retry failed.";
  2178. $dbh->disconnect();
  2179. return 0;
  2180. }
  2181. Log3 $hash->{NAME}, 2, "DBLog retry ok.";
  2182. }
  2183. eval {$dbh->commit() if(!$dbh->{AutoCommit});};
  2184. $dbh->disconnect();
  2185. return $sth;
  2186. }
  2187. sub DbLog_ExecSQL1($$$)
  2188. {
  2189. my ($hash,$dbh,$sql)= @_;
  2190. $dbh->{RaiseError} = 1;
  2191. $dbh->{PrintError} = 0;
  2192. my $sth;
  2193. eval { $sth = $dbh->do($sql); };
  2194. if($@) {
  2195. Log3 $hash->{NAME}, 2, "DBLog error: $@";
  2196. return 0;
  2197. }
  2198. return $sth;
  2199. }
  2200. ################################################################
  2201. #
  2202. # GET Funktion
  2203. # wird zb. zur Generierung der Plots implizit aufgerufen
  2204. # infile : [-|current|history]
  2205. # outfile: [-|ALL|INT|WEBCHART]
  2206. #
  2207. ################################################################
  2208. sub DbLog_Get($@) {
  2209. my ($hash, @a) = @_;
  2210. my $name = $hash->{NAME};
  2211. my $utf8 = defined($hash->{UTF8})?$hash->{UTF8}:0;
  2212. my $dbh;
  2213. return dbReadings($hash,@a) if $a[1] =~ m/^Readings/;
  2214. return "Usage: get $a[0] <in> <out> <from> <to> <column_spec>...\n".
  2215. " where column_spec is <device>:<reading>:<default>:<fn>\n" .
  2216. " see the #DbLog entries in the .gplot files\n" .
  2217. " <in> is not used, only for compatibility for FileLog, please use - \n" .
  2218. " <out> is a prefix, - means stdout\n"
  2219. if(int(@a) < 5);
  2220. shift @a;
  2221. my $inf = lc(shift @a);
  2222. my $outf = lc(shift @a);
  2223. my $from = shift @a;
  2224. my $to = shift @a; # Now @a contains the list of column_specs
  2225. my ($internal, @fld);
  2226. if($inf eq "-") {
  2227. $inf = "history";
  2228. }
  2229. if($outf eq "int" && $inf eq "current") {
  2230. $inf = "history";
  2231. Log3 $hash->{NAME}, 3, "Defining DbLog SVG-Plots with :CURRENT is deprecated. Please define DbLog SVG-Plots with :HISTORY instead of :CURRENT. (define <mySVG> SVG <DbLogDev>:<gplotfile>:HISTORY)";
  2232. }
  2233. if($outf eq "int") {
  2234. $outf = "-";
  2235. $internal = 1;
  2236. } elsif($outf eq "array"){
  2237. } elsif(lc($outf) eq "webchart") {
  2238. # redirect the get request to the chartQuery function
  2239. return chartQuery($hash, @_);
  2240. }
  2241. my @readings = ();
  2242. my (%sqlspec, %from_datetime, %to_datetime);
  2243. #uebergebenen Timestamp anpassen
  2244. #moegliche Formate: YYYY | YYYY-MM | YYYY-MM-DD | YYYY-MM-DD_HH24
  2245. $from =~ s/_/\ /g;
  2246. $to =~ s/_/\ /g;
  2247. %from_datetime = DbLog_explode_datetime($from, DbLog_explode_datetime("2000-01-01 00:00:00", ()));
  2248. %to_datetime = DbLog_explode_datetime($to, DbLog_explode_datetime("2099-01-01 00:00:00", ()));
  2249. $from = $from_datetime{datetime};
  2250. $to = $to_datetime{datetime};
  2251. my ($retval,$retvaldummy,$hour,$sql_timestamp, $sql_device, $sql_reading, $sql_value, $type, $event, $unit) = "";
  2252. my @ReturnArray;
  2253. my $writeout = 0;
  2254. my (@min, @max, @sum, @cnt, @lastv, @lastd, @mind, @maxd);
  2255. my (%tstamp, %lasttstamp, $out_tstamp, $out_value, $minval, $maxval, $deltacalc); #fuer delta-h/d Berechnung
  2256. #extract the Device:Reading arguments into @readings array
  2257. for(my $i = 0; $i < int(@a); $i++) {
  2258. @fld = split(":", $a[$i], 5);
  2259. $readings[$i][0] = $fld[0]; # Device
  2260. $readings[$i][1] = $fld[1]; # Reading
  2261. $readings[$i][2] = $fld[2]; # Default
  2262. $readings[$i][3] = $fld[3]; # function
  2263. $readings[$i][4] = $fld[4]; # regexp
  2264. $readings[$i][1] = "%" if(!$readings[$i][1] || length($readings[$i][1])==0); #falls Reading nicht gefuellt setze Joker
  2265. }
  2266. $dbh = $hash->{DBHP};
  2267. if ( !$dbh || not $dbh->ping ) {
  2268. # DB Session dead, try to reopen now !
  2269. return "Can't connect to database." if(!DbLog_ConnectPush($hash,1));
  2270. $dbh = $hash->{DBHP};
  2271. }
  2272. if( $hash->{PID} != $$ ) {
  2273. #create new connection for plotfork
  2274. $dbh->disconnect();
  2275. return "Can't connect to database." if(!DbLog_ConnectPush($hash,1));
  2276. $dbh = $hash->{DBHP};
  2277. }
  2278. #vorbereiten der DB-Abfrage, DB-Modell-abhaengig
  2279. if ($hash->{MODEL} eq "POSTGRESQL") {
  2280. $sqlspec{get_timestamp} = "TO_CHAR(TIMESTAMP, 'YYYY-MM-DD HH24:MI:SS')";
  2281. $sqlspec{from_timestamp} = "TO_TIMESTAMP('$from', 'YYYY-MM-DD HH24:MI:SS')";
  2282. $sqlspec{to_timestamp} = "TO_TIMESTAMP('$to', 'YYYY-MM-DD HH24:MI:SS')";
  2283. #$sqlspec{reading_clause} = "(DEVICE || '|' || READING)";
  2284. $sqlspec{order_by_hour} = "TO_CHAR(TIMESTAMP, 'YYYY-MM-DD HH24')";
  2285. $sqlspec{max_value} = "MAX(VALUE)";
  2286. $sqlspec{day_before} = "($sqlspec{from_timestamp} - INTERVAL '1 DAY')";
  2287. } elsif ($hash->{MODEL} eq "ORACLE") {
  2288. $sqlspec{get_timestamp} = "TO_CHAR(TIMESTAMP, 'YYYY-MM-DD HH24:MI:SS')";
  2289. $sqlspec{from_timestamp} = "TO_TIMESTAMP('$from', 'YYYY-MM-DD HH24:MI:SS')";
  2290. $sqlspec{to_timestamp} = "TO_TIMESTAMP('$to', 'YYYY-MM-DD HH24:MI:SS')";
  2291. $sqlspec{order_by_hour} = "TO_CHAR(TIMESTAMP, 'YYYY-MM-DD HH24')";
  2292. $sqlspec{max_value} = "MAX(VALUE)";
  2293. $sqlspec{day_before} = "DATE_SUB($sqlspec{from_timestamp},INTERVAL 1 DAY)";
  2294. } elsif ($hash->{MODEL} eq "MYSQL") {
  2295. $sqlspec{get_timestamp} = "DATE_FORMAT(TIMESTAMP, '%Y-%m-%d %H:%i:%s')";
  2296. $sqlspec{from_timestamp} = "STR_TO_DATE('$from', '%Y-%m-%d %H:%i:%s')";
  2297. $sqlspec{to_timestamp} = "STR_TO_DATE('$to', '%Y-%m-%d %H:%i:%s')";
  2298. $sqlspec{order_by_hour} = "DATE_FORMAT(TIMESTAMP, '%Y-%m-%d %H')";
  2299. $sqlspec{max_value} = "MAX(CAST(VALUE AS DECIMAL(20,8)))";
  2300. $sqlspec{day_before} = "DATE_SUB($sqlspec{from_timestamp},INTERVAL 1 DAY)";
  2301. } elsif ($hash->{MODEL} eq "SQLITE") {
  2302. $sqlspec{get_timestamp} = "TIMESTAMP";
  2303. $sqlspec{from_timestamp} = "'$from'";
  2304. $sqlspec{to_timestamp} = "'$to'";
  2305. $sqlspec{order_by_hour} = "strftime('%Y-%m-%d %H', TIMESTAMP)";
  2306. $sqlspec{max_value} = "MAX(VALUE)";
  2307. $sqlspec{day_before} = "date($sqlspec{from_timestamp},'-1 day')";
  2308. } else {
  2309. $sqlspec{get_timestamp} = "TIMESTAMP";
  2310. $sqlspec{from_timestamp} = "'$from'";
  2311. $sqlspec{to_timestamp} = "'$to'";
  2312. $sqlspec{order_by_hour} = "strftime('%Y-%m-%d %H', TIMESTAMP)";
  2313. $sqlspec{max_value} = "MAX(VALUE)";
  2314. $sqlspec{day_before} = "date($sqlspec{from_timestamp},'-1 day')";
  2315. }
  2316. if($outf =~ m/(all|array)/) {
  2317. $sqlspec{all} = ",TYPE,EVENT,UNIT";
  2318. $sqlspec{all_max} = ",MAX(TYPE) AS TYPE,MAX(EVENT) AS EVENT,MAX(UNIT) AS UNIT";
  2319. } else {
  2320. $sqlspec{all} = "";
  2321. $sqlspec{all_max} = "";
  2322. }
  2323. for(my $i=0; $i<int(@readings); $i++) {
  2324. # ueber alle Readings
  2325. # Variablen initialisieren
  2326. $min[$i] = (~0 >> 1);
  2327. $max[$i] = -(~0 >> 1);
  2328. $sum[$i] = 0;
  2329. $cnt[$i] = 0;
  2330. $lastv[$i] = 0;
  2331. $lastd[$i] = "undef";
  2332. $mind[$i] = "undef";
  2333. $maxd[$i] = "undef";
  2334. $minval = (~0 >> 1);
  2335. $maxval = -(~0 >> 1);
  2336. $deltacalc = 0;
  2337. if($readings[$i]->[3] && ($readings[$i]->[3] eq "delta-h" || $readings[$i]->[3] eq "delta-d")) {
  2338. $deltacalc = 1;
  2339. }
  2340. my $stm;
  2341. my $stm2;
  2342. my $stmdelta;
  2343. $stm = "SELECT
  2344. MAX($sqlspec{get_timestamp}) AS TIMESTAMP,
  2345. MAX(DEVICE) AS DEVICE,
  2346. MAX(READING) AS READING,
  2347. $sqlspec{max_value}
  2348. $sqlspec{all_max} ";
  2349. $stm .= "FROM current " if($inf eq "current");
  2350. $stm .= "FROM history " if($inf eq "history");
  2351. $stm .= "WHERE 1=1 ";
  2352. $stm .= "AND DEVICE = '".$readings[$i]->[0]."' " if ($readings[$i]->[0] !~ m(\%));
  2353. $stm .= "AND DEVICE LIKE '".$readings[$i]->[0]."' " if(($readings[$i]->[0] !~ m(^\%$)) && ($readings[$i]->[0] =~ m(\%)));
  2354. $stm .= "AND READING = '".$readings[$i]->[1]."' " if ($readings[$i]->[1] !~ m(\%));
  2355. $stm .= "AND READING LIKE '".$readings[$i]->[1]."' " if(($readings[$i]->[1] !~ m(^%$)) && ($readings[$i]->[1] =~ m(\%)));
  2356. $stmdelta = $stm;
  2357. $stm .= "AND TIMESTAMP < $sqlspec{from_timestamp} ";
  2358. $stm .= "AND TIMESTAMP > $sqlspec{day_before} ";
  2359. $stm .= "UNION ALL ";
  2360. $stm2 = "SELECT
  2361. $sqlspec{get_timestamp},
  2362. DEVICE,
  2363. READING,
  2364. VALUE
  2365. $sqlspec{all} ";
  2366. $stm2 .= "FROM current " if($inf eq "current");
  2367. $stm2 .= "FROM history " if($inf eq "history");
  2368. $stm2 .= "WHERE 1=1 ";
  2369. $stm2 .= "AND DEVICE = '".$readings[$i]->[0]."' " if ($readings[$i]->[0] !~ m(\%));
  2370. $stm2 .= "AND DEVICE LIKE '".$readings[$i]->[0]."' " if(($readings[$i]->[0] !~ m(^\%$)) && ($readings[$i]->[0] =~ m(\%)));
  2371. $stm2 .= "AND READING = '".$readings[$i]->[1]."' " if ($readings[$i]->[1] !~ m(\%));
  2372. $stm2 .= "AND READING LIKE '".$readings[$i]->[1]."' " if(($readings[$i]->[1] !~ m(^%$)) && ($readings[$i]->[1] =~ m(\%)));
  2373. $stm2 .= "AND TIMESTAMP >= $sqlspec{from_timestamp} ";
  2374. $stm2 .= "AND TIMESTAMP < $sqlspec{to_timestamp} ";
  2375. $stm2 .= "ORDER BY TIMESTAMP";
  2376. if($deltacalc) {
  2377. $stmdelta .= "AND TIMESTAMP >= $sqlspec{from_timestamp} ";
  2378. $stmdelta .= "AND TIMESTAMP < $sqlspec{to_timestamp} ";
  2379. $stmdelta .= "GROUP BY $sqlspec{order_by_hour} " if($deltacalc);
  2380. $stmdelta .= "ORDER BY TIMESTAMP";
  2381. $stm .= $stmdelta;
  2382. } else {
  2383. $stm = $stm2;
  2384. }
  2385. Log3 $hash->{NAME}, 4, "Processing Statement: $stm";
  2386. my $sth= $dbh->prepare($stm) ||
  2387. return "Cannot prepare statement $stm: $DBI::errstr";
  2388. my $rc= $sth->execute() ||
  2389. return "Cannot execute statement $stm: $DBI::errstr";
  2390. if($outf =~ m/(all|array)/) {
  2391. $sth->bind_columns(undef, \$sql_timestamp, \$sql_device, \$sql_reading, \$sql_value, \$type, \$event, \$unit);
  2392. }
  2393. else {
  2394. $sth->bind_columns(undef, \$sql_timestamp, \$sql_device, \$sql_reading, \$sql_value);
  2395. }
  2396. if ($outf =~ m/(all)/) {
  2397. $retval .= "Timestamp: Device, Type, Event, Reading, Value, Unit\n";
  2398. $retval .= "=====================================================\n";
  2399. }
  2400. while($sth->fetch()) {
  2401. ############ Auswerten des 5. Parameters: Regexp ###################
  2402. # die Regexep wird vor der Function ausgewertet und der Wert im Feld
  2403. # Value angepasst.
  2404. ####################################################################
  2405. if($readings[$i]->[4]) {
  2406. #evaluate
  2407. my $val = $sql_value;
  2408. my $ts = $sql_timestamp;
  2409. eval("$readings[$i]->[4]");
  2410. $sql_value = $val;
  2411. $sql_timestamp = $ts;
  2412. if($@) {Log3 $hash->{NAME}, 3, "DbLog: Error in inline function: <".$readings[$i]->[4].">, Error: $@";}
  2413. }
  2414. if($sql_timestamp lt $from && $deltacalc) {
  2415. if(Scalar::Util::looks_like_number($sql_value)){
  2416. #nur setzen wenn nummerisch
  2417. $minval = $sql_value if($sql_value < $minval);
  2418. $maxval = $sql_value if($sql_value > $maxval);
  2419. $lastv[$i] = $sql_value;
  2420. }
  2421. } else {
  2422. $writeout = 0;
  2423. $out_value = "";
  2424. $out_tstamp = "";
  2425. $retvaldummy = "";
  2426. if($readings[$i]->[4]) {
  2427. $out_tstamp = $sql_timestamp;
  2428. $writeout=1 if(!$deltacalc);
  2429. }
  2430. ############ Auswerten des 4. Parameters: function ###################
  2431. if($readings[$i]->[3] && $readings[$i]->[3] eq "int") {
  2432. #nur den integerwert uebernehmen falls zb value=15°C
  2433. $out_value = $1 if($sql_value =~ m/^(\d+).*/o);
  2434. $out_tstamp = $sql_timestamp;
  2435. $writeout=1;
  2436. } elsif ($readings[$i]->[3] && $readings[$i]->[3] =~ m/^int(\d+).*/o) {
  2437. #Uebernehme den Dezimalwert mit den angegebenen Stellen an Nachkommastellen
  2438. $out_value = $1 if($sql_value =~ m/^([-\.\d]+).*/o);
  2439. $out_tstamp = $sql_timestamp;
  2440. $writeout=1;
  2441. } elsif ($readings[$i]->[3] && $readings[$i]->[3] eq "delta-ts" && lc($sql_value) !~ m(ignore)) {
  2442. #Berechung der vergangen Sekunden seit dem letten Logeintrag
  2443. #zb. die Zeit zwischen on/off
  2444. my @a = split("[- :]", $sql_timestamp);
  2445. my $akt_ts = mktime($a[5],$a[4],$a[3],$a[2],$a[1]-1,$a[0]-1900,0,0,-1);
  2446. if($lastd[$i] ne "undef") {
  2447. @a = split("[- :]", $lastd[$i]);
  2448. }
  2449. my $last_ts = mktime($a[5],$a[4],$a[3],$a[2],$a[1]-1,$a[0]-1900,0,0,-1);
  2450. $out_tstamp = $sql_timestamp;
  2451. $out_value = sprintf("%02d", $akt_ts - $last_ts);
  2452. if(lc($sql_value) =~ m(hide)){$writeout=0;} else {$writeout=1;}
  2453. } elsif ($readings[$i]->[3] && $readings[$i]->[3] eq "delta-h") {
  2454. #Berechnung eines Stundenwertes
  2455. %tstamp = DbLog_explode_datetime($sql_timestamp, ());
  2456. if($lastd[$i] eq "undef") {
  2457. %lasttstamp = DbLog_explode_datetime($sql_timestamp, ());
  2458. $lasttstamp{hour} = "00";
  2459. } else {
  2460. %lasttstamp = DbLog_explode_datetime($lastd[$i], ());
  2461. }
  2462. # 04 01
  2463. # 06 23
  2464. if("$tstamp{hour}" ne "$lasttstamp{hour}") {
  2465. # Aenderung der stunde, Berechne Delta
  2466. #wenn die Stundendifferenz größer 1 ist muss ein Dummyeintrag erstellt werden
  2467. $retvaldummy = "";
  2468. if(($tstamp{hour}-$lasttstamp{hour}) > 1) {
  2469. for (my $j=$lasttstamp{hour}+1; $j < $tstamp{hour}; $j++) {
  2470. $out_value = "0";
  2471. $hour = $j;
  2472. $hour = '0'.$j if $j<10;
  2473. $cnt[$i]++;
  2474. $out_tstamp = DbLog_implode_datetime($tstamp{year}, $tstamp{month}, $tstamp{day}, $hour, "30", "00");
  2475. if ($outf =~ m/(all)/) {
  2476. # Timestamp: Device, Type, Event, Reading, Value, Unit
  2477. $retvaldummy .= sprintf("%s: %s, %s, %s, %s, %s, %s\n", $out_tstamp, $sql_device, $type, $event, $sql_reading, $out_value, $unit);
  2478. } elsif ($outf =~ m/(array)/) {
  2479. push(@ReturnArray, {"tstamp" => $out_tstamp, "device" => $sql_device, "type" => $type, "event" => $event, "reading" => $sql_reading, "value" => $out_value, "unit" => $unit});
  2480. } else {
  2481. $out_tstamp =~ s/\ /_/g; #needed by generating plots
  2482. $retvaldummy .= "$out_tstamp $out_value\n";
  2483. }
  2484. }
  2485. }
  2486. if(($tstamp{hour}-$lasttstamp{hour}) < 0) {
  2487. for (my $j=0; $j < $tstamp{hour}; $j++) {
  2488. $out_value = "0";
  2489. $hour = $j;
  2490. $hour = '0'.$j if $j<10;
  2491. $cnt[$i]++;
  2492. $out_tstamp = DbLog_implode_datetime($tstamp{year}, $tstamp{month}, $tstamp{day}, $hour, "30", "00");
  2493. if ($outf =~ m/(all)/) {
  2494. # Timestamp: Device, Type, Event, Reading, Value, Unit
  2495. $retvaldummy .= sprintf("%s: %s, %s, %s, %s, %s, %s\n", $out_tstamp, $sql_device, $type, $event, $sql_reading, $out_value, $unit);
  2496. } elsif ($outf =~ m/(array)/) {
  2497. push(@ReturnArray, {"tstamp" => $out_tstamp, "device" => $sql_device, "type" => $type, "event" => $event, "reading" => $sql_reading, "value" => $out_value, "unit" => $unit});
  2498. } else {
  2499. $out_tstamp =~ s/\ /_/g; #needed by generating plots
  2500. $retvaldummy .= "$out_tstamp $out_value\n";
  2501. }
  2502. }
  2503. }
  2504. $out_value = sprintf("%g", $maxval - $minval);
  2505. $sum[$i] += $out_value;
  2506. $cnt[$i]++;
  2507. $out_tstamp = DbLog_implode_datetime($lasttstamp{year}, $lasttstamp{month}, $lasttstamp{day}, $lasttstamp{hour}, "30", "00");
  2508. #$minval = (~0 >> 1);
  2509. $minval = $maxval;
  2510. # $maxval = -(~0 >> 1);
  2511. $writeout=1;
  2512. }
  2513. } elsif ($readings[$i]->[3] && $readings[$i]->[3] eq "delta-d") {
  2514. #Berechnung eines Tageswertes
  2515. %tstamp = DbLog_explode_datetime($sql_timestamp, ());
  2516. if($lastd[$i] eq "undef") {
  2517. %lasttstamp = DbLog_explode_datetime($sql_timestamp, ());
  2518. } else {
  2519. %lasttstamp = DbLog_explode_datetime($lastd[$i], ());
  2520. }
  2521. if("$tstamp{day}" ne "$lasttstamp{day}") {
  2522. # Aenderung des Tages, Berechne Delta
  2523. $out_value = sprintf("%g", $maxval - $minval);
  2524. $sum[$i] += $out_value;
  2525. $cnt[$i]++;
  2526. $out_tstamp = DbLog_implode_datetime($lasttstamp{year}, $lasttstamp{month}, $lasttstamp{day}, "12", "00", "00");
  2527. # $minval = (~0 >> 1);
  2528. $minval = $maxval;
  2529. # $maxval = -(~0 >> 1);
  2530. $writeout=1;
  2531. }
  2532. } else {
  2533. $out_value = $sql_value;
  2534. $out_tstamp = $sql_timestamp;
  2535. $writeout=1;
  2536. }
  2537. # Wenn Attr SuppressUndef gesetzt ist, dann ausfiltern aller undef-Werte
  2538. $writeout = 0 if (!defined($sql_value) && AttrVal($hash->{NAME}, "suppressUndef", 0));
  2539. ###################### Ausgabe ###########################
  2540. if($writeout) {
  2541. if ($outf =~ m/(all)/) {
  2542. # Timestamp: Device, Type, Event, Reading, Value, Unit
  2543. $retval .= sprintf("%s: %s, %s, %s, %s, %s, %s\n", $out_tstamp, $sql_device, $type, $event, $sql_reading, $out_value, $unit);
  2544. $retval .= $retvaldummy;
  2545. } elsif ($outf =~ m/(array)/) {
  2546. push(@ReturnArray, {"tstamp" => $out_tstamp, "device" => $sql_device, "type" => $type, "event" => $event, "reading" => $sql_reading, "value" => $out_value, "unit" => $unit});
  2547. } else {
  2548. $out_tstamp =~ s/\ /_/g; #needed by generating plots
  2549. $retval .= "$out_tstamp $out_value\n";
  2550. $retval .= $retvaldummy;
  2551. }
  2552. }
  2553. if(Scalar::Util::looks_like_number($sql_value)){
  2554. #nur setzen wenn nummerisch
  2555. if($deltacalc) {
  2556. if(Scalar::Util::looks_like_number($out_value)){
  2557. if($out_value < $min[$i]) {
  2558. $min[$i] = $out_value;
  2559. $mind[$i] = $out_tstamp;
  2560. }
  2561. if($out_value > $max[$i]) {
  2562. $max[$i] = $out_value;
  2563. $maxd[$i] = $out_tstamp;
  2564. }
  2565. }
  2566. $maxval = $sql_value;
  2567. } else {
  2568. if($sql_value < $min[$i]) {
  2569. $min[$i] = $sql_value;
  2570. $mind[$i] = $sql_timestamp;
  2571. }
  2572. if($sql_value > $max[$i]) {
  2573. $max[$i] = $sql_value;
  2574. $maxd[$i] = $sql_timestamp;
  2575. }
  2576. $sum[$i] += $sql_value;
  2577. $minval = $sql_value if($sql_value < $minval);
  2578. $maxval = $sql_value if($sql_value > $maxval);
  2579. }
  2580. } else {
  2581. $min[$i] = 0;
  2582. $max[$i] = 0;
  2583. $sum[$i] = 0;
  2584. $minval = 0;
  2585. $maxval = 0;
  2586. }
  2587. if(!$deltacalc) {
  2588. $cnt[$i]++;
  2589. $lastv[$i] = $sql_value;
  2590. } else {
  2591. $lastv[$i] = $out_value if($out_value);
  2592. }
  2593. $lastd[$i] = $sql_timestamp;
  2594. }
  2595. } #while fetchrow
  2596. ######## den letzten Abschlusssatz rausschreiben ##########
  2597. if($readings[$i]->[3] && ($readings[$i]->[3] eq "delta-h" || $readings[$i]->[3] eq "delta-d")) {
  2598. if($lastd[$i] eq "undef") {
  2599. $out_value = "0";
  2600. $out_tstamp = DbLog_implode_datetime($from_datetime{year}, $from_datetime{month}, $from_datetime{day}, $from_datetime{hour}, "30", "00") if($readings[$i]->[3] eq "delta-h");
  2601. $out_tstamp = DbLog_implode_datetime($from_datetime{year}, $from_datetime{month}, $from_datetime{day}, "12", "00", "00") if($readings[$i]->[3] eq "delta-d");
  2602. } else {
  2603. %lasttstamp = DbLog_explode_datetime($lastd[$i], ());
  2604. $out_value = sprintf("%g", $maxval - $minval);
  2605. $out_tstamp = DbLog_implode_datetime($lasttstamp{year}, $lasttstamp{month}, $lasttstamp{day}, $lasttstamp{hour}, "30", "00") if($readings[$i]->[3] eq "delta-h");
  2606. $out_tstamp = DbLog_implode_datetime($lasttstamp{year}, $lasttstamp{month}, $lasttstamp{day}, "12", "00", "00") if($readings[$i]->[3] eq "delta-d");
  2607. }
  2608. $sum[$i] += $out_value;
  2609. $cnt[$i]++;
  2610. if($outf =~ m/(all)/) {
  2611. $retval .= sprintf("%s: %s %s %s %s %s %s\n", $out_tstamp, $sql_device, $type, $event, $sql_reading, $out_value, $unit);
  2612. } elsif ($outf =~ m/(array)/) {
  2613. push(@ReturnArray, {"tstamp" => $out_tstamp, "device" => $sql_device, "type" => $type, "event" => $event, "reading" => $sql_reading, "value" => $out_value, "unit" => $unit});
  2614. } else {
  2615. $out_tstamp =~ s/\ /_/g; #needed by generating plots
  2616. $retval .= "$out_tstamp $out_value\n";
  2617. }
  2618. }
  2619. # DatenTrenner setzen
  2620. $retval .= "#$readings[$i]->[0]";
  2621. $retval .= ":";
  2622. $retval .= "$readings[$i]->[1]" if($readings[$i]->[1]);
  2623. $retval .= ":";
  2624. $retval .= "$readings[$i]->[2]" if($readings[$i]->[2]);
  2625. $retval .= ":";
  2626. $retval .= "$readings[$i]->[3]" if($readings[$i]->[3]);
  2627. $retval .= ":";
  2628. $retval .= "$readings[$i]->[4]" if($readings[$i]->[4]);
  2629. $retval .= "\n";
  2630. } #for @readings
  2631. #Ueberfuehren der gesammelten Werte in die globale Variable %data
  2632. for(my $j=0; $j<int(@readings); $j++) {
  2633. my $k = $j+1;
  2634. $data{"min$k"} = $min[$j];
  2635. $data{"max$k"} = $max[$j];
  2636. $data{"avg$k"} = $cnt[$j] ? sprintf("%0.2f", $sum[$j]/$cnt[$j]) : 0;
  2637. $data{"sum$k"} = $sum[$j];
  2638. $data{"cnt$k"} = $cnt[$j];
  2639. $data{"currval$k"} = $lastv[$j];
  2640. $data{"currdate$k"} = $lastd[$j];
  2641. $data{"mindate$k"} = $mind[$j];
  2642. $data{"maxdate$k"} = $maxd[$j];
  2643. }
  2644. #cleanup (plotfork) connection
  2645. $dbh->disconnect() if( $hash->{PID} != $$ );
  2646. if($internal) {
  2647. $internal_data = \$retval;
  2648. return undef;
  2649. } elsif($outf =~ m/(array)/) {
  2650. return @ReturnArray;
  2651. } else {
  2652. $retval = Encode::encode_utf8($retval) if($utf8);
  2653. # Log3 $name, 5, "DbLog $name -> Result of get:\n$retval";
  2654. return $retval;
  2655. }
  2656. }
  2657. ##########################################################################
  2658. #
  2659. # Konfigurationscheck DbLog <-> Datenbank
  2660. #
  2661. ##########################################################################
  2662. sub DbLog_configcheck($) {
  2663. my ($hash)= @_;
  2664. my $name = $hash->{NAME};
  2665. my $dbmodel = $hash->{MODEL};
  2666. my $dbconn = $hash->{dbconn};
  2667. my $dbname = (split(/;|=/, $dbconn))[1];
  2668. my ($check, $rec,%dbconfig);
  2669. ### Start
  2670. #######################################################################
  2671. $check = "<html>";
  2672. $check .= "<u><b>Result of DbLog version check</u></b><br><br>";
  2673. $check .= "Used DbLog version: $hash->{VERSION} <br>";
  2674. $check .= "<b>Recommendation:</b> Your running version may be the current one. Please check for updates of DbLog periodically. <br><br>";
  2675. ### Configuration read check
  2676. #######################################################################
  2677. $check .= "<u><b>Result of configuration read check</u></b><br><br>";
  2678. my $st = configDBUsed()?"configDB (don't forget upload configuration file if changed. Use \"configdb filelist\" and look for your configuration file.)":"file";
  2679. $check .= "Connection parameter store type: $st <br>";
  2680. my ($err, @config) = FileRead($hash->{CONFIGURATION});
  2681. if (!$err) {
  2682. eval join("\n", @config);
  2683. $rec = "parameter: ";
  2684. $rec .= "Connection -> could not read, " if (!defined $dbconfig{connection});
  2685. $rec .= "Connection -> ".$dbconfig{connection}.", " if (defined $dbconfig{connection});
  2686. $rec .= "User -> could not read, " if (!defined $dbconfig{user});
  2687. $rec .= "User -> ".$dbconfig{user}.", " if (defined $dbconfig{user});
  2688. $rec .= "Password -> could not read " if (!defined $dbconfig{password});
  2689. $rec .= "Password -> read o.k. " if (defined $dbconfig{password});
  2690. } else {
  2691. $rec = $err;
  2692. }
  2693. $check .= "Connection $rec <br><br>";
  2694. ### Connection und Encoding check
  2695. #######################################################################
  2696. my (@ce,@se);
  2697. my ($chutf8mod,$chutf8dat);
  2698. if($dbmodel =~ /MYSQL/) {
  2699. @ce = DbLog_sqlget($hash,"SHOW VARIABLES LIKE 'character_set_connection'");
  2700. $chutf8mod = @ce?uc($ce[1]):"no result";
  2701. @se = DbLog_sqlget($hash,"SHOW VARIABLES LIKE 'character_set_database'");
  2702. $chutf8dat = @se?uc($se[1]):"no result";
  2703. if($chutf8mod eq $chutf8dat) {
  2704. $rec = "settings o.k.";
  2705. } else {
  2706. $rec = "Both encodings should be identical. You can adjust the usage of UTF8 connection by setting the UTF8 parameter in file '$hash->{CONFIGURATION}' to the right value. ";
  2707. }
  2708. }
  2709. if($dbmodel =~ /POSTGRESQL/) {
  2710. @ce = DbLog_sqlget($hash,"SHOW CLIENT_ENCODING");
  2711. $chutf8mod = @ce?uc($ce[0]):"no result";
  2712. @se = DbLog_sqlget($hash,"select character_set_name from information_schema.character_sets");
  2713. $chutf8dat = @se?uc($se[0]):"no result";
  2714. if($chutf8mod eq $chutf8dat) {
  2715. $rec = "settings o.k.";
  2716. } else {
  2717. $rec = "This is only an information. PostgreSQL supports automatic character set conversion between server and client for certain character set combinations. The conversion information is stored in the pg_conversion system catalog. PostgreSQL comes with some predefined conversions.";
  2718. }
  2719. }
  2720. if($dbmodel =~ /SQLITE/) {
  2721. @ce = DbLog_sqlget($hash,"PRAGMA encoding");
  2722. $chutf8dat = @ce?uc($ce[0]):"no result";
  2723. @se = DbLog_sqlget($hash,"PRAGMA table_info(history)");
  2724. $rec = "This is only an information about text encoding used by the main database.";
  2725. }
  2726. $check .= "<u><b>Result of connection check</u></b><br><br>";
  2727. if(@ce && @se) {
  2728. $check .= "Connection to database $dbname successfully done. <br>";
  2729. $check .= "<b>Recommendation:</b> settings o.k. <br><br>";
  2730. }
  2731. if(!@ce || !@se) {
  2732. $check .= "Connection to database was not successful. <br>";
  2733. $check .= "<b>Recommendation:</b> Plese check logfile for further information. <br><br>";
  2734. # $check .= "</html>";
  2735. return $check;
  2736. }
  2737. $check .= "<u><b>Result of encoding check</u></b><br><br>";
  2738. $check .= "Encoding used by Client (connection): $chutf8mod <br>" if($dbmodel !~ /SQLITE/);
  2739. $check .= "Encoding used by DB $dbname: $chutf8dat <br>";
  2740. $check .= "<b>Recommendation:</b> $rec <br><br>";
  2741. ### Check Betriebsmodus
  2742. #######################################################################
  2743. my $mode = $hash->{MODE};
  2744. my $sfx = AttrVal("global", "language", "EN");
  2745. $sfx = ($sfx eq "EN" ? "" : "_$sfx");
  2746. $check .= "<u><b>Result of logmode check</u></b><br><br>";
  2747. $check .= "Logmode of DbLog-device $name is: $mode <br>";
  2748. if($mode =~ /asynchronous/) {
  2749. my $max = AttrVal("global", "blockingCallMax", 0);
  2750. if(!$max || $max >= 6) {
  2751. $rec = "settings o.k.";
  2752. } else {
  2753. $rec = "WARNING - you are running asynchronous mode that is recommended, but the value of global device attribute \"blockingCallMax\" is set quite small. <br>";
  2754. $rec .= "This may cause problems in operation. It is recommended to <b>increase</b> the <b>global blockingCallMax</b> attribute.";
  2755. }
  2756. } else {
  2757. $rec = "Switch $name to the asynchronous logmode by setting the 'asyncMode' attribute. The advantage of this mode is to log events non-blocking. <br>";
  2758. $rec .= "There are attributes 'syncInterval' and 'cacheLimit' relevant for this working mode. <br>";
  2759. $rec .= "Please refer to commandref for further informations about these attributes.";
  2760. }
  2761. $check .= "<b>Recommendation:</b> $rec <br><br>";
  2762. if($mode =~ /asynchronous/) {
  2763. my $shutdownWait = AttrVal($name,"shutdownWait",undef);
  2764. my $bpt = ReadingsVal($name,"background_processing_time",undef);
  2765. my $bptv = defined($bpt)?int($bpt)+2:2;
  2766. # $shutdownWait = defined($shutdownWait)?$shutdownWait:undef;
  2767. my $sdw = defined($shutdownWait)?$shutdownWait:" ";
  2768. $check .= "<u><b>Result of shutdown sequence preparation check</u></b><br><br>";
  2769. $check .= "Attribute \"shutdownWait\" is set to: $sdw<br>";
  2770. if(!defined($shutdownWait) || $shutdownWait < $bptv) {
  2771. if(!$bpt) {
  2772. $rec = "Due to Reading \"background_processing_time\" is not available (you may set attribute \"showproctime\"), there is only a rough estimate to<br>";
  2773. $rec .= "set attribute \"shutdownWait\" to $bptv seconds.<br>";
  2774. } else {
  2775. $rec = "Please set this attribute at least to $bptv seconds to avoid data loss when system shutdown is initiated.";
  2776. }
  2777. } else {
  2778. if(!$bpt) {
  2779. $rec = "The setting may be ok. But due to the Reading \"background_processing_time\" is not available (you may set attribute \"showproctime\"), the current <br>";
  2780. $rec .= "setting is only a rough estimate.<br>";
  2781. } else {
  2782. $rec = "settings o.k.";
  2783. }
  2784. }
  2785. $check .= "<b>Recommendation:</b> $rec <br><br>";
  2786. }
  2787. ### Check Plot Erstellungsmodus
  2788. #######################################################################
  2789. $check .= "<u><b>Result of plot generation method check</u></b><br><br>";
  2790. my @webdvs = devspec2array("TYPE=FHEMWEB:FILTER=STATE=Initialized");
  2791. my $forks = 1;
  2792. my $wall;
  2793. foreach (@webdvs) {
  2794. my $web = $_;
  2795. $wall .= $web.": plotfork=".AttrVal($web,"plotfork",0)."<br>";
  2796. $forks = 0 if(!AttrVal($web,"plotfork",0));
  2797. }
  2798. if(!$forks) {
  2799. $check .= "WARNING - at least one of your FHEMWEB devices have attribute \"plotfork = 1\" not set. This may cause blocking situations when creating plots. <br>";
  2800. $check .= $wall;
  2801. $rec = "You should set attribute \"plotfork = 1\" in relevant devices";
  2802. } else {
  2803. $check .= $wall;
  2804. $rec = "settings o.k.";
  2805. }
  2806. $check .= "<b>Recommendation:</b> $rec <br><br>";
  2807. ### Check Spaltenbreite history
  2808. #######################################################################
  2809. my (@sr_dev,@sr_typ,@sr_evt,@sr_rdg,@sr_val,@sr_unt);
  2810. my ($cdat_dev,$cdat_typ,$cdat_evt,$cdat_rdg,$cdat_val,$cdat_unt);
  2811. my ($cmod_dev,$cmod_typ,$cmod_evt,$cmod_rdg,$cmod_val,$cmod_unt);
  2812. if($dbmodel =~ /MYSQL/) {
  2813. @sr_dev = DbLog_sqlget($hash,"SHOW FIELDS FROM history where FIELD='DEVICE'");
  2814. @sr_typ = DbLog_sqlget($hash,"SHOW FIELDS FROM history where FIELD='TYPE'");
  2815. @sr_evt = DbLog_sqlget($hash,"SHOW FIELDS FROM history where FIELD='EVENT'");
  2816. @sr_rdg = DbLog_sqlget($hash,"SHOW FIELDS FROM history where FIELD='READING'");
  2817. @sr_val = DbLog_sqlget($hash,"SHOW FIELDS FROM history where FIELD='VALUE'");
  2818. @sr_unt = DbLog_sqlget($hash,"SHOW FIELDS FROM history where FIELD='UNIT'");
  2819. }
  2820. if($dbmodel =~ /POSTGRESQL/) {
  2821. @sr_dev = DbLog_sqlget($hash,"select column_name,character_maximum_length from information_schema.columns where table_name='history' and column_name='device'");
  2822. @sr_typ = DbLog_sqlget($hash,"select column_name,character_maximum_length from information_schema.columns where table_name='history' and column_name='type'");
  2823. @sr_evt = DbLog_sqlget($hash,"select column_name,character_maximum_length from information_schema.columns where table_name='history' and column_name='event'");
  2824. @sr_rdg = DbLog_sqlget($hash,"select column_name,character_maximum_length from information_schema.columns where table_name='history' and column_name='reading'");
  2825. @sr_val = DbLog_sqlget($hash,"select column_name,character_maximum_length from information_schema.columns where table_name='history' and column_name='value'");
  2826. @sr_unt = DbLog_sqlget($hash,"select column_name,character_maximum_length from information_schema.columns where table_name='history' and column_name='unit'");
  2827. }
  2828. if($dbmodel =~ /SQLITE/) {
  2829. my $dev = (DbLog_sqlget($hash,"SELECT sql FROM sqlite_master WHERE name = 'history'"))[0];
  2830. $cdat_dev = $dev?$dev:"no result";
  2831. $cdat_typ = $cdat_evt = $cdat_rdg = $cdat_val = $cdat_unt = $cdat_dev;
  2832. $cdat_dev =~ s/.*DEVICE.varchar\(([\d]*)\).*/$1/e;
  2833. $cdat_typ =~ s/.*TYPE.varchar\(([\d]*)\).*/$1/e;
  2834. $cdat_evt =~ s/.*EVENT.varchar\(([\d]*)\).*/$1/e;
  2835. $cdat_rdg =~ s/.*READING.varchar\(([\d]*)\).*/$1/e;
  2836. $cdat_val =~ s/.*VALUE.varchar\(([\d]*)\).*/$1/e;
  2837. $cdat_unt =~ s/.*UNIT.varchar\(([\d]*)\).*/$1/e;
  2838. }
  2839. if ($dbmodel !~ /SQLITE/) {
  2840. $cdat_dev = @sr_dev?($sr_dev[1]):"no result";
  2841. $cdat_dev =~ tr/varchar\(|\)//d if($cdat_dev ne "no result");
  2842. $cdat_typ = @sr_typ?($sr_typ[1]):"no result";
  2843. $cdat_typ =~ tr/varchar\(|\)//d if($cdat_typ ne "no result");
  2844. $cdat_evt = @sr_evt?($sr_evt[1]):"no result";
  2845. $cdat_evt =~ tr/varchar\(|\)//d if($cdat_evt ne "no result");
  2846. $cdat_rdg = @sr_rdg?($sr_rdg[1]):"no result";
  2847. $cdat_rdg =~ tr/varchar\(|\)//d if($cdat_rdg ne "no result");
  2848. $cdat_val = @sr_val?($sr_val[1]):"no result";
  2849. $cdat_val =~ tr/varchar\(|\)//d if($cdat_val ne "no result");
  2850. $cdat_unt = @sr_unt?($sr_unt[1]):"no result";
  2851. $cdat_unt =~ tr/varchar\(|\)//d if($cdat_unt ne "no result");
  2852. }
  2853. $cmod_dev = $hash->{HELPER}{DEVICECOL};
  2854. $cmod_typ = $hash->{HELPER}{TYPECOL};
  2855. $cmod_evt = $hash->{HELPER}{EVENTCOL};
  2856. $cmod_rdg = $hash->{HELPER}{READINGCOL};
  2857. $cmod_val = $hash->{HELPER}{VALUECOL};
  2858. $cmod_unt = $hash->{HELPER}{UNITCOL};
  2859. if($cdat_dev >= $cmod_dev && $cdat_typ >= $cmod_typ && $cdat_evt >= $cmod_evt && $cdat_rdg >= $cmod_rdg && $cdat_val >= $cmod_val && $cdat_unt >= $cmod_unt) {
  2860. $rec = "settings o.k.";
  2861. } else {
  2862. if ($dbmodel !~ /SQLITE/) {
  2863. $rec = "The relation between column width in table history and the field width used in device $name don't meet the requirements. ";
  2864. $rec .= "Please make sure that the width of database field definition is equal or larger than the field width used by the module. Compare the given results.<br>";
  2865. $rec .= "Currently the default values for field width are: <br><br>";
  2866. $rec .= "DEVICE: $columns{DEVICE} <br>";
  2867. $rec .= "TYPE: $columns{TYPE} <br>";
  2868. $rec .= "EVENT: $columns{EVENT} <br>";
  2869. $rec .= "READING: $columns{READING} <br>";
  2870. $rec .= "VALUE: $columns{VALUE} <br>";
  2871. $rec .= "UNIT: $columns{UNIT} <br><br>";
  2872. $rec .= "You can change the column width in database by a statement like <b>'alter table history modify VALUE varchar(128);</b>' (example for changing field 'VALUE'). ";
  2873. $rec .= "You can do it for example by executing 'sqlCmd' in DbRep or in a SQL-Editor of your choice. (switch $name to asynchron mode for non-blocking). <br>";
  2874. $rec .= "Alternatively the field width used by $name can be adjusted by setting attributes 'colEvent', 'colReading', 'colValue'. (pls. refer to commandref)";
  2875. } else {
  2876. $rec = "WARNING - The relation between column width in table history and the field width used by device $name should be equal but it differs.";
  2877. $rec .= "The field width used by $name can be adjusted by setting attributes 'colEvent', 'colReading', 'colValue'. (pls. refer to commandref)";
  2878. $rec .= "Because you use SQLite this is only a warning. Normally the database can handle these differences. ";
  2879. }
  2880. }
  2881. $check .= "<u><b>Result of table 'history' check</u></b><br><br>";
  2882. $check .= "Column width set in DB $dbname.history: 'DEVICE' = $cdat_dev, 'TYPE' = $cdat_typ, 'EVENT' = $cdat_evt, 'READING' = $cdat_rdg, 'VALUE' = $cdat_val, 'UNIT' = $cdat_unt <br>";
  2883. $check .= "Column width used by $name: 'DEVICE' = $cmod_dev, 'TYPE' = $cmod_typ, 'EVENT' = $cmod_evt, 'READING' = $cmod_rdg, 'VALUE' = $cmod_val, 'UNIT' = $cmod_unt <br>";
  2884. $check .= "<b>Recommendation:</b> $rec <br><br>";
  2885. ### Check Spaltenbreite current
  2886. #######################################################################
  2887. if($dbmodel =~ /MYSQL/) {
  2888. @sr_dev = DbLog_sqlget($hash,"SHOW FIELDS FROM current where FIELD='DEVICE'");
  2889. @sr_typ = DbLog_sqlget($hash,"SHOW FIELDS FROM current where FIELD='TYPE'");
  2890. @sr_evt = DbLog_sqlget($hash,"SHOW FIELDS FROM current where FIELD='EVENT'");
  2891. @sr_rdg = DbLog_sqlget($hash,"SHOW FIELDS FROM current where FIELD='READING'");
  2892. @sr_val = DbLog_sqlget($hash,"SHOW FIELDS FROM current where FIELD='VALUE'");
  2893. @sr_unt = DbLog_sqlget($hash,"SHOW FIELDS FROM current where FIELD='UNIT'");
  2894. }
  2895. if($dbmodel =~ /POSTGRESQL/) {
  2896. @sr_dev = DbLog_sqlget($hash,"select column_name,character_maximum_length from information_schema.columns where table_name='current' and column_name='device'");
  2897. @sr_typ = DbLog_sqlget($hash,"select column_name,character_maximum_length from information_schema.columns where table_name='current' and column_name='type'");
  2898. @sr_evt = DbLog_sqlget($hash,"select column_name,character_maximum_length from information_schema.columns where table_name='current' and column_name='event'");
  2899. @sr_rdg = DbLog_sqlget($hash,"select column_name,character_maximum_length from information_schema.columns where table_name='current' and column_name='reading'");
  2900. @sr_val = DbLog_sqlget($hash,"select column_name,character_maximum_length from information_schema.columns where table_name='current' and column_name='value'");
  2901. @sr_unt = DbLog_sqlget($hash,"select column_name,character_maximum_length from information_schema.columns where table_name='current' and column_name='unit'");
  2902. }
  2903. if($dbmodel =~ /SQLITE/) {
  2904. my $dev = (DbLog_sqlget($hash,"SELECT sql FROM sqlite_master WHERE name = 'current'"))[0];
  2905. $cdat_dev = $dev?$dev:"no result";
  2906. $cdat_typ = $cdat_evt = $cdat_rdg = $cdat_val = $cdat_unt = $cdat_dev;
  2907. $cdat_dev =~ s/.*DEVICE.varchar\(([\d]*)\).*/$1/e;
  2908. $cdat_typ =~ s/.*TYPE.varchar\(([\d]*)\).*/$1/e;
  2909. $cdat_evt =~ s/.*EVENT.varchar\(([\d]*)\).*/$1/e;
  2910. $cdat_rdg =~ s/.*READING.varchar\(([\d]*)\).*/$1/e;
  2911. $cdat_val =~ s/.*VALUE.varchar\(([\d]*)\).*/$1/e;
  2912. $cdat_unt =~ s/.*UNIT.varchar\(([\d]*)\).*/$1/e;
  2913. }
  2914. if ($dbmodel !~ /SQLITE/) {
  2915. $cdat_dev = @sr_dev?($sr_dev[1]):"no result";
  2916. $cdat_dev =~ tr/varchar\(|\)//d if($cdat_dev ne "no result");
  2917. $cdat_typ = @sr_typ?($sr_typ[1]):"no result";
  2918. $cdat_typ =~ tr/varchar\(|\)//d if($cdat_typ ne "no result");
  2919. $cdat_evt = @sr_evt?($sr_evt[1]):"no result";
  2920. $cdat_evt =~ tr/varchar\(|\)//d if($cdat_evt ne "no result");
  2921. $cdat_rdg = @sr_rdg?($sr_rdg[1]):"no result";
  2922. $cdat_rdg =~ tr/varchar\(|\)//d if($cdat_rdg ne "no result");
  2923. $cdat_val = @sr_val?($sr_val[1]):"no result";
  2924. $cdat_val =~ tr/varchar\(|\)//d if($cdat_val ne "no result");
  2925. $cdat_unt = @sr_unt?($sr_unt[1]):"no result";
  2926. $cdat_unt =~ tr/varchar\(|\)//d if($cdat_unt ne "no result");
  2927. }
  2928. $cmod_dev = $hash->{HELPER}{DEVICECOL};
  2929. $cmod_typ = $hash->{HELPER}{TYPECOL};
  2930. $cmod_evt = $hash->{HELPER}{EVENTCOL};
  2931. $cmod_rdg = $hash->{HELPER}{READINGCOL};
  2932. $cmod_val = $hash->{HELPER}{VALUECOL};
  2933. $cmod_unt = $hash->{HELPER}{UNITCOL};
  2934. if($cdat_dev >= $cmod_dev && $cdat_typ >= $cmod_typ && $cdat_evt >= $cmod_evt && $cdat_rdg >= $cmod_rdg && $cdat_val >= $cmod_val && $cdat_unt >= $cmod_unt) {
  2935. $rec = "settings o.k.";
  2936. } else {
  2937. if ($dbmodel !~ /SQLITE/) {
  2938. $rec = "The relation between column width in table current and the field width used in device $name don't meet the requirements. ";
  2939. $rec .= "Please make sure that the width of database field definition is equal or larger than the field width used by the module. Compare the given results.<br>";
  2940. $rec .= "Currently the default values for field width are: <br><br>";
  2941. $rec .= "DEVICE: $columns{DEVICE} <br>";
  2942. $rec .= "TYPE: $columns{TYPE} <br>";
  2943. $rec .= "EVENT: $columns{EVENT} <br>";
  2944. $rec .= "READING: $columns{READING} <br>";
  2945. $rec .= "VALUE: $columns{VALUE} <br>";
  2946. $rec .= "UNIT: $columns{UNIT} <br><br>";
  2947. $rec .= "You can change the column width in database by a statement like <b>'alter table current modify VALUE varchar(128);</b>' (example for changing field 'VALUE'). ";
  2948. $rec .= "You can do it for example by executing 'sqlCmd' in DbRep or in a SQL-Editor of your choice. (switch $name to asynchron mode for non-blocking). <br>";
  2949. $rec .= "Alternatively the field width used by $name can be adjusted by setting attributes 'colEvent', 'colReading', 'colValue'. (pls. refer to commandref)";
  2950. } else {
  2951. $rec = "WARNING - The relation between column width in table current and the field width used by device $name should be equal but it differs. ";
  2952. $rec .= "The field width used by $name can be adjusted by setting attributes 'colEvent', 'colReading', 'colValue'. (pls. refer to commandref)";
  2953. $rec .= "Because you use SQLite this is only a warning. Normally the database can handle these differences. ";
  2954. }
  2955. }
  2956. $check .= "<u><b>Result of table 'current' check</u></b><br><br>";
  2957. $check .= "Column width set in DB $dbname.current: 'DEVICE' = $cdat_dev, 'TYPE' = $cdat_typ, 'EVENT' = $cdat_evt, 'READING' = $cdat_rdg, 'VALUE' = $cdat_val, 'UNIT' = $cdat_unt <br>";
  2958. $check .= "Column width used by $name: 'DEVICE' = $cmod_dev, 'TYPE' = $cmod_typ, 'EVENT' = $cmod_evt, 'READING' = $cmod_rdg, 'VALUE' = $cmod_val, 'UNIT' = $cmod_unt <br>";
  2959. $check .= "<b>Recommendation:</b> $rec <br><br>";
  2960. #}
  2961. ### Check Vorhandensein Search_Idx mit den empfohlenen Spalten
  2962. #######################################################################
  2963. my (@six,@six_dev,@six_rdg,@six_tsp);
  2964. my ($idef,$idef_dev,$idef_rdg,$idef_tsp);
  2965. $check .= "<u><b>Result of check 'Search_Idx' availability</u></b><br><br>";
  2966. if($dbmodel =~ /MYSQL/) {
  2967. @six = DbLog_sqlget($hash,"SHOW INDEX FROM history where Key_name='Search_Idx'");
  2968. if (!@six) {
  2969. $check .= "The index 'Search_Idx' is missing. <br>";
  2970. $rec = "You can create the index by executing statement <b>'CREATE INDEX Search_Idx ON `history` (DEVICE, READING, TIMESTAMP) USING BTREE;'</b> <br>";
  2971. $rec .= "Depending on your database size this command may running a long time. <br>";
  2972. $rec .= "Please make sure the device '$name' is operating in asynchronous mode to avoid FHEM from blocking when creating the index. <br>";
  2973. $rec .= "<b>Note:</b> If you have just created another index which covers the same fields and order as suggested (e.g. a primary key) you don't need to create the 'Search_Idx' as well ! <br>";
  2974. } else {
  2975. @six_dev = DbLog_sqlget($hash,"SHOW INDEX FROM history where Key_name='Search_Idx' and Column_name='DEVICE'");
  2976. @six_rdg = DbLog_sqlget($hash,"SHOW INDEX FROM history where Key_name='Search_Idx' and Column_name='READING'");
  2977. @six_tsp = DbLog_sqlget($hash,"SHOW INDEX FROM history where Key_name='Search_Idx' and Column_name='TIMESTAMP'");
  2978. if (@six_dev && @six_rdg && @six_tsp) {
  2979. $check .= "Index 'Search_Idx' exists and contains recommended fields 'DEVICE', 'READING', 'TIMESTAMP'. <br>";
  2980. $rec = "settings o.k.";
  2981. } else {
  2982. $check .= "Index 'Search_Idx' exists but doesn't contain recommended field 'DEVICE'. <br>" if (!@six_dev);
  2983. $check .= "Index 'Search_Idx' exists but doesn't contain recommended field 'READING'. <br>" if (!@six_rdg);
  2984. $check .= "Index 'Search_Idx' exists but doesn't contain recommended field 'TIMESTAMP'. <br>" if (!@six_tsp);
  2985. $rec = "The index should contain the fields 'DEVICE', 'READING', 'TIMESTAMP'. ";
  2986. $rec .= "You can change the index by executing e.g. <br>";
  2987. $rec .= "<b>'ALTER TABLE `history` DROP INDEX `Search_Idx`, ADD INDEX `Search_Idx` (`DEVICE`, `READING`, `TIMESTAMP`) USING BTREE;'</b> <br>";
  2988. $rec .= "Depending on your database size this command may running a long time. <br>";
  2989. }
  2990. }
  2991. }
  2992. if($dbmodel =~ /POSTGRESQL/) {
  2993. @six = DbLog_sqlget($hash,"SELECT * FROM pg_indexes WHERE tablename='history' and indexname ='Search_Idx'");
  2994. if (!@six) {
  2995. $check .= "The index 'Search_Idx' is missing. <br>";
  2996. $rec = "You can create the index by executing statement <b>'CREATE INDEX \"Search_Idx\" ON history USING btree (device, reading, \"timestamp\")'</b> <br>";
  2997. $rec .= "Depending on your database size this command may running a long time. <br>";
  2998. $rec .= "Please make sure the device '$name' is operating in asynchronous mode to avoid FHEM from blocking when creating the index. <br>";
  2999. $rec .= "<b>Note:</b> If you have just created another index which covers the same fields and order as suggested (e.g. a primary key) you don't need to create the 'Search_Idx' as well ! <br>";
  3000. } else {
  3001. $idef = $six[4];
  3002. $idef_dev = 1 if($idef =~ /device/);
  3003. $idef_rdg = 1 if($idef =~ /reading/);
  3004. $idef_tsp = 1 if($idef =~ /timestamp/);
  3005. if ($idef_dev && $idef_rdg && $idef_tsp) {
  3006. $check .= "Index 'Search_Idx' exists and contains recommended fields 'DEVICE', 'READING', 'TIMESTAMP'. <br>";
  3007. $rec = "settings o.k.";
  3008. } else {
  3009. $check .= "Index 'Search_Idx' exists but doesn't contain recommended field 'DEVICE'. <br>" if (!$idef_dev);
  3010. $check .= "Index 'Search_Idx' exists but doesn't contain recommended field 'READING'. <br>" if (!$idef_rdg);
  3011. $check .= "Index 'Search_Idx' exists but doesn't contain recommended field 'TIMESTAMP'. <br>" if (!$idef_tsp);
  3012. $rec = "The index should contain the fields 'DEVICE', 'READING', 'TIMESTAMP'. ";
  3013. $rec .= "You can change the index by executing e.g. <br>";
  3014. $rec .= "<b>'DROP INDEX \"Search_Idx\"; CREATE INDEX \"Search_Idx\" ON history USING btree (device, reading, \"timestamp\")'</b> <br>";
  3015. $rec .= "Depending on your database size this command may running a long time. <br>";
  3016. }
  3017. }
  3018. }
  3019. if($dbmodel =~ /SQLITE/) {
  3020. @six = DbLog_sqlget($hash,"SELECT name,sql FROM sqlite_master WHERE type='index' AND name='Search_Idx'");
  3021. if (!$six[0]) {
  3022. $check .= "The index 'Search_Idx' is missing. <br>";
  3023. $rec = "You can create the index by executing statement <b>'CREATE INDEX Search_Idx ON `history` (DEVICE, READING, TIMESTAMP)'</b> <br>";
  3024. $rec .= "Depending on your database size this command may running a long time. <br>";
  3025. $rec .= "Please make sure the device '$name' is operating in asynchronous mode to avoid FHEM from blocking when creating the index. <br>";
  3026. $rec .= "<b>Note:</b> If you have just created another index which covers the same fields and order as suggested (e.g. a primary key) you don't need to create the 'Search_Idx' as well ! <br>";
  3027. } else {
  3028. $idef = $six[1];
  3029. $idef_dev = 1 if(lc($idef) =~ /device/);
  3030. $idef_rdg = 1 if(lc($idef) =~ /reading/);
  3031. $idef_tsp = 1 if(lc($idef) =~ /timestamp/);
  3032. if ($idef_dev && $idef_rdg && $idef_tsp) {
  3033. $check .= "Index 'Search_Idx' exists and contains recommended fields 'DEVICE', 'READING', 'TIMESTAMP'. <br>";
  3034. $rec = "settings o.k.";
  3035. } else {
  3036. $check .= "Index 'Search_Idx' exists but doesn't contain recommended field 'DEVICE'. <br>" if (!$idef_dev);
  3037. $check .= "Index 'Search_Idx' exists but doesn't contain recommended field 'READING'. <br>" if (!$idef_rdg);
  3038. $check .= "Index 'Search_Idx' exists but doesn't contain recommended field 'TIMESTAMP'. <br>" if (!$idef_tsp);
  3039. $rec = "The index should contain the fields 'DEVICE', 'READING', 'TIMESTAMP'. ";
  3040. $rec .= "You can change the index by executing e.g. <br>";
  3041. $rec .= "<b>'DROP INDEX \"Search_Idx\"; CREATE INDEX Search_Idx ON `history` (DEVICE, READING, TIMESTAMP)'</b> <br>";
  3042. $rec .= "Depending on your database size this command may running a long time. <br>";
  3043. }
  3044. }
  3045. }
  3046. $check .= "<b>Recommendation:</b> $rec <br><br>";
  3047. ### Check Index Report_Idx für DbRep-Device falls DbRep verwendet wird
  3048. #######################################################################
  3049. my ($dbrp,$irep,);
  3050. my (@dix,@dix_rdg,@dix_tsp,$irep_rdg,$irep_tsp);
  3051. my $isused = 0;
  3052. my @repdvs = devspec2array("TYPE=DbRep");
  3053. $check .= "<u><b>Result of check 'Report_Idx' availability for DbRep-devices</u></b><br><br>";
  3054. foreach (@repdvs) {
  3055. $dbrp = $_;
  3056. if(!$defs{$dbrp}) {
  3057. Log3 ($name, 2, "DbLog $name -> Device '$dbrp' found by configCheck doesn't exist !");
  3058. next;
  3059. }
  3060. if ($defs{$dbrp}->{DEF} eq $name) {
  3061. # DbRep Device verwendet aktuelles DbLog-Device
  3062. Log3 ($name, 5, "DbLog $name -> DbRep-Device '$dbrp' uses $name.");
  3063. $isused = 1;
  3064. }
  3065. }
  3066. if ($isused) {
  3067. if($dbmodel =~ /MYSQL/) {
  3068. @dix = DbLog_sqlget($hash,"SHOW INDEX FROM history where Key_name='Report_Idx'");
  3069. if (!@dix) {
  3070. $check .= "At least one DbRep-device assigned to $name is used, but the recommended index 'Report_Idx' is missing. <br>";
  3071. $rec = "You can create the index by executing statement <b>'CREATE INDEX Report_Idx ON `history` (TIMESTAMP, READING) USING BTREE;'</b> <br>";
  3072. $rec .= "Depending on your database size this command may running a long time. <br>";
  3073. $rec .= "Please make sure the device '$name' is operating in asynchronous mode to avoid FHEM from blocking when creating the index. <br>";
  3074. $rec .= "<b>Note:</b> If you have just created another index which covers the same fields and order as suggested (e.g. a primary key) you don't need to create the 'Report_Idx' as well ! <br>";
  3075. } else {
  3076. @dix_rdg = DbLog_sqlget($hash,"SHOW INDEX FROM history where Key_name='Report_Idx' and Column_name='READING'");
  3077. @dix_tsp = DbLog_sqlget($hash,"SHOW INDEX FROM history where Key_name='Report_Idx' and Column_name='TIMESTAMP'");
  3078. if (@dix_rdg && @dix_tsp) {
  3079. $check .= "At least one DbRep-device assigned to $name is used. ";
  3080. $check .= "Index 'Report_Idx' exists and contains recommended fields 'TIMESTAMP', 'READING'. <br>";
  3081. $rec = "settings o.k.";
  3082. } else {
  3083. $check .= "You use at least one DbRep-device assigned to $name. ";
  3084. $check .= "Index 'Report_Idx' exists but doesn't contain recommended field 'READING'. <br>" if (!@dix_rdg);
  3085. $check .= "Index 'Report_Idx' exists but doesn't contain recommended field 'TIMESTAMP'. <br>" if (!@dix_tsp);
  3086. $rec = "The index should contain the fields 'TIMESTAMP', 'READING'. ";
  3087. $rec .= "You can change the index by executing e.g. <br>";
  3088. $rec .= "<b>'ALTER TABLE `history` DROP INDEX `Report_Idx`, ADD INDEX `Report_Idx` (`TIMESTAMP`, `READING`) USING BTREE'</b> <br>";
  3089. $rec .= "Depending on your database size this command may running a long time. <br>";
  3090. }
  3091. }
  3092. }
  3093. if($dbmodel =~ /POSTGRESQL/) {
  3094. @dix = DbLog_sqlget($hash,"SELECT * FROM pg_indexes WHERE tablename='history' and indexname ='Report_Idx'");
  3095. if (!@dix) {
  3096. $check .= "You use at least one DbRep-device assigned to $name, but the recommended index 'Report_Idx' is missing. <br>";
  3097. $rec = "You can create the index by executing statement <b>'CREATE INDEX \"Report_Idx\" ON history USING btree (\"timestamp\", reading)'</b> <br>";
  3098. $rec .= "Depending on your database size this command may running a long time. <br>";
  3099. $rec .= "Please make sure the device '$name' is operating in asynchronous mode to avoid FHEM from blocking when creating the index. <br>";
  3100. $rec .= "<b>Note:</b> If you have just created another index which covers the same fields and order as suggested (e.g. a primary key) you don't need to create the 'Report_Idx' as well ! <br>";
  3101. } else {
  3102. $irep = $dix[4];
  3103. $irep_rdg = 1 if($irep =~ /reading/);
  3104. $irep_tsp = 1 if($irep =~ /timestamp/);
  3105. if ($irep_rdg && $irep_tsp) {
  3106. $check .= "Index 'Report_Idx' exists and contains recommended fields 'TIMESTAMP', 'READING'. <br>";
  3107. $rec = "settings o.k.";
  3108. } else {
  3109. $check .= "Index 'Report_Idx' exists but doesn't contain recommended field 'READING'. <br>" if (!$irep_rdg);
  3110. $check .= "Index 'Report_Idx' exists but doesn't contain recommended field 'TIMESTAMP'. <br>" if (!$irep_tsp);
  3111. $rec = "The index should contain the fields 'TIMESTAMP', 'READING'. ";
  3112. $rec .= "You can change the index by executing e.g. <br>";
  3113. $rec .= "<b>'DROP INDEX \"Report_Idx\"; CREATE INDEX \"Report_Idx\" ON history USING btree (\"timestamp\", reading)'</b> <br>";
  3114. $rec .= "Depending on your database size this command may running a long time. <br>";
  3115. }
  3116. }
  3117. }
  3118. if($dbmodel =~ /SQLITE/) {
  3119. @dix = DbLog_sqlget($hash,"SELECT name,sql FROM sqlite_master WHERE type='index' AND name='Report_Idx'");
  3120. if (!$dix[0]) {
  3121. $check .= "The index 'Report_Idx' is missing. <br>";
  3122. $rec = "You can create the index by executing statement <b>'CREATE INDEX Report_Idx ON `history` (TIMESTAMP, READING)'</b> <br>";
  3123. $rec .= "Depending on your database size this command may running a long time. <br>";
  3124. $rec .= "Please make sure the device '$name' is operating in asynchronous mode to avoid FHEM from blocking when creating the index. <br>";
  3125. $rec .= "<b>Note:</b> If you have just created another index which covers the same fields and order as suggested (e.g. a primary key) you don't need to create the 'Search_Idx' as well ! <br>";
  3126. } else {
  3127. $irep = $dix[1];
  3128. $irep_rdg = 1 if(lc($irep) =~ /reading/);
  3129. $irep_tsp = 1 if(lc($irep) =~ /timestamp/);
  3130. if ($irep_rdg && $irep_tsp) {
  3131. $check .= "Index 'Report_Idx' exists and contains recommended fields 'TIMESTAMP', 'READING'. <br>";
  3132. $rec = "settings o.k.";
  3133. } else {
  3134. $check .= "Index 'Report_Idx' exists but doesn't contain recommended field 'READING'. <br>" if (!$irep_rdg);
  3135. $check .= "Index 'Report_Idx' exists but doesn't contain recommended field 'TIMESTAMP'. <br>" if (!$irep_tsp);
  3136. $rec = "The index should contain the fields 'TIMESTAMP', 'READING'. ";
  3137. $rec .= "You can change the index by executing e.g. <br>";
  3138. $rec .= "<b>'DROP INDEX \"Report_Idx\"; CREATE INDEX Report_Idx ON `history` (TIMESTAMP, READING)'</b> <br>";
  3139. $rec .= "Depending on your database size this command may running a long time. <br>";
  3140. }
  3141. }
  3142. }
  3143. } else {
  3144. $check .= "No DbRep-device assigned to $name is used. Hence an index for DbRep isn't needed. <br>";
  3145. $rec = "settings o.k.";
  3146. }
  3147. $check .= "<b>Recommendation:</b> $rec <br><br>";
  3148. $check .= "</html>";
  3149. return $check;
  3150. }
  3151. sub DbLog_sqlget($$) {
  3152. my ($hash,$sql)= @_;
  3153. my $name = $hash->{NAME};
  3154. my ($dbh,$sth,@sr);
  3155. Log3 ($name, 4, "DbLog $name - Executing SQL: $sql");
  3156. $dbh = DbLog_ConnectNewDBH($hash);
  3157. return if(!$dbh);
  3158. eval { $sth = $dbh->prepare("$sql");
  3159. $sth->execute;
  3160. };
  3161. if($@) {
  3162. $dbh->disconnect if($dbh);
  3163. Log3 ($name, 2, "DbLog $name - $@");
  3164. return @sr;
  3165. }
  3166. @sr = $sth->fetchrow;
  3167. $sth->finish;
  3168. $dbh->disconnect;
  3169. no warnings 'uninitialized';
  3170. Log3 ($name, 4, "DbLog $name - SQL result: @sr");
  3171. use warnings;
  3172. return @sr;
  3173. }
  3174. #########################################################################################
  3175. #
  3176. # Addlog - einfügen des Readingwertes eines gegebenen Devices
  3177. #
  3178. #########################################################################################
  3179. sub DbLog_AddLog($$$) {
  3180. my ($hash,$devrdspec,$value)= @_;
  3181. my $name = $hash->{NAME};
  3182. my $async = AttrVal($name, "asyncMode", undef);
  3183. my $value_fn = AttrVal( $name, "valueFn", "" );
  3184. my $ce = AttrVal($name, "cacheEvents", 0);
  3185. my ($dev_type,$dev_name,$dev_reading,$read_val,$event,$ut);
  3186. my @row_array;
  3187. return if(IsDisabled($name) || !$hash->{HELPER}{COLSET} || $init_done != 1);
  3188. # Funktion aus Attr valueFn validieren
  3189. if( $value_fn =~ m/^\s*(\{.*\})\s*$/s ) {
  3190. $value_fn = $1;
  3191. } else {
  3192. $value_fn = '';
  3193. }
  3194. my $ts = TimeNow();
  3195. my $now = gettimeofday();
  3196. my $rdspec = (split ":",$devrdspec)[-1];
  3197. my @dc = split(":",$devrdspec);
  3198. pop @dc;
  3199. my $devspec = join(':',@dc);
  3200. my @exdvs = devspec2array($devspec);
  3201. Log3 $name, 4, "DbLog $name -> Addlog known devices by devspec: @exdvs";
  3202. foreach (@exdvs) {
  3203. $dev_name = $_;
  3204. if(!$defs{$dev_name}) {
  3205. Log3 $name, 2, "DbLog $name -> Device '$dev_name' used by addLog doesn't exist !";
  3206. next;
  3207. }
  3208. my $r = $defs{$dev_name}{READINGS};
  3209. my @exrds;
  3210. foreach my $rd (sort keys %{$r}) {
  3211. push @exrds,$rd if($rd =~ m/^$rdspec$/);
  3212. }
  3213. Log3 $name, 4, "DbLog $name -> Readings extracted from Regex: @exrds";
  3214. if(!@exrds) {
  3215. Log3 $name, 4, "DbLog $name -> no Reading of device '$dev_name' selected from '$rdspec' used by addLog !";
  3216. next;
  3217. }
  3218. foreach (@exrds) {
  3219. $dev_reading = $_;
  3220. $read_val = $value?$value:ReadingsVal($dev_name,$dev_reading,"");
  3221. $dev_type = uc($defs{$dev_name}{TYPE});
  3222. # dummy-Event zusammenstellen
  3223. $event = $dev_reading.": ".$read_val;
  3224. # den zusammengestellten Event parsen lassen (evtl. Unit zuweisen)
  3225. my @r = DbLog_ParseEvent($dev_name, $dev_type, $event);
  3226. $dev_reading = $r[0];
  3227. $read_val = $r[1];
  3228. $ut = $r[2];
  3229. if(!defined $dev_reading) {$dev_reading = "";}
  3230. if(!defined $read_val) {$read_val = "";}
  3231. if(!defined $ut || $ut eq "") {$ut = AttrVal("$dev_name", "unit", "");}
  3232. $event = "addLog";
  3233. $defs{$dev_name}{Helper}{DBLOG}{$dev_reading}{$hash->{NAME}}{TIME} = $now;
  3234. $defs{$dev_name}{Helper}{DBLOG}{$dev_reading}{$hash->{NAME}}{VALUE} = $read_val;
  3235. # Anwender spezifische Funktion anwenden
  3236. if($value_fn ne '') {
  3237. my $TIMESTAMP = $ts;
  3238. my $DEVICE = $dev_name;
  3239. my $DEVICETYPE = $dev_type;
  3240. my $EVENT = $event;
  3241. my $READING = $dev_reading;
  3242. my $VALUE = $read_val;
  3243. my $UNIT = $ut;
  3244. my $IGNORE = 0;
  3245. eval $value_fn;
  3246. Log3 $name, 2, "DbLog $name -> error valueFn: ".$@ if($@);
  3247. next if($IGNORE); # aktueller Event wird nicht geloggt wenn $IGNORE=1 gesetzt in $value_fn
  3248. $ts = $TIMESTAMP if($TIMESTAMP =~ /^(\d{4})-(\d{2})-(\d{2} \d{2}):(\d{2}):(\d{2})$/);
  3249. $dev_name = $DEVICE if($DEVICE ne '');
  3250. $dev_type = $DEVICETYPE if($DEVICETYPE ne '');
  3251. $dev_reading = $READING if($READING ne '');
  3252. $read_val = $VALUE if(defined $VALUE);
  3253. $ut = $UNIT if(defined $UNIT);
  3254. }
  3255. no warnings 'uninitialized';
  3256. # Daten auf maximale Länge beschneiden
  3257. ($dev_name,$dev_type,$event,$dev_reading,$read_val,$ut) = DbLog_cutCol($hash,$dev_name,$dev_type,$event,$dev_reading,$read_val,$ut);
  3258. if(AttrVal($name, "useCharfilter",0)) {
  3259. $dev_reading = DbLog_charfilter($dev_reading);
  3260. $read_val = DbLog_charfilter($read_val);
  3261. }
  3262. my $row = ($ts."|".$dev_name."|".$dev_type."|".$event."|".$dev_reading."|".$read_val."|".$ut);
  3263. Log3 $hash->{NAME}, 3, "DbLog $name -> addLog created - TS: $ts, Device: $dev_name, Type: $dev_type, Event: $event, Reading: $dev_reading, Value: $read_val, Unit: $ut"
  3264. if(!AttrVal($name, "suppressAddLogV3",0));
  3265. use warnings;
  3266. if($async) {
  3267. # asynchoner non-blocking Mode
  3268. # Cache & CacheIndex für Events zum asynchronen Schreiben in DB
  3269. $hash->{cache}{index}++;
  3270. my $index = $hash->{cache}{index};
  3271. $hash->{cache}{".memcache"}{$index} = $row;
  3272. my $memcount = $hash->{cache}{".memcache"}?scalar(keys%{$hash->{cache}{".memcache"}}):0;
  3273. if($ce == 1) {
  3274. readingsSingleUpdate($hash, "CacheUsage", $memcount, 1);
  3275. } else {
  3276. readingsSingleUpdate($hash, 'CacheUsage', $memcount, 0);
  3277. }
  3278. } else {
  3279. # synchoner Mode
  3280. push(@row_array, $row);
  3281. }
  3282. }
  3283. }
  3284. if(!$async) {
  3285. if(@row_array) {
  3286. # synchoner Mode
  3287. # return wenn "reopen" mit Ablaufzeit gestartet ist
  3288. return if($hash->{HELPER}{REOPEN_RUNS});
  3289. my $error = DbLog_Push($hash, 1, @row_array);
  3290. my $state = $error?$error:(IsDisabled($name))?"disabled":"connected";
  3291. my $evt = ($state eq $hash->{HELPER}{OLDSTATE})?0:1;
  3292. readingsSingleUpdate($hash, "state", $state, $evt);
  3293. $hash->{HELPER}{OLDSTATE} = $state;
  3294. Log3 $name, 5, "DbLog $name -> DbLog_Push Returncode: $error";
  3295. }
  3296. }
  3297. return;
  3298. }
  3299. #########################################################################################
  3300. #
  3301. # Subroutine addCacheLine - einen Datensatz zum Cache hinzufügen
  3302. #
  3303. #########################################################################################
  3304. sub DbLog_addCacheLine($$$$$$$$) {
  3305. my ($hash,$i_timestamp,$i_dev,$i_type,$i_evt,$i_reading,$i_val,$i_unit) = @_;
  3306. my $name = $hash->{NAME};
  3307. my $ce = AttrVal($name, "cacheEvents", 0);
  3308. my $value_fn = AttrVal( $name, "valueFn", "" );
  3309. # Funktion aus Attr valueFn validieren
  3310. if( $value_fn =~ m/^\s*(\{.*\})\s*$/s ) {
  3311. $value_fn = $1;
  3312. } else {
  3313. $value_fn = '';
  3314. }
  3315. if($value_fn ne '') {
  3316. my $TIMESTAMP = $i_timestamp;
  3317. my $DEVICE = $i_dev;
  3318. my $DEVICETYPE = $i_type;
  3319. my $EVENT = $i_evt;
  3320. my $READING = $i_reading;
  3321. my $VALUE = $i_val;
  3322. my $UNIT = $i_unit;
  3323. my $IGNORE = 0;
  3324. eval $value_fn;
  3325. Log3 $name, 2, "DbLog $name -> error valueFn: ".$@ if($@);
  3326. if($IGNORE) {
  3327. # aktueller Event wird nicht geloggt wenn $IGNORE=1 gesetzt in $value_fn
  3328. Log3 $hash->{NAME}, 4, "DbLog $name -> Event ignored by valueFn - TS: $i_timestamp, Device: $i_dev, Type: $i_type, Event: $i_evt, Reading: $i_reading, Value: $i_val, Unit: $i_unit";
  3329. next;
  3330. }
  3331. $i_timestamp = $TIMESTAMP if($TIMESTAMP =~ /(19[0-9][0-9]|2[0-9][0-9][0-9])-(0[1-9]|1[1-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1]) (0[0-9]|1[1-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])/);
  3332. $i_dev = $DEVICE if($DEVICE ne '');
  3333. $i_type = $DEVICETYPE if($DEVICETYPE ne '');
  3334. $i_reading = $READING if($READING ne '');
  3335. $i_val = $VALUE if(defined $VALUE);
  3336. $i_unit = $UNIT if(defined $UNIT);
  3337. }
  3338. no warnings 'uninitialized';
  3339. # Daten auf maximale Länge beschneiden
  3340. ($i_dev,$i_type,$i_evt,$i_reading,$i_val,$i_unit) = DbLog_cutCol($hash,$i_dev,$i_type,$i_evt,$i_reading,$i_val,$i_unit);
  3341. my $row = ($i_timestamp."|".$i_dev."|".$i_type."|".$i_evt."|".$i_reading."|".$i_val."|".$i_unit);
  3342. $row = DbLog_charfilter($row) if(AttrVal($name, "useCharfilter",0));
  3343. Log3 $hash->{NAME}, 3, "DbLog $name -> added by addCacheLine - TS: $i_timestamp, Device: $i_dev, Type: $i_type, Event: $i_evt, Reading: $i_reading, Value: $i_val, Unit: $i_unit";
  3344. use warnings;
  3345. eval { # one transaction
  3346. $hash->{cache}{index}++;
  3347. my $index = $hash->{cache}{index};
  3348. $hash->{cache}{".memcache"}{$index} = $row;
  3349. my $memcount = $hash->{cache}{".memcache"}?scalar(keys%{$hash->{cache}{".memcache"}}):0;
  3350. if($ce == 1) {
  3351. readingsSingleUpdate($hash, "CacheUsage", $memcount, 1);
  3352. } else {
  3353. readingsSingleUpdate($hash, 'CacheUsage', $memcount, 0);
  3354. }
  3355. };
  3356. return;
  3357. }
  3358. #########################################################################################
  3359. #
  3360. # Subroutine cutCol - Daten auf maximale Länge beschneiden
  3361. #
  3362. #########################################################################################
  3363. sub DbLog_cutCol($$$$$$$) {
  3364. my ($hash,$dn,$dt,$evt,$rd,$val,$unit)= @_;
  3365. my $name = $hash->{NAME};
  3366. my $colevent = AttrVal($name, 'colEvent', undef);
  3367. my $colreading = AttrVal($name, 'colReading', undef);
  3368. my $colvalue = AttrVal($name, 'colValue', undef);
  3369. if ($hash->{MODEL} ne 'SQLITE' || defined($colevent) || defined($colreading) || defined($colvalue) ) {
  3370. $dn = substr($dn,0, $hash->{HELPER}{DEVICECOL});
  3371. $dt = substr($dt,0, $hash->{HELPER}{TYPECOL});
  3372. $evt = substr($evt,0, $hash->{HELPER}{EVENTCOL});
  3373. $rd = substr($rd,0, $hash->{HELPER}{READINGCOL});
  3374. $val = substr($val,0, $hash->{HELPER}{VALUECOL});
  3375. $unit = substr($unit,0, $hash->{HELPER}{UNITCOL}) if($unit);
  3376. }
  3377. return ($dn,$dt,$evt,$rd,$val,$unit);
  3378. }
  3379. ###############################################################################
  3380. # liefert zurück ob Autocommit ($useac) bzw. Transaktion ($useta)
  3381. # verwendet werden soll
  3382. #
  3383. # basic_ta:on - Autocommit Servereinstellung / Transaktion ein
  3384. # basic_ta:off - Autocommit Servereinstellung / Transaktion aus
  3385. # ac:on_ta:on - Autocommit ein / Transaktion ein
  3386. # ac:on_ta:off - Autocommit ein / Transaktion aus
  3387. # ac:off_ta:on - Autocommit aus / Transaktion ein (AC aus impliziert TA ein)
  3388. #
  3389. # Autocommit: 0/1/2 = aus/ein/Servereinstellung
  3390. # Transaktion: 0/1 = aus/ein
  3391. ###############################################################################
  3392. sub DbLog_commitMode ($) {
  3393. my ($hash) = @_;
  3394. my $name = $hash->{NAME};
  3395. my $useac = 2; # default Servereinstellung
  3396. my $useta = 1; # default Transaktion ein
  3397. my $cm = AttrVal($name, "commitMode", "basic_ta:on");
  3398. my ($ac,$ta) = split("_",$cm);
  3399. $useac = ($ac =~ /off/)?0:($ac =~ /on/)?1:2;
  3400. $useta = 0 if($ta =~ /off/);
  3401. return($useac,$useta);
  3402. }
  3403. ###############################################################################
  3404. # Zeichencodierung für Payload filtern
  3405. ###############################################################################
  3406. sub DbLog_charfilter ($) {
  3407. my ($txt) = @_;
  3408. # nur erwünschte Zeichen in payload, ASCII %d32-126
  3409. $txt =~ s/ß/ss/g;
  3410. $txt =~ s/ä/ae/g;
  3411. $txt =~ s/ö/oe/g;
  3412. $txt =~ s/ü/ue/g;
  3413. $txt =~ s/Ä/Ae/g;
  3414. $txt =~ s/Ö/Oe/g;
  3415. $txt =~ s/Ü/Ue/g;
  3416. $txt =~ s/€/EUR/g;
  3417. $txt =~ tr/ A-Za-z0-9!"#$%&'()*+,-.\/:;<=>?@[\\]^_`{|}~//cd;
  3418. return($txt);
  3419. }
  3420. #########################################################################################
  3421. ### DBLog - Historische Werte ausduennen (alte blockiernde Variante) > Forum #41089
  3422. #########################################################################################
  3423. sub DbLog_reduceLog($@) {
  3424. my ($hash,@a) = @_;
  3425. my ($ret,$cmd,$row,$filter,$exclude,$c,$day,$hour,$lastHour,$updDate,$updHour,$average,$processingDay,$lastUpdH,%hourlyKnown,%averageHash,@excludeRegex,@dayRows,@averageUpd,@averageUpdD);
  3426. my ($name,$startTime,$currentHour,$currentDay,$deletedCount,$updateCount,$sum,$rowCount,$excludeCount) = ($hash->{NAME},time(),99,0,0,0,0,0,0);
  3427. my $dbh = DbLog_ConnectNewDBH($hash);
  3428. return if(!$dbh);
  3429. if ($a[-1] =~ /^EXCLUDE=(.+:.+)+/i) {
  3430. ($filter) = $a[-1] =~ /^EXCLUDE=(.+)/i;
  3431. @excludeRegex = split(',',$filter);
  3432. } elsif ($a[-1] =~ /^INCLUDE=.+:.+$/i) {
  3433. $filter = 1;
  3434. }
  3435. if (defined($a[3])) {
  3436. $average = ($a[3] =~ /average=day/i) ? "AVERAGE=DAY" : ($a[3] =~ /average/i) ? "AVERAGE=HOUR" : 0;
  3437. }
  3438. Log3($name, 3, "DbLog $name: reduceLog requested with DAYS=$a[2]"
  3439. .(($average || $filter) ? ', ' : '').(($average) ? "$average" : '')
  3440. .(($average && $filter) ? ", " : '').(($filter) ? uc((split('=',$a[-1]))[0]).'='.(split('=',$a[-1]))[1] : ''));
  3441. my ($useac,$useta) = DbLog_commitMode($hash);
  3442. my $ac = ($dbh->{AutoCommit})?"ON":"OFF";
  3443. my $tm = ($useta)?"ON":"OFF";
  3444. Log3 $hash->{NAME}, 4, "DbLog $name -> AutoCommit mode: $ac, Transaction mode: $tm";
  3445. if ($hash->{MODEL} eq 'SQLITE') { $cmd = "datetime('now', '-$a[2] days')"; }
  3446. elsif ($hash->{MODEL} eq 'MYSQL') { $cmd = "DATE_SUB(CURDATE(),INTERVAL $a[2] DAY)"; }
  3447. elsif ($hash->{MODEL} eq 'POSTGRESQL') { $cmd = "NOW() - INTERVAL '$a[2]' DAY"; }
  3448. else { $ret = 'Unknown database type.'; }
  3449. if ($cmd) {
  3450. my $sth_del = $dbh->prepare_cached("DELETE FROM history WHERE (DEVICE=?) AND (READING=?) AND (TIMESTAMP=?) AND (VALUE=?)");
  3451. my $sth_upd = $dbh->prepare_cached("UPDATE history SET TIMESTAMP=?, EVENT=?, VALUE=? WHERE (DEVICE=?) AND (READING=?) AND (TIMESTAMP=?) AND (VALUE=?)");
  3452. my $sth_delD = $dbh->prepare_cached("DELETE FROM history WHERE (DEVICE=?) AND (READING=?) AND (TIMESTAMP=?)");
  3453. my $sth_updD = $dbh->prepare_cached("UPDATE history SET TIMESTAMP=?, EVENT=?, VALUE=? WHERE (DEVICE=?) AND (READING=?) AND (TIMESTAMP=?)");
  3454. my $sth_get = $dbh->prepare("SELECT TIMESTAMP,DEVICE,'',READING,VALUE FROM history WHERE "
  3455. .($a[-1] =~ /^INCLUDE=(.+):(.+)$/i ? "DEVICE like '$1' AND READING like '$2' AND " : '')
  3456. ."TIMESTAMP < $cmd ORDER BY TIMESTAMP ASC"); # '' was EVENT, no longer in use
  3457. $sth_get->execute();
  3458. do {
  3459. $row = $sth_get->fetchrow_arrayref || ['0000-00-00 00:00:00','D','','R','V']; # || execute last-day dummy
  3460. $ret = 1;
  3461. ($day,$hour) = $row->[0] =~ /-(\d{2})\s(\d{2}):/;
  3462. $rowCount++ if($day != 00);
  3463. if ($day != $currentDay) {
  3464. if ($currentDay) { # false on first executed day
  3465. if (scalar @dayRows) {
  3466. ($lastHour) = $dayRows[-1]->[0] =~ /(.*\d+\s\d{2}):/;
  3467. $c = 0;
  3468. for my $delRow (@dayRows) {
  3469. $c++ if($day != 00 || $delRow->[0] !~ /$lastHour/);
  3470. }
  3471. if($c) {
  3472. $deletedCount += $c;
  3473. Log3($name, 3, "DbLog $name: reduceLog deleting $c records of day: $processingDay");
  3474. $dbh->{RaiseError} = 1;
  3475. $dbh->{PrintError} = 0;
  3476. eval {$dbh->begin_work() if($dbh->{AutoCommit});};
  3477. eval {
  3478. my $i = 0;
  3479. my $k = 1;
  3480. my $th = ($#dayRows <= 2000)?100:($#dayRows <= 30000)?1000:10000;
  3481. for my $delRow (@dayRows) {
  3482. if($day != 00 || $delRow->[0] !~ /$lastHour/) {
  3483. Log3($name, 5, "DbLog $name: DELETE FROM history WHERE (DEVICE=$delRow->[1]) AND (READING=$delRow->[3]) AND (TIMESTAMP=$delRow->[0]) AND (VALUE=$delRow->[4])");
  3484. $sth_del->execute(($delRow->[1], $delRow->[3], $delRow->[0], $delRow->[4]));
  3485. $i++;
  3486. if($i == $th) {
  3487. my $prog = $k * $i;
  3488. Log3($name, 3, "DbLog $name: reduceLog deletion progress of day: $processingDay is: $prog");
  3489. $i = 0;
  3490. $k++;
  3491. }
  3492. }
  3493. }
  3494. };
  3495. if ($@) {
  3496. Log3($hash->{NAME}, 3, "DbLog $name: reduceLog ! FAILED ! for day $processingDay");
  3497. eval {$dbh->rollback() if(!$dbh->{AutoCommit});};
  3498. $ret = 0;
  3499. } else {
  3500. eval {$dbh->commit() if(!$dbh->{AutoCommit});};
  3501. }
  3502. $dbh->{RaiseError} = 0;
  3503. $dbh->{PrintError} = 1;
  3504. }
  3505. @dayRows = ();
  3506. }
  3507. if ($ret && defined($a[3]) && $a[3] =~ /average/i) {
  3508. $dbh->{RaiseError} = 1;
  3509. $dbh->{PrintError} = 0;
  3510. eval {$dbh->begin_work() if($dbh->{AutoCommit});};
  3511. eval {
  3512. push(@averageUpd, {%hourlyKnown}) if($day != 00);
  3513. $c = 0;
  3514. for my $hourHash (@averageUpd) { # Only count for logging...
  3515. for my $hourKey (keys %$hourHash) {
  3516. $c++ if ($hourHash->{$hourKey}->[0] && scalar(@{$hourHash->{$hourKey}->[4]}) > 1);
  3517. }
  3518. }
  3519. $updateCount += $c;
  3520. Log3($name, 3, "DbLog $name: reduceLog (hourly-average) updating $c records of day: $processingDay") if($c); # else only push to @averageUpdD
  3521. my $i = 0;
  3522. my $k = 1;
  3523. my $th = ($c <= 2000)?100:($c <= 30000)?1000:10000;
  3524. for my $hourHash (@averageUpd) {
  3525. for my $hourKey (keys %$hourHash) {
  3526. if ($hourHash->{$hourKey}->[0]) { # true if reading is a number
  3527. ($updDate,$updHour) = $hourHash->{$hourKey}->[0] =~ /(.*\d+)\s(\d{2}):/;
  3528. if (scalar(@{$hourHash->{$hourKey}->[4]}) > 1) { # true if reading has multiple records this hour
  3529. for (@{$hourHash->{$hourKey}->[4]}) { $sum += $_; }
  3530. $average = sprintf('%.3f', $sum/scalar(@{$hourHash->{$hourKey}->[4]}) );
  3531. $sum = 0;
  3532. Log3($name, 5, "DbLog $name: UPDATE history SET TIMESTAMP=$updDate $updHour:30:00, EVENT='rl_av_h', VALUE=$average WHERE DEVICE=$hourHash->{$hourKey}->[1] AND READING=$hourHash->{$hourKey}->[3] AND TIMESTAMP=$hourHash->{$hourKey}->[0] AND VALUE=$hourHash->{$hourKey}->[4]->[0]");
  3533. $sth_upd->execute(("$updDate $updHour:30:00", 'rl_av_h', $average, $hourHash->{$hourKey}->[1], $hourHash->{$hourKey}->[3], $hourHash->{$hourKey}->[0], $hourHash->{$hourKey}->[4]->[0]));
  3534. $i++;
  3535. if($i == $th) {
  3536. my $prog = $k * $i;
  3537. Log3($name, 3, "DbLog $name: reduceLog (hourly-average) updating progress of day: $processingDay is: $prog");
  3538. $i = 0;
  3539. $k++;
  3540. }
  3541. push(@averageUpdD, ["$updDate $updHour:30:00", 'rl_av_h', $average, $hourHash->{$hourKey}->[1], $hourHash->{$hourKey}->[3], $updDate]) if (defined($a[3]) && $a[3] =~ /average=day/i);
  3542. } else {
  3543. push(@averageUpdD, [$hourHash->{$hourKey}->[0], $hourHash->{$hourKey}->[2], $hourHash->{$hourKey}->[4]->[0], $hourHash->{$hourKey}->[1], $hourHash->{$hourKey}->[3], $updDate]) if (defined($a[3]) && $a[3] =~ /average=day/i);
  3544. }
  3545. }
  3546. }
  3547. }
  3548. };
  3549. if ($@) {
  3550. Log3($hash->{NAME}, 3, "DbLog $name: reduceLog average=hour ! FAILED ! for day $processingDay");
  3551. eval {$dbh->rollback() if(!$dbh->{AutoCommit});};
  3552. @averageUpdD = ();
  3553. } else {
  3554. eval {$dbh->commit() if(!$dbh->{AutoCommit});};
  3555. }
  3556. $dbh->{RaiseError} = 0;
  3557. $dbh->{PrintError} = 1;
  3558. @averageUpd = ();
  3559. }
  3560. if (defined($a[3]) && $a[3] =~ /average=day/i && scalar(@averageUpdD) && $day != 00) {
  3561. $dbh->{RaiseError} = 1;
  3562. $dbh->{PrintError} = 0;
  3563. eval {$dbh->begin_work() if($dbh->{AutoCommit});};
  3564. eval {
  3565. for (@averageUpdD) {
  3566. push(@{$averageHash{$_->[3].$_->[4]}->{tedr}}, [$_->[0], $_->[1], $_->[3], $_->[4]]);
  3567. $averageHash{$_->[3].$_->[4]}->{sum} += $_->[2];
  3568. $averageHash{$_->[3].$_->[4]}->{date} = $_->[5];
  3569. }
  3570. $c = 0;
  3571. for (keys %averageHash) {
  3572. if(scalar @{$averageHash{$_}->{tedr}} == 1) {
  3573. delete $averageHash{$_};
  3574. } else {
  3575. $c += (scalar(@{$averageHash{$_}->{tedr}}) - 1);
  3576. }
  3577. }
  3578. $deletedCount += $c;
  3579. $updateCount += keys(%averageHash);
  3580. my ($id,$iu) = 0;
  3581. my ($kd,$ku) = 1;
  3582. my $thd = ($c <= 2000)?100:($c <= 30000)?1000:10000;
  3583. my $thu = ((keys %averageHash) <= 2000)?100:((keys %averageHash) <= 30000)?1000:10000;
  3584. Log3($name, 3, "DbLog $name: reduceLog (daily-average) updating ".(keys %averageHash).", deleting $c records of day: $processingDay") if(keys %averageHash);
  3585. for my $reading (keys %averageHash) {
  3586. $average = sprintf('%.3f', $averageHash{$reading}->{sum}/scalar(@{$averageHash{$reading}->{tedr}}));
  3587. $lastUpdH = pop @{$averageHash{$reading}->{tedr}};
  3588. for (@{$averageHash{$reading}->{tedr}}) {
  3589. Log3($name, 5, "DbLog $name: DELETE FROM history WHERE DEVICE='$_->[2]' AND READING='$_->[3]' AND TIMESTAMP='$_->[0]'");
  3590. $sth_delD->execute(($_->[2], $_->[3], $_->[0]));
  3591. $id++;
  3592. if($id == $thd) {
  3593. my $prog = $kd * $id;
  3594. Log3($name, 3, "DbLog $name: reduceLog (daily-average) deleting progress of day: $processingDay is: $prog");
  3595. $id = 0;
  3596. $kd++;
  3597. }
  3598. }
  3599. Log3($name, 5, "DbLog $name: UPDATE history SET TIMESTAMP=$averageHash{$reading}->{date} 12:00:00, EVENT='rl_av_d', VALUE=$average WHERE (DEVICE=$lastUpdH->[2]) AND (READING=$lastUpdH->[3]) AND (TIMESTAMP=$lastUpdH->[0])");
  3600. $sth_updD->execute(($averageHash{$reading}->{date}." 12:00:00", 'rl_av_d', $average, $lastUpdH->[2], $lastUpdH->[3], $lastUpdH->[0]));
  3601. $iu++;
  3602. if($iu == $thu) {
  3603. my $prog = $ku * $id;
  3604. Log3($name, 3, "DbLog $name: reduceLog (daily-average) updating progress of day: $processingDay is: $prog");
  3605. $iu = 0;
  3606. $ku++;
  3607. }
  3608. }
  3609. };
  3610. if ($@) {
  3611. Log3($hash->{NAME}, 3, "DbLog $name: reduceLog average=day ! FAILED ! for day $processingDay");
  3612. eval {$dbh->rollback() if(!$dbh->{AutoCommit});};
  3613. } else {
  3614. eval {$dbh->commit() if(!$dbh->{AutoCommit});};
  3615. }
  3616. $dbh->{RaiseError} = 0;
  3617. $dbh->{PrintError} = 1;
  3618. }
  3619. %averageHash = ();
  3620. %hourlyKnown = ();
  3621. @averageUpd = ();
  3622. @averageUpdD = ();
  3623. $currentHour = 99;
  3624. }
  3625. $currentDay = $day;
  3626. }
  3627. if ($hour != $currentHour) { # forget records from last hour, but remember these for average
  3628. if (defined($a[3]) && $a[3] =~ /average/i && keys(%hourlyKnown)) {
  3629. push(@averageUpd, {%hourlyKnown});
  3630. }
  3631. %hourlyKnown = ();
  3632. $currentHour = $hour;
  3633. }
  3634. if (defined $hourlyKnown{$row->[1].$row->[3]}) { # remember first readings for device per h, other can be deleted
  3635. push(@dayRows, [@$row]);
  3636. if (defined($a[3]) && $a[3] =~ /average/i && defined($row->[4]) && $row->[4] =~ /^-?(?:\d+(?:\.\d*)?|\.\d+)$/ && $hourlyKnown{$row->[1].$row->[3]}->[0]) {
  3637. if ($hourlyKnown{$row->[1].$row->[3]}->[0]) {
  3638. push(@{$hourlyKnown{$row->[1].$row->[3]}->[4]}, $row->[4]);
  3639. }
  3640. }
  3641. } else {
  3642. $exclude = 0;
  3643. for (@excludeRegex) {
  3644. $exclude = 1 if("$row->[1]:$row->[3]" =~ /^$_$/);
  3645. }
  3646. if ($exclude) {
  3647. $excludeCount++ if($day != 00);
  3648. } else {
  3649. $hourlyKnown{$row->[1].$row->[3]} = (defined($row->[4]) && $row->[4] =~ /^-?(?:\d+(?:\.\d*)?|\.\d+)$/) ? [$row->[0],$row->[1],$row->[2],$row->[3],[$row->[4]]] : [0];
  3650. }
  3651. }
  3652. $processingDay = (split(' ',$row->[0]))[0];
  3653. } while( $day != 00 );
  3654. my $result = "Rows processed: $rowCount, deleted: $deletedCount"
  3655. .((defined($a[3]) && $a[3] =~ /average/i)? ", updated: $updateCount" : '')
  3656. .(($excludeCount)? ", excluded: $excludeCount" : '')
  3657. .", time: ".sprintf('%.2f',time() - $startTime)."sec";
  3658. Log3($name, 3, "DbLog $name: reduceLog executed. $result");
  3659. readingsSingleUpdate($hash,"reduceLogState",$result,1);
  3660. $ret = "reduceLog executed. $result";
  3661. }
  3662. $dbh->disconnect();
  3663. return $ret;
  3664. }
  3665. #########################################################################################
  3666. ### DBLog - Historische Werte ausduennen non-blocking > Forum #41089
  3667. #########################################################################################
  3668. sub DbLog_reduceLogNbl($) {
  3669. my ($name) = @_;
  3670. my $hash = $defs{$name};
  3671. my $dbconn = $hash->{dbconn};
  3672. my $dbuser = $hash->{dbuser};
  3673. my $dbpassword = $attr{"sec$name"}{secret};
  3674. my @a = @{$hash->{HELPER}{REDUCELOG}};
  3675. my $utf8 = defined($hash->{UTF8})?$hash->{UTF8}:0;
  3676. delete $hash->{HELPER}{REDUCELOG};
  3677. my ($ret,$cmd,$row,$filter,$exclude,$c,$day,$hour,$lastHour,$updDate,$updHour,$average,$processingDay,$lastUpdH,%hourlyKnown,%averageHash,@excludeRegex,@dayRows,@averageUpd,@averageUpdD);
  3678. my ($startTime,$currentHour,$currentDay,$deletedCount,$updateCount,$sum,$rowCount,$excludeCount) = (time(),99,0,0,0,0,0,0);
  3679. my $dbh;
  3680. Log3 ($name, 5, "DbLog $name -> Start DbLog_reduceLogNbl");
  3681. my ($useac,$useta) = DbLog_commitMode($hash);
  3682. if(!$useac) {
  3683. eval {$dbh = DBI->connect("dbi:$dbconn", $dbuser, $dbpassword, { PrintError => 0, RaiseError => 1, AutoCommit => 0 });};
  3684. } elsif($useac == 1) {
  3685. eval {$dbh = DBI->connect("dbi:$dbconn", $dbuser, $dbpassword, { PrintError => 0, RaiseError => 1, AutoCommit => 1 });};
  3686. } else {
  3687. # Server default
  3688. eval {$dbh = DBI->connect("dbi:$dbconn", $dbuser, $dbpassword, { PrintError => 0, RaiseError => 1 });};
  3689. }
  3690. if ($@) {
  3691. my $err = encode_base64($@,"");
  3692. Log3 ($name, 2, "DbLog $name -> DbLog_reduceLogNbl - $@");
  3693. Log3 ($name, 5, "DbLog $name -> DbLog_reduceLogNbl finished");
  3694. return "$name|''|$err";
  3695. }
  3696. if ($a[-1] =~ /^EXCLUDE=(.+:.+)+/i) {
  3697. ($filter) = $a[-1] =~ /^EXCLUDE=(.+)/i;
  3698. @excludeRegex = split(',',$filter);
  3699. } elsif ($a[-1] =~ /^INCLUDE=.+:.+$/i) {
  3700. $filter = 1;
  3701. }
  3702. if (defined($a[3])) {
  3703. $average = ($a[3] =~ /average=day/i) ? "AVERAGE=DAY" : ($a[3] =~ /average/i) ? "AVERAGE=HOUR" : 0;
  3704. }
  3705. Log3($name, 3, "DbLog $name: reduceLogNbl requested with DAYS=$a[2]"
  3706. .(($average || $filter) ? ', ' : '').(($average) ? "$average" : '')
  3707. .(($average && $filter) ? ", " : '').(($filter) ? uc((split('=',$a[-1]))[0]).'='.(split('=',$a[-1]))[1] : ''));
  3708. my $ac = ($dbh->{AutoCommit})?"ON":"OFF";
  3709. my $tm = ($useta)?"ON":"OFF";
  3710. Log3 $hash->{NAME}, 4, "DbLog $name -> AutoCommit mode: $ac, Transaction mode: $tm";
  3711. if ($hash->{MODEL} eq 'SQLITE') { $cmd = "datetime('now', '-$a[2] days')"; }
  3712. elsif ($hash->{MODEL} eq 'MYSQL') { $cmd = "DATE_SUB(CURDATE(),INTERVAL $a[2] DAY)"; }
  3713. elsif ($hash->{MODEL} eq 'POSTGRESQL') { $cmd = "NOW() - INTERVAL '$a[2]' DAY"; }
  3714. else { $ret = 'Unknown database type.'; }
  3715. if ($cmd) {
  3716. my ($sth_del, $sth_upd, $sth_delD, $sth_updD, $sth_get);
  3717. eval { $sth_del = $dbh->prepare_cached("DELETE FROM history WHERE (DEVICE=?) AND (READING=?) AND (TIMESTAMP=?) AND (VALUE=?)");
  3718. $sth_upd = $dbh->prepare_cached("UPDATE history SET TIMESTAMP=?, EVENT=?, VALUE=? WHERE (DEVICE=?) AND (READING=?) AND (TIMESTAMP=?) AND (VALUE=?)");
  3719. $sth_delD = $dbh->prepare_cached("DELETE FROM history WHERE (DEVICE=?) AND (READING=?) AND (TIMESTAMP=?)");
  3720. $sth_updD = $dbh->prepare_cached("UPDATE history SET TIMESTAMP=?, EVENT=?, VALUE=? WHERE (DEVICE=?) AND (READING=?) AND (TIMESTAMP=?)");
  3721. $sth_get = $dbh->prepare("SELECT TIMESTAMP,DEVICE,'',READING,VALUE FROM history WHERE "
  3722. .($a[-1] =~ /^INCLUDE=(.+):(.+)$/i ? "DEVICE like '$1' AND READING like '$2' AND " : '')
  3723. ."TIMESTAMP < $cmd ORDER BY TIMESTAMP ASC"); # '' was EVENT, no longer in use
  3724. };
  3725. if ($@) {
  3726. my $err = encode_base64($@,"");
  3727. Log3 ($name, 2, "DbLog $name -> DbLog_reduceLogNbl - $@");
  3728. Log3 ($name, 5, "DbLog $name -> DbLog_reduceLogNbl finished");
  3729. return "$name|''|$err";
  3730. }
  3731. eval { $sth_get->execute(); };
  3732. if ($@) {
  3733. my $err = encode_base64($@,"");
  3734. Log3 ($name, 2, "DbLog $name -> DbLog_reduceLogNbl - $@");
  3735. Log3 ($name, 5, "DbLog $name -> DbLog_reduceLogNbl finished");
  3736. return "$name|''|$err";
  3737. }
  3738. do {
  3739. $row = $sth_get->fetchrow_arrayref || ['0000-00-00 00:00:00','D','','R','V']; # || execute last-day dummy
  3740. $ret = 1;
  3741. ($day,$hour) = $row->[0] =~ /-(\d{2})\s(\d{2}):/;
  3742. $rowCount++ if($day != 00);
  3743. if ($day != $currentDay) {
  3744. if ($currentDay) { # false on first executed day
  3745. if (scalar @dayRows) {
  3746. ($lastHour) = $dayRows[-1]->[0] =~ /(.*\d+\s\d{2}):/;
  3747. $c = 0;
  3748. for my $delRow (@dayRows) {
  3749. $c++ if($day != 00 || $delRow->[0] !~ /$lastHour/);
  3750. }
  3751. if($c) {
  3752. $deletedCount += $c;
  3753. Log3($name, 3, "DbLog $name: reduceLogNbl deleting $c records of day: $processingDay");
  3754. $dbh->{RaiseError} = 1;
  3755. $dbh->{PrintError} = 0;
  3756. eval {$dbh->begin_work() if($dbh->{AutoCommit});};
  3757. if ($@) {
  3758. Log3 ($name, 2, "DbLog $name -> DbLog_reduceLogNbl - $@");
  3759. }
  3760. eval {
  3761. my $i = 0;
  3762. my $k = 1;
  3763. my $th = ($#dayRows <= 2000)?100:($#dayRows <= 30000)?1000:10000;
  3764. for my $delRow (@dayRows) {
  3765. if($day != 00 || $delRow->[0] !~ /$lastHour/) {
  3766. Log3($name, 4, "DbLog $name: DELETE FROM history WHERE (DEVICE=$delRow->[1]) AND (READING=$delRow->[3]) AND (TIMESTAMP=$delRow->[0]) AND (VALUE=$delRow->[4])");
  3767. $sth_del->execute(($delRow->[1], $delRow->[3], $delRow->[0], $delRow->[4]));
  3768. $i++;
  3769. if($i == $th) {
  3770. my $prog = $k * $i;
  3771. Log3($name, 3, "DbLog $name: reduceLogNbl deletion progress of day: $processingDay is: $prog");
  3772. $i = 0;
  3773. $k++;
  3774. }
  3775. }
  3776. }
  3777. };
  3778. if ($@) {
  3779. Log3($hash->{NAME}, 3, "DbLog $name: reduceLogNbl ! FAILED ! for day $processingDay");
  3780. eval {$dbh->rollback() if(!$dbh->{AutoCommit});};
  3781. if ($@) {
  3782. Log3 ($name, 2, "DbLog $name -> DbLog_reduceLogNbl - $@");
  3783. }
  3784. $ret = 0;
  3785. } else {
  3786. eval {$dbh->commit() if(!$dbh->{AutoCommit});};
  3787. if ($@) {
  3788. Log3 ($name, 2, "DbLog $name -> DbLog_reduceLogNbl - $@");
  3789. }
  3790. }
  3791. $dbh->{RaiseError} = 0;
  3792. $dbh->{PrintError} = 1;
  3793. }
  3794. @dayRows = ();
  3795. }
  3796. if ($ret && defined($a[3]) && $a[3] =~ /average/i) {
  3797. $dbh->{RaiseError} = 1;
  3798. $dbh->{PrintError} = 0;
  3799. eval {$dbh->begin_work() if($dbh->{AutoCommit});};
  3800. if ($@) {
  3801. Log3 ($name, 2, "DbLog $name -> DbLog_reduceLogNbl - $@");
  3802. }
  3803. eval {
  3804. push(@averageUpd, {%hourlyKnown}) if($day != 00);
  3805. $c = 0;
  3806. for my $hourHash (@averageUpd) { # Only count for logging...
  3807. for my $hourKey (keys %$hourHash) {
  3808. $c++ if ($hourHash->{$hourKey}->[0] && scalar(@{$hourHash->{$hourKey}->[4]}) > 1);
  3809. }
  3810. }
  3811. $updateCount += $c;
  3812. Log3($name, 3, "DbLog $name: reduceLogNbl (hourly-average) updating $c records of day: $processingDay") if($c); # else only push to @averageUpdD
  3813. my $i = 0;
  3814. my $k = 1;
  3815. my $th = ($c <= 2000)?100:($c <= 30000)?1000:10000;
  3816. for my $hourHash (@averageUpd) {
  3817. for my $hourKey (keys %$hourHash) {
  3818. if ($hourHash->{$hourKey}->[0]) { # true if reading is a number
  3819. ($updDate,$updHour) = $hourHash->{$hourKey}->[0] =~ /(.*\d+)\s(\d{2}):/;
  3820. if (scalar(@{$hourHash->{$hourKey}->[4]}) > 1) { # true if reading has multiple records this hour
  3821. for (@{$hourHash->{$hourKey}->[4]}) { $sum += $_; }
  3822. $average = sprintf('%.3f', $sum/scalar(@{$hourHash->{$hourKey}->[4]}) );
  3823. $sum = 0;
  3824. Log3($name, 4, "DbLog $name: UPDATE history SET TIMESTAMP=$updDate $updHour:30:00, EVENT='rl_av_h', VALUE=$average WHERE DEVICE=$hourHash->{$hourKey}->[1] AND READING=$hourHash->{$hourKey}->[3] AND TIMESTAMP=$hourHash->{$hourKey}->[0] AND VALUE=$hourHash->{$hourKey}->[4]->[0]");
  3825. $sth_upd->execute(("$updDate $updHour:30:00", 'rl_av_h', $average, $hourHash->{$hourKey}->[1], $hourHash->{$hourKey}->[3], $hourHash->{$hourKey}->[0], $hourHash->{$hourKey}->[4]->[0]));
  3826. $i++;
  3827. if($i == $th) {
  3828. my $prog = $k * $i;
  3829. Log3($name, 3, "DbLog $name: reduceLogNbl (hourly-average) updating progress of day: $processingDay is: $prog");
  3830. $i = 0;
  3831. $k++;
  3832. }
  3833. push(@averageUpdD, ["$updDate $updHour:30:00", 'rl_av_h', $average, $hourHash->{$hourKey}->[1], $hourHash->{$hourKey}->[3], $updDate]) if (defined($a[3]) && $a[3] =~ /average=day/i);
  3834. } else {
  3835. push(@averageUpdD, [$hourHash->{$hourKey}->[0], $hourHash->{$hourKey}->[2], $hourHash->{$hourKey}->[4]->[0], $hourHash->{$hourKey}->[1], $hourHash->{$hourKey}->[3], $updDate]) if (defined($a[3]) && $a[3] =~ /average=day/i);
  3836. }
  3837. }
  3838. }
  3839. }
  3840. };
  3841. if ($@) {
  3842. Log3($hash->{NAME}, 3, "DbLog $name: reduceLogNbl average=hour ! FAILED ! for day $processingDay");
  3843. eval {$dbh->rollback() if(!$dbh->{AutoCommit});};
  3844. if ($@) {
  3845. Log3 ($name, 2, "DbLog $name -> DbLog_reduceLogNbl - $@");
  3846. }
  3847. @averageUpdD = ();
  3848. } else {
  3849. eval {$dbh->commit() if(!$dbh->{AutoCommit});};
  3850. if ($@) {
  3851. Log3 ($name, 2, "DbLog $name -> DbLog_reduceLogNbl - $@");
  3852. }
  3853. }
  3854. $dbh->{RaiseError} = 0;
  3855. $dbh->{PrintError} = 1;
  3856. @averageUpd = ();
  3857. }
  3858. if (defined($a[3]) && $a[3] =~ /average=day/i && scalar(@averageUpdD) && $day != 00) {
  3859. $dbh->{RaiseError} = 1;
  3860. $dbh->{PrintError} = 0;
  3861. eval {$dbh->begin_work() if($dbh->{AutoCommit});};
  3862. if ($@) {
  3863. Log3 ($name, 2, "DbLog $name -> DbLog_reduceLogNbl - $@");
  3864. }
  3865. eval {
  3866. for (@averageUpdD) {
  3867. push(@{$averageHash{$_->[3].$_->[4]}->{tedr}}, [$_->[0], $_->[1], $_->[3], $_->[4]]);
  3868. $averageHash{$_->[3].$_->[4]}->{sum} += $_->[2];
  3869. $averageHash{$_->[3].$_->[4]}->{date} = $_->[5];
  3870. }
  3871. $c = 0;
  3872. for (keys %averageHash) {
  3873. if(scalar @{$averageHash{$_}->{tedr}} == 1) {
  3874. delete $averageHash{$_};
  3875. } else {
  3876. $c += (scalar(@{$averageHash{$_}->{tedr}}) - 1);
  3877. }
  3878. }
  3879. $deletedCount += $c;
  3880. $updateCount += keys(%averageHash);
  3881. my ($id,$iu) = 0;
  3882. my ($kd,$ku) = 1;
  3883. my $thd = ($c <= 2000)?100:($c <= 30000)?1000:10000;
  3884. my $thu = ((keys %averageHash) <= 2000)?100:((keys %averageHash) <= 30000)?1000:10000;
  3885. Log3($name, 3, "DbLog $name: reduceLogNbl (daily-average) updating ".(keys %averageHash).", deleting $c records of day: $processingDay") if(keys %averageHash);
  3886. for my $reading (keys %averageHash) {
  3887. $average = sprintf('%.3f', $averageHash{$reading}->{sum}/scalar(@{$averageHash{$reading}->{tedr}}));
  3888. $lastUpdH = pop @{$averageHash{$reading}->{tedr}};
  3889. for (@{$averageHash{$reading}->{tedr}}) {
  3890. Log3($name, 5, "DbLog $name: DELETE FROM history WHERE DEVICE='$_->[2]' AND READING='$_->[3]' AND TIMESTAMP='$_->[0]'");
  3891. $sth_delD->execute(($_->[2], $_->[3], $_->[0]));
  3892. $id++;
  3893. if($id == $thd) {
  3894. my $prog = $kd * $id;
  3895. Log3($name, 3, "DbLog $name: reduceLogNbl (daily-average) deleting progress of day: $processingDay is: $prog");
  3896. $id = 0;
  3897. $kd++;
  3898. }
  3899. }
  3900. Log3($name, 4, "DbLog $name: UPDATE history SET TIMESTAMP=$averageHash{$reading}->{date} 12:00:00, EVENT='rl_av_d', VALUE=$average WHERE (DEVICE=$lastUpdH->[2]) AND (READING=$lastUpdH->[3]) AND (TIMESTAMP=$lastUpdH->[0])");
  3901. $sth_updD->execute(($averageHash{$reading}->{date}." 12:00:00", 'rl_av_d', $average, $lastUpdH->[2], $lastUpdH->[3], $lastUpdH->[0]));
  3902. $iu++;
  3903. if($iu == $thu) {
  3904. my $prog = $ku * $id;
  3905. Log3($name, 3, "DbLog $name: reduceLogNbl (daily-average) updating progress of day: $processingDay is: $prog");
  3906. $iu = 0;
  3907. $ku++;
  3908. }
  3909. }
  3910. };
  3911. if ($@) {
  3912. Log3($hash->{NAME}, 3, "DbLog $name: reduceLogNbl average=day ! FAILED ! for day $processingDay");
  3913. eval {$dbh->rollback() if(!$dbh->{AutoCommit});};
  3914. if ($@) {
  3915. Log3 ($name, 2, "DbLog $name -> DbLog_reduceLogNbl - $@");
  3916. }
  3917. } else {
  3918. eval {$dbh->commit() if(!$dbh->{AutoCommit});};
  3919. if ($@) {
  3920. Log3 ($name, 2, "DbLog $name -> DbLog_reduceLogNbl - $@");
  3921. }
  3922. }
  3923. $dbh->{RaiseError} = 0;
  3924. $dbh->{PrintError} = 1;
  3925. }
  3926. %averageHash = ();
  3927. %hourlyKnown = ();
  3928. @averageUpd = ();
  3929. @averageUpdD = ();
  3930. $currentHour = 99;
  3931. }
  3932. $currentDay = $day;
  3933. }
  3934. if ($hour != $currentHour) { # forget records from last hour, but remember these for average
  3935. if (defined($a[3]) && $a[3] =~ /average/i && keys(%hourlyKnown)) {
  3936. push(@averageUpd, {%hourlyKnown});
  3937. }
  3938. %hourlyKnown = ();
  3939. $currentHour = $hour;
  3940. }
  3941. if (defined $hourlyKnown{$row->[1].$row->[3]}) { # remember first readings for device per h, other can be deleted
  3942. push(@dayRows, [@$row]);
  3943. if (defined($a[3]) && $a[3] =~ /average/i && defined($row->[4]) && $row->[4] =~ /^-?(?:\d+(?:\.\d*)?|\.\d+)$/ && $hourlyKnown{$row->[1].$row->[3]}->[0]) {
  3944. if ($hourlyKnown{$row->[1].$row->[3]}->[0]) {
  3945. push(@{$hourlyKnown{$row->[1].$row->[3]}->[4]}, $row->[4]);
  3946. }
  3947. }
  3948. } else {
  3949. $exclude = 0;
  3950. for (@excludeRegex) {
  3951. $exclude = 1 if("$row->[1]:$row->[3]" =~ /^$_$/);
  3952. }
  3953. if ($exclude) {
  3954. $excludeCount++ if($day != 00);
  3955. } else {
  3956. $hourlyKnown{$row->[1].$row->[3]} = (defined($row->[4]) && $row->[4] =~ /^-?(?:\d+(?:\.\d*)?|\.\d+)$/) ? [$row->[0],$row->[1],$row->[2],$row->[3],[$row->[4]]] : [0];
  3957. }
  3958. }
  3959. $processingDay = (split(' ',$row->[0]))[0];
  3960. } while( $day != 00 );
  3961. my $result = "Rows processed: $rowCount, deleted: $deletedCount"
  3962. .((defined($a[3]) && $a[3] =~ /average/i)? ", updated: $updateCount" : '')
  3963. .(($excludeCount)? ", excluded: $excludeCount" : '')
  3964. .", time: ".sprintf('%.2f',time() - $startTime)."sec";
  3965. Log3($name, 3, "DbLog $name: reduceLogNbl finished. $result");
  3966. $ret = $result;
  3967. $ret = "reduceLogNbl finished. $result";
  3968. }
  3969. $dbh->disconnect();
  3970. $ret = encode_base64($ret,"");
  3971. Log3 ($name, 5, "DbLog $name -> DbLog_reduceLogNbl finished");
  3972. return "$name|$ret|0";
  3973. }
  3974. #########################################################################################
  3975. # DBLog - reduceLogNbl non-blocking Rückkehrfunktion
  3976. #########################################################################################
  3977. sub DbLog_reduceLogNbl_finished($) {
  3978. my ($string) = @_;
  3979. my @a = split("\\|",$string);
  3980. my $name = $a[0];
  3981. my $hash = $defs{$name};
  3982. my $ret = decode_base64($a[1]);
  3983. my $err = decode_base64($a[2]) if ($a[2]);
  3984. readingsSingleUpdate($hash,"reduceLogState",$err?$err:$ret,1);
  3985. delete $hash->{HELPER}{REDUCELOG_PID};
  3986. return;
  3987. }
  3988. #########################################################################################
  3989. # DBLog - count non-blocking
  3990. #########################################################################################
  3991. sub DbLog_countNbl($) {
  3992. my ($name) = @_;
  3993. my $hash = $defs{$name};
  3994. my ($cc,$hc,$bst,$st,$rt);
  3995. # Background-Startzeit
  3996. $bst = [gettimeofday];
  3997. my $dbh = DbLog_ConnectNewDBH($hash);
  3998. if (!$dbh) {
  3999. my $err = encode_base64("DbLog $name: DBLog_Set - count - DB connect not possible","");
  4000. return "$name|0|0|$err|0";
  4001. } else {
  4002. Log3 $name,4,"DbLog $name: Records count requested.";
  4003. # SQL-Startzeit
  4004. $st = [gettimeofday];
  4005. $hc = $dbh->selectrow_array('SELECT count(*) FROM history');
  4006. $cc = $dbh->selectrow_array('SELECT count(*) FROM current');
  4007. $dbh->disconnect();
  4008. # SQL-Laufzeit ermitteln
  4009. $rt = tv_interval($st);
  4010. }
  4011. # Background-Laufzeit ermitteln
  4012. my $brt = tv_interval($bst);
  4013. $rt = $rt.",".$brt;
  4014. return "$name|$cc|$hc|0|$rt";
  4015. }
  4016. #########################################################################################
  4017. # DBLog - count non-blocking Rückkehrfunktion
  4018. #########################################################################################
  4019. sub DbLog_countNbl_finished($)
  4020. {
  4021. my ($string) = @_;
  4022. my @a = split("\\|",$string);
  4023. my $name = $a[0];
  4024. my $hash = $defs{$name};
  4025. my $cc = $a[1];
  4026. my $hc = $a[2];
  4027. my $err = decode_base64($a[3]) if ($a[3]);
  4028. my $bt = $a[4] if($a[4]);
  4029. readingsSingleUpdate($hash,"state",$err,1) if($err);
  4030. readingsSingleUpdate($hash,"countHistory",$hc,1) if ($hc);
  4031. readingsSingleUpdate($hash,"countCurrent",$cc,1) if ($cc);
  4032. if(AttrVal($name, "showproctime", undef) && $bt) {
  4033. my ($rt,$brt) = split(",", $bt);
  4034. readingsBeginUpdate($hash);
  4035. readingsBulkUpdate($hash, "background_processing_time", sprintf("%.4f",$brt));
  4036. readingsBulkUpdate($hash, "sql_processing_time", sprintf("%.4f",$rt));
  4037. readingsEndUpdate($hash, 1);
  4038. }
  4039. delete $hash->{HELPER}{COUNT_PID};
  4040. return;
  4041. }
  4042. #########################################################################################
  4043. # DBLog - deleteOldDays non-blocking
  4044. #########################################################################################
  4045. sub DbLog_deldaysNbl($) {
  4046. my ($name) = @_;
  4047. my $hash = $defs{$name};
  4048. my $dbconn = $hash->{dbconn};
  4049. my $dbuser = $hash->{dbuser};
  4050. my $dbpassword = $attr{"sec$name"}{secret};
  4051. my $days = delete($hash->{HELPER}{DELDAYS});
  4052. my ($cmd,$dbh,$rows,$error,$sth,$ret,$bst,$brt,$st,$rt);
  4053. Log3 ($name, 5, "DbLog $name -> Start DbLog_deldaysNbl $days");
  4054. # Background-Startzeit
  4055. $bst = [gettimeofday];
  4056. my ($useac,$useta) = DbLog_commitMode($hash);
  4057. if(!$useac) {
  4058. eval {$dbh = DBI->connect("dbi:$dbconn", $dbuser, $dbpassword, { PrintError => 0, RaiseError => 1, AutoCommit => 0 });};
  4059. } elsif($useac == 1) {
  4060. eval {$dbh = DBI->connect("dbi:$dbconn", $dbuser, $dbpassword, { PrintError => 0, RaiseError => 1, AutoCommit => 1 });};
  4061. } else {
  4062. # Server default
  4063. eval {$dbh = DBI->connect("dbi:$dbconn", $dbuser, $dbpassword, { PrintError => 0, RaiseError => 1 });};
  4064. }
  4065. if ($@) {
  4066. $error = encode_base64($@,"");
  4067. Log3 ($name, 2, "DbLog $name - Error: $@");
  4068. Log3 ($name, 5, "DbLog $name -> DbLog_deldaysNbl finished");
  4069. return "$name|0|0|$error";
  4070. }
  4071. my $ac = ($dbh->{AutoCommit})?"ON":"OFF";
  4072. my $tm = ($useta)?"ON":"OFF";
  4073. Log3 $hash->{NAME}, 4, "DbLog $name -> AutoCommit mode: $ac, Transaction mode: $tm";
  4074. $cmd = "delete from history where TIMESTAMP < ";
  4075. if ($hash->{MODEL} eq 'SQLITE') {
  4076. $cmd .= "datetime('now', '-$days days')";
  4077. } elsif ($hash->{MODEL} eq 'MYSQL') {
  4078. $cmd .= "DATE_SUB(CURDATE(),INTERVAL $days DAY)";
  4079. } elsif ($hash->{MODEL} eq 'POSTGRESQL') {
  4080. $cmd .= "NOW() - INTERVAL '$days' DAY";
  4081. } else {
  4082. $ret = 'Unknown database type. Maybe you can try userCommand anyway.';
  4083. $error = encode_base64($ret,"");
  4084. Log3 ($name, 2, "DbLog $name - Error: $ret");
  4085. Log3 ($name, 5, "DbLog $name -> DbLog_deldaysNbl finished");
  4086. return "$name|0|0|$error";
  4087. }
  4088. # SQL-Startzeit
  4089. $st = [gettimeofday];
  4090. eval {
  4091. $sth = $dbh->prepare($cmd);
  4092. $sth->execute();
  4093. };
  4094. if ($@) {
  4095. $error = encode_base64($@,"");
  4096. Log3 ($name, 2, "DbLog $name - $@");
  4097. $dbh->disconnect;
  4098. Log3 ($name, 4, "DbLog $name -> BlockingCall DbLog_deldaysNbl finished");
  4099. return "$name|0|0|$error";
  4100. } else {
  4101. $rows = $sth->rows;
  4102. $dbh->commit() if(!$dbh->{AutoCommit});
  4103. $dbh->disconnect;
  4104. }
  4105. # SQL-Laufzeit ermitteln
  4106. $rt = tv_interval($st);
  4107. # Background-Laufzeit ermitteln
  4108. $brt = tv_interval($bst);
  4109. $rt = $rt.",".$brt;
  4110. Log3 ($name, 5, "DbLog $name -> DbLog_deldaysNbl finished");
  4111. return "$name|$rows|$rt|0";
  4112. }
  4113. #########################################################################################
  4114. # DBLog - deleteOldDays non-blocking Rückkehrfunktion
  4115. #########################################################################################
  4116. sub DbLog_deldaysNbl_done($) {
  4117. my ($string) = @_;
  4118. my @a = split("\\|",$string);
  4119. my $name = $a[0];
  4120. my $hash = $defs{$name};
  4121. my $rows = $a[1];
  4122. my $bt = $a[2] if($a[2]);
  4123. my $err = decode_base64($a[3]) if ($a[3]);
  4124. Log3 ($name, 5, "DbLog $name -> Start DbLog_deldaysNbl_done");
  4125. if ($err) {
  4126. readingsSingleUpdate($hash,"state",$err,1);
  4127. delete $hash->{HELPER}{DELDAYS_PID};
  4128. Log3 ($name, 5, "DbLog $name -> DbLog_deldaysNbl_done finished");
  4129. return;
  4130. } else {
  4131. if(AttrVal($name, "showproctime", undef) && $bt) {
  4132. my ($rt,$brt) = split(",", $bt);
  4133. readingsBeginUpdate($hash);
  4134. readingsBulkUpdate($hash, "background_processing_time", sprintf("%.4f",$brt));
  4135. readingsBulkUpdate($hash, "sql_processing_time", sprintf("%.4f",$rt));
  4136. readingsEndUpdate($hash, 1);
  4137. }
  4138. readingsSingleUpdate($hash, "lastRowsDeleted", $rows ,1);
  4139. }
  4140. my $db = (split(/;|=/, $hash->{dbconn}))[1];
  4141. Log3 ($name, 3, "DbLog $name -> deleteOldDaysNbl finished. $rows entries of database $db deleted.");
  4142. delete $hash->{HELPER}{DELDAYS_PID};
  4143. Log3 ($name, 5, "DbLog $name -> DbLog_deldaysNbl_done finished");
  4144. return;
  4145. }
  4146. ################################################################
  4147. # benutzte DB-Feldlängen in Helper und Internals setzen
  4148. ################################################################
  4149. sub DbLog_setinternalcols ($){
  4150. my ($hash)= @_;
  4151. my $name = $hash->{NAME};
  4152. $hash->{HELPER}{DEVICECOL} = $columns{DEVICE};
  4153. $hash->{HELPER}{TYPECOL} = $columns{TYPE};
  4154. $hash->{HELPER}{EVENTCOL} = AttrVal($name, "colEvent", $columns{EVENT});
  4155. $hash->{HELPER}{READINGCOL} = AttrVal($name, "colReading", $columns{READING});
  4156. $hash->{HELPER}{VALUECOL} = AttrVal($name, "colValue", $columns{VALUE});
  4157. $hash->{HELPER}{UNITCOL} = $columns{UNIT};
  4158. $hash->{COLUMNS} = "field length used for Device: $hash->{HELPER}{DEVICECOL}, Type: $hash->{HELPER}{TYPECOL}, Event: $hash->{HELPER}{EVENTCOL}, Reading: $hash->{HELPER}{READINGCOL}, Value: $hash->{HELPER}{VALUECOL}, Unit: $hash->{HELPER}{UNITCOL} ";
  4159. # Statusbit "Columns sind gesetzt"
  4160. $hash->{HELPER}{COLSET} = 1;
  4161. return;
  4162. }
  4163. ################################################################
  4164. # reopen DB-Connection nach Ablauf set ... reopen [n] seconds
  4165. ################################################################
  4166. sub DbLog_reopen ($){
  4167. my ($hash) = @_;
  4168. my $name = $hash->{NAME};
  4169. my $async = AttrVal($name, "asyncMode", undef);
  4170. RemoveInternalTimer($hash, "DbLog_reopen");
  4171. if(DbLog_ConnectPush($hash)) {
  4172. # Statusbit "Kein Schreiben in DB erlauben" löschen
  4173. my $delay = delete $hash->{HELPER}{REOPEN_RUNS};
  4174. Log3($name, 2, "DbLog $name: Database connection reopened (it was $delay seconds closed).") if($delay);
  4175. readingsSingleUpdate($hash, "state", "reopened", 1);
  4176. $hash->{HELPER}{OLDSTATE} = "reopened";
  4177. DbLog_execmemcache($hash) if($async);
  4178. } else {
  4179. InternalTimer(gettimeofday()+30, "DbLog_reopen", $hash, 0);
  4180. }
  4181. return;
  4182. }
  4183. ################################################################
  4184. # check ob primary key genutzt wird
  4185. ################################################################
  4186. sub DbLog_checkUsePK ($$){
  4187. my ($hash,$dbh) = @_;
  4188. my $name = $hash->{NAME};
  4189. my $dbconn = $hash->{dbconn};
  4190. my $upkh = 0;
  4191. my $upkc = 0;
  4192. my (@pkh,@pkc);
  4193. my $db = (split("=",(split(";",$dbconn))[0]))[1];
  4194. eval {@pkh = $dbh->primary_key( undef, undef, 'history' );};
  4195. eval {@pkc = $dbh->primary_key( undef, undef, 'current' );};
  4196. my $pkh = (!@pkh || @pkh eq "")?"none":join(",",@pkh);
  4197. my $pkc = (!@pkc || @pkc eq "")?"none":join(",",@pkc);
  4198. $pkh =~ tr/"//d;
  4199. $pkc =~ tr/"//d;
  4200. $upkh = 1 if(@pkh && @pkh ne "none");
  4201. $upkc = 1 if(@pkc && @pkc ne "none");
  4202. Log3 $hash->{NAME}, 5, "DbLog $name -> Primary Key used in $db.history: $pkh";
  4203. Log3 $hash->{NAME}, 5, "DbLog $name -> Primary Key used in $db.current: $pkc";
  4204. return ($upkh,$upkc,$pkh,$pkc);
  4205. }
  4206. ################################################################
  4207. # Routine für FHEMWEB Detailanzeige
  4208. ################################################################
  4209. sub DbLog_fhemwebFn($$$$) {
  4210. my ($FW_wname, $d, $room, $pageHash) = @_; # pageHash is set for summaryFn.
  4211. my $ret;
  4212. my $newIdx=1;
  4213. while($defs{"SVG_${d}_$newIdx"}) {
  4214. $newIdx++;
  4215. }
  4216. my $name = "SVG_${d}_$newIdx";
  4217. $ret .= FW_pH("cmd=define $name SVG $d:templateDB:HISTORY;".
  4218. "set $name copyGplotFile&detail=$name",
  4219. "<div class=\"dval\">Create SVG plot from DbLog</div>", 0, "dval", 1);
  4220. return $ret;
  4221. }
  4222. ################################################################
  4223. # Dropdown-Menü cuurent-Tabelle SVG-Editor
  4224. ################################################################
  4225. sub DbLog_sampleDataFn($$$$$) {
  4226. my ($dlName, $dlog, $max, $conf, $wName) = @_;
  4227. my $desc = "Device:Reading";
  4228. my @htmlArr;
  4229. my @example;
  4230. my @colregs;
  4231. my $counter;
  4232. my $currentPresent = AttrVal($dlName,'DbLogType','History');
  4233. my $dbhf = DbLog_ConnectNewDBH($defs{$dlName});
  4234. return if(!$dbhf);
  4235. # check presence of table current
  4236. # avoids fhem from crash if table 'current' is not present and attr DbLogType is set to /Current/
  4237. my $prescurr = eval {$dbhf->selectrow_array("select count(*) from current");} || 0;
  4238. Log3($dlName, 5, "DbLog $dlName: Table current present : $prescurr (0 = not present or no content)");
  4239. if($currentPresent =~ m/Current|SampleFill/ && $prescurr) {
  4240. # Table Current present, use it for sample data
  4241. my $query = "select device,reading from current where device <> '' group by device,reading";
  4242. my $sth = $dbhf->prepare( $query );
  4243. $sth->execute();
  4244. while (my @line = $sth->fetchrow_array()) {
  4245. $counter++;
  4246. push (@example, join (" ",@line)) if($counter <= 8); # show max 8 examples
  4247. push (@colregs, "$line[0]:$line[1]"); # push all eventTypes to selection list
  4248. }
  4249. $dbhf->disconnect();
  4250. my $cols = join(",", sort { "\L$a" cmp "\L$b" } @colregs);
  4251. # $max = 8 if($max > 8); # auskommentiert 27.02.2018, Notwendigkeit unklar (forum:#76008)
  4252. for(my $r=0; $r < $max; $r++) {
  4253. my @f = split(":", ($dlog->[$r] ? $dlog->[$r] : ":::"), 4);
  4254. my $ret = "";
  4255. $ret .= SVG_sel("par_${r}_0", $cols, "$f[0]:$f[1]");
  4256. # $ret .= SVG_txt("par_${r}_2", "", $f[2], 1); # Default not yet implemented
  4257. # $ret .= SVG_txt("par_${r}_3", "", $f[3], 3); # Function
  4258. # $ret .= SVG_txt("par_${r}_4", "", $f[4], 3); # RegExp
  4259. push @htmlArr, $ret;
  4260. }
  4261. } else {
  4262. # Table Current not present, so create an empty input field
  4263. push @example, "No sample data due to missing table 'Current'";
  4264. # $max = 8 if($max > 8); # auskommentiert 27.02.2018, Notwendigkeit unklar (forum:#76008)
  4265. for(my $r=0; $r < $max; $r++) {
  4266. my @f = split(":", ($dlog->[$r] ? $dlog->[$r] : ":::"), 4);
  4267. my $ret = "";
  4268. no warnings 'uninitialized'; # Forum:74690, bug unitialized
  4269. $ret .= SVG_txt("par_${r}_0", "", "$f[0]:$f[1]:$f[2]:$f[3]", 20);
  4270. use warnings;
  4271. # $ret .= SVG_txt("par_${r}_2", "", $f[2], 1); # Default not yet implemented
  4272. # $ret .= SVG_txt("par_${r}_3", "", $f[3], 3); # Function
  4273. # $ret .= SVG_txt("par_${r}_4", "", $f[4], 3); # RegExp
  4274. push @htmlArr, $ret;
  4275. }
  4276. }
  4277. return ($desc, \@htmlArr, join("<br>", @example));
  4278. }
  4279. ################################################################
  4280. #
  4281. # Charting Specific functions start here
  4282. #
  4283. ################################################################
  4284. ################################################################
  4285. #
  4286. # Error handling, returns a JSON String
  4287. #
  4288. ################################################################
  4289. sub jsonError($) {
  4290. my $errormsg = $_[0];
  4291. my $json = '{"success": "false", "msg":"'.$errormsg.'"}';
  4292. return $json;
  4293. }
  4294. ################################################################
  4295. #
  4296. # Prepare the SQL String
  4297. #
  4298. ################################################################
  4299. sub prepareSql(@) {
  4300. my ($hash, @a) = @_;
  4301. my $starttime = $_[5];
  4302. $starttime =~ s/_/ /;
  4303. my $endtime = $_[6];
  4304. $endtime =~ s/_/ /;
  4305. my $device = $_[7];
  4306. my $userquery = $_[8];
  4307. my $xaxis = $_[9];
  4308. my $yaxis = $_[10];
  4309. my $savename = $_[11];
  4310. my $jsonChartConfig = $_[12];
  4311. my $pagingstart = $_[13];
  4312. my $paginglimit = $_[14];
  4313. my $dbmodel = $hash->{MODEL};
  4314. my ($sql, $jsonstring, $countsql, $hourstats, $daystats, $weekstats, $monthstats, $yearstats);
  4315. if ($dbmodel eq "POSTGRESQL") {
  4316. ### POSTGRESQL Queries for Statistics ###
  4317. ### hour:
  4318. $hourstats = "SELECT to_char(timestamp, 'YYYY-MM-DD HH24:00:00') AS TIMESTAMP, SUM(VALUE::float) AS SUM, ";
  4319. $hourstats .= "AVG(VALUE::float) AS AVG, MIN(VALUE::float) AS MIN, MAX(VALUE::float) AS MAX, ";
  4320. $hourstats .= "COUNT(VALUE) AS COUNT FROM history WHERE READING = '$yaxis' AND DEVICE = '$device' ";
  4321. $hourstats .= "AND TIMESTAMP Between '$starttime' AND '$endtime' GROUP BY 1 ORDER BY 1;";
  4322. ### day:
  4323. $daystats = "SELECT to_char(timestamp, 'YYYY-MM-DD 00:00:00') AS TIMESTAMP, SUM(VALUE::float) AS SUM, ";
  4324. $daystats .= "AVG(VALUE::float) AS AVG, MIN(VALUE::float) AS MIN, MAX(VALUE::float) AS MAX, ";
  4325. $daystats .= "COUNT(VALUE) AS COUNT FROM history WHERE READING = '$yaxis' AND DEVICE = '$device' ";
  4326. $daystats .= "AND TIMESTAMP Between '$starttime' AND '$endtime' GROUP BY 1 ORDER BY 1;";
  4327. ### week:
  4328. $weekstats = "SELECT date_trunc('week',timestamp) AS TIMESTAMP, SUM(VALUE::float) AS SUM, ";
  4329. $weekstats .= "AVG(VALUE::float) AS AVG, MIN(VALUE::float) AS MIN, MAX(VALUE::float) AS MAX, ";
  4330. $weekstats .= "COUNT(VALUE) AS COUNT FROM history WHERE READING = '$yaxis' AND DEVICE = '$device' ";
  4331. $weekstats .= "AND TIMESTAMP Between '$starttime' AND '$endtime' GROUP BY 1 ORDER BY 1;";
  4332. ### month:
  4333. $monthstats = "SELECT to_char(timestamp, 'YYYY-MM-01 00:00:00') AS TIMESTAMP, SUM(VALUE::float) AS SUM, ";
  4334. $monthstats .= "AVG(VALUE::float) AS AVG, MIN(VALUE::float) AS MIN, MAX(VALUE::float) AS MAX, ";
  4335. $monthstats .= "COUNT(VALUE) AS COUNT FROM history WHERE READING = '$yaxis' AND DEVICE = '$device' ";
  4336. $monthstats .= "AND TIMESTAMP Between '$starttime' AND '$endtime' GROUP BY 1 ORDER BY 1;";
  4337. ### year:
  4338. $yearstats = "SELECT to_char(timestamp, 'YYYY-01-01 00:00:00') AS TIMESTAMP, SUM(VALUE::float) AS SUM, ";
  4339. $yearstats .= "AVG(VALUE::float) AS AVG, MIN(VALUE::float) AS MIN, MAX(VALUE::float) AS MAX, ";
  4340. $yearstats .= "COUNT(VALUE) AS COUNT FROM history WHERE READING = '$yaxis' AND DEVICE = '$device' ";
  4341. $yearstats .= "AND TIMESTAMP Between '$starttime' AND '$endtime' GROUP BY 1 ORDER BY 1;";
  4342. } elsif ($dbmodel eq "MYSQL") {
  4343. ### MYSQL Queries for Statistics ###
  4344. ### hour:
  4345. $hourstats = "SELECT date_format(timestamp, '%Y-%m-%d %H:00:00') AS TIMESTAMP, SUM(CAST(VALUE AS DECIMAL(12,4))) AS SUM, ";
  4346. $hourstats .= "AVG(CAST(VALUE AS DECIMAL(12,4))) AS AVG, MIN(CAST(VALUE AS DECIMAL(12,4))) AS MIN, ";
  4347. $hourstats .= "MAX(CAST(VALUE AS DECIMAL(12,4))) AS MAX, COUNT(VALUE) AS COUNT FROM history WHERE READING = '$yaxis' ";
  4348. $hourstats .= "AND DEVICE = '$device' AND TIMESTAMP Between '$starttime' AND '$endtime' GROUP BY 1 ORDER BY 1;";
  4349. ### day:
  4350. $daystats = "SELECT date_format(timestamp, '%Y-%m-%d 00:00:00') AS TIMESTAMP, SUM(CAST(VALUE AS DECIMAL(12,4))) AS SUM, ";
  4351. $daystats .= "AVG(CAST(VALUE AS DECIMAL(12,4))) AS AVG, MIN(CAST(VALUE AS DECIMAL(12,4))) AS MIN, ";
  4352. $daystats .= "MAX(CAST(VALUE AS DECIMAL(12,4))) AS MAX, COUNT(VALUE) AS COUNT FROM history WHERE READING = '$yaxis' ";
  4353. $daystats .= "AND DEVICE = '$device' AND TIMESTAMP Between '$starttime' AND '$endtime' GROUP BY 1 ORDER BY 1;";
  4354. ### week:
  4355. $weekstats = "SELECT date_format(timestamp, '%Y-%m-%d 00:00:00') AS TIMESTAMP, SUM(CAST(VALUE AS DECIMAL(12,4))) AS SUM, ";
  4356. $weekstats .= "AVG(CAST(VALUE AS DECIMAL(12,4))) AS AVG, MIN(CAST(VALUE AS DECIMAL(12,4))) AS MIN, ";
  4357. $weekstats .= "MAX(CAST(VALUE AS DECIMAL(12,4))) AS MAX, COUNT(VALUE) AS COUNT FROM history WHERE READING = '$yaxis' ";
  4358. $weekstats .= "AND DEVICE = '$device' AND TIMESTAMP Between '$starttime' AND '$endtime' ";
  4359. $weekstats .= "GROUP BY date_format(timestamp, '%Y-%u 00:00:00') ORDER BY 1;";
  4360. ### month:
  4361. $monthstats = "SELECT date_format(timestamp, '%Y-%m-01 00:00:00') AS TIMESTAMP, SUM(CAST(VALUE AS DECIMAL(12,4))) AS SUM, ";
  4362. $monthstats .= "AVG(CAST(VALUE AS DECIMAL(12,4))) AS AVG, MIN(CAST(VALUE AS DECIMAL(12,4))) AS MIN, ";
  4363. $monthstats .= "MAX(CAST(VALUE AS DECIMAL(12,4))) AS MAX, COUNT(VALUE) AS COUNT FROM history WHERE READING = '$yaxis' ";
  4364. $monthstats .= "AND DEVICE = '$device' AND TIMESTAMP Between '$starttime' AND '$endtime' GROUP BY 1 ORDER BY 1;";
  4365. ### year:
  4366. $yearstats = "SELECT date_format(timestamp, '%Y-01-01 00:00:00') AS TIMESTAMP, SUM(CAST(VALUE AS DECIMAL(12,4))) AS SUM, ";
  4367. $yearstats .= "AVG(CAST(VALUE AS DECIMAL(12,4))) AS AVG, MIN(CAST(VALUE AS DECIMAL(12,4))) AS MIN, ";
  4368. $yearstats .= "MAX(CAST(VALUE AS DECIMAL(12,4))) AS MAX, COUNT(VALUE) AS COUNT FROM history WHERE READING = '$yaxis' ";
  4369. $yearstats .= "AND DEVICE = '$device' AND TIMESTAMP Between '$starttime' AND '$endtime' GROUP BY 1 ORDER BY 1;";
  4370. } elsif ($dbmodel eq "SQLITE") {
  4371. ### SQLITE Queries for Statistics ###
  4372. ### hour:
  4373. $hourstats = "SELECT TIMESTAMP, SUM(CAST(VALUE AS FLOAT)) AS SUM, AVG(CAST(VALUE AS FLOAT)) AS AVG, ";
  4374. $hourstats .= "MIN(CAST(VALUE AS FLOAT)) AS MIN, MAX(CAST(VALUE AS FLOAT)) AS MAX, COUNT(VALUE) AS COUNT ";
  4375. $hourstats .= "FROM history WHERE READING = '$yaxis' AND DEVICE = '$device' ";
  4376. $hourstats .= "AND TIMESTAMP Between '$starttime' AND '$endtime' GROUP BY strftime('%Y-%m-%d %H:00:00', TIMESTAMP);";
  4377. ### day:
  4378. $daystats = "SELECT TIMESTAMP, SUM(CAST(VALUE AS FLOAT)) AS SUM, AVG(CAST(VALUE AS FLOAT)) AS AVG, ";
  4379. $daystats .= "MIN(CAST(VALUE AS FLOAT)) AS MIN, MAX(CAST(VALUE AS FLOAT)) AS MAX, COUNT(VALUE) AS COUNT ";
  4380. $daystats .= "FROM history WHERE READING = '$yaxis' AND DEVICE = '$device' ";
  4381. $daystats .= "AND TIMESTAMP Between '$starttime' AND '$endtime' GROUP BY strftime('%Y-%m-%d 00:00:00', TIMESTAMP);";
  4382. ### week:
  4383. $weekstats = "SELECT TIMESTAMP, SUM(CAST(VALUE AS FLOAT)) AS SUM, AVG(CAST(VALUE AS FLOAT)) AS AVG, ";
  4384. $weekstats .= "MIN(CAST(VALUE AS FLOAT)) AS MIN, MAX(CAST(VALUE AS FLOAT)) AS MAX, COUNT(VALUE) AS COUNT ";
  4385. $weekstats .= "FROM history WHERE READING = '$yaxis' AND DEVICE = '$device' ";
  4386. $weekstats .= "AND TIMESTAMP Between '$starttime' AND '$endtime' GROUP BY strftime('%Y-%W 00:00:00', TIMESTAMP);";
  4387. ### month:
  4388. $monthstats = "SELECT TIMESTAMP, SUM(CAST(VALUE AS FLOAT)) AS SUM, AVG(CAST(VALUE AS FLOAT)) AS AVG, ";
  4389. $monthstats .= "MIN(CAST(VALUE AS FLOAT)) AS MIN, MAX(CAST(VALUE AS FLOAT)) AS MAX, COUNT(VALUE) AS COUNT ";
  4390. $monthstats .= "FROM history WHERE READING = '$yaxis' AND DEVICE = '$device' ";
  4391. $monthstats .= "AND TIMESTAMP Between '$starttime' AND '$endtime' GROUP BY strftime('%Y-%m 00:00:00', TIMESTAMP);";
  4392. ### year:
  4393. $yearstats = "SELECT TIMESTAMP, SUM(CAST(VALUE AS FLOAT)) AS SUM, AVG(CAST(VALUE AS FLOAT)) AS AVG, ";
  4394. $yearstats .= "MIN(CAST(VALUE AS FLOAT)) AS MIN, MAX(CAST(VALUE AS FLOAT)) AS MAX, COUNT(VALUE) AS COUNT ";
  4395. $yearstats .= "FROM history WHERE READING = '$yaxis' AND DEVICE = '$device' ";
  4396. $yearstats .= "AND TIMESTAMP Between '$starttime' AND '$endtime' GROUP BY strftime('%Y 00:00:00', TIMESTAMP);";
  4397. } else {
  4398. $sql = "errordb";
  4399. }
  4400. if($userquery eq "getreadings") {
  4401. $sql = "SELECT distinct(reading) FROM history WHERE device = '".$device."'";
  4402. } elsif($userquery eq "getdevices") {
  4403. $sql = "SELECT distinct(device) FROM history";
  4404. } elsif($userquery eq "timerange") {
  4405. $sql = "SELECT ".$xaxis.", VALUE FROM history WHERE READING = '$yaxis' AND DEVICE = '$device' AND TIMESTAMP Between '$starttime' AND '$endtime' ORDER BY TIMESTAMP;";
  4406. } elsif($userquery eq "hourstats") {
  4407. $sql = $hourstats;
  4408. } elsif($userquery eq "daystats") {
  4409. $sql = $daystats;
  4410. } elsif($userquery eq "weekstats") {
  4411. $sql = $weekstats;
  4412. } elsif($userquery eq "monthstats") {
  4413. $sql = $monthstats;
  4414. } elsif($userquery eq "yearstats") {
  4415. $sql = $yearstats;
  4416. } elsif($userquery eq "savechart") {
  4417. $sql = "INSERT INTO frontend (TYPE, NAME, VALUE) VALUES ('savedchart', '$savename', '$jsonChartConfig')";
  4418. } elsif($userquery eq "renamechart") {
  4419. $sql = "UPDATE frontend SET NAME = '$savename' WHERE ID = '$jsonChartConfig'";
  4420. } elsif($userquery eq "deletechart") {
  4421. $sql = "DELETE FROM frontend WHERE TYPE = 'savedchart' AND ID = '".$savename."'";
  4422. } elsif($userquery eq "updatechart") {
  4423. $sql = "UPDATE frontend SET VALUE = '$jsonChartConfig' WHERE ID = '".$savename."'";
  4424. } elsif($userquery eq "getcharts") {
  4425. $sql = "SELECT * FROM frontend WHERE TYPE = 'savedchart'";
  4426. } elsif($userquery eq "getTableData") {
  4427. if ($device ne '""' && $yaxis ne '""') {
  4428. $sql = "SELECT * FROM history WHERE READING = '$yaxis' AND DEVICE = '$device' ";
  4429. $sql .= "AND TIMESTAMP Between '$starttime' AND '$endtime'";
  4430. $sql .= " LIMIT '$paginglimit' OFFSET '$pagingstart'";
  4431. $countsql = "SELECT count(*) FROM history WHERE READING = '$yaxis' AND DEVICE = '$device' ";
  4432. $countsql .= "AND TIMESTAMP Between '$starttime' AND '$endtime'";
  4433. } elsif($device ne '""' && $yaxis eq '""') {
  4434. $sql = "SELECT * FROM history WHERE DEVICE = '$device' ";
  4435. $sql .= "AND TIMESTAMP Between '$starttime' AND '$endtime'";
  4436. $sql .= " LIMIT '$paginglimit' OFFSET '$pagingstart'";
  4437. $countsql = "SELECT count(*) FROM history WHERE DEVICE = '$device' ";
  4438. $countsql .= "AND TIMESTAMP Between '$starttime' AND '$endtime'";
  4439. } else {
  4440. $sql = "SELECT * FROM history";
  4441. $sql .= " WHERE TIMESTAMP Between '$starttime' AND '$endtime'";
  4442. $sql .= " LIMIT '$paginglimit' OFFSET '$pagingstart'";
  4443. $countsql = "SELECT count(*) FROM history";
  4444. $countsql .= " WHERE TIMESTAMP Between '$starttime' AND '$endtime'";
  4445. }
  4446. return ($sql, $countsql);
  4447. } else {
  4448. $sql = "error";
  4449. }
  4450. return $sql;
  4451. }
  4452. ################################################################
  4453. #
  4454. # Do the query
  4455. #
  4456. ################################################################
  4457. sub chartQuery($@) {
  4458. my ($sql, $countsql) = prepareSql(@_);
  4459. if ($sql eq "error") {
  4460. return jsonError("Could not setup SQL String. Maybe the Database is busy, please try again!");
  4461. } elsif ($sql eq "errordb") {
  4462. return jsonError("The Database Type is not supported!");
  4463. }
  4464. my ($hash, @a) = @_;
  4465. my $dbhf = DbLog_ConnectNewDBH($hash);
  4466. return if(!$dbhf);
  4467. my $totalcount;
  4468. if (defined $countsql && $countsql ne "") {
  4469. my $query_handle = $dbhf->prepare($countsql)
  4470. or return jsonError("Could not prepare statement: " . $dbhf->errstr . ", SQL was: " .$countsql);
  4471. $query_handle->execute()
  4472. or return jsonError("Could not execute statement: " . $query_handle->errstr);
  4473. my @data = $query_handle->fetchrow_array();
  4474. $totalcount = join(", ", @data);
  4475. }
  4476. # prepare the query
  4477. my $query_handle = $dbhf->prepare($sql)
  4478. or return jsonError("Could not prepare statement: " . $dbhf->errstr . ", SQL was: " .$sql);
  4479. # execute the query
  4480. $query_handle->execute()
  4481. or return jsonError("Could not execute statement: " . $query_handle->errstr);
  4482. my $columns = $query_handle->{'NAME'};
  4483. my $columncnt;
  4484. # When columns are empty but execution was successful, we have done a successful INSERT, UPDATE or DELETE
  4485. if($columns) {
  4486. $columncnt = scalar @$columns;
  4487. } else {
  4488. return '{"success": "true", "msg":"All ok"}';
  4489. }
  4490. my $i = 0;
  4491. my $jsonstring = '{"data":[';
  4492. while ( my @data = $query_handle->fetchrow_array()) {
  4493. if($i == 0) {
  4494. $jsonstring .= '{';
  4495. } else {
  4496. $jsonstring .= ',{';
  4497. }
  4498. for ($i = 0; $i < $columncnt; $i++) {
  4499. $jsonstring .= '"';
  4500. $jsonstring .= uc($query_handle->{NAME}->[$i]);
  4501. $jsonstring .= '":';
  4502. if (defined $data[$i]) {
  4503. my $fragment = substr($data[$i],0,1);
  4504. if ($fragment eq "{") {
  4505. $jsonstring .= $data[$i];
  4506. } else {
  4507. $jsonstring .= '"'.$data[$i].'"';
  4508. }
  4509. } else {
  4510. $jsonstring .= '""'
  4511. }
  4512. if($i != ($columncnt -1)) {
  4513. $jsonstring .= ',';
  4514. }
  4515. }
  4516. $jsonstring .= '}';
  4517. }
  4518. $dbhf->disconnect();
  4519. $jsonstring .= ']';
  4520. if (defined $totalcount && $totalcount ne "") {
  4521. $jsonstring .= ',"totalCount": '.$totalcount.'}';
  4522. } else {
  4523. $jsonstring .= '}';
  4524. }
  4525. return $jsonstring;
  4526. }
  4527. #
  4528. # get <dbLog> ReadingsVal <device> <reading> <default>
  4529. # get <dbLog> ReadingsTimestamp <device> <reading> <default>
  4530. #
  4531. sub dbReadings($@) {
  4532. my($hash,@a) = @_;
  4533. my $dbhf = DbLog_ConnectNewDBH($hash);
  4534. return if(!$dbhf);
  4535. return 'Wrong Syntax for ReadingsVal!' unless defined($a[4]);
  4536. my $DbLogType = AttrVal($a[0],'DbLogType','current');
  4537. my $query;
  4538. if (lc($DbLogType) =~ m(current) ) {
  4539. $query = "select VALUE,TIMESTAMP from current where DEVICE= '$a[2]' and READING= '$a[3]'";
  4540. } else {
  4541. $query = "select VALUE,TIMESTAMP from history where DEVICE= '$a[2]' and READING= '$a[3]' order by TIMESTAMP desc limit 1";
  4542. }
  4543. my ($reading,$timestamp) = $dbhf->selectrow_array($query);
  4544. $dbhf->disconnect();
  4545. $reading = (defined($reading)) ? $reading : $a[4];
  4546. $timestamp = (defined($timestamp)) ? $timestamp : $a[4];
  4547. return $reading if $a[1] eq 'ReadingsVal';
  4548. return $timestamp if $a[1] eq 'ReadingsTimestamp';
  4549. return "Syntax error: $a[1]";
  4550. }
  4551. 1;
  4552. =pod
  4553. =item helper
  4554. =item summary logs events into a database
  4555. =item summary_DE loggt Events in eine Datenbank
  4556. =begin html
  4557. <a name="DbLog"></a>
  4558. <h3>DbLog</h3>
  4559. <ul>
  4560. <br>
  4561. With DbLog events can be stored in a database. SQLite, MySQL/MariaDB and PostgreSQL are supported databases. <br><br>
  4562. <b>Prereqisites</b> <br><br>
  4563. The Perl-modules <code>DBI</code> and <code>DBD::&lt;dbtype&gt;</code> are needed to be installed (use <code>cpan -i &lt;module&gt;</code>
  4564. if your distribution does not have it).
  4565. <br><br>
  4566. On a debian based system you may install these modules for instance by: <br><br>
  4567. <ul>
  4568. <table>
  4569. <colgroup> <col width=5%> <col width=95%> </colgroup>
  4570. <tr><td> <b>DBI</b> </td><td>: <code> sudo apt-get install libdbi-perl </code> </td></tr>
  4571. <tr><td> <b>MySQL</b> </td><td>: <code> sudo apt-get install [mysql-server] mysql-client libdbd-mysql libdbd-mysql-perl </code> (mysql-server only if you use a local MySQL-server installation) </td></tr>
  4572. <tr><td> <b>SQLite</b> </td><td>: <code> sudo apt-get install sqlite3 libdbi-perl libdbd-sqlite3-perl </code> </td></tr>
  4573. <tr><td> <b>PostgreSQL</b> </td><td>: <code> sudo apt-get install libdbd-pg-perl </code> </td></tr>
  4574. </table>
  4575. </ul>
  4576. <br>
  4577. <br>
  4578. <b>Preparations</b> <br><br>
  4579. At first you need to setup the database. <br>
  4580. Sample code and Scripts to prepare a MySQL/PostgreSQL/SQLite database you can find in
  4581. <a href="https://svn.fhem.de/trac/browser/trunk/fhem/contrib/dblog">SVN -&gt; contrib/dblog/db_create_&lt;DBType&gt;.sql</a>. <br>
  4582. (<b>Caution:</b> The local FHEM-Installation subdirectory ./contrib/dblog doesn't contain the freshest scripts !!)
  4583. <br><br>
  4584. The database contains two tables: <code>current</code> and <code>history</code>. <br>
  4585. The latter contains all events whereas the former only contains the last event for any given reading and device.
  4586. Please consider the <a href="#DbLogattr">attribute</a> DbLogType implicitly to determine the usage of tables
  4587. <code>current</code> and <code>history</code>.
  4588. <br><br>
  4589. The columns have the following meaning: <br><br>
  4590. <ul>
  4591. <table>
  4592. <colgroup> <col width=5%> <col width=95%> </colgroup>
  4593. <tr><td> TIMESTAMP </td><td>: timestamp of event, e.g. <code>2007-12-30 21:45:22</code> </td></tr>
  4594. <tr><td> DEVICE </td><td>: device name, e.g. <code>Wetterstation</code> </td></tr>
  4595. <tr><td> TYPE </td><td>: device type, e.g. <code>KS300</code> </td></tr>
  4596. <tr><td> EVENT </td><td>: event specification as full string, e.g. <code>humidity: 71 (%)</code> </td></tr>
  4597. <tr><td> READING </td><td>: name of reading extracted from event, e.g. <code>humidity</code> </td></tr>
  4598. <tr><td> VALUE </td><td>: actual reading extracted from event, e.g. <code>71</code> </td></tr>
  4599. <tr><td> UNIT </td><td>: unit extracted from event, e.g. <code>%</code> </td></tr>
  4600. </table>
  4601. </ul>
  4602. <br>
  4603. <br>
  4604. <b>create index</b> <br>
  4605. Due to reading performance, e.g. on creation of SVG-plots, it is very important that the <b>index "Search_Idx"</b>
  4606. or a comparable index (e.g. a primary key) is applied.
  4607. A sample code for creation of that index is also available in mentioned scripts of
  4608. <a href="https://svn.fhem.de/trac/browser/trunk/fhem/contrib/dblog">SVN -&gt; contrib/dblog/db_create_&lt;DBType&gt;.sql</a>.
  4609. <br><br>
  4610. The index "Search_Idx" can be created, e.g. in database 'fhem', by these statements (also subsequently): <br><br>
  4611. <ul>
  4612. <table>
  4613. <colgroup> <col width=5%> <col width=95%> </colgroup>
  4614. <tr><td> <b>MySQL</b> </td><td>: <code> CREATE INDEX Search_Idx ON `fhem`.`history` (DEVICE, READING, TIMESTAMP); </code> </td></tr>
  4615. <tr><td> <b>SQLite</b> </td><td>: <code> CREATE INDEX Search_Idx ON `history` (DEVICE, READING, TIMESTAMP); </code> </td></tr>
  4616. <tr><td> <b>PostgreSQL</b> </td><td>: <code> CREATE INDEX "Search_Idx" ON history USING btree (device, reading, "timestamp"); </code> </td></tr>
  4617. </table>
  4618. </ul>
  4619. <br>
  4620. For the connection to the database a <b>configuration file</b> is used.
  4621. The configuration is stored in a separate file to avoid storing the password in the main configuration file and to have it
  4622. visible in the output of the <a href="https://fhem.de/commandref.html#list">list</a> command.
  4623. <br><br>
  4624. The <b>configuration file</b> should be copied e.g. to /opt/fhem and has the following structure you have to customize
  4625. suitable to your conditions (decomment the appropriate raws and adjust it): <br><br>
  4626. <pre>
  4627. ####################################################################################
  4628. # database configuration file
  4629. #
  4630. # NOTE:
  4631. # If you don't use a value for user / password please delete the leading hash mark
  4632. # and write 'user => ""' respectively 'password => ""' instead !
  4633. #
  4634. #
  4635. ## for MySQL
  4636. ####################################################################################
  4637. #%dbconfig= (
  4638. # connection => "mysql:database=fhem;host=&lt;database host&gt;;port=3306",
  4639. # user => "fhemuser",
  4640. # password => "fhempassword",
  4641. # # optional enable(1) / disable(0) UTF-8 support (at least V 4.042 is necessary)
  4642. # utf8 => 1
  4643. #);
  4644. ####################################################################################
  4645. #
  4646. ## for PostgreSQL
  4647. ####################################################################################
  4648. #%dbconfig= (
  4649. # connection => "Pg:database=fhem;host=&lt;database host&gt;",
  4650. # user => "fhemuser",
  4651. # password => "fhempassword"
  4652. #);
  4653. ####################################################################################
  4654. #
  4655. ## for SQLite (username and password stay empty for SQLite)
  4656. ####################################################################################
  4657. #%dbconfig= (
  4658. # connection => "SQLite:dbname=/opt/fhem/fhem.db",
  4659. # user => "",
  4660. # password => ""
  4661. #);
  4662. ####################################################################################
  4663. </pre>
  4664. <br>
  4665. <a name="DbLogdefine"></a>
  4666. <b>Define</b>
  4667. <ul>
  4668. <br>
  4669. <code>define &lt;name&gt; DbLog &lt;configfilename&gt; &lt;regexp&gt;</code>
  4670. <br><br>
  4671. <code>&lt;configfilename&gt;</code> is the prepared <b>configuration file</b>. <br>
  4672. <code>&lt;regexp&gt;</code> is identical to the specification of regex in the <a href="https://fhem.de/commandref.html#FileLog">FileLog</a> definition.
  4673. <br><br>
  4674. <b>Example:</b>
  4675. <ul>
  4676. <code>define myDbLog DbLog /etc/fhem/db.conf .*:.*</code><br>
  4677. all events will stored into the database
  4678. </ul>
  4679. <br>
  4680. After you have defined your DbLog-device it is recommended to run the <b>configuration check</b> <br><br>
  4681. <ul>
  4682. <code>set &lt;name&gt; configCheck</code> <br>
  4683. </ul>
  4684. <br>
  4685. This check reports some important settings and gives recommendations back to you if proposals are indentified.
  4686. <br><br>
  4687. DbLog distinguishes between the synchronous (default) and asynchronous logmode. The logmode is adjustable by the
  4688. <a href="#DbLogattr">attribute</a> asyncMode. Since version 2.13.5 DbLog is supporting primary key (PK) set in table
  4689. current or history. If you want use PostgreSQL with PK it has to be at lest version 9.5.
  4690. <br><br>
  4691. The content of VALUE will be optimized for automated post-processing, e.g. <code>yes</code> is translated to <code>1</code>
  4692. <br><br>
  4693. The stored values can be retrieved by the following code like FileLog:<br>
  4694. <ul>
  4695. <code>get myDbLog - - 2012-11-10 2012-11-10 KS300:temperature::</code>
  4696. </ul>
  4697. <br>
  4698. <b>transfer FileLog-data to DbLog </b> <br><br>
  4699. There is the special module 98_FileLogConvert.pm available to transfer filelog-data to the DbLog-database. <br>
  4700. The module can be downloaded <a href="https://svn.fhem.de/trac/browser/trunk/fhem/contrib/98_FileLogConvert.pm"> here</a>
  4701. or from directory ./contrib instead.
  4702. Further informations and help you can find in the corresponding <a href="https://forum.fhem.de/index.php/topic,66383.0.html">
  4703. Forumthread </a>. <br><br><br>
  4704. <b>Reporting and Management of DbLog database content</b> <br><br>
  4705. By using <a href="https://fhem.de/commandref.html#SVG">SVG</a> database content can be visualized. <br>
  4706. Beyond that the module <a href="https://fhem.de/commandref.html#DbRep">DbRep</a> can be used to prepare tabular
  4707. database reports or you can manage the database content with available functions of that module.
  4708. <br><br><br>
  4709. <b>Troubleshooting</b> <br><br>
  4710. If after successful definition the DbLog-device doesn't work as expected, the following notes may help:
  4711. <br><br>
  4712. <ul>
  4713. <li> Have the preparatory steps as described in commandref been done ? (install software components, create tables and index) </li>
  4714. <li> Was "set &lt;name&gt; configCheck" executed after definition and potential errors fixed or rather the hints implemented ? </li>
  4715. <li> If configDB is used ... has the database configuration file been imported into configDB (e.g. by "configDB fileimport ./db.conf") ? </li>
  4716. <li> When creating a SVG-plot and no drop-down list with proposed values appear -> set attribute "DbLogType" to "Current/History". </li>
  4717. </ul>
  4718. <br>
  4719. If the notes don't lead to success, please increase verbose level of the DbLog-device to 4 or 5 and observe entries in
  4720. logfile relating to the DbLog-device.
  4721. For problem analysis please post the output of "list &lt;name&gt;", the result of "set &lt;name&gt; configCheck" and the
  4722. logfile entries of DbLog-device to the forum thread.
  4723. <br><br>
  4724. </ul>
  4725. <br>
  4726. <br>
  4727. <a name="DbLogset"></a>
  4728. <b>Set</b>
  4729. <ul>
  4730. <code>set &lt;name&gt; addCacheLine YYYY-MM-DD HH:MM:SS|&lt;device&gt;|&lt;type&gt;|&lt;event&gt;|&lt;reading&gt;|&lt;value&gt;|[&lt;unit&gt;] </code><br><br>
  4731. <ul> In asynchronous mode a new dataset is inserted to the Cache and will be processed at the next database sync cycle.
  4732. <br><br>
  4733. <b>Example:</b> <br>
  4734. set &lt;name&gt; addCacheLine 2017-12-05 17:03:59|MaxBathRoom|MAX|valveposition: 95|valveposition|95|% <br>
  4735. </ul><br>
  4736. <code>set &lt;name&gt; addLog &lt;devspec&gt;:&lt;Reading&gt; [Value] </code><br><br>
  4737. <ul> Inserts an additional log entry of a device/reading combination into the database.
  4738. Optionally you can enter a "Value" that is used as reading value for the dataset. If the value isn't specified (default),
  4739. the current value of the specified reading will be inserted into the database. The field "$EVENT" will be filled automatically
  4740. by "addLog". The device can be declared by a <a href="#devspec">device specification (devspec)</a>.
  4741. "Reading" will be evaluated as regular expression.
  4742. By the addLog-command NO additional events will be created !<br><br>
  4743. <b>Examples:</b> <br>
  4744. set &lt;name&gt; addLog SMA_Energymeter:Bezug_Wirkleistung <br>
  4745. set &lt;name&gt; addLog TYPE=SSCam:state <br>
  4746. set &lt;name&gt; addLog MyWetter:(fc10.*|fc8.*) <br>
  4747. set &lt;name&gt; addLog MyWetter:(wind|wind_ch.*) 20 <br>
  4748. set &lt;name&gt; addLog TYPE=CUL_HM:FILTER=model=HM-CC-RT-DN:FILTER=subType!=(virtual|):(measured-temp|desired-temp|actuator) <br>
  4749. </ul><br>
  4750. <code>set &lt;name&gt; clearReadings </code><br><br>
  4751. <ul> This function clears readings which were created by different DbLog-functions. </ul><br>
  4752. <code>set &lt;name&gt; commitCache </code><br><br>
  4753. <ul>In asynchronous mode (<a href="#DbLogattr">attribute</a> asyncMode=1), the cached data in memory will be written into the database
  4754. and subsequently the cache will be cleared. Thereby the internal timer for the asynchronous mode Modus will be set new.
  4755. The command can be usefull in case of you want to write the cached data manually or e.g. by an AT-device on a defined
  4756. point of time into the database. </ul><br>
  4757. <code>set &lt;name&gt; configCheck </code><br><br>
  4758. <ul>This command checks some important settings and give recommendations back to you if proposals are identified.
  4759. </ul><br>
  4760. <code>set &lt;name&gt; count </code><br/><br/>
  4761. <ul>Count records in tables current and history and write results into readings countCurrent and countHistory.</ul><br/>
  4762. <code>set &lt;name&gt; countNbl </code><br/><br/>
  4763. <ul>The non-blocking execution of "set &lt;name&gt; count".</ul><br/>
  4764. <code>set &lt;name&gt; deleteOldDays &lt;n&gt;</code><br/><br/>
  4765. <ul>Delete records from history older than &lt;n&gt; days. Number of deleted records will be written into reading lastRowsDeleted.</ul><br/>
  4766. <code>set &lt;name&gt; deleteOldDaysNbl &lt;n&gt;</code><br/><br/>
  4767. <ul>Is identical to function "deleteOldDays" whereupon deleteOldDaysNbl will be executed non-blocking. </ul><br/>
  4768. <code>set &lt;name&gt; eraseReadings </code><br><br>
  4769. <ul> This function deletes all readings except reading "state". </ul><br>
  4770. <a name="DbLogsetexportCache"></a>
  4771. <code>set &lt;name&gt; exportCache [nopurge | purgecache] </code><br><br>
  4772. <ul>If DbLog is operating in asynchronous mode, it's possible to exoprt the cache content into a textfile.
  4773. The file will be written to the directory (global->modpath)/log/ by default setting. The detination directory can be
  4774. changed by the <a href="#DbLogattr">attribute</a> expimpdir. <br>
  4775. The filename will be generated automatically and is built by a prefix "cache_", followed by DbLog-devicename and the
  4776. present timestmp, e.g. "cache_LogDB_2017-03-23_22-13-55". <br>
  4777. There are two options possible, "nopurge" respectively "purgecache". The option determines whether the cache content
  4778. will be deleted after export or not.
  4779. Using option "nopurge" (default) the cache content will be preserved. <br>
  4780. The <a href="#DbLogattr">attribute</a> "exportCacheAppend" defines, whether every export process creates a new export file
  4781. (default) or the cache content is appended to an existing (newest) export file.
  4782. </ul><br>
  4783. <code>set &lt;name&gt; importCachefile &lt;file&gt; </code><br><br>
  4784. <ul>Imports an textfile into the database which has been written by the "exportCache" function.
  4785. The allocatable files will be searched in directory (global->modpath)/log/ by default and a drop-down list will be
  4786. generated from the files which are found in the directory.
  4787. The source directory can be changed by the <a href="#DbLogattr">attribute</a> expimpdir. <br>
  4788. Only that files will be shown which are correlate on pattern starting with "cache_", followed by the DbLog-devicename. <br>
  4789. For example a file with the name "cache_LogDB_2017-03-23_22-13-55", will match if Dblog-device has name "LogDB". <br>
  4790. After the import has been successfully done, a prefix "impdone_" will be added at begin of the filename and this file
  4791. ddoesn't appear on the drop-down list anymore. <br>
  4792. If you want to import a cachefile from another source database, you may adapt the filename so it fits the search criteria
  4793. "DbLog-Device" in its name. After renaming the file appeares again on the drop-down list. </ul><br>
  4794. <code>set &lt;name&gt; listCache </code><br><br>
  4795. <ul>If DbLog is set to asynchronous mode (attribute asyncMode=1), you can use that command to list the events are cached in memory.</ul><br>
  4796. <code>set &lt;name&gt; purgeCache </code><br><br>
  4797. <ul>In asynchronous mode (<a href="#DbLogattr">attribute</a> asyncMode=1), the in memory cached data will be deleted.
  4798. With this command data won't be written from cache into the database. </ul><br>
  4799. <code>set &lt;name&gt; reduceLog &lt;n&gt; [average[=day]] [exclude=deviceRegExp1:ReadingRegExp1,deviceRegExp2:ReadingRegExp2,...]</code> <br><br>
  4800. <ul>Reduces records older than &lt;n&gt; days to one record each hour (the 1st) per device & reading. <br><br>
  4801. <b>CAUTION:</b> It is strongly recommended to check if the default INDEX 'Search_Idx' exists on the table 'history'! <br>
  4802. The execution of this command may take (without INDEX) extremely long. FHEM will be <b>blocked completely</b> after issuing the command to completion ! <br><br>
  4803. With the optional argument 'average' not only the records will be reduced, but all numerical values of an hour
  4804. will be reduced to a single average. <br>
  4805. With the optional argument 'average=day' not only the records will be reduced, but all numerical values of a
  4806. day will be reduced to a single average. (implies 'average') <br>
  4807. You can optional set the last argument to "EXCLUDE=deviceRegExp1:ReadingRegExp1,deviceRegExp2:ReadingRegExp2,...."
  4808. to exclude device/readings from reduceLog. <br>
  4809. You can optional set the last argument to "INCLUDE=Database-deviceRegExp:Database-ReadingRegExp" to delimit
  4810. the SELECT statement which is executet on the database. This reduces the system RAM load and increases the
  4811. performance. (Wildcards are % and _) <br>
  4812. </ul><br>
  4813. <code>set &lt;name&gt; reduceLogNbl &lt;n&gt; [average[=day]] [exclude=deviceRegExp1:ReadingRegExp1,deviceRegExp2:ReadingRegExp2,...]</code> <br><br>
  4814. <ul>Same function as "set &lt;name&gt; reduceLog" but FHEM won't be blocked due to this function is implemented non-blocking ! <br>
  4815. </ul><br>
  4816. <code>set &lt;name&gt; reopen [n] </code><br/><br/>
  4817. <ul>Perform a database disconnect and immediate reconnect to clear cache and flush journal file if no time [n] was set. <br>
  4818. If optionally a delay time of [n] seconds was set, the database connection will be disconnect immediately but it was only reopened
  4819. after [n] seconds. In synchronous mode the events won't saved during that time. In asynchronous mode the events will be
  4820. stored in the memory cache and saved into database after the reconnect was done. </ul><br/>
  4821. <code>set &lt;name&gt; rereadcfg </code><br/><br/>
  4822. <ul>Perform a database disconnect and immediate reconnect to clear cache and flush journal file.<br/>
  4823. Probably same behavior als reopen, but rereadcfg will read the configuration data before reconnect.</ul><br/>
  4824. <code>set &lt;name&gt; userCommand &lt;validSqlStatement&gt;</code><br/><br/>
  4825. <ul><b>DO NOT USE THIS COMMAND UNLESS YOU REALLY (REALLY!) KNOW WHAT YOU ARE DOING!!!</b><br/><br/>
  4826. Performs any (!!!) sql statement on connected database. Usercommand and result will be written into
  4827. corresponding readings.</br>
  4828. The result can only be a single line. If the SQL-Statement seems to deliver a multiline result, it can be suitable
  4829. to use the analysis module <a href=https://fhem.de/commandref.html#DbRep>DbRep</a>.</br>
  4830. If the database interface delivers no result (undef), the reading "userCommandResult" contains the message
  4831. "no result".
  4832. </ul><br/>
  4833. </ul><br>
  4834. <a name="DbLogget"></a>
  4835. <b>Get</b>
  4836. <ul>
  4837. <code>get &lt;name&gt; ReadingsVal&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;device&gt; &lt;reading&gt; &lt;default&gt;</code><br/>
  4838. <code>get &lt;name&gt; ReadingsTimestamp &lt;device&gt; &lt;reading&gt; &lt;default&gt;</code><br/>
  4839. <br/>
  4840. Retrieve one single value, use and syntax are similar to ReadingsVal() and ReadingsTimestamp() functions.<br/>
  4841. </ul>
  4842. <br/>
  4843. <br/>
  4844. <ul>
  4845. <code>get &lt;name&gt; &lt;infile&gt; &lt;outfile&gt; &lt;from&gt;
  4846. &lt;to&gt; &lt;column_spec&gt; </code>
  4847. <br><br>
  4848. Read data from the Database, used by frontends to plot data without direct
  4849. access to the Database.<br>
  4850. <ul>
  4851. <li>&lt;in&gt;<br>
  4852. A dummy parameter for FileLog compatibility. Sessing by defaultto <code>-</code><br>
  4853. <ul>
  4854. <li>current: reading actual readings from table "current"</li>
  4855. <li>history: reading history readings from table "history"</li>
  4856. <li>-: identical to "history"</li>
  4857. </ul>
  4858. </li>
  4859. <li>&lt;out&gt;<br>
  4860. A dummy parameter for FileLog compatibility. Setting by default to <code>-</code>
  4861. to check the output for plot-computing.<br>
  4862. Set it to the special keyword
  4863. <code>all</code> to get all columns from Database.
  4864. <ul>
  4865. <li>ALL: get all colums from table, including a header</li>
  4866. <li>Array: get the columns as array of hashes</li>
  4867. <li>INT: internally used by generating plots</li>
  4868. <li>-: default</li>
  4869. </ul>
  4870. </li>
  4871. <li>&lt;from&gt; / &lt;to&gt;<br>
  4872. Used to select the data. Please use the following timeformat or
  4873. an initial substring of it:<br>
  4874. <ul><code>YYYY-MM-DD_HH24:MI:SS</code></ul></li>
  4875. <li>&lt;column_spec&gt;<br>
  4876. For each column_spec return a set of data separated by
  4877. a comment line on the current connection.<br>
  4878. Syntax: &lt;device&gt;:&lt;reading&gt;:&lt;default&gt;:&lt;fn&gt;:&lt;regexp&gt;<br>
  4879. <ul>
  4880. <li>&lt;device&gt;<br>
  4881. The name of the device. Case sensitive. Using a the joker "%" is supported.</li>
  4882. <li>&lt;reading&gt;<br>
  4883. The reading of the given device to select. Case sensitive. Using a the joker "%" is supported.
  4884. </li>
  4885. <li>&lt;default&gt;<br>
  4886. no implemented yet
  4887. </li>
  4888. <li>&lt;fn&gt;
  4889. One of the following:
  4890. <ul>
  4891. <li>int<br>
  4892. Extract the integer at the beginning of the string. Used e.g.
  4893. for constructs like 10%</li>
  4894. <li>int&lt;digit&gt;<br>
  4895. Extract the decimal digits including negative character and
  4896. decimal point at the beginning og the string. Used e.g.
  4897. for constructs like 15.7&deg;C</li>
  4898. <li>delta-h / delta-d<br>
  4899. Return the delta of the values for a given hour or a given day.
  4900. Used if the column contains a counter, as is the case for the
  4901. KS300 rain column.</li>
  4902. <li>delta-ts<br>
  4903. Replaced the original value with a measured value of seconds since
  4904. the last and the actual logentry.
  4905. </li>
  4906. </ul></li>
  4907. <li>&lt;regexp&gt;<br>
  4908. The string is evaluated as a perl expression. The regexp is executed
  4909. before &lt;fn&gt; parameter.<br>
  4910. Note: The string/perl expression cannot contain spaces,
  4911. as the part after the space will be considered as the
  4912. next column_spec.<br>
  4913. <b>Keywords</b>
  4914. <li>$val is the current value returned from the Database.</li>
  4915. <li>$ts is the current timestamp returned from the Database.</li>
  4916. <li>This Logentry will not print out if $val contains th keyword "hide".</li>
  4917. <li>This Logentry will not print out and not used in the following processing
  4918. if $val contains th keyword "ignore".</li>
  4919. </li>
  4920. </ul></li>
  4921. </ul>
  4922. <br><br>
  4923. Examples:
  4924. <ul>
  4925. <li><code>get myDbLog - - 2012-11-10 2012-11-20 KS300:temperature</code></li>
  4926. <li><code>get myDbLog current ALL - - %:temperature</code></li><br>
  4927. you will get all actual readings "temperature" from all logged devices.
  4928. Be careful by using "history" as inputfile because a long execution time will be expected!
  4929. <li><code>get myDbLog - - 2012-11-10_10 2012-11-10_20 KS300:temperature::int1</code><br>
  4930. like from 10am until 08pm at 10.11.2012</li>
  4931. <li><code>get myDbLog - all 2012-11-10 2012-11-20 KS300:temperature</code></li>
  4932. <li><code>get myDbLog - - 2012-11-10 2012-11-20 KS300:temperature KS300:rain::delta-h KS300:rain::delta-d</code></li>
  4933. <li><code>get myDbLog - - 2012-11-10 2012-11-20 MyFS20:data:::$val=~s/(on|off).*/$1eq"on"?1:0/eg</code><br>
  4934. return 1 for all occurance of on* (on|on-for-timer etc) and 0 for all off*</li>
  4935. <li><code>get myDbLog - - 2012-11-10 2012-11-20 Bodenfeuchte:data:::$val=~s/.*B:\s([-\.\d]+).*/$1/eg</code><br>
  4936. Example of OWAD: value like this: <code>"A: 49.527 % B: 66.647 % C: 9.797 % D: 0.097 V"</code><br>
  4937. and output for port B is like this: <code>2012-11-20_10:23:54 66.647</code></li>
  4938. <li><code>get DbLog - - 2013-05-26 2013-05-28 Pumpe:data::delta-ts:$val=~s/on/hide/</code><br>
  4939. Setting up a "Counter of Uptime". The function delta-ts gets the seconds between the last and the
  4940. actual logentry. The keyword "hide" will hide the logentry of "on" because this time
  4941. is a "counter of Downtime"</li>
  4942. </ul>
  4943. <br><br>
  4944. </ul>
  4945. <b>Get</b> when used for webcharts
  4946. <ul>
  4947. <code>get &lt;name&gt; &lt;infile&gt; &lt;outfile&gt; &lt;from&gt;
  4948. &lt;to&gt; &lt;device&gt; &lt;querytype&gt; &lt;xaxis&gt; &lt;yaxis&gt; &lt;savename&gt; </code>
  4949. <br><br>
  4950. Query the Database to retrieve JSON-Formatted Data, which is used by the charting frontend.
  4951. <br>
  4952. <ul>
  4953. <li>&lt;name&gt;<br>
  4954. The name of the defined DbLog, like it is given in fhem.cfg.</li>
  4955. <li>&lt;in&gt;<br>
  4956. A dummy parameter for FileLog compatibility. Always set to <code>-</code></li>
  4957. <li>&lt;out&gt;<br>
  4958. A dummy parameter for FileLog compatibility. Set it to <code>webchart</code>
  4959. to use the charting related get function.
  4960. </li>
  4961. <li>&lt;from&gt; / &lt;to&gt;<br>
  4962. Used to select the data. Please use the following timeformat:<br>
  4963. <ul><code>YYYY-MM-DD_HH24:MI:SS</code></ul></li>
  4964. <li>&lt;device&gt;<br>
  4965. A string which represents the device to query.</li>
  4966. <li>&lt;querytype&gt;<br>
  4967. A string which represents the method the query should use. Actually supported values are: <br>
  4968. <code>getreadings</code> to retrieve the possible readings for a given device<br>
  4969. <code>getdevices</code> to retrieve all available devices<br>
  4970. <code>timerange</code> to retrieve charting data, which requires a given xaxis, yaxis, device, to and from<br>
  4971. <code>savechart</code> to save a chart configuration in the database. Requires a given xaxis, yaxis, device, to and from, and a 'savename' used to save the chart<br>
  4972. <code>deletechart</code> to delete a saved chart. Requires a given id which was set on save of the chart<br>
  4973. <code>getcharts</code> to get a list of all saved charts.<br>
  4974. <code>getTableData</code> to get jsonformatted data from the database. Uses paging Parameters like start and limit.<br>
  4975. <code>hourstats</code> to get statistics for a given value (yaxis) for an hour.<br>
  4976. <code>daystats</code> to get statistics for a given value (yaxis) for a day.<br>
  4977. <code>weekstats</code> to get statistics for a given value (yaxis) for a week.<br>
  4978. <code>monthstats</code> to get statistics for a given value (yaxis) for a month.<br>
  4979. <code>yearstats</code> to get statistics for a given value (yaxis) for a year.<br>
  4980. </li>
  4981. <li>&lt;xaxis&gt;<br>
  4982. A string which represents the xaxis</li>
  4983. <li>&lt;yaxis&gt;<br>
  4984. A string which represents the yaxis</li>
  4985. <li>&lt;savename&gt;<br>
  4986. A string which represents the name a chart will be saved with</li>
  4987. <li>&lt;chartconfig&gt;<br>
  4988. A jsonstring which represents the chart to save</li>
  4989. <li>&lt;pagingstart&gt;<br>
  4990. An integer used to determine the start for the sql used for query 'getTableData'</li>
  4991. <li>&lt;paginglimit&gt;<br>
  4992. An integer used to set the limit for the sql used for query 'getTableData'</li>
  4993. </ul>
  4994. <br><br>
  4995. Examples:
  4996. <ul>
  4997. <li><code>get logdb - webchart "" "" "" getcharts</code><br>
  4998. Retrieves all saved charts from the Database</li>
  4999. <li><code>get logdb - webchart "" "" "" getdevices</code><br>
  5000. Retrieves all available devices from the Database</li>
  5001. <li><code>get logdb - webchart "" "" ESA2000_LED_011e getreadings</code><br>
  5002. Retrieves all available Readings for a given device from the Database</li>
  5003. <li><code>get logdb - webchart 2013-02-11_00:00:00 2013-02-12_00:00:00 ESA2000_LED_011e timerange TIMESTAMP day_kwh</code><br>
  5004. Retrieves charting data, which requires a given xaxis, yaxis, device, to and from<br>
  5005. Will ouput a JSON like this: <code>[{'TIMESTAMP':'2013-02-11 00:10:10','VALUE':'0.22431388090756'},{'TIMESTAMP'.....}]</code></li>
  5006. <li><code>get logdb - webchart 2013-02-11_00:00:00 2013-02-12_00:00:00 ESA2000_LED_011e savechart TIMESTAMP day_kwh tageskwh</code><br>
  5007. Will save a chart in the database with the given name and the chart configuration parameters</li>
  5008. <li><code>get logdb - webchart "" "" "" deletechart "" "" 7</code><br>
  5009. Will delete a chart from the database with the given id</li>
  5010. </ul>
  5011. <br><br>
  5012. </ul>
  5013. <a name="DbLogattr"></a>
  5014. <b>Attributes</b>
  5015. <br><br>
  5016. <ul><b>addStateEvent</b>
  5017. <ul>
  5018. <code>attr &lt;device&gt; addStateEvent [0|1]
  5019. </code><br>
  5020. As you probably know the event associated with the state Reading is special, as the "state: "
  5021. string is stripped, i.e event is not "state: on" but just "on". <br>
  5022. Mostly it is desireable to get the complete event without "state: " stripped, so it is the default behavior of DbLog.
  5023. That means you will get state-event complete as "state: xxx". <br>
  5024. In some circumstances, e.g. older or special modules, it is a good idea to set addStateEvent to "0".
  5025. Try it if you have trouble with the default adjustment.
  5026. <br>
  5027. </ul>
  5028. </ul>
  5029. <br>
  5030. <ul><b>asyncMode</b>
  5031. <ul>
  5032. <code>attr &lt;device&gt; asyncMode [1|0]
  5033. </code><br>
  5034. This attribute determines the operation mode of DbLog. If asynchronous mode is active (asyncMode=1), the events which should be saved
  5035. at first will be cached in memory. After synchronisation time cycle (attribute syncInterval), or if the count limit of datasets in cache
  5036. is reached (attribute cacheLimit), the cached events get saved into the database using bulk insert.
  5037. If the database isn't available, the events will be cached in memeory furthermore, and tried to save into database again after
  5038. the next synchronisation time cycle if the database is available. <br>
  5039. In asynchronous mode the data insert into database will be executed non-blocking by a background process.
  5040. You can adjust the timeout value for this background process by attribute "timeout" (default 86400s). <br>
  5041. In synchronous mode (normal mode) the events won't be cached im memory and get saved into database immediately. If the database isn't
  5042. available the events are get lost. <br>
  5043. </ul>
  5044. </ul>
  5045. <br>
  5046. <ul><b>commitMode</b>
  5047. <ul>
  5048. <code>attr &lt;device&gt; commitMode [basic_ta:on | basic_ta:off | ac:on_ta:on | ac:on_ta:off | ac:off_ta:on]
  5049. </code><br>
  5050. Change the usage of database autocommit- and/or transaction- behavior. <br>
  5051. This attribute is an advanced feature and should only be used in a concrete case of need or support case. <br><br>
  5052. <ul>
  5053. <li>basic_ta:on - autocommit server basic setting / transaktion on (default) </li>
  5054. <li>basic_ta:off - autocommit server basic setting / transaktion off </li>
  5055. <li>ac:on_ta:on - autocommit on / transaktion on </li>
  5056. <li>ac:on_ta:off - autocommit on / transaktion off </li>
  5057. <li>ac:off_ta:on - autocommit off / transaktion on (autocommit off set transaktion on implicitly) </li>
  5058. </ul>
  5059. </ul>
  5060. </ul>
  5061. <br>
  5062. <ul><b>cacheEvents</b>
  5063. <ul>
  5064. <code>attr &lt;device&gt; cacheEvents [2|1|0]
  5065. </code><br>
  5066. <ul>
  5067. <li>cacheEvents=1: creates events of reading CacheUsage at point of time when a new dataset has been added to the cache. </li>
  5068. <li>cacheEvents=2: creates events of reading CacheUsage at point of time when in aychronous mode a new write cycle to the
  5069. database starts. In that moment CacheUsage contains the number of datasets which will be written to
  5070. the database. </li><br>
  5071. </ul>
  5072. </ul>
  5073. </ul>
  5074. <br>
  5075. <ul><b>cacheLimit</b>
  5076. <ul>
  5077. <code>
  5078. attr &lt;device&gt; cacheLimit &lt;n&gt;
  5079. </code><br>
  5080. In asynchronous logging mode the content of cache will be written into the database and cleared if the number &lt;n&gt; datasets
  5081. in cache has reached (default: 500). Thereby the timer of asynchronous logging mode will be set new to the value of
  5082. attribute "syncInterval". In case of error the next write attempt will be started at the earliest after syncInterval/2. <br>
  5083. </ul>
  5084. </ul>
  5085. <br>
  5086. <ul><b>colEvent</b>
  5087. <ul>
  5088. <code>
  5089. attr &lt;device&gt; colEvent &lt;n&gt;
  5090. </code><br>
  5091. The field length of database field EVENT will be adjusted. By this attribute the default value in the DbLog-device can be
  5092. adjusted if the field length in the databse was changed nanually. If colEvent=0 is set, the database field
  5093. EVENT won't be filled . <br>
  5094. <b>Note:</b> <br>
  5095. If the attribute is set, all of the field length limits are valid also for SQLite databases as noticed in Internal COLUMNS ! <br>
  5096. </ul>
  5097. </ul>
  5098. <br>
  5099. <ul><b>colReading</b>
  5100. <ul>
  5101. <code>
  5102. attr &lt;device&gt; colReading &lt;n&gt;
  5103. </code><br>
  5104. The field length of database field READING will be adjusted. By this attribute the default value in the DbLog-device can be
  5105. adjusted if the field length in the databse was changed nanually. If colReading=0 is set, the database field
  5106. READING won't be filled . <br>
  5107. <b>Note:</b> <br>
  5108. If the attribute is set, all of the field length limits are valid also for SQLite databases as noticed in Internal COLUMNS ! <br>
  5109. </ul>
  5110. </ul>
  5111. <br>
  5112. <ul><b>colValue</b>
  5113. <ul>
  5114. <code>
  5115. attr &lt;device&gt; colValue &lt;n&gt;
  5116. </code><br>
  5117. The field length of database field VALUE will be adjusted. By this attribute the default value in the DbLog-device can be
  5118. adjusted if the field length in the databse was changed nanually. If colEvent=0 is set, the database field
  5119. VALUE won't be filled . <br>
  5120. <b>Note:</b> <br>
  5121. If the attribute is set, all of the field length limits are valid also for SQLite databases as noticed in Internal COLUMNS ! <br>
  5122. </ul>
  5123. </ul>
  5124. <br>
  5125. <ul><b>DbLogType</b>
  5126. <ul>
  5127. <code>
  5128. attr &lt;device&gt; DbLogType [Current|History|Current/History]
  5129. </code><br>
  5130. This attribute determines which table or which tables in the database are wanted to use. If the attribute isn't set,
  5131. the adjustment <i>history</i> will be used as default. <br>
  5132. The meaning of the adjustments in detail are: <br><br>
  5133. <ul>
  5134. <table>
  5135. <colgroup> <col width=10%> <col width=90%> </colgroup>
  5136. <tr><td> <b>Current</b> </td><td>Events are only logged into the current-table.
  5137. The entries of current-table will evaluated with SVG-creation. </td></tr>
  5138. <tr><td> <b>History</b> </td><td>Events are only logged into the history-table. No dropdown list with proposals will created with the
  5139. SVG-creation. </td></tr>
  5140. <tr><td> <b>Current/History</b> </td><td>Events will be logged both the current- and the history-table.
  5141. The entries of current-table will evaluated with SVG-creation. </td></tr>
  5142. <tr><td> <b>SampleFill/History</b> </td><td>Events are only logged into the history-table. The entries of current-table will evaluated with SVG-creation
  5143. and can be filled up with a customizable extract of the history-table by using a
  5144. <a href="http://fhem.de/commandref.html#DbRep">DbRep-device</a> command
  5145. "set &lt;DbRep-name&gt; tableCurrentFillup" (advanced feature). </td></tr>
  5146. </table>
  5147. </ul>
  5148. <br>
  5149. <br>
  5150. <b>Note:</b> <br>
  5151. The current-table has to be used to get a Device:Reading-DropDown list when a SVG-Plot will be created. <br>
  5152. </ul>
  5153. </ul>
  5154. <br>
  5155. <ul><b>DbLogSelectionMode</b>
  5156. <ul>
  5157. <code>
  5158. attr &lt;device&gt; DbLogSelectionMode [Exclude|Include|Exclude/Include]
  5159. </code><br>
  5160. Thise DbLog-Device-Attribute specifies how the device specific Attributes DbLogExclude and DbLogInclude are handled.
  5161. If this Attribute is missing it defaults to "Exclude".
  5162. <ul>
  5163. <li>Exclude: DbLog behaves just as usual. This means everything specified in the regex in DEF will be logged by default and anything excluded
  5164. via the DbLogExclude attribute will not be logged</li>
  5165. <li>Include: Nothing will be logged, except the readings specified via regex in the DbLogInclude attribute </li>
  5166. <li>Exclude/Include: Just almost the same as Exclude, but if the reading matches the DbLogExclude attribute, then
  5167. it will further be checked against the regex in DbLogInclude whicht may possibly re-include the already
  5168. excluded reading. </li>
  5169. </ul>
  5170. </ul>
  5171. </ul>
  5172. <br>
  5173. <ul><b>DbLogInclude</b>
  5174. <ul>
  5175. <code>
  5176. attr &lt;device&gt; DbLogInclude regex:MinInterval,[regex:MinInterval] ...
  5177. </code><br>
  5178. A new Attribute DbLogInclude will be propagated
  5179. to all Devices if DBLog is used. DbLogInclude works just like DbLogExclude but
  5180. to include matching readings.
  5181. See also DbLogSelectionMode-Attribute of DbLog-Device which takes influence on
  5182. on how DbLogExclude and DbLogInclude are handled. <br>
  5183. <b>Example</b> <br>
  5184. <code>attr MyDevice1 DbLogInclude .*</code> <br>
  5185. <code>attr MyDevice2 DbLogInclude state,(floorplantext|MyUserReading):300,battery:3600</code>
  5186. </ul>
  5187. </ul>
  5188. <br>
  5189. <ul><b>DbLogExclude</b>
  5190. <ul>
  5191. <code>
  5192. attr &lt;device&gt; DbLogExclude regex:MinInterval,[regex:MinInterval] ...
  5193. </code><br>
  5194. A new Attribute DbLogExclude will be propagated to all Devices if DBLog is used.
  5195. DbLogExclude will work as regexp to exclude defined readings to log. Each individual regexp-group are separated by comma.
  5196. If a MinInterval is set, the logentry is dropped if the defined interval is not reached and value vs. lastvalue is eqal.
  5197. <br><br>
  5198. <b>Example</b> <br>
  5199. <code>attr MyDevice1 DbLogExclude .*</code> <br>
  5200. <code>attr MyDevice2 DbLogExclude state,(floorplantext|MyUserReading):300,battery:3600</code>
  5201. </ul>
  5202. </ul>
  5203. <br>
  5204. <ul><b>excludeDevs</b>
  5205. <ul>
  5206. <code>
  5207. attr &lt;device&gt; excludeDevs &lt;devspec1&gt;,&lt;devspec2&gt;,&lt;devspec..&gt;
  5208. </code><br>
  5209. The devices "devspec1", "devspec2" up to "devspec.." are excluded from logging into database. This attribute
  5210. will only be evaluated if internal "NOTIFYDEV" is not defined.
  5211. Thereby devices can be explicit excluded from logging. The devices to exclude can be specified as
  5212. <a href="#devspec">device-specification</a>.
  5213. For further informations about devspec please see <a href="#devspec">device-specification</a>. <br><br>
  5214. <b>Example</b> <br>
  5215. <code>
  5216. attr &lt;device&gt; excludeDevs global,Log.*,Cam.*,TYPE=DbLog
  5217. </code><br>
  5218. # The devices global respectively devices starting with "Log" or "Cam" and devices with Type=DbLog
  5219. are excluded from database logging. <br>
  5220. </ul>
  5221. </ul>
  5222. <br>
  5223. <ul><b>expimpdir</b>
  5224. <ul>
  5225. <code>
  5226. attr &lt;device&gt; expimpdir &lt;directory&gt;
  5227. </code><br>
  5228. If the cache content will be exported by <a href="#DbLogsetexportCache">"exportCache"</a> or the "importCachefile"
  5229. command, the file will be written into or read from that directory. The default directory is
  5230. "(global->modpath)/log/".
  5231. Make sure the specified directory is existing and writable. <br><br>
  5232. <b>Example</b> <br>
  5233. <code>
  5234. attr &lt;device&gt; expimpdir /opt/fhem/cache/
  5235. </code><br>
  5236. </ul>
  5237. </ul>
  5238. <br>
  5239. <ul><b>exportCacheAppend</b>
  5240. <ul>
  5241. <code>
  5242. attr &lt;device&gt; exportCacheAppend [1|0]
  5243. </code><br>
  5244. If set, the export of cache ("set &lt;device&gt; exportCache") appends the content to the newest available
  5245. export file. If there is no exististing export file, it will be new created. <br>
  5246. If the attribute not set, every export process creates a new export file . (default)<br/>
  5247. </ul>
  5248. </ul>
  5249. <br>
  5250. <ul><b>noNotifyDev</b>
  5251. <ul>
  5252. <code>
  5253. attr &lt;device&gt; noNotifyDev [1|0]
  5254. </code><br>
  5255. Enforces that NOTIFYDEV won't set and hence won't used. <br>
  5256. </ul>
  5257. </ul>
  5258. <br>
  5259. <ul><b>noSupportPK</b>
  5260. <ul>
  5261. <code>
  5262. attr &lt;device&gt; noSupportPK [1|0]
  5263. </code><br>
  5264. Deactivates the support of a set primary key by the module.<br>
  5265. </ul>
  5266. </ul>
  5267. <br>
  5268. <ul><b>syncEvents</b>
  5269. <ul>
  5270. <code>attr &lt;device&gt; syncEvents [1|0]
  5271. </code><br>
  5272. events of reading syncEvents will be created. <br>
  5273. </ul>
  5274. </ul>
  5275. <br>
  5276. <ul><b>shutdownWait</b>
  5277. <ul>
  5278. <code>attr &lt;device&gt; shutdownWait <n>
  5279. </code><br>
  5280. causes fhem shutdown to wait n seconds for pending database commit<br/>
  5281. </ul>
  5282. </ul>
  5283. <br>
  5284. <ul><b>showproctime</b>
  5285. <ul>
  5286. <code>attr &lt;device&gt; [1|0]
  5287. </code><br>
  5288. If set, the reading "sql_processing_time" shows the required execution time (in seconds) for the sql-requests. This is not calculated
  5289. for a single sql-statement, but the summary of all sql-statements necessary for within an executed DbLog-function in background.
  5290. The reading "background_processing_time" shows the total time used in background. <br>
  5291. </ul>
  5292. </ul>
  5293. <br>
  5294. <ul><b>showNotifyTime</b>
  5295. <ul>
  5296. <code>attr &lt;device&gt; showNotifyTime [1|0]
  5297. </code><br>
  5298. If set, the reading "notify_processing_time" shows the required execution time (in seconds) in the DbLog
  5299. Notify-function. This attribute is practical for performance analyses and helps to determine the differences of time
  5300. required when the operation mode was switched from synchronous to the asynchronous mode. <br>
  5301. </ul>
  5302. </ul>
  5303. <br>
  5304. <ul><b>syncInterval</b>
  5305. <ul>
  5306. <code>attr &lt;device&gt; syncInterval &lt;n&gt;
  5307. </code><br>
  5308. If DbLog is set to asynchronous operation mode (attribute asyncMode=1), with this attribute you can setup the interval in seconds
  5309. used for storage the in memory cached events into the database. THe default value is 30 seconds. <br>
  5310. </ul>
  5311. </ul>
  5312. <br>
  5313. <ul><b>suppressAddLogV3</b>
  5314. <ul>
  5315. <code>attr &lt;device&gt; suppressAddLogV3 [1|0]
  5316. </code><br>
  5317. If set, verbose3-Logfileentries done by the addLog-function will be suppressed. <br>
  5318. </ul>
  5319. </ul>
  5320. <br>
  5321. <ul><b>suppressUndef</b>
  5322. <ul>
  5323. <code>
  5324. attr &lt;device&gt; ignoreUndef <n>
  5325. </code><br>
  5326. suppresses all undef values when returning data from the DB via get <br>
  5327. <b>Example</b> <br>
  5328. <code>#DbLog eMeter:power:::$val=($val>1500)?undef:$val</code>
  5329. </ul>
  5330. </ul>
  5331. <br>
  5332. <ul><b>timeout</b>
  5333. <ul>
  5334. <code>
  5335. attr &lt;device&gt; timeout <n>
  5336. </code><br>
  5337. setup timeout of the write cycle into database in asynchronous mode (default 86400s) <br>
  5338. </ul>
  5339. </ul>
  5340. <br>
  5341. <ul><b>useCharfilter</b>
  5342. <ul>
  5343. <code>
  5344. attr &lt;device&gt; useCharfilter [0|1] <n>
  5345. </code><br>
  5346. If set, only ASCII characters from 32 to 126 are accepted in event.
  5347. That are the characters " A-Za-z0-9!"#$%&'()*+,-.\/:;<=>?@[\\]^_`{|}~" .<br>
  5348. Mutated vowel and "€" are transcribed (e.g. ä to ae). (default: 0). <br>
  5349. </ul>
  5350. </ul>
  5351. <br>
  5352. <ul><b>valueFn</b>
  5353. <ul>
  5354. <code>
  5355. attr &lt;device&gt; valueFn {}
  5356. </code><br>
  5357. Perl expression that can use and change values of $TIMESTAMP, $DEVICE, $DEVICETYPE, $READING, $VALUE (value of reading) and
  5358. $UNIT (unit of reading value).
  5359. It also has readonly-access to $EVENT for evaluation in your expression. <br>
  5360. If $TIMESTAMP should be changed, it must meet the condition "yyyy-mm-dd hh:mm:ss", otherwise the $timestamp wouldn't
  5361. be changed.
  5362. In addition you can set the variable $IGNORE=1 if you want skip a dataset from logging. <br><br>
  5363. <b>Examples</b> <br>
  5364. <code>
  5365. attr &lt;device&gt; valueFn {if ($DEVICE eq "living_Clima" && $VALUE eq "off" ){$VALUE=0;} elsif ($DEVICE eq "e-power"){$VALUE= sprintf "%.1f", $VALUE;}}
  5366. </code> <br>
  5367. # change value "off" to "0" of device "living_Clima" and rounds value of e-power to 1f <br><br>
  5368. <code>
  5369. attr &lt;device&gt; valueFn {if ($DEVICE eq "SMA_Energymeter" && $READING eq "state"){$IGNORE=1;}}
  5370. </code><br>
  5371. # don't log the dataset of device "SMA_Energymeter" if the reading is "state" <br><br>
  5372. <code>
  5373. attr &lt;device&gt; valueFn {if ($DEVICE eq "Dum.Energy" && $READING eq "TotalConsumption"){$UNIT="W";}}
  5374. </code><br>
  5375. # set the unit of device "Dum.Energy" to "W" if reading is "TotalConsumption" <br><br>
  5376. </ul>
  5377. </ul>
  5378. <br>
  5379. <ul><b>verbose4Devs</b>
  5380. <ul>
  5381. <code>
  5382. attr &lt;device&gt; verbose4Devs &lt;device1&gt;,&lt;device2&gt;,&lt;device..&gt;
  5383. </code><br>
  5384. If verbose level 4 is used, only output of devices set in this attribute will be reported in FHEM central logfile. If this attribute
  5385. isn't set, output of all relevant devices will be reported if using verbose level 4.
  5386. The given devices are evaluated as Regex. <br>
  5387. <b>Example</b> <br>
  5388. <code>
  5389. attr &lt;device&gt; verbose4Devs sys.*,.*5000.*,Cam.*,global
  5390. </code><br>
  5391. # The devices starting with "sys", "Cam" respectively devices are containing "5000" in its name and the device "global" will be reported in FHEM
  5392. central Logfile if verbose=4 is set. <br>
  5393. </ul>
  5394. </ul>
  5395. <br>
  5396. </ul>
  5397. =end html
  5398. =begin html_DE
  5399. <a name="DbLog"></a>
  5400. <h3>DbLog</h3>
  5401. <ul>
  5402. <br>
  5403. Mit DbLog werden Events in einer Datenbank gespeichert. Es wird SQLite, MySQL/MariaDB und PostgreSQL unterstützt. <br><br>
  5404. <b>Voraussetzungen</b> <br><br>
  5405. Die Perl-Module <code>DBI</code> und <code>DBD::&lt;dbtype&gt;</code> müssen installiert werden (use <code>cpan -i &lt;module&gt;</code>
  5406. falls die eigene Distribution diese nicht schon mitbringt).
  5407. <br><br>
  5408. Auf einem Debian-System können diese Module z.Bsp. installiert werden mit: <br><br>
  5409. <ul>
  5410. <table>
  5411. <colgroup> <col width=5%> <col width=95%> </colgroup>
  5412. <tr><td> <b>DBI</b> </td><td>: <code> sudo apt-get install libdbi-perl </code> </td></tr>
  5413. <tr><td> <b>MySQL</b> </td><td>: <code> sudo apt-get install [mysql-server] mysql-client libdbd-mysql libdbd-mysql-perl </code> (mysql-server nur bei lokaler MySQL-Server-Installation) </td></tr>
  5414. <tr><td> <b>SQLite</b> </td><td>: <code> sudo apt-get install sqlite3 libdbi-perl libdbd-sqlite3-perl </code> </td></tr>
  5415. <tr><td> <b>PostgreSQL</b> </td><td>: <code> sudo apt-get install libdbd-pg-perl </code> </td></tr>
  5416. </table>
  5417. </ul>
  5418. <br>
  5419. <br>
  5420. <b>Vorbereitungen</b> <br><br>
  5421. Zunächst muss die Datenbank angelegt werden. <br>
  5422. Beispielcode bzw. Scripts zum Erstellen einer MySQL/PostgreSQL/SQLite Datenbank ist im
  5423. <a href="https://svn.fhem.de/trac/browser/trunk/fhem/contrib/dblog">SVN -&gt; contrib/dblog/db_create_&lt;DBType&gt;.sql</a>
  5424. enthalten. <br>
  5425. (<b>Achtung:</b> Die lokale FHEM-Installation enthält im Unterverzeichnis ./contrib/dblog nicht die aktuellsten
  5426. Scripte !!) <br><br>
  5427. Die Datenbank beinhaltet 2 Tabellen: <code>current</code> und <code>history</code>. <br>
  5428. Die Tabelle <code>current</code> enthält den letzten Stand pro Device und Reading. <br>
  5429. In der Tabelle <code>history</code> sind alle Events historisch gespeichert. <br>
  5430. Beachten sie bitte unbedingt das <a href="#DbLogattr">Attribut</a> DbLogType um die Benutzung der Tabellen
  5431. <code>current</code> und <code>history</code> festzulegen.
  5432. <br><br>
  5433. Die Tabellenspalten haben folgende Bedeutung: <br><br>
  5434. <ul>
  5435. <table>
  5436. <colgroup> <col width=5%> <col width=95%> </colgroup>
  5437. <tr><td> TIMESTAMP </td><td>: Zeitpunkt des Events, z.B. <code>2007-12-30 21:45:22</code> </td></tr>
  5438. <tr><td> DEVICE </td><td>: Name des Devices, z.B. <code>Wetterstation</code> </td></tr>
  5439. <tr><td> TYPE </td><td>: Type des Devices, z.B. <code>KS300</code> </td></tr>
  5440. <tr><td> EVENT </td><td>: das auftretende Event als volle Zeichenkette, z.B. <code>humidity: 71 (%)</code> </td></tr>
  5441. <tr><td> READING </td><td>: Name des Readings, ermittelt aus dem Event, z.B. <code>humidity</code> </td></tr>
  5442. <tr><td> VALUE </td><td>: aktueller Wert des Readings, ermittelt aus dem Event, z.B. <code>humidity</code> </td></tr>
  5443. <tr><td> UNIT </td><td>: Einheit, ermittelt aus dem Event, z.B. <code>%</code> </td></tr>
  5444. </table>
  5445. </ul>
  5446. <br>
  5447. <br>
  5448. <b>Index anlegen</b> <br>
  5449. Für die Leseperformance, z.B. bei der Erstellung von SVG-PLots, ist es von besonderer Bedeutung dass der <b>Index "Search_Idx"</b>
  5450. oder ein vergleichbarer Index (z.B. ein Primary Key) angelegt ist. <br><br>
  5451. Der Index "Search_Idx" kann mit diesen Statements, z.B. in der Datenbank 'fhem', angelegt werden (auch nachträglich): <br><br>
  5452. <ul>
  5453. <table>
  5454. <colgroup> <col width=5%> <col width=95%> </colgroup>
  5455. <tr><td> <b>MySQL</b> </td><td>: <code> CREATE INDEX Search_Idx ON `fhem`.`history` (DEVICE, READING, TIMESTAMP); </code> </td></tr>
  5456. <tr><td> <b>SQLite</b> </td><td>: <code> CREATE INDEX Search_Idx ON `history` (DEVICE, READING, TIMESTAMP); </code> </td></tr>
  5457. <tr><td> <b>PostgreSQL</b> </td><td>: <code> CREATE INDEX "Search_Idx" ON history USING btree (device, reading, "timestamp"); </code> </td></tr>
  5458. </table>
  5459. </ul>
  5460. <br>
  5461. Der Code zur Anlage ist ebenfalls in den Scripten
  5462. <a href="https://svn.fhem.de/trac/browser/trunk/fhem/contrib/dblog">SVN -&gt; contrib/dblog/db_create_&lt;DBType&gt;.sql</a>
  5463. enthalten. <br><br>
  5464. Für die Verbindung zur Datenbank wird eine <b>Konfigurationsdatei</b> verwendet.
  5465. Die Konfiguration ist in einer sparaten Datei abgelegt um das Datenbankpasswort nicht in Klartext in der
  5466. FHEM-Haupt-Konfigurationsdatei speichern zu müssen.
  5467. Ansonsten wäre es mittels des <a href="https://fhem.de/commandref_DE.html#list">list</a> Befehls einfach auslesbar.
  5468. <br><br>
  5469. Die <b>Konfigurationsdatei</b> wird z.B. nach /opt/fhem kopiert und hat folgenden Aufbau, den man an seine Umgebung
  5470. anpassen muß (entsprechende Zeilen entkommentieren und anpassen): <br><br>
  5471. <pre>
  5472. ####################################################################################
  5473. # database configuration file
  5474. #
  5475. # NOTE:
  5476. # If you don't use a value for user / password please delete the leading hash mark
  5477. # and write 'user => ""' respectively 'password => ""' instead !
  5478. #
  5479. #
  5480. ## for MySQL
  5481. ####################################################################################
  5482. #%dbconfig= (
  5483. # connection => "mysql:database=fhem;host=&lt;database host&gt;;port=3306",
  5484. # user => "fhemuser",
  5485. # password => "fhempassword",
  5486. # # optional enable(1) / disable(0) UTF-8 support (at least V 4.042 is necessary)
  5487. # utf8 => 1
  5488. #);
  5489. ####################################################################################
  5490. #
  5491. ## for PostgreSQL
  5492. ####################################################################################
  5493. #%dbconfig= (
  5494. # connection => "Pg:database=fhem;host=&lt;database host&gt;",
  5495. # user => "fhemuser",
  5496. # password => "fhempassword"
  5497. #);
  5498. ####################################################################################
  5499. #
  5500. ## for SQLite (username and password stay empty for SQLite)
  5501. ####################################################################################
  5502. #%dbconfig= (
  5503. # connection => "SQLite:dbname=/opt/fhem/fhem.db",
  5504. # user => "",
  5505. # password => ""
  5506. #);
  5507. ####################################################################################
  5508. </pre>
  5509. <br>
  5510. <a name="DbLogdefine"></a>
  5511. <b>Define</b>
  5512. <ul>
  5513. <br>
  5514. <code>define &lt;name&gt; DbLog &lt;configfilename&gt; &lt;regexp&gt;</code>
  5515. <br><br>
  5516. <code>&lt;configfilename&gt;</code> ist die vorbereitete <b>Konfigurationsdatei</b>. <br>
  5517. <code>&lt;regexp&gt;</code> ist identisch <a href="https://fhem.de/commandref_DE.html#FileLog">FileLog</a> der Filelog-Definition.
  5518. <br><br>
  5519. <b>Beispiel:</b>
  5520. <ul>
  5521. <code>define myDbLog DbLog /etc/fhem/db.conf .*:.*</code><br>
  5522. speichert alles in der Datenbank
  5523. </ul>
  5524. <br>
  5525. Nachdem das DbLog-Device definiert wurde, ist empfohlen einen <b>Konfigurationscheck</b> auszuführen: <br><br>
  5526. <ul>
  5527. <code>set &lt;name&gt; configCheck</code> <br>
  5528. </ul>
  5529. <br>
  5530. Dieser Check prüft einige wichtige Einstellungen des DbLog-Devices und gibt Empfehlungen für potentielle Verbesserungen.
  5531. <br><br>
  5532. <br>
  5533. DbLog unterscheidet den synchronen (Default) und asynchronen Logmodus. Der Logmodus ist über das
  5534. <a href="#DbLogattr">Attribut</a> asyncMode einstellbar. Ab Version 2.13.5 unterstützt DbLog einen gesetzten
  5535. Primary Key (PK) in den Tabellen Current und History. Soll PostgreSQL mit PK genutzt werden, muss PostgreSQL mindestens
  5536. Version 9.5 sein.
  5537. <br><br>
  5538. Der gespeicherte Wert des Readings wird optimiert für eine automatisierte Nachverarbeitung, z.B. <code>yes</code> wird transformiert
  5539. nach <code>1</code>. <br><br>
  5540. Die gespeicherten Werte können mittels GET Funktion angezeigt werden:
  5541. <ul>
  5542. <code>get myDbLog - - 2012-11-10 2012-11-10 KS300:temperature</code>
  5543. </ul>
  5544. <br>
  5545. <b>FileLog-Dateien nach DbLog übertragen</b> <br><br>
  5546. Zur Übertragung von vorhandenen Filelog-Daten in die DbLog-Datenbank steht das spezielle Modul 98_FileLogConvert.pm
  5547. zur Verfügung. <br>
  5548. Dieses Modul kann <a href="https://svn.fhem.de/trac/browser/trunk/fhem/contrib/98_FileLogConvert.pm"> hier</a>
  5549. bzw. aus dem Verzeichnis ./contrib geladen werden.
  5550. Weitere Informationen und Hilfestellung gibt es im entsprechenden <a href="https://forum.fhem.de/index.php/topic,66383.0.html">
  5551. Forumthread </a>. <br><br><br>
  5552. <b>Reporting und Management von DbLog-Datenbankinhalten</b> <br><br>
  5553. Mit Hilfe <a href="https://fhem.de/commandref_DE.html#SVG">SVG</a> können Datenbankinhalte visualisiert werden. <br>
  5554. Darüber hinaus kann das Modul <a href="https://fhem.de/commandref_DE.html#DbRep">DbRep</a> genutzt werden um tabellarische
  5555. Datenbankauswertungen anzufertigen oder den Datenbankinhalt mit den zur Verfügung stehenden Funktionen zu verwalten.
  5556. <br><br><br>
  5557. <b>Troubleshooting</b> <br><br>
  5558. Wenn nach der erfolgreichen Definition das DbLog-Device nicht wie erwartet arbeitet,
  5559. können folgende Hinweise hilfreich sein: <br><br>
  5560. <ul>
  5561. <li> Wurden die vorbereitenden Schritte gemacht, die in der commandref beschrieben sind ? (Softwarekomponenten installieren, Tabellen, Index anlegen) </li>
  5562. <li> Wurde ein "set &lt;name&gt; configCheck" nach dem Define durchgeführt und eventuelle Fehler beseitigt bzw. Empfehlungen umgesetzt ? </li>
  5563. <li> Falls configDB in Benutzung ... wurde das DB-Konfigurationsfile in configDB importiert (z.B. mit "configDB fileimport ./db.conf") ? </li>
  5564. <li> Beim Anlegen eines SVG-Plots erscheint keine Drop-Down Liste mit Vorschlagswerten -> Attribut "DbLogType" auf "Current/History" setzen. </li>
  5565. </ul>
  5566. <br>
  5567. Sollten diese Hinweise nicht zum Erfolg führen, bitte den verbose-Level im DbLog Device auf 4 oder 5 hochsetzen und
  5568. die Einträge bezüglich des DbLog-Device im Logfile beachten.
  5569. Zur Problemanalyse bitte die Ausgabe von "list &lt;name&gt;", das Ergebnis von "set &lt;name&gt; configCheck" und die
  5570. Ausgaben des DbLog-Device im Logfile im Forumthread posten.
  5571. <br><br>
  5572. </ul>
  5573. <br>
  5574. <br>
  5575. <a name="DbLogset"></a>
  5576. <b>Set</b>
  5577. <ul>
  5578. <code>set &lt;name&gt; addCacheLine YYYY-MM-DD HH:MM:SS|&lt;device&gt;|&lt;type&gt;|&lt;event&gt;|&lt;reading&gt;|&lt;value&gt;|[&lt;unit&gt;] </code><br><br>
  5579. <ul> Im asynchronen Modus wird ein neuer Datensatz in den Cache eingefügt und beim nächsten Synclauf mit abgearbeitet.
  5580. <br><br>
  5581. <b>Beispiel:</b> <br>
  5582. set &lt;name&gt; addCacheLine 2017-12-05 17:03:59|MaxBathRoom|MAX|valveposition: 95|valveposition|95|% <br>
  5583. </ul><br>
  5584. <code>set &lt;name&gt; addLog &lt;devspec&gt;:&lt;Reading&gt; [Value] </code><br><br>
  5585. <ul> Fügt einen zusatzlichen Logeintrag einer Device/Reading-Kombination in die Datenbank ein.
  5586. Optional kann "Value" für den Readingwert angegeben werden. Ist Value nicht angegeben, wird der aktuelle
  5587. Wert des Readings in die DB eingefügt. Das Feld "$EVENT" wird automatisch mit "addLog" belegt. Das Device kann
  5588. als <a href="#devspec">Geräte-Spezifikation</a> angegeben werden. "Reading" wird als regulärer Ausdruck ausgewertet.
  5589. Es wird KEIN zusätzlicher Event im System erzeugt !<br><br>
  5590. <b>Beispiele:</b> <br>
  5591. set &lt;name&gt; addLog SMA_Energymeter:Bezug_Wirkleistung <br>
  5592. set &lt;name&gt; addLog TYPE=SSCam:state <br>
  5593. set &lt;name&gt; addLog MyWetter:(fc10.*|fc8.*) <br>
  5594. set &lt;name&gt; addLog MyWetter:(wind|wind_ch.*) 20 <br>
  5595. set &lt;name&gt; addLog TYPE=CUL_HM:FILTER=model=HM-CC-RT-DN:FILTER=subType!=(virtual|):(measured-temp|desired-temp|actuator) <br>
  5596. </ul><br>
  5597. <code>set &lt;name&gt; clearReadings </code><br><br>
  5598. <ul> Leert Readings die von verschiedenen DbLog-Funktionen angelegt wurden. </ul><br>
  5599. <code>set &lt;name&gt; eraseReadings </code><br><br>
  5600. <ul> Löscht alle Readings außer dem Reading "state". </ul><br>
  5601. <code>set &lt;name&gt; commitCache </code><br><br>
  5602. <ul>Im asynchronen Modus (<a href="#DbLogattr">Attribut</a> asyncMode=1), werden die im Speicher gecachten Daten in die Datenbank geschrieben
  5603. und danach der Cache geleert. Der interne Timer des asynchronen Modus wird dabei neu gesetzt.
  5604. Der Befehl kann nützlich sein um manuell oder z.B. über ein AT den Cacheinhalt zu einem definierten Zeitpunkt in die
  5605. Datenbank zu schreiben. </ul><br>
  5606. <code>set &lt;name&gt; configCheck </code><br><br>
  5607. <ul>Es werden einige wichtige Einstellungen geprüft und Empfehlungen gegeben falls potentielle Verbesserungen
  5608. identifiziert wurden.
  5609. </ul><br/>
  5610. <code>set &lt;name&gt; count </code><br><br>
  5611. <ul>Zählt die Datensätze in den Tabellen current und history und schreibt die Ergebnisse in die Readings
  5612. countCurrent und countHistory.</ul><br>
  5613. <code>set &lt;name&gt; countNbl </code><br/><br>
  5614. <ul>Die non-blocking Ausführung von "set &lt;name&gt; count".</ul><br>
  5615. <code>set &lt;name&gt; deleteOldDays &lt;n&gt;</code><br/><br>
  5616. <ul>Löscht Datensätze in Tabelle history, die älter sind als &lt;n&gt; Tage sind.
  5617. Die Anzahl der gelöschten Datens&auml;tze wird in das Reading lastRowsDeleted geschrieben.</ul><br>
  5618. <code>set &lt;name&gt; deleteOldDaysNbl &lt;n&gt;</code><br><br>
  5619. <ul>Identisch zu Funktion "deleteOldDays" wobei deleteOldDaysNbl nicht blockierend ausgeführt wird. </ul><br>
  5620. <a name="DbLogsetexportCache"></a>
  5621. <code>set &lt;name&gt; exportCache [nopurge | purgecache] </code><br><br>
  5622. <ul>Wenn DbLog im asynchronen Modus betrieben wird, kann der Cache mit diesem Befehl in ein Textfile geschrieben
  5623. werden. Das File wird per Default in dem Verzeichnis (global->modpath)/log/ erstellt. Das Zielverzeichnis kann mit
  5624. dem <a href="#DbLogattr">Attribut</a> "expimpdir" geändert werden. <br>
  5625. Der Name des Files wird automatisch generiert und enthält den Präfix "cache_", gefolgt von dem DbLog-Devicenamen und
  5626. dem aktuellen Zeitstempel, z.B. "cache_LogDB_2017-03-23_22-13-55". <br>
  5627. Mit den Optionen "nopurge" bzw. "purgecache" wird festgelegt, ob der Cacheinhalt nach dem Export gelöscht werden
  5628. soll oder nicht. Mit "nopurge" (default) bleibt der Cacheinhalt erhalten. <br>
  5629. Das <a href="#DbLogattr">Attribut</a> "exportCacheAppend" bestimmt dabei, ob mit jedem Exportvorgang ein neues Exportfile
  5630. angelegt wird (default) oder der Cacheinhalt an das bestehende (neueste) Exportfile angehängt wird.
  5631. </ul><br>
  5632. <code>set &lt;name&gt; importCachefile &lt;file&gt; </code><br><br>
  5633. <ul>Importiert ein mit "exportCache" geschriebenes File in die Datenbank.
  5634. Die verfügbaren Dateien werden per Default im Verzeichnis (global->modpath)/log/ gesucht und eine Drop-Down Liste
  5635. erzeugt sofern Dateien gefunden werden. Das Quellverzeichnis kann mit dem <a href="#DbLogattr">Attribut</a> expimpdir geändert werden. <br>
  5636. Es werden nur die Dateien angezeigt, die dem Muster "cache_", gefolgt von dem DbLog-Devicenamen entsprechen. <br>
  5637. Zum Beispiel "cache_LogDB_2017-03-23_22-13-55", falls das Log-Device "LogDB" heißt. <br>
  5638. Nach einem erfolgreichen Import wird das File mit dem Präfix "impdone_" versehen und erscheint dann nicht mehr
  5639. in der Drop-Down Liste. Soll ein Cachefile in eine andere als der Quelldatenbank importiert werden, kann das
  5640. DbLog-Device im Filenamen angepasst werden damit dieses File den Suchktiterien entspricht und in der Drop-Down Liste
  5641. erscheint. </ul><br>
  5642. <code>set &lt;name&gt; listCache </code><br><br>
  5643. <ul>Wenn DbLog im asynchronen Modus betrieben wird (Attribut asyncMode=1), können mit diesem Befehl die im Speicher gecachten Events
  5644. angezeigt werden.</ul><br>
  5645. <code>set &lt;name&gt; purgeCache </code><br><br>
  5646. <ul>Im asynchronen Modus (<a href="#DbLogattr">Attribut</a> asyncMode=1), werden die im Speicher gecachten Daten gelöscht.
  5647. Es werden keine Daten aus dem Cache in die Datenbank geschrieben. </ul><br>
  5648. <code>set &lt;name&gt; reduceLog &lt;n&gt; [average[=day]] [exclude=deviceRegExp1:ReadingRegExp1,deviceRegExp2:ReadingRegExp2,...]</code><br><br>
  5649. <ul>Reduziert historische Datensaetze, die älter sind als &lt;n&gt; Tage auf einen Eintrag pro Stunde (den ersten) je Device & Reading.<br><br>
  5650. <b>ACHTUNG:</b> Es wird dringend empfohlen zu überprüfen ob der standard INDEX 'Search_Idx' in der Tabelle 'history' existiert! <br>
  5651. Die Abarbeitung dieses Befehls dauert unter Umständen (ohne INDEX) extrem lange. FHEM wird durch den Befehl bis
  5652. zur Fertigstellung <b>komplett blockiert !</b> <br><br>
  5653. Das Reading "reduceLogState" zeigt den Ausführungsstatus des letzten reduceLog-Befehls. <br><br>
  5654. Durch die optionale Angabe von 'average' wird nicht nur die Datenbank bereinigt, sondern alle numerischen Werte
  5655. einer Stunde werden auf einen einzigen Mittelwert reduziert. <br>
  5656. Durch die optionale Angabe von 'average=day' wird nicht nur die Datenbank bereinigt, sondern alle numerischen
  5657. Werte eines Tages auf einen einzigen Mittelwert reduziert. (impliziert 'average') <br>
  5658. Optional kann als letzer Parameter "EXCLUDE=deviceRegExp1:ReadingRegExp1,deviceRegExp2:ReadingRegExp2,...."
  5659. angegeben werden um device/reading Kombinationen von reduceLog auszuschließen. <br>
  5660. Optional kann als letzer Parameter "INCLUDE=Database-deviceRegExp:Database-ReadingRegExp" angegeben werden um
  5661. die auf die Datenbank ausgeführte SELECT-Abfrage einzugrenzen, was die RAM-Belastung verringert und die
  5662. Performance erhöht. (Wildcards sind % und _) <br>
  5663. </ul><br>
  5664. <code>set &lt;name&gt; reduceLogNbl &lt;n&gt; [average[=day]] [exclude=deviceRegExp1:ReadingRegExp1,deviceRegExp2:ReadingRegExp2,...]</code><br><br>
  5665. <ul>
  5666. Führt die gleiche Funktion wie "set &lt;name&gt; reduceLog" aus. Im Gegensatz zu reduceLog wird mit FHEM wird durch den Befehl reduceLogNbl nicht
  5667. mehr blockiert da diese Funktion non-blocking implementiert ist ! <br>
  5668. </ul><br>
  5669. <code>set &lt;name&gt; reopen [n]</code><br/><br/>
  5670. <ul>Schließt die Datenbank und öffnet sie danach sofort wieder wenn keine Zeit [n] in Sekunden angegeben wurde.
  5671. Dabei wird die Journaldatei geleert und neu angelegt.<br/>
  5672. Verbessert den Datendurchsatz und vermeidet Speicherplatzprobleme. <br>
  5673. Wurde eine optionale Verzögerungszeit [n] in Sekunden angegeben, wird die Verbindung zur Datenbank geschlossen und erst
  5674. nach Ablauf von [n] Sekunden wieder neu verbunden.
  5675. Im synchronen Modus werden die Events in dieser Zeit nicht gespeichert.
  5676. Im asynchronen Modus werden die Events im Cache gespeichert und nach dem Reconnect in die Datenbank geschrieben. </ul><br>
  5677. <code>set &lt;name&gt; rereadcfg </code><br/><br/>
  5678. <ul>Schließt die Datenbank und öffnet sie danach sofort wieder. Dabei wird die Journaldatei geleert und neu angelegt.<br/>
  5679. Verbessert den Datendurchsatz und vermeidet Speicherplatzprobleme.<br/>
  5680. Zwischen dem Schließen der Verbindung und dem Neuverbinden werden die Konfigurationsdaten neu gelesen</ul><br/>
  5681. <code>set &lt;name&gt; userCommand &lt;validSqlStatement&gt;</code><br/><br/>
  5682. <ul><b>BENUTZE DIESE FUNKTION NUR, WENN DU WIRKLICH (WIRKLICH!) WEISST, WAS DU TUST!!!</b><br/><br/>
  5683. Führt einen beliebigen (!!!) sql Befehl in der Datenbank aus. Der Befehl und ein zurückgeliefertes
  5684. Ergebnis wird in das Reading "userCommand" bzw. "userCommandResult" geschrieben. Das Ergebnis kann nur
  5685. einzeilig sein.
  5686. Für SQL-Statements, die mehrzeilige Ergebnisse liefern, kann das Auswertungsmodul
  5687. <a href=https://fhem.de/commandref_DE.html#DbRep>DbRep</a> genutzt werden.</br>
  5688. Wird von der Datenbankschnittstelle kein Ergebnis (undef) zurückgeliefert, erscheint die Meldung "no result"
  5689. im Reading "userCommandResult".
  5690. </ul><br>
  5691. </ul><br>
  5692. <a name="DbLogget"></a>
  5693. <b>Get</b>
  5694. <ul>
  5695. <code>get &lt;name&gt; ReadingsVal&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;device&gt; &lt;reading&gt; &lt;default&gt;</code><br/>
  5696. <code>get &lt;name&gt; ReadingsTimestamp &lt;device&gt; &lt;reading&gt; &lt;default&gt;</code><br/>
  5697. <br/>
  5698. Liest einen einzelnen Wert aus der Datenbank, Benutzung und Syntax sind weitgehend identisch zu ReadingsVal() und ReadingsTimestamp().<br/>
  5699. </ul>
  5700. <br/>
  5701. <br/>
  5702. <ul>
  5703. <code>get &lt;name&gt; &lt;infile&gt; &lt;outfile&gt; &lt;from&gt;
  5704. &lt;to&gt; &lt;column_spec&gt; </code>
  5705. <br><br>
  5706. Liesst Daten aus der Datenbank. Wird durch die Frontends benutzt um Plots
  5707. zu generieren ohne selbst auf die Datenank zugreifen zu müssen.
  5708. <br>
  5709. <ul>
  5710. <li>&lt;in&gt;<br>
  5711. Ein Parameter um eine Kompatibilität zum Filelog herzustellen.
  5712. Dieser Parameter ist per default immer auf <code>-</code> zu setzen.<br>
  5713. Folgende Ausprägungen sind zugelassen:<br>
  5714. <ul>
  5715. <li>current: die aktuellen Werte aus der Tabelle "current" werden gelesen.</li>
  5716. <li>history: die historischen Werte aus der Tabelle "history" werden gelesen.</li>
  5717. <li>-: identisch wie "history"</li>
  5718. </ul>
  5719. </li>
  5720. <li>&lt;out&gt;<br>
  5721. Ein Parameter um eine Kompatibilität zum Filelog herzustellen.
  5722. Dieser Parameter ist per default immer auf <code>-</code> zu setzen um die
  5723. Ermittlung der Daten aus der Datenbank für die Plotgenerierung zu prüfen.<br>
  5724. Folgende Ausprägungen sind zugelassen:<br>
  5725. <ul>
  5726. <li>ALL: Es werden alle Spalten der Datenbank ausgegeben. Inclusive einer Überschrift.</li>
  5727. <li>Array: Es werden alle Spalten der Datenbank als Hash ausgegeben. Alle Datensätze als Array zusammengefasst.</li>
  5728. <li>INT: intern zur Plotgenerierung verwendet</li>
  5729. <li>-: default</li>
  5730. </ul>
  5731. </li>
  5732. <li>&lt;from&gt; / &lt;to&gt;<br>
  5733. Wird benutzt um den Zeitraum der Daten einzugrenzen. Es ist das folgende
  5734. Zeitformat oder ein Teilstring davon zu benutzen:<br>
  5735. <ul><code>YYYY-MM-DD_HH24:MI:SS</code></ul></li>
  5736. <li>&lt;column_spec&gt;<br>
  5737. Für jede column_spec Gruppe wird ein Datenset zurückgegeben welches
  5738. durch einen Kommentar getrennt wird. Dieser Kommentar repräsentiert
  5739. die column_spec.<br>
  5740. Syntax: &lt;device&gt;:&lt;reading&gt;:&lt;default&gt;:&lt;fn&gt;:&lt;regexp&gt;<br>
  5741. <ul>
  5742. <li>&lt;device&gt;<br>
  5743. Der Name des Devices. Achtung: Gross/Kleinschreibung beachten!<br>
  5744. Es kann ein % als Jokerzeichen angegeben werden.</li>
  5745. <li>&lt;reading&gt;<br>
  5746. Das Reading des angegebenen Devices zur Datenselektion.<br>
  5747. Es kann ein % als Jokerzeichen angegeben werden.<br>
  5748. Achtung: Gross/Kleinschreibung beachten!
  5749. </li>
  5750. <li>&lt;default&gt;<br>
  5751. Zur Zeit noch nicht implementiert.
  5752. </li>
  5753. <li>&lt;fn&gt;
  5754. Angabe einer speziellen Funktion:
  5755. <ul>
  5756. <li>int<br>
  5757. Ermittelt den Zahlenwert ab dem Anfang der Zeichenkette aus der
  5758. Spalte "VALUE". Benutzt z.B. für Ausprägungen wie 10%.
  5759. </li>
  5760. <li>int&lt;digit&gt;<br>
  5761. Ermittelt den Zahlenwert ab dem Anfang der Zeichenkette aus der
  5762. Spalte "VALUE", inclusive negativen Vorzeichen und Dezimaltrenner.
  5763. Benutzt z.B. für Auspägungen wie -5.7&deg;C.
  5764. </li>
  5765. <li>delta-h / delta-d<br>
  5766. Ermittelt die relative Veränderung eines Zahlenwertes pro Stunde
  5767. oder pro Tag. Wird benutzt z.B. für Spalten die einen
  5768. hochlaufenden Zähler enthalten wie im Falle für ein KS300 Regenzähler
  5769. oder dem 1-wire Modul OWCOUNT.
  5770. </li>
  5771. <li>delta-ts<br>
  5772. Ermittelt die vergangene Zeit zwischen dem letzten und dem aktuellen Logeintrag
  5773. in Sekunden und ersetzt damit den originalen Wert.
  5774. </li>
  5775. </ul></li>
  5776. <li>&lt;regexp&gt;<br>
  5777. Diese Zeichenkette wird als Perl Befehl ausgewertet.
  5778. Die regexp wird vor dem angegebenen &lt;fn&gt; Parameter ausgeführt.
  5779. <br>
  5780. Bitte zur Beachtung: Diese Zeichenkette darf keine Leerzeichen
  5781. enthalten da diese sonst als &lt;column_spec&gt; Trennung
  5782. interpretiert werden und alles nach dem Leerzeichen als neue
  5783. &lt;column_spec&gt; gesehen wird.<br>
  5784. <b>Schlüsselwörter</b>
  5785. <li>$val ist der aktuelle Wert die die Datenbank für ein Device/Reading ausgibt.</li>
  5786. <li>$ts ist der aktuelle Timestamp des Logeintrages.</li>
  5787. <li>Wird als $val das Schlüsselwort "hide" zurückgegeben, so wird dieser Logeintrag nicht
  5788. ausgegeben, trotzdem aber für die Zeitraumberechnung verwendet.</li>
  5789. <li>Wird als $val das Schlüsselwort "ignore" zurückgegeben, so wird dieser Logeintrag
  5790. nicht für eine Folgeberechnung verwendet.</li>
  5791. </li>
  5792. </ul></li>
  5793. </ul>
  5794. <br><br>
  5795. <b>Beispiele:</b>
  5796. <ul>
  5797. <li><code>get myDbLog - - 2012-11-10 2012-11-20 KS300:temperature</code></li>
  5798. <li><code>get myDbLog current ALL - - %:temperature</code></li><br>
  5799. Damit erhält man alle aktuellen Readings "temperature" von allen in der DB geloggten Devices.
  5800. Achtung: bei Nutzung von Jokerzeichen auf die history-Tabelle kann man sein FHEM aufgrund langer Laufzeit lahmlegen!
  5801. <li><code>get myDbLog - - 2012-11-10_10 2012-11-10_20 KS300:temperature::int1</code><br>
  5802. gibt Daten aus von 10Uhr bis 20Uhr am 10.11.2012</li>
  5803. <li><code>get myDbLog - all 2012-11-10 2012-11-20 KS300:temperature</code></li>
  5804. <li><code>get myDbLog - - 2012-11-10 2012-11-20 KS300:temperature KS300:rain::delta-h KS300:rain::delta-d</code></li>
  5805. <li><code>get myDbLog - - 2012-11-10 2012-11-20 MyFS20:data:::$val=~s/(on|off).*/$1eq"on"?1:0/eg</code><br>
  5806. gibt 1 zurück für alle Ausprägungen von on* (on|on-for-timer etc) und 0 für alle off*</li>
  5807. <li><code>get myDbLog - - 2012-11-10 2012-11-20 Bodenfeuchte:data:::$val=~s/.*B:\s([-\.\d]+).*/$1/eg</code><br>
  5808. Beispiel von OWAD: Ein Wert wie z.B.: <code>"A: 49.527 % B: 66.647 % C: 9.797 % D: 0.097 V"</code><br>
  5809. und die Ausgabe ist für das Reading B folgende: <code>2012-11-20_10:23:54 66.647</code></li>
  5810. <li><code>get DbLog - - 2013-05-26 2013-05-28 Pumpe:data::delta-ts:$val=~s/on/hide/</code><br>
  5811. Realisierung eines Betriebsstundenzählers. Durch delta-ts wird die Zeit in Sek zwischen den Log-
  5812. Einträgen ermittelt. Die Zeiten werden bei den on-Meldungen nicht ausgegeben welche einer Abschaltzeit
  5813. entsprechen würden.</li>
  5814. </ul>
  5815. <br><br>
  5816. </ul>
  5817. <b>Get</b> für die Nutzung von webcharts
  5818. <ul>
  5819. <code>get &lt;name&gt; &lt;infile&gt; &lt;outfile&gt; &lt;from&gt;
  5820. &lt;to&gt; &lt;device&gt; &lt;querytype&gt; &lt;xaxis&gt; &lt;yaxis&gt; &lt;savename&gt; </code>
  5821. <br><br>
  5822. Liest Daten aus der Datenbank aus und gibt diese in JSON formatiert aus. Wird für das Charting Frontend genutzt
  5823. <br>
  5824. <ul>
  5825. <li>&lt;name&gt;<br>
  5826. Der Name des definierten DbLogs, so wie er in der fhem.cfg angegeben wurde.</li>
  5827. <li>&lt;in&gt;<br>
  5828. Ein Dummy Parameter um eine Kompatibilität zum Filelog herzustellen.
  5829. Dieser Parameter ist immer auf <code>-</code> zu setzen.</li>
  5830. <li>&lt;out&gt;<br>
  5831. Ein Dummy Parameter um eine Kompatibilität zum Filelog herzustellen.
  5832. Dieser Parameter ist auf <code>webchart</code> zu setzen um die Charting Get Funktion zu nutzen.
  5833. </li>
  5834. <li>&lt;from&gt; / &lt;to&gt;<br>
  5835. Wird benutzt um den Zeitraum der Daten einzugrenzen. Es ist das folgende
  5836. Zeitformat zu benutzen:<br>
  5837. <ul><code>YYYY-MM-DD_HH24:MI:SS</code></ul></li>
  5838. <li>&lt;device&gt;<br>
  5839. Ein String, der das abzufragende Device darstellt.</li>
  5840. <li>&lt;querytype&gt;<br>
  5841. Ein String, der die zu verwendende Abfragemethode darstellt. Zur Zeit unterstützte Werte sind: <br>
  5842. <code>getreadings</code> um für ein bestimmtes device alle Readings zu erhalten<br>
  5843. <code>getdevices</code> um alle verfügbaren devices zu erhalten<br>
  5844. <code>timerange</code> um Chart-Daten abzufragen. Es werden die Parameter 'xaxis', 'yaxis', 'device', 'to' und 'from' benötigt<br>
  5845. <code>savechart</code> um einen Chart unter Angabe eines 'savename' und seiner zugehörigen Konfiguration abzuspeichern<br>
  5846. <code>deletechart</code> um einen zuvor gespeicherten Chart unter Angabe einer id zu löschen<br>
  5847. <code>getcharts</code> um eine Liste aller gespeicherten Charts zu bekommen.<br>
  5848. <code>getTableData</code> um Daten aus der Datenbank abzufragen und in einer Tabelle darzustellen. Benötigt paging Parameter wie start und limit.<br>
  5849. <code>hourstats</code> um Statistiken für einen Wert (yaxis) für eine Stunde abzufragen.<br>
  5850. <code>daystats</code> um Statistiken für einen Wert (yaxis) für einen Tag abzufragen.<br>
  5851. <code>weekstats</code> um Statistiken für einen Wert (yaxis) für eine Woche abzufragen.<br>
  5852. <code>monthstats</code> um Statistiken für einen Wert (yaxis) für einen Monat abzufragen.<br>
  5853. <code>yearstats</code> um Statistiken für einen Wert (yaxis) für ein Jahr abzufragen.<br>
  5854. </li>
  5855. <li>&lt;xaxis&gt;<br>
  5856. Ein String, der die X-Achse repräsentiert</li>
  5857. <li>&lt;yaxis&gt;<br>
  5858. Ein String, der die Y-Achse repräsentiert</li>
  5859. <li>&lt;savename&gt;<br>
  5860. Ein String, unter dem ein Chart in der Datenbank gespeichert werden soll</li>
  5861. <li>&lt;chartconfig&gt;<br>
  5862. Ein jsonstring der den zu speichernden Chart repräsentiert</li>
  5863. <li>&lt;pagingstart&gt;<br>
  5864. Ein Integer um den Startwert für die Abfrage 'getTableData' festzulegen</li>
  5865. <li>&lt;paginglimit&gt;<br>
  5866. Ein Integer um den Limitwert für die Abfrage 'getTableData' festzulegen</li>
  5867. </ul>
  5868. <br><br>
  5869. Beispiele:
  5870. <ul>
  5871. <li><code>get logdb - webchart "" "" "" getcharts</code><br>
  5872. Liefert alle gespeicherten Charts aus der Datenbank</li>
  5873. <li><code>get logdb - webchart "" "" "" getdevices</code><br>
  5874. Liefert alle verfügbaren Devices aus der Datenbank</li>
  5875. <li><code>get logdb - webchart "" "" ESA2000_LED_011e getreadings</code><br>
  5876. Liefert alle verfügbaren Readings aus der Datenbank unter Angabe eines Gerätes</li>
  5877. <li><code>get logdb - webchart 2013-02-11_00:00:00 2013-02-12_00:00:00 ESA2000_LED_011e timerange TIMESTAMP day_kwh</code><br>
  5878. Liefert Chart-Daten, die auf folgenden Parametern basieren: 'xaxis', 'yaxis', 'device', 'to' und 'from'<br>
  5879. Die Ausgabe erfolgt als JSON, z.B.: <code>[{'TIMESTAMP':'2013-02-11 00:10:10','VALUE':'0.22431388090756'},{'TIMESTAMP'.....}]</code></li>
  5880. <li><code>get logdb - webchart 2013-02-11_00:00:00 2013-02-12_00:00:00 ESA2000_LED_011e savechart TIMESTAMP day_kwh tageskwh</code><br>
  5881. Speichert einen Chart unter Angabe eines 'savename' und seiner zugehörigen Konfiguration</li>
  5882. <li><code>get logdb - webchart "" "" "" deletechart "" "" 7</code><br>
  5883. Löscht einen zuvor gespeicherten Chart unter Angabe einer id</li>
  5884. </ul>
  5885. <br><br>
  5886. </ul>
  5887. <a name="DbLogattr"></a>
  5888. <b>Attribute</b>
  5889. <br><br>
  5890. <ul><b>addStateEvent</b>
  5891. <ul>
  5892. <code>attr &lt;device&gt; addStateEvent [0|1]
  5893. </code><br>
  5894. Bekanntlich wird normalerweise bei einem Event mit dem Reading "state" der state-String entfernt, d.h.
  5895. der Event ist nicht zum Beispiel "state: on" sondern nur "on". <br>
  5896. Meistens ist es aber hilfreich in DbLog den kompletten Event verarbeiten zu können. Deswegen übernimmt DbLog per Default
  5897. den Event inklusive dem Reading-String "state". <br>
  5898. In einigen Fällen, z.B. alten oder speziellen Modulen, ist es allerdings wünschenswert den state-String wie gewöhnlich
  5899. zu entfernen. In diesen Fällen bitte addStateEvent = "0" setzen.
  5900. Versuchen sie bitte diese Einstellung, falls es mit dem Standard Probleme geben sollte.
  5901. <br>
  5902. </ul>
  5903. </ul>
  5904. <br>
  5905. <ul><b>asyncMode</b>
  5906. <ul>
  5907. <code>attr &lt;device&gt; asyncMode [1|0]
  5908. </code><br>
  5909. Dieses Attribut stellt den Arbeitsmodus von DbLog ein. Im asynchronen Modus (asyncMode=1), werden die zu speichernden Events zunächst in Speicher
  5910. gecacht. Nach Ablauf der Synchronisationszeit (Attribut syncInterval) oder bei Erreichen der maximalen Anzahl der Datensätze im Cache
  5911. (Attribut cacheLimit) werden die gecachten Events im Block in die Datenbank geschrieben.
  5912. Ist die Datenbank nicht verfügbar, werden die Events weiterhin im Speicher gehalten und nach Ablauf des Syncintervalls in die Datenbank
  5913. geschrieben falls sie dann verfügbar ist. <br>
  5914. Im asynchronen Mode werden die Daten nicht blockierend mit einem separaten Hintergrundprozess in die Datenbank geschrieben.
  5915. Det Timeout-Wert für diesen Hintergrundprozess kann mit dem Attribut "timeout" (Default 86400s) eingestellt werden.
  5916. Im synchronen Modus (Normalmodus) werden die Events nicht gecacht und sofort in die Datenbank geschrieben. Ist die Datenbank nicht
  5917. verfügbar gehen sie verloren.<br>
  5918. </ul>
  5919. </ul>
  5920. <br>
  5921. <ul><b>commitMode</b>
  5922. <ul>
  5923. <code>attr &lt;device&gt; commitMode [basic_ta:on | basic_ta:off | ac:on_ta:on | ac:on_ta:off | ac:off_ta:on]
  5924. </code><br>
  5925. Ändert die Verwendung der Datenbank Autocommit- und/oder Transaktionsfunktionen.
  5926. Dieses Attribut ist ein advanced feature und sollte nur im konkreten Bedarfs- bzw. Supportfall geändert werden.<br><br>
  5927. <ul>
  5928. <li>basic_ta:on - Autocommit Servereinstellung / Transaktion ein (default) </li>
  5929. <li>basic_ta:off - Autocommit Servereinstellung / Transaktion aus </li>
  5930. <li>ac:on_ta:on - Autocommit ein / Transaktion ein </li>
  5931. <li>ac:on_ta:off - Autocommit ein / Transaktion aus </li>
  5932. <li>ac:off_ta:on - Autocommit aus / Transaktion ein (Autocommit aus impliziert Transaktion ein) </li>
  5933. </ul>
  5934. </ul>
  5935. </ul>
  5936. <br>
  5937. <ul><b>cacheEvents</b>
  5938. <ul>
  5939. <code>attr &lt;device&gt; cacheEvents [2|1|0]
  5940. </code><br>
  5941. <ul>
  5942. <li>cacheEvents=1: es werden Events für das Reading CacheUsage erzeugt wenn ein Event zum Cache hinzugefügt wurde. </li>
  5943. <li>cacheEvents=2: es werden Events für das Reading CacheUsage erzeugt wenn im asynchronen Mode der Schreibzyklus in die
  5944. Datenbank beginnt. CacheUsage enthält zu diesem Zeitpunkt die Anzahl der in die Datenbank zu schreibenden
  5945. Datensätze. </li><br>
  5946. </ul>
  5947. </ul>
  5948. </ul>
  5949. <br>
  5950. <ul><b>cacheLimit</b>
  5951. <ul>
  5952. <code>
  5953. attr &lt;device&gt; cacheLimit &lt;n&gt;
  5954. </code><br>
  5955. Im asynchronen Logmodus wird der Cache in die Datenbank weggeschrieben und geleert wenn die Anzahl &lt;n&gt; Datensätze
  5956. im Cache erreicht ist (Default: 500). Der Timer des asynchronen Logmodus wird dabei neu auf den Wert des Attributs "syncInterval"
  5957. gesetzt. Im Fehlerfall wird ein erneuter Schreibversuch frühestens nach syncInterval/2 gestartet. <br>
  5958. </ul>
  5959. </ul>
  5960. <br>
  5961. <ul><b>colEvent</b>
  5962. <ul>
  5963. <code>
  5964. attr &lt;device&gt; colEvent &lt;n&gt;
  5965. </code><br>
  5966. Die Feldlänge für das DB-Feld EVENT wird userspezifisch angepasst. Mit dem Attribut kann der Default-Wert im Modul
  5967. verändert werden wenn die Feldlänge in der Datenbank manuell geändert wurde. Mit colEvent=0 wird das Datenbankfeld
  5968. EVENT nicht gefüllt. <br>
  5969. <b>Hinweis:</b> <br>
  5970. Mit gesetztem Attribut gelten alle Feldlängenbegrenzungen auch für SQLite DB wie im Internal COLUMNS angezeigt ! <br>
  5971. </ul>
  5972. </ul>
  5973. <br>
  5974. <ul><b>colReading</b>
  5975. <ul>
  5976. <code>
  5977. attr &lt;device&gt; colReading &lt;n&gt;
  5978. </code><br>
  5979. Die Feldlänge für das DB-Feld READING wird userspezifisch angepasst. Mit dem Attribut kann der Default-Wert im Modul
  5980. verändert werden wenn die Feldlänge in der Datenbank manuell geändert wurde. Mit colReading=0 wird das Datenbankfeld
  5981. READING nicht gefüllt. <br>
  5982. <b>Hinweis:</b> <br>
  5983. Mit gesetztem Attribut gelten alle Feldlängenbegrenzungen auch für SQLite DB wie im Internal COLUMNS angezeigt ! <br>
  5984. </ul>
  5985. </ul>
  5986. <br>
  5987. <ul><b>colValue</b>
  5988. <ul>
  5989. <code>
  5990. attr &lt;device&gt; colValue &lt;n&gt;
  5991. </code><br>
  5992. Die Feldlänge für das DB-Feld VALUE wird userspezifisch angepasst. Mit dem Attribut kann der Default-Wert im Modul
  5993. verändert werden wenn die Feldlänge in der Datenbank manuell geändert wurde. Mit colValue=0 wird das Datenbankfeld
  5994. VALUE nicht gefüllt. <br>
  5995. <b>Hinweis:</b> <br>
  5996. Mit gesetztem Attribut gelten alle Feldlängenbegrenzungen auch für SQLite DB wie im Internal COLUMNS angezeigt ! <br>
  5997. </ul>
  5998. </ul>
  5999. <br>
  6000. <ul><b>DbLogType</b>
  6001. <ul>
  6002. <code>
  6003. attr &lt;device&gt; DbLogType [Current|History|Current/History|SampleFill/History]
  6004. </code><br>
  6005. Dieses Attribut legt fest, welche Tabelle oder Tabellen in der Datenbank genutzt werden sollen. Ist dieses Attribut nicht gesetzt, wird
  6006. per default die Einstellung <i>history</i> verwendet. <br><br>
  6007. Bedeutung der Einstellungen sind: <br><br>
  6008. <ul>
  6009. <table>
  6010. <colgroup> <col width=10%> <col width=90%> </colgroup>
  6011. <tr><td> <b>Current</b> </td><td>Events werden nur in die current-Tabelle geloggt.
  6012. Die current-Tabelle wird bei der SVG-Erstellung ausgewertet. </td></tr>
  6013. <tr><td> <b>History</b> </td><td>Events werden nur in die history-Tabelle geloggt. Es wird keine DropDown-Liste mit Vorschlägen bei der SVG-Erstellung
  6014. erzeugt. </td></tr>
  6015. <tr><td> <b>Current/History</b> </td><td>Events werden sowohl in die current- also auch in die hitory Tabelle geloggt.
  6016. Die current-Tabelle wird bei der SVG-Erstellung ausgewertet.</td></tr>
  6017. <tr><td> <b>SampleFill/History</b> </td><td>Events werden nur in die history-Tabelle geloggt. Die current-Tabelle wird bei der SVG-Erstellung ausgewertet und
  6018. kann zur Erzeugung einer DropDown-Liste mittels einem
  6019. <a href="http://fhem.de/commandref_DE.html#DbRep">DbRep-Device</a> <br> "set &lt;DbRep-Name&gt; tableCurrentFillup" mit
  6020. einem einstellbaren Extract der history-Tabelle gefüllt werden (advanced Feature). </td></tr>
  6021. </table>
  6022. </ul>
  6023. <br>
  6024. <br>
  6025. <b>Hinweis:</b> <br>
  6026. Die Current-Tabelle muß genutzt werden um eine Device:Reading-DropDownliste zur Erstellung eines
  6027. SVG-Plots zu erhalten. <br>
  6028. </ul>
  6029. </ul>
  6030. <br>
  6031. <ul><b>DbLogSelectionMode</b>
  6032. <ul>
  6033. <code>
  6034. attr &lt;device&gt; DbLogSelectionMode [Exclude|Include|Exclude/Include]
  6035. </code><br>
  6036. Dieses, fuer DbLog-Devices spezifische Attribut beeinflußt, wie die Device-spezifischen Attributes
  6037. DbLogExclude und DbLogInclude (s.u.) ausgewertet werden.<br>
  6038. Fehlt dieses Attribut, wird dafuer "Exclude" als Default angenommen. <br>
  6039. <ul>
  6040. <li>Exclude: DbLog verhaelt sich wie bisher auch, alles was ueber die RegExp im DEF angegeben ist, wird geloggt, bis auf das,
  6041. was ueber die RegExp in DbLogExclude ausgeschlossen wird. <br>
  6042. Das Attribut DbLogInclude wird in diesem Fall nicht beruecksichtigt</li>
  6043. <li>Include: Es wird nur das geloggt was ueber die RegExp in DbLogInclude eingeschlossen wird. <br>
  6044. Das Attribut DbLogExclude wird in diesem Fall ebenso wenig beruecksichtigt wie die Regex im DEF. </li>
  6045. <li>Exclude/Include: Funktioniert im Wesentlichen wie "Exclude", nur das sowohl DbLogExclude als auch DbLogInclude
  6046. geprueft werden. Readings die durch DbLogExclude zwar ausgeschlossen wurden, mit DbLogInclude aber wiederum eingeschlossen werden,
  6047. werden somit dennoch geloggt. </li>
  6048. </ul>
  6049. </ul>
  6050. </ul>
  6051. <br>
  6052. <ul><b>DbLogInclude</b>
  6053. <ul>
  6054. <code>
  6055. attr &lt;device&gt; DbLogInclude regex:MinInterval,[regex:MinInterval] ...
  6056. </code><br>
  6057. Wenn DbLog genutzt wird, wird in allen Devices das Attribut <i>DbLogInclude</i> propagiert.
  6058. DbLogInclude funktioniert im Endeffekt genau wie DbLogExclude, ausser dass eben readings mit diesen RegExp
  6059. in das Logging eingeschlossen werden koennen, statt ausgeschlossen.
  6060. Siehe dazu auch das DbLog-Device-Spezifische Attribut DbLogSelectionMode, das beeinflußt wie
  6061. DbLogExclude und DbLogInclude ausgewertet werden. <br>
  6062. <b>Beispiel</b> <br>
  6063. <code>attr MyDevice1 DbLogInclude .*</code> <br>
  6064. <code>attr MyDevice2 DbLogInclude state,(floorplantext|MyUserReading):300,battery:3600</code>
  6065. </ul>
  6066. </ul>
  6067. <br>
  6068. <ul><b>DbLogExclude</b>
  6069. <ul>
  6070. <code>
  6071. attr &lt;device&gt; DbLogExclude regex:MinInterval,[regex:MinInterval] ...
  6072. </code><br>
  6073. Wenn DbLog genutzt wird, wird in alle Devices das Attribut <i>DbLogExclude</i> propagiert.
  6074. Der Wert des Attributes wird als Regexp ausgewertet und schliesst die damit matchenden Readings von einem Logging aus.
  6075. Einzelne Regexp werden durch Kommata getrennt. Ist MinIntervall angegeben, so wird der Logeintrag nur
  6076. dann nicht geloggt, wenn das Intervall noch nicht erreicht und der Wert des Readings sich nicht verändert hat. <br><br>
  6077. <b>Beispiel</b> <br>
  6078. <code>attr MyDevice1 DbLogExclude .*</code> <br>
  6079. <code>attr MyDevice2 DbLogExclude state,(floorplantext|MyUserReading):300,battery:3600</code>
  6080. </ul>
  6081. </ul>
  6082. <br>
  6083. <ul><b>excludeDevs</b>
  6084. <ul>
  6085. <code>
  6086. attr &lt;device&gt; excludeDevs &lt;devspec1&gt;,&lt;devspec2&gt;,&lt;devspec..&gt;
  6087. </code><br>
  6088. Die Devices "devspec1", "devspec2" bis "devspec.." werden vom Logging in die Datenbank ausgeschlossen.
  6089. Diese Attribut wirkt nur wenn kein Internal "NOTIFYDEV" vorhanden ist.
  6090. Dadurch können Devices explizit vom Logging ausgeschlossen werden.
  6091. Die auszuschließenden Devices können als <a href="#devspec">Geräte-Spezifikation</a> angegeben werden.
  6092. Für weitere Details bezüglich devspec siehe <a href="#devspec">Geräte-Spezifikation</a>. <br><br>
  6093. <b>Beispiel</b> <br>
  6094. <code>
  6095. attr &lt;device&gt; excludeDevs global,Log.*,Cam.*,TYPE=DbLog
  6096. </code><br>
  6097. # Es werden die Devices global bzw. Devices beginnend mit "Log" oder "Cam" bzw. Devices vom Typ "DbLog" vom Datenbanklogging ausgeschlossen. <br>
  6098. </ul>
  6099. </ul>
  6100. <br>
  6101. <ul><b>expimpdir</b>
  6102. <ul>
  6103. <code>
  6104. attr &lt;device&gt; expimpdir &lt;directory&gt;
  6105. </code><br>
  6106. In diesem Verzeichnis wird das Cachefile beim Export angelegt bzw. beim Import gesucht. Siehe set-Kommandos
  6107. <a href="#DbLogsetexportCache">"exportCache"</a> bzw. "importCachefile". Das Default-Verzeichnis ist "(global->modpath)/log/".
  6108. Das im Attribut angegebene Verzeichnis muss vorhanden und beschreibbar sein. <br><br>
  6109. <b>Beispiel</b> <br>
  6110. <code>
  6111. attr &lt;device&gt; expimpdir /opt/fhem/cache/
  6112. </code><br>
  6113. </ul>
  6114. </ul>
  6115. <br>
  6116. <ul><b>exportCacheAppend</b>
  6117. <ul>
  6118. <code>
  6119. attr &lt;device&gt; exportCacheAppend [1|0]
  6120. </code><br>
  6121. Wenn gesetzt, wird beim Export des Cache ("set &lt;device&gt; exportCache") der Cacheinhalt an das neueste bereits vorhandene
  6122. Exportfile angehängt. Ist noch kein Exportfile vorhanden, wird es neu angelegt. <br>
  6123. Ist das Attribut nicht gesetzt, wird bei jedem Exportvorgang ein neues Exportfile angelegt. (default)<br/>
  6124. </ul>
  6125. </ul>
  6126. <br>
  6127. <ul><b>noNotifyDev</b>
  6128. <ul>
  6129. <code>
  6130. attr &lt;device&gt; noNotifyDev [1|0]
  6131. </code><br>
  6132. Erzwingt dass NOTIFYDEV nicht gesetzt und somit nicht verwendet wird.<br>
  6133. </ul>
  6134. </ul>
  6135. <br>
  6136. <ul><b>noSupportPK</b>
  6137. <ul>
  6138. <code>
  6139. attr &lt;device&gt; noSupportPK [1|0]
  6140. </code><br>
  6141. Deaktiviert die programmtechnische Unterstützung eines gesetzten Primary Key durch das Modul.<br>
  6142. </ul>
  6143. </ul>
  6144. <br>
  6145. <ul><b>shutdownWait</b>
  6146. <ul>
  6147. <code>
  6148. attr &lt;device&gt; shutdownWait <n>
  6149. </code><br>
  6150. FHEM wartet während des shutdowns fuer n Sekunden, um die Datenbank korrekt zu beenden<br/>
  6151. </ul>
  6152. </ul>
  6153. <br>
  6154. <ul><b>showproctime</b>
  6155. <ul>
  6156. <code>attr &lt;device&gt; showproctime [1|0]
  6157. </code><br>
  6158. Wenn gesetzt, zeigt das Reading "sql_processing_time" die benötigte Abarbeitungszeit (in Sekunden) für die SQL-Ausführung der
  6159. durchgeführten Funktion. Dabei wird nicht ein einzelnes SQL-Statement, sondern die Summe aller notwendigen SQL-Abfragen innerhalb der
  6160. jeweiligen Funktion betrachtet. Das Reading "background_processing_time" zeigt die im Kindprozess BlockingCall verbrauchte Zeit.<br>
  6161. </ul>
  6162. </ul>
  6163. <br>
  6164. <ul><b>showNotifyTime</b>
  6165. <ul>
  6166. <code>attr &lt;device&gt; showNotifyTime [1|0]
  6167. </code><br>
  6168. Wenn gesetzt, zeigt das Reading "notify_processing_time" die benötigte Abarbeitungszeit (in Sekunden) für die
  6169. Abarbeitung der DbLog Notify-Funktion. Das Attribut ist für Performance Analysen geeignet und hilft auch die Unterschiede
  6170. im Zeitbedarf bei der Umschaltung des synchronen in den asynchronen Modus festzustellen. <br>
  6171. </ul>
  6172. </ul>
  6173. <br>
  6174. <ul><b>syncEvents</b>
  6175. <ul>
  6176. <code>attr &lt;device&gt; syncEvents [1|0]
  6177. </code><br>
  6178. es werden Events für Reading NextSync erzeugt. <br>
  6179. </ul>
  6180. </ul>
  6181. <br>
  6182. <ul><b>syncInterval</b>
  6183. <ul>
  6184. <code>attr &lt;device&gt; syncInterval &lt;n&gt;
  6185. </code><br>
  6186. Wenn DbLog im asynchronen Modus betrieben wird (Attribut asyncMode=1), wird mit diesem Attribut das Intervall in Sekunden zur Speicherung
  6187. der im Speicher gecachten Events in die Datenbank eingestellt. Der Defaultwert ist 30 Sekunden. <br>
  6188. </ul>
  6189. </ul>
  6190. <br>
  6191. <ul><b>suppressAddLogV3</b>
  6192. <ul>
  6193. <code>attr &lt;device&gt; suppressAddLogV3 [1|0]
  6194. </code><br>
  6195. Wenn gesetzt werden verbose3-Logeinträge durch die addLog-Funktion unterdrückt. <br>
  6196. </ul>
  6197. </ul>
  6198. <br>
  6199. <ul><b>suppressUndef</b>
  6200. <ul>
  6201. <code>attr &lt;device&gt; ignoreUndef <n>
  6202. </code><br>
  6203. Unterdrueckt alle undef Werte die durch eine Get-Anfrage zb. Plot aus der Datenbank selektiert werden <br>
  6204. <b>Beispiel</b> <br>
  6205. <code>#DbLog eMeter:power:::$val=($val>1500)?undef:$val</code>
  6206. </ul>
  6207. </ul>
  6208. <br>
  6209. <ul><b>timeout</b>
  6210. <ul>
  6211. <code>
  6212. attr &lt;device&gt; timeout <n>
  6213. </code><br>
  6214. Setzt den Timeout-Wert für den Schreibzyklus in die Datenbank im asynchronen Modus (default 86400s). <br>
  6215. </ul>
  6216. </ul>
  6217. <br>
  6218. <ul><b>useCharfilter</b>
  6219. <ul>
  6220. <code>
  6221. attr &lt;device&gt; useCharfilter [0|1] <n>
  6222. </code><br>
  6223. wenn gesetzt, werden nur ASCII Zeichen von 32 bis 126 im Event akzeptiert. (default: 0) <br>
  6224. Das sind die Zeichen " A-Za-z0-9!"#$%&'()*+,-.\/:;<=>?@[\\]^_`{|}~". <br>
  6225. Umlaute und "€" werden umgesetzt (z.B. ä nach ae, € nach EUR). <br>
  6226. </ul>
  6227. </ul>
  6228. <br>
  6229. <ul><b>valueFn</b>
  6230. <ul>
  6231. <code>
  6232. attr &lt;device&gt; valueFn {}
  6233. </code><br>
  6234. Es kann über einen Perl-Ausdruck auf die Variablen $TIMESTAMP, $DEVICE, $DEVICETYPE, $READING, $VALUE (Wert des Readings) und
  6235. $UNIT (Einheit des Readingswert) zugegriffen werden und diese verändern, d.h. die veränderten Werte werden geloggt.
  6236. Außerdem hat man lesenden Zugriff auf $EVENT für eine Auswertung im Perl-Ausdruck.
  6237. Diese Variable kann aber nicht verändert werden. <br>
  6238. Soll $TIMESTAMP verändert werden, muss die Form "yyyy-mm-dd hh:mm:ss" eingehalten werden, ansonsten wird der
  6239. geänderte $timestamp nicht übernommen.
  6240. Zusätzlich kann durch Setzen der Variable "$IGNORE=1" ein Datensatz vom Logging ausgeschlossen werden. <br><br>
  6241. <b>Beispiele</b> <br>
  6242. <code>
  6243. attr &lt;device&gt; valueFn {if ($DEVICE eq "living_Clima" && $VALUE eq "off" ){$VALUE=0;} elsif ($DEVICE eq "e-power"){$VALUE= sprintf "%.1f", $VALUE;}}
  6244. </code> <br>
  6245. # ändert den Reading-Wert des Gerätes "living_Clima" von "off" zu "0" und rundet den Wert vom Gerät "e-power" <br><br>
  6246. <code>
  6247. attr &lt;device&gt; valueFn {if ($DEVICE eq "SMA_Energymeter" && $READING eq "state"){$IGNORE=1;}}
  6248. </code><br>
  6249. # der Datensatz wird nicht geloggt wenn Device = "SMA_Energymeter" und das Reading = "state" ist <br><br>
  6250. <code>
  6251. attr &lt;device&gt; valueFn {if ($DEVICE eq "Dum.Energy" && $READING eq "TotalConsumption"){$UNIT="W";}}
  6252. </code><br>
  6253. # setzt die Einheit des Devices "Dum.Energy" auf "W" wenn das Reading = "TotalConsumption" ist <br><br>
  6254. </ul>
  6255. </ul>
  6256. <br>
  6257. <ul><b>verbose4Devs</b>
  6258. <ul>
  6259. <code>
  6260. attr &lt;device&gt; verbose4Devs &lt;device1&gt;,&lt;device2&gt;,&lt;device..&gt;
  6261. </code><br>
  6262. Mit verbose Level 4 werden nur Ausgaben bezüglich der in diesem Attribut aufgeführten Devices im Logfile protokolliert. Ohne dieses
  6263. Attribut werden mit verbose 4 Ausgaben aller relevanten Devices im Logfile protokolliert.
  6264. Die angegebenen Devices werden als Regex ausgewertet. <br>
  6265. <b>Beispiel</b> <br>
  6266. <code>
  6267. attr &lt;device&gt; verbose4Devs sys.*,.*5000.*,Cam.*,global
  6268. </code><br>
  6269. # Es werden Devices beginnend mit "sys", "Cam" bzw. Devices die "5000" enthalten und das Device "global" protokolliert falls verbose=4
  6270. eingestellt ist. <br>
  6271. </ul>
  6272. </ul>
  6273. <br>
  6274. </ul>
  6275. =end html_DE
  6276. =cut