####################################################################################################
sub CommandDbReadingsVal {
my ($cl, $param) = @_;
my ($name, $devread, $ts, $default) = split m{\s+}x, $param;
$ts =~ s/_/ /;
my $ret = DbReadingsVal($name, $devread, $ts, $default);
return $ret;
}
sub DbReadingsVal($$$$) {
my $name = shift // return qq{A DbRep-device must be specified};
my $devread = shift // return qq{"device:reading" must be specified};
my $ts = shift // return qq{The Command needs a timestamp defined in format "YYYY-MM-DD_hh:mm:ss"};
my $default = shift // return qq{The Command needs a default value defined};
my ($err,$ret,$sql);
if(!defined($defs{$name})) {
return qq{DbRep-device "$name" doesn't exist.};
}
if(!$defs{$name}{TYPE} eq "DbRep") {
return qq{"$name" is not a DbRep-device but of type "}.$defs{$name}{TYPE}.qq{"};
}
my $hash = $defs{$name};
my $dbmodel = $defs{$hash->{HELPER}{DBLOGDEVICE}}{MODEL};
$ts =~ s/_/ /;
if($ts !~ /^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})$/x) {
return qq{timestamp has not the valid format. Use "YYYY-MM-DD_hh:mm:ss" as timestamp.};
}
my ($dev,$reading) = split(":",$devread);
if(!$dev || !$reading) {
return qq{"device:reading" must be specified};
}
if($dbmodel eq "MYSQL") {
$sql = "select value from (
( select *, TIMESTAMPDIFF(SECOND, '$ts', timestamp) as diff from history
where device='$dev' and reading='$reading' and timestamp >= '$ts' order by timestamp asc limit 1
)
union
( select *, TIMESTAMPDIFF(SECOND, timestamp, '$ts') as diff from history
where device='$dev' and reading='$reading' and timestamp < '$ts' order by timestamp desc limit 1
)
) x order by diff limit 1;";
} elsif ($dbmodel eq "SQLITE") {
$sql = "select value from (
select value, (julianday(timestamp) - julianday('$ts')) * 86400.0 as diff from history
where device='$dev' and reading='$reading' and timestamp >= '$ts'
union
select value, (julianday('$ts') - julianday(timestamp)) * 86400.0 as diff from history
where device='$dev' and reading='$reading' and timestamp < '$ts'
)
x order by diff limit 1;";
} elsif ($dbmodel eq "POSTGRESQL") {
$sql = "select value from (
select value, EXTRACT(EPOCH FROM (timestamp - '$ts')) as diff from history
where device='$dev' and reading='$reading' and timestamp >= '$ts'
union
select value, EXTRACT(EPOCH FROM ('$ts' - timestamp)) as diff from history
where device='$dev' and reading='$reading' and timestamp < '$ts'
)
x order by diff limit 1;";
} else {
return qq{DbReadingsVal is not implemented for $dbmodel};
}
$hash->{LASTCMD} = "sqlCmdBlocking $sql";
$ret = DbRep_sqlCmdBlocking($name,$sql);
$ret = $ret ? $ret : $default;
return $ret;
}
####################################################################################################
# Browser Refresh nach DB-Abfrage
####################################################################################################
sub browser_refresh {
my ($hash) = @_;
RemoveInternalTimer($hash, "browser_refresh");
{FW_directNotify("#FHEMWEB:WEB", "location.reload('true')", "")};
# map { FW_directNotify("#FHEMWEB:$_", "location.reload(true)", "") } devspec2array("WEB.*");
return;
}
###################################################################################
# Associated Devices setzen
###################################################################################
sub DbRep_modAssociatedWith {
my $hash = shift;
my $cmd = shift;
my $awdev = shift;
my $name = $hash->{NAME};
my (@naw,@edvs,@edvspcs,$edevswc);
my ($edevs,$idevice,$edevice) = ('','','');
if($cmd eq "del") {
readingsDelete($hash,".associatedWith");
return;
}
($idevice,$edevice) = split(/EXCLUDE=/i,$awdev);
if($edevice) {
@edvs = split(",",$edevice);
for my $e (@edvs) {
$e =~ s/%/\.*/g if($e !~ /^%$/); # SQL Wildcard % auflösen
@edvspcs = devspec2array($e);
@edvspcs = map { my $e = $_; $e =~ s/\.\*/%/xg; } @edvspcs;
if((map {$_ =~ /%/;} @edvspcs) && $edevice !~ /^%$/) { # Devices mit Wildcard (%) aussortieren, die nicht aufgelöst werden konnten
$edevswc .= "|" if($edevswc);
$edevswc .= join(" ",@edvspcs);
}
else {
$edevs .= "|" if($edevs);
$edevs .= join("|",@edvspcs);
}
}
}
if($idevice) {
my @nadev = split("[, ]", $idevice);
for my $d (@nadev) {
$d =~ s/%/\.*/g if($d !~ /^%$/); # SQL Wildcard % in Regex
my @a = devspec2array($d);
for (@a) {
next if(!$defs{$_});
push(@naw, $_) if($_ !~ /$edevs/);
}
}
}
if(@naw) {
ReadingsSingleUpdateValue ($hash, ".associatedWith", join(" ",@naw), 0);
}
else {
readingsDelete($hash, ".associatedWith");
}
return;
}
####################################################################################################
# Test-Sub zu Testzwecken
####################################################################################################
sub DbRep_testexit {
my $hash = shift;
my $name = $hash->{NAME};
return;
}
1;
=pod
=item helper
=item summary Reporting and management of DbLog database content.
=item summary_DE Reporting und Management von DbLog-Datenbank Inhalten.
=begin html
DbRep
The purpose of this module is browsing and managing the content of DbLog-databases. The searchresults can be evaluated concerning to various aggregations and the appropriate
Readings will be filled. The data selection will been done by declaration of device, reading and the time settings of selection-begin and selection-end.
Almost all database operations are implemented nonblocking. If there are exceptions it will be suggested to.
Optional the execution time of SQL-statements in background can also be determined and provided as reading.
(refer to attributes).
All existing readings will be deleted when a new operation starts. By attribute "readingPreventFromDel" a comma separated list of readings which are should prevent
from deletion can be provided.
Currently the following functions are provided:
- Selection of all datasets within adjustable time limits.
- Exposure of datasets of a Device/Reading-combination within adjustable time limits.
- Selection of datasets by usage of dynamically calclated time limits at execution time.
- Highlighting doublets when select and display datasets (fetchrows)
- Calculation of quantity of datasets of a Device/Reading-combination within adjustable time limits and several aggregations.
- The calculation of summary-, difference-, maximum-, minimum- and averageValues of numeric readings within adjustable time limits and several aggregations.
- write back results of summary-, difference-, maximum-, minimum- and average calculation into the database
- The deletion of datasets. The containment of deletion can be done by Device and/or Reading as well as fix or dynamically calculated time limits at execution time.
- export of datasets to file (CSV-format).
- import of datasets from file (CSV-Format).
- rename of device/readings in datasets
- change of reading values in the database (changeValue)
- automatic rename of device names in datasets and other DbRep-definitions after FHEM "rename" command (see DbRep-Agent)
- Execution of arbitrary user specific SQL-commands (non-blocking)
- Execution of arbitrary user specific SQL-commands (blocking) for usage in user own code (sqlCmdBlocking)
- creation of backups of the database in running state non-blocking (MySQL, SQLite)
- transfer dumpfiles to a FTP server after backup incl. version control
- restore of SQLite- and MySQL-Dumps non-blocking
- optimize the connected database (optimizeTables, vacuum)
- report of existing database processes (MySQL)
- purge content of current-table
- fill up the current-table with a (tunable) extract of the history-table
- delete consecutive datasets with different timestamp but same values (clearing up consecutive doublets)
- Repair of a corrupted SQLite database ("database disk image is malformed")
- transmission of datasets from source database into another (Standby) database (syncStandby)
- reduce the amount of datasets in database (reduceLog)
- delete of duplicate records (delDoublets)
- drop and (re)create of indexes which are needed for DbLog and DbRep (index)
To activate the function Autorename the attribute "role" has to be assigned to a defined DbRep-device. The standard role after DbRep definition is "Client".
Please read more in section DbRep-Agent about autorename function.
DbRep provides a UserExit function. With this interface the user can execute own program code dependent from free
definable Reading/Value-combinations (Regex). The interface works without respectively independent from event
generation.
Further informations you can find as described at userExitFn attribute.
Once a DbRep-Device is defined, the Perl function DbReadingsVal provided as well as and the FHEM command dbReadingsVal.
With this function you can, similar to the well known ReadingsVal, get a reading value from database.
The function is executed blocking with a standard timeout of 10 seconds to prevent a permanent blocking of FHEM.
The timeout is adjustable with the attribute timeout.
The command syntax for the Perl function is:
DbReadingsVal("<name>","<device:reading>","<timestamp>","<default>")
Example:
$ret = DbReadingsVal("Rep.LogDB1","MyWetter:temperature","2018-01-13_08:00:00","");
attr <name> userReadings oldtemp {DbReadingsVal("Rep.LogDB1","MyWetter:temperature","2018-04-13_08:00:00","")}
attr <name> userReadings todayPowerIn
{
my ($sec,$min,$hour,$mday,$month,$year,$wday,$yday,$isdst) = localtime(gettimeofday());
$month++;
$year+=1900;
my $today = sprintf('%04d-%02d-%02d', $year,$month,$mday);
DbReadingsVal("Rep.LogDB1","SMA_Energymeter:Bezug_Wirkleistung_Zaehler",$today."_00:00:00",0)
}
The command syntax for the FHEM command is:
dbReadingsVal <name> <device:reading> <timestamp> <default>
Example:
dbReadingsVal Rep.LogDB1 MyWetter:temperature 2018-01-13_08:00:00 0
<name> | : name of the DbRep-Device to request |
<device:reading> | : device:reading whose value is to deliver |
<timestamp> | : timestamp of reading whose value is to deliver (*) in format "YYYY-MM-DD_hh:mm:ss" |
<default> | : default value if no reading value can be retrieved |
(*) If no value can be retrieved at the <timestamp> exactly requested, the chronological most convenient reading
value is delivered back.
FHEM-Forum:
Modul 93_DbRep - Reporting and Management of database content (DbLog).
Preparations
The module requires the usage of a DbLog instance and the credentials of the database definition will be used.
Only the content of table "history" will be included if isn't other is explained.
Overview which other Perl-modules DbRep is using:
Net::FTP (only if FTP-Transfer after database dump is used)
Net::FTPSSL (only if FTP-Transfer with encoding after database dump is used)
POSIX
Time::HiRes
Time::Local
Scalar::Util
DBI
Color (FHEM-module)
IO::Compress::Gzip
IO::Uncompress::Gunzip
Blocking (FHEM-module)
Definition
define <name> DbRep <name of DbLog-instance>
(<name of DbLog-instance> - name of the database instance which is wanted to analyze needs to be inserted)
Due to a good operation performance, the database should contain the index "Report_Idx". Please create it after the DbRep
device definition by the following set command if it isn't already existing on the database:
set <name> index recreate_Report_Idx
Set
Currently following set-commands are included. They are used to trigger the evaluations and define the evaluation option option itself.
The criteria of searching database content and determine aggregation is carried out by setting several attributes.
Note:
If you are in detail view it could be necessary to refresh the browser to see the result of operation as soon in DeviceOverview section "state = done" will be shown.
- adminCredentials <User> <Passwort>
- Save a user / password for the privileged respectively administrative database access.
The user is required for database operations which has to be executed by a privileged user.
Please see also attribute useAdminCredentials.
(only valid if database type is MYSQL and DbRep-type "Client")
- averageValue [display | writeToDB | writeToDBSingle | writeToDBSingleStart | writeToDBInTime]
Calculates an average value of the database field "VALUE" in the time limits
of the possible time.*-attributes.
The reading to be evaluated must be specified in the attribute reading
must be specified.
With the attribute averageCalcForm the calculation variant
is used for Averaging defined.
If none or the option display is specified, the results are only displayed. With
the options writeToDB, writeToDBSingle, writeToDBSingleStart or writeToDBInTime the
calculation results are written with a new reading name into the database.
writeToDB | : writes one value each with the time stamps XX:XX:01 and XX:XX:59 within the respective evaluation period |
writeToDBSingle | : writes only one value with the time stamp XX:XX:59 at the end of an evaluation period |
writeToDBSingleStart | : writes only one value with the time stamp XX:XX:01 at the begin of an evaluation period |
writeToDBInTime | : writes a value at the beginning and end of the time limits of an evaluation period |
The new reading name is formed from a prefix and the original reading name,
where the original reading name can be replaced by the attribute "readingNameMap".
The prefix consists of the educational function and the aggregation.
The timestamp of the new readings in the database is determined by the set aggregation period
if no clear time of the result can be determined.
The field "EVENT" is filled with "calculated".
Example of building a new reading name from the original reading "totalpac":
avgam_day_totalpac
# <creation function>_<aggregation>_<original reading>
Summarized the relevant attributes to control this function are:
averageCalcForm | : choose the calculation variant for average determination |
device | : include or exclude <device> from selection |
executeBeforeProc | : execution of FHEM command (or Perl-routine) before operation |
executeAfterProc | : execution of FHEM command (or Perl-routine) after operation |
reading | : include or exclude <reading> from selection |
time.* | : a number of attributes to limit selection by time |
valueFilter | : an additional REGEXP to control the record selection. The REGEXP is applied to the database field 'VALUE'. |
- cancelDump - stops a running database dump.
- changeValue old="<old String>" new="<new String>"
Changes the stored value of a reading.
If the selection is limited to certain device/reading combinations by the attributes
device or reading, they are taken into account
in the same way as set time limits (time.* attributes).
If these constraints are missing, the entire database is searched and the specified value is
is changed.
The "string" can be:
<old String> : | - a simple string with/without spaces, e.g. "OL 12"
|
| - a string with use of SQL wildcard, e.g. "%OL%"
|
| |
| |
<new String> : | - a simple string with/without spaces, e.g. "12 kWh"
|
| - Perl code enclosed in {"..."} including quotes, e.g. {"($VALUE,$UNIT) = split(" ",$VALUE)"}
|
| The variables $VALUE and $UNIT are passed to the Perl expression. They can be changed |
| within the Perl code. The returned value of $VALUE and $UNIT is stored |
| in the VALUE or UNIT field of the record. |
Examples:
set <name> changeValue old="OL" new="12 OL"
# the old field value "OL" is changed to "12 OL".
set <name> changeValue old="%OL%" new="12 OL"
# contains the field VALUE the substring "OL", it is changed to "12 OL".
set <name> changeValue old="12 kWh" new={"($VALUE,$UNIT) = split(" ",$VALUE)"}
# the old field value "12 kWh" is splitted to VALUE=12 and UNIT=kWh and saved into the database fields
set <name> changeValue old="24%" new={"$VALUE = (split(" ",$VALUE))[0]"}
# if the old field value begins with "24", it is splitted and VALUE=24 is saved (e.g. "24 kWh")
Summarized the relevant attributes to control function changeValue are:
device | : include or exclude <device> from selection |
reading | : include or exclude <reading> from selection |
time.* | : a number of attributes to limit selection by time |
executeBeforeProc | : execute a FHEM command (or Perl-routine) before start of changeValue |
executeAfterProc | : execute a FHEM command (or Perl-routine) after changeValue is finished |
valueFilter | : an additional REGEXP to control the record selection. The REGEXP is applied to the database field 'VALUE'. |
- countEntries [history|current] - provides the number of table entries (default: history) between time period set
by time.* -attributes if set.
If time.* attributes not set, all entries of the table will be count.
The device and reading can be used to
limit the evaluation.
By default the summary of all counted datasets, labeled by "ALLREADINGS", will be created.
If the attribute "countEntriesDetail" is set, the number of every reading
is reported additionally.
The relevant attributes for this function are:
aggregation | : aggregatiion/grouping of time intervals |
countEntriesDetail | : detailed report the count of datasets (per reading) |
device | : include or exclude <device> from selection |
reading | : include or exclude <reading> from selection |
executeBeforeProc | : execution of FHEM command (or Perl-routine) before operation |
executeAfterProc | : execution of FHEM command (or Perl-routine) after operation |
time.* | : a number of attributes to limit selection by time |
valueFilter | : an additional REGEXP to control the record selection. The REGEXP is applied to the database field 'VALUE'. |
- delDoublets [adviceDelete | delete] - show respectively delete duplicate/multiple datasets.
Therefore the fields TIMESTAMP, DEVICE, READING and VALUE of records are compared.
The attributes to define the scope of aggregation, time period, device and reading are
considered. If attribute aggregation is not set or set to "no", it will change to the default aggregation
period "day".
adviceDelete | : simulates the datasets to delete in database (nothing will be deleted !) |
delete | : deletes the doublets |
Due to security reasons the attribute allowDeletion needs
to be set for execute the "delete" option.
The amount of datasets to show by commands "delDoublets adviceDelete" is initially limited
and can be adjusted by limit attribute.
The adjustment of "limit" has no impact to the "delDoublets delete" function, but affects
ONLY the display of the data.
Before and after this "delDoublets" it is possible to execute a FHEM command or Perl script
(please see attributes executeBeforeProc,
executeAfterProc).
Example:
Output of records to delete included their amount by "delDoublets adviceDelete":
2018-11-07_14-11-38__Dum.Energy__T 260.9_|_2
2018-11-07_14-12-37__Dum.Energy__T 260.9_|_2
2018-11-07_14-15-38__Dum.Energy__T 264.0_|_2
2018-11-07_14-16-37__Dum.Energy__T 264.0_|_2
In the created readings after "_|_" the amount of the appropriate records to delete
is shown. The records are deleted by command "delDoublets delete".
Zusammengefasst sind die zur Steuerung dieser Funktion relevanten Attribute:
allowDeletion | : needs to be set to execute the delete option |
aggregation | : choose the aggregation period |
limit | : limits ONLY the count of datasets to display |
device | : include or exclude <device> from selection |
reading | : include or exclude <reading> from selection |
executeBeforeProc | : execute a FHEM command (or Perl-routine) before start of the function |
executeAfterProc | : execute a FHEM command (or Perl-routine) after the function is finished |
time.* | : a number of attributes to limit selection by time |
valueFilter | : an additional REGEXP to control the record selection. The REGEXP is applied to the database field 'VALUE'. |
- delEntries [<no>[:<nn>]] - deletes all database entries or only the database entries specified by attributes
device and/or reading.
The time limits are considered according to the available time.*-attributes:
"timestamp_begin" is set -> deletes db entries from this timestamp until current date/time
"timestamp_end" is set -> deletes db entries until this timestamp
both Timestamps are set -> deletes db entries between these timestamps
"timeOlderThan" is set -> delete entries older than current time minus "timeOlderThan"
"timeDiffToNow" is set -> delete db entries from current time minus "timeDiffToNow" until now
Due to security reasons the attribute allowDeletion needs to be set to unlock the
delete-function.
Time limits (days) can be specified as an option. In this case, any time.*-attributes set are
overmodulated.
Records older than <no> days and (optionally) newer than
<nn> days are considered.
The relevant attributes to control function changeValue delEntries are:
allowDeletion | : unlock the delete function |
device | : include or exclude <device> from selection |
reading | : include or exclude <reading> from selection |
time.* | : a number of attributes to limit selection by time |
executeBeforeProc | : execute a FHEM command (or Perl-routine) before start of delEntries |
executeAfterProc | : execute a FHEM command (or Perl-routine) after delEntries is finished |
- delSeqDoublets [adviceRemain | adviceDelete | delete] - show respectively delete identical sequentially datasets.
Therefore Device,Reading and Value of the sequentially datasets are compared.
Not deleted are the first und the last dataset of a aggregation period (e.g. hour,day,week and so on) as
well as the datasets before or after a value change (database field VALUE).
The attributes to define the scope of aggregation, time period, device and reading are
considered. If attribute aggregation is not set or set to "no", it will change to the default aggregation
period "day". For datasets containing numerical values it is possible to determine a variance with attribute
seqDoubletsVariance.
Up to this value consecutive numerical datasets are handled as identical and should be
deleted.
adviceRemain | : simulates the remaining datasets in database after delete-operation (nothing will be deleted !) |
adviceDelete | : simulates the datasets to delete in database (nothing will be deleted !) |
delete | : deletes the consecutive doublets (see example) |
Due to security reasons the attribute allowDeletion needs to be set for
execute the "delete" option.
The amount of datasets to show by commands "delSeqDoublets adviceDelete", "delSeqDoublets adviceRemain" is
initially limited (default: 1000) and can be adjusted by attribute limit.
The adjustment of "limit" has no impact to the "delSeqDoublets delete" function, but affects ONLY the
display of the data.
Before and after this "delSeqDoublets" it is possible to execute a FHEM command or Perl-script
(please see executeBeforeProc and
executeAfterProc).
Example - the remaining datasets after executing delete-option are are marked as bold:
2017-11-25_00-00-05__eg.az.fridge_Pwr__power 0
2017-11-25_00-02-26__eg.az.fridge_Pwr__power 0
2017-11-25_00-04-33__eg.az.fridge_Pwr__power 0
2017-11-25_01-06-10__eg.az.fridge_Pwr__power 0
2017-11-25_01-08-21__eg.az.fridge_Pwr__power 0
2017-11-25_01-08-59__eg.az.fridge_Pwr__power 60.32
2017-11-25_01-11-21__eg.az.fridge_Pwr__power 56.26
2017-11-25_01-27-54__eg.az.fridge_Pwr__power 6.19
2017-11-25_01-28-51__eg.az.fridge_Pwr__power 0
2017-11-25_01-31-00__eg.az.fridge_Pwr__power 0
2017-11-25_01-33-59__eg.az.fridge_Pwr__power 0
2017-11-25_02-39-29__eg.az.fridge_Pwr__power 0
2017-11-25_02-41-18__eg.az.fridge_Pwr__power 105.28
2017-11-25_02-41-26__eg.az.fridge_Pwr__power 61.52
2017-11-25_03-00-06__eg.az.fridge_Pwr__power 47.46
2017-11-25_03-00-33__eg.az.fridge_Pwr__power 0
2017-11-25_03-02-07__eg.az.fridge_Pwr__power 0
2017-11-25_23-37-42__eg.az.fridge_Pwr__power 0
2017-11-25_23-40-10__eg.az.fridge_Pwr__power 0
2017-11-25_23-42-24__eg.az.fridge_Pwr__power 1
2017-11-25_23-42-24__eg.az.fridge_Pwr__power 1
2017-11-25_23-45-27__eg.az.fridge_Pwr__power 1
2017-11-25_23-47-07__eg.az.fridge_Pwr__power 0
2017-11-25_23-55-27__eg.az.fridge_Pwr__power 0
2017-11-25_23-48-15__eg.az.fridge_Pwr__power 0
2017-11-25_23-50-21__eg.az.fridge_Pwr__power 59.1
2017-11-25_23-55-14__eg.az.fridge_Pwr__power 52.31
2017-11-25_23-58-09__eg.az.fridge_Pwr__power 51.73
Summarized the relevant attributes to control this function are:
allowDeletion | : needs to be set to execute the delete option |
aggregation | : choose the aggregation period |
limit | : limits ONLY the count of datasets to display |
device | : include or exclude <device> from selection |
reading | : include or exclude <reading> from selection |
executeBeforeProc | : execute a FHEM command (or Perl-routine) before start of the function |
executeAfterProc | : execute a FHEM command (or Perl-routine) after the function is finished |
seqDoubletsVariance | : Up to this value consecutive numerical datasets are handled as identical and should be deleted |
time.* | : a number of attributes to limit selection by time |
valueFilter | : an additional REGEXP to control the record selection. The REGEXP is applied to the database field 'VALUE'. |
- deviceRename <old_name>,<new_name> -
renames the device name of a device inside the connected database (Internal DATABASE).
The devicename will allways be changed in the entire database. Possibly set time limits or restrictions by
device and/or reading will not be considered.
Example:
set <name> deviceRename ST_5000,ST5100
# The amount of renamed device names (datasets) will be displayed in reading "device_renamed".
# If the device name to be renamed was not found in the database, a WARNUNG will appear in reading "device_not_renamed".
# Appropriate entries will be written to Logfile if verbose >= 3 is set.
Note:
Even though the function itself is designed non-blocking, make sure the assigned DbLog-device
is operating in asynchronous mode to avoid FHEMWEB from blocking.
The relevant attributes to control this function are:
executeBeforeProc | : execution of FHEM command (or Perl-routine) before operation |
executeAfterProc | : execution of FHEM command (or Perl-routine) after operation |
- diffValue [display | writeToDB]
- calculates the difference of database column "VALUE" in the given time period. (see also the several time*-attributes).
The reading to evaluate must be defined in attribute reading.
This function is mostly reasonable if values are increasing permanently and don't write value differences into the database.
The difference will always be generated between all consecutive datasets (VALUE-Field) and add them together, in doing add carry value of the
previous aggregation period to the next aggregation period in case the previous period contains a value.
A possible counter overrun (restart with value "0") will be considered (compare attribute diffAccept).
If only one dataset will be found within the evalution period, the difference can be calculated only in combination with the balanced
difference of the previous aggregation period. In this case a logical inaccuracy according the assignment of the difference to the particular aggregation period
can be possible. Hence in warning in "state" will be placed and the reading "less_data_in_period" with a list of periods
with only one dataset found in it will be created.
Note:
Within the evaluation respectively aggregation period (day, week, month, etc.) you should make available at least one dataset
at the beginning and one dataset at the end of each aggregation period to take the difference calculation as much as possible.
Is no or the option "display" specified, the results are only displayed. Using
option "writeToDB" the calculation results are stored in the database with a new reading
name.
The new readingname is built of a prefix and the original reading name,
in which the original reading name can be partly replaced by the value of attribute readingNameMap.
The prefix is made up of the creation function and the aggregation.
The timestamp of the new stored readings is deviated from aggregation period,
unless no unique point of time of the result can be determined.
The field "EVENT" will be filled with "calculated".
Example of building a new reading name from the original reading "totalpac":
diff_day_totalpac
# <creation function>_<aggregation>_<original reading>
Summarized the relevant attributes to control this function are:
aggregation | : choose the aggregation period |
diffAccept | : the accepted maximum difference between sequential records |
device | : include or exclude <device> from selection |
executeBeforeProc | : execution of FHEM command (or Perl-routine) before operation |
executeAfterProc | : execution of FHEM command (or Perl-routine) after operation |
reading | : include or exclude <reading> from selection |
readingNameMap | : rename the resulted reading name |
time.* | : a number of attributes to limit selection by time |
valueFilter | : an additional REGEXP to control the record selection. The REGEXP is applied to the database field 'VALUE'. |
- dumpMySQL [clientSide | serverSide]
Creates a dump of the connected MySQL database.
Depending from selected option the dump will be created on Client- or on Server-Side.
The variants differs each other concerning the executing system, the creating location, the usage of
attributes, the function result and the needed hardware ressources.
The option "clientSide" e.g. needs more powerful FHEM-Server hardware, but saves all available
tables inclusive possibly created views.
With attribute "dumpCompress" a compression of dump file after creation can be switched on.
Option clientSide
The dump will be created by client (FHEM-Server) and will be saved in FHEM log-directory ((typical /opt/fhem/log/)) by
default.
The target directory can be set by attribute dumpDirLocal and has to be
writable by the FHEM process.
Before executing the dump a table optimization can be processed optionally (see attribute
"optimizeTablesBeforeDump") as well as a FHEM-command (attribute "executeBeforeProc").
After the dump a FHEM-command can be executed as well (see attribute "executeAfterProc").
Note:
To avoid FHEM from blocking, you have to operate DbLog in asynchronous mode if the table
optimization want to be used !
By the attributes dumpMemlimit and
dumpSpeed the run-time behavior of the function can be
controlled to optimize the performance and demand of ressources.
The attributes relevant for function "dumpMySQL clientSide" are:
dumpComment | : User comment in head of dump file |
dumpCompress | : compress of dump files after creation |
dumpDirLocal | : the local destination directory for dump file creation |
dumpMemlimit | : limits memory usage |
dumpSpeed | : limits CPU utilization |
dumpFilesKeep | : number of dump files to keep |
executeBeforeProc | : execution of FHEM command (or Perl-routine) before dump |
executeAfterProc | : execution of FHEM command (or Perl-routine) after dump |
optimizeTablesBeforeDump | : table optimization before dump |
After a successfull finished dump the old dumpfiles are deleted and only the number of files
defined by attribute "dumpFilesKeep" (default: 3) remain in the target directory
"dumpDirLocal". If "dumpFilesKeep = 0" is set, all
dumpfiles (also the current created file), are deleted. This setting can be helpful, if FTP transmission is used
and the created dumps are only keep remain in the FTP destination directory.
The naming convention of dump files is: <dbname>_<date>_<time>.sql[.gzip]
To rebuild the database from a dump file the command:
set <name> restoreMySQL <filename>
can be used.
The created dumpfile (uncompressed) can imported on the MySQL-Server by:
mysql -u <user> -p <dbname> < <filename>.sql
as well to restore the database from dump file.
Option serverSide
The dump will be created on the MySQL-Server and will be saved in its Home-directory
by default.
The whole history-table (not the current-table) will be exported CSV-formatted without
any restrictions.
Before executing the dump a table optimization can be processed optionally (see attribute
"optimizeTablesBeforeDump") as well as a FHEM-command (attribute "executeBeforeProc").
Note:
To avoid FHEM from blocking, you have to operate DbLog in asynchronous mode if the table
optimization is used !
After the dump a FHEM-command can be executed as well (see attribute "executeAfterProc").
The attributes relevant for function "dumpMySQL serverSide" are:
dumpDirRemote | : destination directory of dump file on remote server |
dumpCompress | : compress of dump files after creation |
dumpDirLocal | : the local mounted directory dumpDirRemote |
dumpFilesKeep | : number of dump files to keep |
executeBeforeProc | : execution of FHEM command (or Perl-routine) before dump |
executeAfterProc | : execution of FHEM command (or Perl-routine) after dump |
optimizeTablesBeforeDump | : table optimization before dump |
The target directory can be set by dumpDirRemote attribute.
It must be located on the MySQL-Host and has to be writable by the MySQL-server process.
The used database user must have the FILE privilege (see Wiki).
Note:
If the internal version management of DbRep should be used and the size of the created dumpfile be
reported, you have to mount the remote MySQL-Server directory "dumpDirRemote" on the client
and publish it to the DbRep-device by fill out the dumpDirLocal attribute.
Same is necessary if ftp transfer after dump is to be used (attribute "ftpUse" respectively "ftpUseSSL").
Example:
attr <name> dumpDirRemote /volume1/ApplicationBackup/dumps_FHEM/
attr <name> dumpDirLocal /sds1/backup/dumps_FHEM/
attr <name> dumpFilesKeep 2
# The dump will be created remote on the MySQL-Server in directory
'/volume1/ApplicationBackup/dumps_FHEM/'.
# The internal version management searches in local mounted directory '/sds1/backup/dumps_FHEM/'
for present dumpfiles and deletes these files except the last two versions.
If the internal version management is used, after a successfull finished dump old dumpfiles will
be deleted and only the number of attribute "dumpFilesKeep" (default: 3) would remain in target
directory "dumpDirLocal" (the mounted "dumpDirRemote").
In that case FHEM needs write permissions to the directory "dumpDirLocal".
The naming convention of dump files is: <dbname>_<date>_<time>.csv[.gzip]
You can start a restore of table history from serverSide-Backup by command:
set <name> <restoreMySQL> <filename>.csv[.gzip]
FTP-Transfer after Dump
If those possibility is be used, the attribute ftpUse or
ftpUseSSL has to be set. The latter if encoding for FTP is to be used.
The module also carries the version control of dump files in FTP-destination by attribute
"ftpDumpFilesKeep".
Further attributes are:
ftpUse | : FTP Transfer after dump will be switched on (without SSL encoding) |
ftpUser | : User for FTP-server login, default: anonymous |
ftpUseSSL | : FTP Transfer with SSL encoding after dump |
ftpDebug | : debugging of FTP communication for diagnostics |
ftpDir | : directory on FTP-server in which the file will be send into (default: "/") |
ftpDumpFilesKeep | : leave the number of dump files in FTP-destination <ftpDir> (default: 3) |
ftpPassive | : set if passive FTP is to be used |
ftpPort | : FTP-Port, default: 21 |
ftpPwd | : password of FTP-User, not set by default |
ftpServer | : name or IP-address of FTP-server. absolutely essential ! |
ftpTimeout | : timeout of FTP-connection in seconds (default: 30). |
- dumpSQLite - creates a dump of the connected SQLite database.
This function uses the SQLite Online Backup API and allow to create a consistent backup of the
database during the normal operation.
The dump will be saved in FHEM log-directory by default.
The target directory can be defined by the dumpDirLocal attribute and
has to be writable by the FHEM process.
Before executing the dump a table optimization can be processed optionally (see attribute
"optimizeTablesBeforeDump").
Note:
To avoid FHEM from blocking, you have to operate DbLog in asynchronous mode if the table
optimization want to be used !
Before and after the dump a FHEM-command can be executed (see attribute "executeBeforeProc",
"executeAfterProc").
The attributes relevant for function "dumpMySQL serverSide" are:
dumpCompress | : compress of dump files after creation |
dumpDirLocal | : Target directory of the dumpfiles |
dumpFilesKeep | : number of dump files to keep |
executeBeforeProc | : execution of FHEM command (or Perl-routine) before dump |
executeAfterProc | : execution of FHEM command (or Perl-routine) after dump |
optimizeTablesBeforeDump | : table optimization before dump |
After a successfull finished dump the old dumpfiles are deleted and only the number of attribute
"dumpFilesKeep" (default: 3) remain in the target directory "dumpDirLocal". If "dumpFilesKeep = 0" is set, all
dumpfiles (also the current created file), are deleted. This setting can be helpful, if FTP transmission is used
and the created dumps are only keep remain in the FTP destination directory.
The naming convention of dump files is: <dbname>_<date>_<time>.sqlitebkp[.gzip]
The database can be restored by command "set <name> restoreSQLite <filename>"
The created dump file can be transfered to a FTP-server. Please see explanations about FTP-
transfer in topic "dumpMySQL".
- eraseReadings - deletes all created readings in the device, except reading "state" and readings, which are
contained in exception list defined by attribute "readingPreventFromDel".
- exportToFile [</path/file>] [MAXLINES=<lines>]
- exports DB-entries to a file in CSV-format of time period specified by time attributes.
The filename can be defined by the expimpfile attribute.
Optionally a file can be specified as a command option (/path/file) and overloads a possibly
defined attribute "expimpfile".
The maximum number of datasets which are exported into one file can be specified
with the optional parameter "MAXLINES". In this case several files with extensions
"_part1", "_part2", "_part3" and so on are created (pls. remember it when you import the files !).
Limitation of selections can be done by attributes device and/or
reading.
The filename may contain wildcards as described
in attribute section of "expimpfile".
By setting attribute "aggregation" the export of datasets will be splitted into time slices
corresponding to the specified aggregation.
If, for example, "aggregation = month" is set, the data are selected in monthly packets and written
into the exportfile. Thereby the usage of main memory is optimized if very large amount of data
is exported and avoid the "died prematurely" error.
The attributes relevant for this function are:
aggregation | : determination of selection time slices |
device | : include or exclude <device> from selection |
reading | : include or exclude <reading> from selection |
time.* | : a number of attributes to limit selection by time |
executeBeforeProc | : execution of FHEM command (or Perl-routine) before export |
executeAfterProc | : execution of FHEM command (or Perl-routine) after export |
expimpfile | : the name of exportfile |
time.* | : a number of attributes to limit selection by time |
valueFilter | : an additional REGEXP to control the record selection. The REGEXP is applied to the database field 'VALUE'. |
- fetchrows [history|current]
- provides all table entries (default: history)
of time period set by time.*-attributes respectively selection conditions
by attributes "device" and "reading".
An aggregation set will not be considered.
The direction of data selection can be determined by the fetchRoute attribute.
Every reading of result is composed of the dataset timestring , an index, the device name
and the reading name.
The function has the capability to reconize multiple occuring datasets (doublets).
Such doublets are marked by an index > 1. Optional a Unique-Index is appended if
datasets with identical timestamp, device and reading but different value are existing.
Doublets can be highlighted in terms of color by setting attribut e"fetchMarkDuplicates".
Note:
Highlighted readings are not displayed again after restart or rereadcfg because of they are not
saved in statefile.
This attribute is preallocated with some colors, but can be changed by colorpicker-widget:
attr <DbRep-Device> widgetOverride fetchMarkDuplicates:colorpicker
The readings of result are composed like the following sceme:
Example:
2017-10-22_03-04-43__1__SMA_Energymeter__Bezug_WirkP_Kosten_Diff__[1]
# <date>_<time>__<index>__<device>__<reading>__[Unique-Index]
For a better overview the relevant attributes are listed here in a table:
device | : include or exclude <device> from selection |
fetchRoute | : direction of selection read in database |
fetchMarkDuplicates | : Highlighting of found doublets |
fetchValueFn | : the displayed value of the VALUE database field can be changed by a function before the reading is created |
limit | : limits the number of datasets to select and display |
reading | : include or exclude <reading> from selection |
executeBeforeProc | : execution of FHEM command (or Perl-routine) before operation |
executeAfterProc | : execution of FHEM command (or Perl-routine) after operation |
time.* | : A number of attributes to limit selection by time |
valueFilter | : an additional REGEXP to control the record selection. The REGEXP is applied to the database field 'VALUE'. |
Note:
Although the module is designed non-blocking, a huge number of selection result (huge number of rows)
can overwhelm the browser session respectively FHEMWEB.
Due to the sample space can be limited by limit attribute.
Of course ths attribute can be increased if your system capabilities allow a higher workload.
- index <Option>
- Reports the existing indexes in the database or creates the index which is needed.
If the index is already created, it will be renewed (dropped and new created)
The possible options are:
list_all | : reports the existing indexes |
recreate_Search_Idx | : create or renew (if existing) the index Search_Idx in table history (index for DbLog) |
drop_Search_Idx | : delete the index Search_Idx in table history |
recreate_Report_Idx | : create or renew (if existing) the index Report_Idx in table history (index for DbRep) |
drop_Report_Idx | : delete the index Report_Idx in table history |
For a better overview the relevant attributes for this operation are listed here:
useAdminCredentials | : use privileged user for the operation |
Note:
The MySQL database user used requires the ALTER, CREATE and INDEX privilege.
These rights can be set with:
set <Name> sqlCmd GRANT INDEX, ALTER, CREATE ON `<db>`.* TO '<user>'@'%';
The useAdminCredentials attribute must usually be set to be able to
change the rights of the used user.
- insert <Date>,<Time>,<Value>,[<Unit>],[<Device>],[<Reading>]
- Manual insertion of a data record into the table "history". Input values for date, time and value are obligatory.
The values for the DB fields TYPE and EVENT are filled with "manual".
If Device, Reading are not set, these values are taken from the corresponding
attributes device, reading.
Note:
Unused fields within the insert command must be enclosed within the string in ","
within the string.
Examples:
set <name> insert 2016-08-01,23:00:09,12.03,kW
set <name> insert 2021-02-02,10:50:00,value with space
set <name> insert 2022-05-16,10:55:00,1800,,SMA_Wechselrichter,etotal
set <name> insert 2022-05-16,10:55:00,1800,,,etotal
The relevant attributes to control this function are:
executeBeforeProc | : execution of FHEM command (or Perl-routine) before operation |
executeAfterProc | : execution of FHEM command (or Perl-routine) after operation |
- importFromFile [<file>]
- imports data in CSV format from file into database.
The filename can be defined by attribute expimpfile.
Optionally a file can be specified as a command option (/path/file) and overloads a possibly
defined attribute "expimpfile". The filename may contain wildcards as described
in attribute section of "expimpfile".
dataset format:
"TIMESTAMP","DEVICE","TYPE","EVENT","READING","VALUE","UNIT"
# The fields "TIMESTAMP","DEVICE","TYPE","EVENT","READING" and "VALUE" have to be set. The field "UNIT" is optional.
The file content will be imported transactional. That means all of the content will be imported or, in case of error, nothing of it.
If an extensive file will be used, DON'T set verbose = 5 because of a lot of datas would be written to the logfile in this case.
It could lead to blocking or overload FHEM !
Example for a source dataset:
"2016-09-25 08:53:56","STP_5000","SMAUTILS","etotal: 11859.573","etotal","11859.573",""
The attributes relevant for this function are:
executeBeforeProc | : execution of FHEM command (or Perl-routine) before import |
executeAfterProc | : execution of FHEM command (or Perl-routine) after import |
expimpfile | : the name of exportfile |
- maxValue [display | writeToDB | deleteOther]
br>
Calculates the maximum value of database column "VALUE" between period given by attributes
timestamp_begin, "timestamp_end" / "timeDiffToNow / timeOlderThan" and so on.
The reading to evaluate must be defined using attribute reading.
The evaluation contains the timestamp of the last appearing of the identified maximum value
within the given period.
If no option or the option display is specified, the results are only displayed. Using
option writeToDB the calculated results are stored in the database with a new reading
name.
The new readingname is built of a prefix and the original reading name,
in which the original reading name can be replaced by the value of attribute readingNameMap.
The prefix is made up of the creation function and the aggregation.
The timestamp of the new stored readings is deviated from aggregation period,
unless no unique point of time of the result can be determined.
The field "EVENT" will be filled with "calculated".
With option deleteOther all datasets except the dataset with the maximum value are deleted.
Example of building a new reading name from the original reading "totalpac":
max_day_totalpac
# <creation function>_<aggregation>_<original reading>
Summarized the relevant attributes to control this function are:
- migrateCollation <Collation>
Migrates the used character set/collation of the database and the tables current and history to the
specified format.
Relevant attributes are:
- minValue [display | writeToDB | deleteOther]
Calculates the minimum value of database column "VALUE" between period given by attributes
timestamp_begin, "timestamp_end" / "timeDiffToNow / timeOlderThan" and so on.
The reading to evaluate must be defined using attribute reading.
The evaluation contains the timestamp of the first appearing of the identified minimum
value within the given period.
If no option or the option display is specified, the results are only displayed. Using
option writeToDB the calculated results are stored in the database with a new reading
name.
The new readingname is built of a prefix and the original reading name,
in which the original reading name can be replaced by the value of attribute readingNameMap.
The prefix is made up of the creation function and the aggregation.
The timestamp of the new stored readings is deviated from aggregation period,
unless no unique point of time of the result can be determined.
The field "EVENT" will be filled with "calculated".
With option deleteOther all datasets except the dataset with the maximum value are deleted.
Example of building a new reading name from the original reading "totalpac":
min_day_totalpac
# <creation function>_<aggregation>_<original reading>
Relevant attributes are:
- optimizeTables [showInfo | execute]
Optimize tables in the connected database (MySQL).
showInfo | : shows information about the used / free space within the database |
execute | : performs optimization of all tables in the database |
Relevant attributes are:
- readingRename <[device:]oldreadingname>,<newreadingname>
Renames the reading name of a device inside the connected database (see Internal DATABASE).
The readingname will allways be changed in the entire database.
Possibly set time limits or restrictions by attributes
device and/or reading will not be considered.
As an option a device can be specified. In this case only the old readings of this device
will be renamed.
Examples:
set <name> readingRename TotalConsumtion,L1_TotalConsumtion
set <name> readingRename Dum.Energy:TotalConsumtion,L1_TotalConsumtion
The amount of renamed reading names (datasets) will be displayed in reading "reading_renamed".
If the reading name to be renamed was not found in the database, a WARNING will appear in reading "reading_not_renamed".
Appropriate entries will be written to Logfile if verbose >= 3 is set.
Relevant attributes are:
- reduceLog [<no>[:<nn>]] [mode] [EXCLUDE=device1:reading1,device2:reading2,...] [INCLUDE=device:reading]
Reduces historical data sets.
Operation without specifying command line operators
The data is cleaned within the time limits defined by the time.*-attributes.
At least one of the time.* attributes must be set (see table below).
The respective missing time accrual is determined by the module in this case.
The working mode is determined by the optional specification of mode:
without specification of mode | : the data is reduced to the first entry per hour per device & reading |
average | : numerical values are reduced to an average value per hour per device & reading, otherwise as without mode |
average=day | : numeric values are reduced to one mean value per day per device & reading, otherwise as without mode |
| The FullDay option (full days are always selected) is used implicitly. |
max | : numeric values are reduced to the maximum value per hour per device & reading, otherwise as without mode |
max=day | : numeric values are reduced to the maximum value per day per device & reading, otherwise as without mode |
| The FullDay option (full days are always selected) is used implicitly. |
min | : numeric values are reduced to the minimum value per hour per device & reading, otherwise as without mode |
min=day | : numeric values are reduced to the minimum value per day per device & reading, otherwise as without mode |
| The FullDay option (full days are always selected) is used implicitly. |
sum | : numeric values are reduced to the sum per hour per Device & Reading, otherwise as without mode |
sum=day | : numeric values are reduced to the sum per day per Device & Reading, otherwise as without mode |
| The FullDay option (full days are always selected) is used implicitly. |
With the attributes device and reading the data records to be considered can be included
or be excluded. Both restrictions reduce the selected data and reduce the
resource requirements.
The read "reduceLogState" contains the execution result of the last reduceLog command.
Relevant attributes are:
executeBeforeProc,
executeAfterProc,
device,
reading,
numDecimalPlaces,
timeOlderThan,
timeDiffToNow,
timestamp_begin,
timestamp_end,
valueFilter,
userExitFn
Examples:
attr <name> timeOlderThan d:200
set <name> reduceLog
# Records older than 200 days are written to the first entry per hour per Device & Reading.
attr <name> timeDiffToNow d:200
set <name> reduceLog average=day
# Records newer than 200 days are limited to one entry per day per Device & Reading.
attr <name> timeDiffToNow d:30
attr <name> device TYPE=SONOSPLAYER EXCLUDE=Sonos_Kueche
attr <name> reading room% EXCLUDE=roomNameAlias
set <name> reduceLog
# Records newer than 30 days that are devices of type SONOSPLAYER
(except Device "Sonos_Kitchen") and the readings start with "room" (except "roomNameAlias")
are reduced to the first entry per hour per Device & Reading.
attr <name> timeDiffToNow d:10
attr <name> timeOlderThan d:5
attr <name> device Luftdaten_remote
set <name> reduceLog average
# Records older than 5 and newer than 10 days and containing DEVICE "Luftdaten_remote
are adjusted. Numerical values of an hour are reduced to an average value
Operation with specification of command line operators
Es werden Datensätze berücksichtigt die älter sind als <no> Tage und (optional) neuer sind als
<nn> Tage.
Records are considered that are older than <no> days and (optionally) newer than
<nn> days.
The working mode is determined by the optional specification of mode as described above.
The additions "EXCLUDE" or "INCLUDE" can be added to exclude or include device/reading combinations in reduceLog
and override the "device" and "reading" attributes, which are ignored in this case.
The specification in "EXCLUDE" is evaluated as a regex. Inside "INCLUDE", SQL wildcards
can be used. (for more information on SQL wildcards, see with get <name> versionNotes 6)
Examples:
set <name> reduceLog 174:180 average EXCLUDE=SMA_Energymeter:Bezug_Wirkleistung INCLUDE=SMA_Energymeter:%
# Records older than 174 and newer than 180 days are reduced to average per hour.
# All readings from the device "SMA_Energymeter" except "Bezug_Wirkleistung" are taken reduced.
Note:
Although the function itself is designed non-blocking, the assigned DbLog device should be operated in
asynchronous mode to avoid blocking FHEMWEB (table lock).
Furthermore it is strongly recommended to create the standard INDEX 'Search_Idx' in the table
'history' !
The processing of this command may take an extremely long time (without INDEX).
- repairSQLite [sec]
Repairs a corrupted SQLite database.
A corruption is usally existent when the error message "database disk image is malformed"
appears in reading "state" of the connected DbLog-device.
If the command was started, the connected DbLog-device will firstly disconnected from the
database for 10 hours (36000 seconds) automatically (breakup time). After the repair is
finished, the DbLog-device will be connected to the (repaired) database immediately.
As an argument the command can be completed by a differing breakup time (in seconds).
The corrupted database is saved as <database>.corrupt in same directory.
Relevant attributes are:
Example:
set <name> repairSQLite
# the database is trying to repair, breakup time is 10 hours
set <name> repairSQLite 600
# the database is trying to repair, breakup time is 10 minutes
Note:
It can't be guaranteed, that the repair attempt proceed successfully and no data loss will result.
Depending from corruption severity data loss may occur or the repair will fail even though
no error appears during the repair process. Please make sure a valid backup took place !
- restoreMySQL <File> - restore a database from serverSide- or clientSide-Dump.
The function provides a drop-down-list of files which can be used for restore.
Usage of serverSide-Dumps
The content of history-table will be restored from a serverSide-Dump.
Therefore the remote directory "dumpDirRemote" of the MySQL-Server has to be mounted on the
Client and make it usable to the DbRep device by setting attribute dumpDirLocal
to the appropriate value.
All files with extension "csv[.gzip]" and if the filename is beginning with the name of the connected database
(see Internal DATABASE) are listed.
Usage of clientSide-Dumps
The used database user needs the FILE privilege (see Wiki).
All tables and views (if present) are restored.
The directory which contains the dump files has to be set by attribute dumpDirLocal
to make it usable by the DbRep device.
All files with extension "sql[.gzip]" and if the filename is beginning with the name of the connected database
(see Internal DATABASE) are listed.
The restore speed depends of the server variable "max_allowed_packet". You can change
this variable in file my.cnf to adapt the speed. Please consider the need of sufficient ressources
(especially RAM).
The database user needs rights for database management, e.g.:
CREATE, ALTER, INDEX, DROP, SHOW VIEW, CREATE VIEW
Relevant attributes are:
- restoreSQLite <File>.sqlitebkp[.gzip]
Restores a backup of SQLite database.
The function provides a drop-down-list of files which can be used for restore.
The data stored in the current database are deleted respectively overwritten.
All files with extension "sqlitebkp[.gzip]" and if the filename is beginning with the name of the connected database
will are listed.
Relevant attributes are:
- sqlCmd
Executes any user-specific command.
If this command contains a delete operation, for safety reasons the attribute
allowDeletion has to be set.
sqlCmd also accepts the setting of SQL session variables such as.
"SET @open:=NULL, @closed:=NULL;" or the use of SQLite PRAGMA prior to the
execution of the SQL statement.
If the session variable or PRAGMA has to be set every time before executing a SQL statement, the
attribute sqlCmdVars can be set.
If the attributes device, reading,
timestamp_begin respectively
timestamp_end
set in the module are to be taken into account in the statement,
the placeholders §device§, §reading§, §timestamp_begin§ respectively
§timestamp_end§ can be used for this purpose.
It should be noted that the placeholders §device§ and §reading§ complex are resolved and
should be applied accordingly as in the example below.
If you want update a dataset, you have to add "TIMESTAMP=TIMESTAMP" to the update-statement to avoid changing the
original timestamp.
Examples of SQL-statements:
- set <name> sqlCmd select DEVICE, count(*) from history where TIMESTAMP >= "2017-01-06 00:00:00" group by DEVICE having count(*) > 800
- set <name> sqlCmd select DEVICE, count(*) from history where TIMESTAMP >= "2017-05-06 00:00:00" group by DEVICE
- set <name> sqlCmd select DEVICE, count(*) from history where TIMESTAMP >= §timestamp_begin§ group by DEVICE
- set <name> sqlCmd select * from history where DEVICE like "Te%t" order by `TIMESTAMP` desc
- set <name> sqlCmd select * from history where `TIMESTAMP` > "2017-05-09 18:03:00" order by `TIMESTAMP` desc
- set <name> sqlCmd select * from current order by `TIMESTAMP` desc
- set <name> sqlCmd select sum(VALUE) as 'Einspeisung am 04.05.2017', count(*) as 'Anzahl' FROM history where `READING` = "Einspeisung_WirkP_Zaehler_Diff" and TIMESTAMP between '2017-05-04' AND '2017-05-05'
- set <name> sqlCmd delete from current
- set <name> sqlCmd delete from history where TIMESTAMP < "2016-05-06 00:00:00"
- set <name> sqlCmd update history set TIMESTAMP=TIMESTAMP,VALUE='Val' WHERE VALUE='TestValue'
- set <name> sqlCmd select * from history where DEVICE = "Test"
- set <name> sqlCmd insert into history (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES ('2017-05-09 17:00:14','Test','manuell','manuell','Tes§e','TestValue','°C')
- set <name> sqlCmd select DEVICE, count(*) from history where §device§ AND TIMESTAMP >= §timestamp_begin§ group by DEVICE
- set <name> sqlCmd select DEVICE, READING, count(*) from history where §device§ AND §reading§ AND TIMESTAMP >= §timestamp_begin§ group by DEVICE, READING
Here you can see examples of a more complex statement (MySQL) with setting SQL session
variables and the SQLite PRAGMA usage:
- set <name> sqlCmd SET @open:=NULL, @closed:=NULL;
SELECT
TIMESTAMP, VALUE,DEVICE,
@open AS open,
@open := IF(VALUE = 'open', TIMESTAMP, NULL) AS curr_open,
@closed := IF(VALUE = 'closed', TIMESTAMP, NULL) AS closed
FROM history WHERE
DATE(TIMESTAMP) = CURDATE() AND
DEVICE = "HT_Fensterkontakt" AND
READING = "state" AND
(VALUE = "open" OR VALUE = "closed")
ORDER BY TIMESTAMP;
- set <name> sqlCmd PRAGMA temp_store=MEMORY; PRAGMA synchronous=FULL; PRAGMA journal_mode=WAL; PRAGMA cache_size=4000; select count(*) from history;
- set <name> sqlCmd PRAGMA temp_store=FILE; PRAGMA temp_store_directory = '/opt/fhem/'; VACUUM;
The formatting of result can be choosen by attribute sqlResultFormat,
as well as the used field separator can be determined by attribute
sqlResultFieldSep.
The module provides a command history once a sqlCmd command was executed successfully.
To use this option, activate the attribute sqlCmdHistoryLength
with list lenght you want.
If the command history is enabled, an indexed list of stored SQL statements is available
with ___list_sqlhistory___ within the sqlCmdHistory command.
An SQL statement can be executed by specifying its index in this form:
set <name> sqlCmd ckey:<Index> (e.g. ckey:4)
Relevant attributes are:
Note:
Even though the module works non-blocking regarding to database operations, a huge
sample space (number of rows/readings) could block the browser session respectively
FHEMWEB.
If you are unsure about the result of the statement, you should preventively add a limit to
the statement.
- sqlCmdHistory
If activated with the attribute sqlCmdHistoryLength,
a stored SQL statement can be selected from a list and executed.
The SQL cache is automatically saved when FHEM is closed and restored when the system is started.
The following entries execute special functions:
___purge_sqlhistory___ | : deletes the history cache |
___list_sqlhistory___ | : shows the SQL statements currently in the cache, including their cache key (ckey) |
___save_sqlhistory___ | : backs up the history cache manually |
___restore_sqlhistory___ | : restores the last backup of the history cache |
Relevant attributes are:
- sqlSpecial
This function provides a drop-down list with a selection of prepared reportings.
The statements result is depicted in reading "SqlResult".
The result can be formatted by attribute sqlResultFormat
a well as the used field separator by attribute sqlResultFieldSep.
50mostFreqLogsLast2days | reports the 50 most occuring log entries of the last 2 days |
allDevCount | all devices occuring in database and their quantity |
allDevReadCount | all device/reading combinations occuring in database and their quantity |
50DevReadCount | the 50 most frequently included device/reading combinations in the database |
recentReadingsOfDevice | determines the newest records of a device available in the database. The |
| device must be defined in attribute device |
readingsDifferenceByTimeDelta | determines the value difference of successive data records of a reading. The |
| device and reading must be defined in the attribute device or reading. |
| The time limits of the evaluation are defined by the time.*-attributes. |
Relevant attributes are:
- sumValue [display | writeToDB | writeToDBSingle | writeToDBInTime]
Calculates the total values of the database field "VALUE" in the time limits
of the possible time.*-attributes.
The reading to be evaluated must be specified in the attribute reading.
This function is useful if continuous value differences of a reading are written
into the database.
If none or the option display is specified, the results are only displayed. With
the options writeToDB, writeToDBSingle or writeToDBInTime the calculation results are written
with a new reading name into the database.
writeToDB | : writes one value each with the time stamps XX:XX:01 and XX:XX:59 within the respective aggregation period |
writeToDBSingle | : writes only one value with the time stamp XX:XX:59 at the end of an aggregation period |
writeToDBInTime | : writes a value at the beginning and end of the time limits of an aggregation period |
The new reading name is formed from a prefix and the original reading name,
where the original reading name can be replaced by the attribute "readingNameMap".
The prefix consists of the educational function and the aggregation.
The timestamp of the new reading in the database is determined by the set aggregation period
if no clear time of the result can be determined.
The field "EVENT" is filled with "calculated".
Example of building a new reading name from the original reading "totalpac":
sum_day_totalpac
# <creation function>_<aggregation>_<original reading>
Relevant attributes are:
- syncStandby <DbLog-Device Standby>
Datasets of the connected database (source) are transmitted into another database
(Standby-database).
Here the "<DbLog-Device Standby>" is the DbLog-Device what is connected to the
Standby-database.
All the datasets which are determined by timestamp_begin attribute
or respectively the attributes "device", "reading" are transmitted.
The datasets are transmitted in time slices accordingly to the adjusted aggregation.
If the attribute "aggregation" has value "no" or "month", the datasets are transmitted
automatically in daily time slices into standby-database.
Source- and Standby-database can be of different types.
Relevant attributes are:
- tableCurrentFillup
The current-table will be filled u with an extract of the history-table.
The attributes for limiting time and device, reading are considered.
Thereby the content of the extract can be affected.
In the associated DbLog-device the attribute "DbLogType" should be set to "SampleFill/History".
Relevant attributes are:
- tableCurrentPurge
Deletes the content of current-table.
There are no limits, e.g. by attributes timestamp_begin, timestamp_end, device or reading
considered.
Relevant attributes are:
- vacuum
Optimizes the tables in the connected database (SQLite, PostgreSQL).
Especially for SQLite databases it is strongly recommended to temporarily close the connection of the relevant DbLog
device to the database (see DbLog reopen command).
Relevant attributes are:
Note:
When the vacuum command is executed, the PRAGMA auto_vacuum = FULL is automatically applied to SQLite databases.
The vacuum command requires additional temporary memory. If there is not enough space in the default TMPDIR directory,
SQLite can be assigned a sufficiently large directory by setting the environment variable SQLITE_TMPDIR.
(see also: www.sqlite.org/tempfiles)
Get
The get-commands of DbRep provide to retrieve some metadata of the used database instance.
Those are for example adjusted server parameter, server variables, datadasestatus- and table informations. THe available get-functions depending of
the used database type. So for SQLite curently only "get svrinfo" is usable. The functions nativ are delivering a lot of outpit values.
They can be limited by function specific attributes.
The filter has to be setup by a comma separated list.
SQL-Wildcard (%) can be used to setup the list arguments.
Note:
After executing a get-funktion in detail view please make a browser refresh to see the results !
- blockinginfo - list the current system wide running background processes (BlockingCalls) together with their informations.
If character string is too long (e.g. arguments) it is reported shortened.
- dbstatus - lists global information about MySQL server status (e.g. informations related to cache, threads, bufferpools, etc. ).
Initially all available informations are reported. Using the attribute showStatus the quantity of
results can be limited to show only the desired values. Further detailed informations of items meaning are
explained here.
Example
attr <name> showStatus %uptime%,%qcache%
get <name> dbstatus
# Only readings containing "uptime" and "qcache" in name will be created
- dbvars - lists global informations about MySQL system variables. Included are e.g. readings related to InnoDB-Home, datafile path,
memory- or cache-parameter and so on. The Output reports initially all available informations. Using the
attribute showVariables the quantity of results can be limited to show only the desired values.
Further detailed informations of items meaning are explained
here.
Example
attr <name> showVariables %version%,%query_cache%
get <name> dbvars
# Only readings containing "version" and "query_cache" in name will be created
- initData - Determines some database properties relevant for the module function.
The command is executed implicitly at the first database connection.
- minTimestamp - Identifies the oldest timestamp in the database (will be executed implicitely at FHEM start).
The timestamp is used as begin of data selection if no time attribut is set to determine the
start date.
- procinfo - Reports the existing database processes in a summary table (only MySQL).
Typically only the own processes of the connection user (set in DbLog configuration file) will be
reported. If all precesses have to be reported, the global "PROCESS" right has to be granted to the
user.
As of MariaDB 5.3 for particular SQL-Statements a progress reporting will be provided
(table row "PROGRESS"). So you can track, for instance, the degree of processing during an index
creation.
Further informations can be found
here.
- sqlCmdBlocking <SQL-statement>
Executes the specified SQL statement blocking with a default timeout of 10 seconds.
The timeout can be set with the attribute timeout.
Examples:
{ fhem("get <name> sqlCmdBlocking select device,count(*) from history where timestamp > '2018-04-01' group by device") }
{ CommandGet(undef,"Rep.LogDB1 sqlCmdBlocking select device,count(*) from history where timestamp > '2018-04-01' group by device") }
get <name> sqlCmdBlocking select device,count(*) from history where timestamp > '2018-04-01' group by device
Because of its mode of operation this function is particular convenient for user own perl scripts.
The input accepts multi line commands and delivers multi line results as well.
This command also accept the setting of SQL session variables like "SET @open:=NULL,
@closed:=NULL;" or PRAGMA for SQLite.
If several fields are selected and passed back, the fieds are separated by the separator defined
by attribute sqlResultFieldSep (default "|"). Several result lines
are separated by newline ("\n").
This function only set/update status readings, the userExitFn function isn't called.
If you create a little routine in 99_myUtils, for example:
sub dbval {
my $name = shift;
my $cmd) = shift;
my $ret = CommandGet(undef,"$name sqlCmdBlocking $cmd");
return $ret;
}
it can be accessed with e.g. those calls:
Examples:
{ dbval("<name>","select count(*) from history") }
$ret = dbval("<name>","select count(*) from history");
storedCredentials - Reports the users / passwords stored for database access by the device.
(only valid if database type is MYSQL)
svrinfo - Common database server informations, e.g. DBMS-version, server address and port and so on. The quantity of elements to get depends
on the database type. Using the attribute showSvrInfo the quantity of results can be limited to show only
the desired values. Further detailed informations of items meaning are explained
here.
Example
attr <name> showSvrInfo %SQL_CATALOG_TERM%,%NAME%
get <name> svrinfo
# Only readings containing "SQL_CATALOG_TERM" and "NAME" in name will be created
tableinfo - Access detailed informations about tables in MySQL database which is connected by the DbRep-device.
All available tables in the connected database will be selected by default.
Using the attribute showTableInfo the results can be limited to tables you want to show.
Further detailed informations of items meaning are explained
here.
Example
attr <name> showTableInfo current,history
get <name> tableinfo
# Only informations related to tables "current" and "history" are going to be created
versionNotes [hints | rel | <key>] -
Shows realease informations and/or hints about the module.
rel | : shows only release information |
hints | : shows only hints |
<key> | : the note with the specified number is displayed |
It contains only main release informations for module users.
If no options are specified, both release informations and hints will be shown. "rel" shows
only release informations and "hints" shows only hints. By the <key>-specification only
the hint with the specified number is shown.
Attributes
Using the module specific attributes you are able to define the scope of evaluation and the aggregation.
The listed attrbutes are not completely relevant for every function of the module. The help of set/get-commands
contain explicitly which attributes are relevant for the specific command.
Note for SQL-Wildcard Usage:
Within the attribute values of "device" and "reading" you may use SQL-Wildcard "%", Character "_" is not supported as a wildcard.
The character "%" stands for any characters.
This rule is valid to all functions except "insert", "importFromFile" and "deviceRename".
The function "insert" doesn't allow setting the mentioned attributes containing the wildcard "%".
In readings the wildcard character "%" will be replaced by "/" to meet the rules of allowed characters in readings.
- aggregation - Aggregation of Device/Reading-selections. Possible values are hour, day, week, month, year and "no".
Delivers e.g. the count of database entries for a day (countEntries), Summation of
difference values of a reading (sumValue) and so on. Using aggregation "no" (default) an
aggregation don't happens but the output contains all values of Device/Reading in the selected time period.
- allowDeletion - unlocks the delete-function
- autoForward - if activated, the result threads of a function are transferred to one or more devices.
The definition takes the form:
{
"<source-reading> => "<dest.device> [=> <dest.-reading>]",
"<source-reading> => "<dest.device> [=> <dest.-reading>]",
...
}
Wildcards (.*) are permitted in the specification <source-reading>.
{
".*" => "Dum.Rep.All",
".*AVGAM.*" => "Dum.Rep => average",
".*SUM.*" => "Dum.Rep.Sum => summary",
}
# all readings are transferred to device "Dum.Rep.All", reading name remains in the target
# readings with "AVGAM" in the name are transferred to the "Dum.Rep" device in the reading "average"
# readings with "SUM" in the name are transferred to the device "Dum.Rep.Sum" in the reading "summary"
- averageCalcForm
Defines the calculation variant for determining the average value with "averageValue".
Currently the following variants are implemented:
avgArithmeticMean: | The arithmetic average is calculated. (default) |
| |
avgDailyMeanGWS: | Calculates the daily medium temperature according the |
| specifications of german weather service. (see also "get <name> versionNotes 2") |
| This variant uses aggregation "day" automatically. |
| |
avgDailyMeanGWSwithGTS: | Same as "avgDailyMeanGWS" and additionally calculates the grassland temperature sum. |
| If the value 200 is reached, the reading "reachedGTSthreshold" is created with the |
| date of the first time this threshold value is reached. |
| Note: the attribute timestamp_begin must be set to the beginning of a year ! |
| Note: The attribute timestamp_begin must be set to the beginning of a year! |
| (see also "get <name> versionNotes 5") |
| |
avgTimeWeightMean: | Calculates the time-weighted average. |
| Note: There must be at least two data points per aggregation period. |
- countEntriesDetail - If set, the function countEntries creates a detailed report of counted datasets of
every reading. By default only the summary of counted datasets is reported.
- device - Selection of particular or several devices.
You can specify a list of devices separated by "," or use device specifications (devspec).
In that case the device names are derived from the device specification and the existing
devices in FHEM before carry out the SQL selection.
If the the device, list or device specification is prepended by "EXCLUDE=",
the devices are excluded from database selection.
The database selection is executed as a logical AND operation of "device" and the attribute
reading.
Examples:
attr <name> device TYPE=DbRep
attr <name> device MySTP_5000
attr <name> device SMA.*,MySTP.*
attr <name> device SMA_Energymeter,MySTP_5000
attr <name> device %5000
attr <name> device TYPE=SSCam EXCLUDE=SDS1_SVS
attr <name> device TYPE=SSCam,TYPE=ESPEasy EXCLUDE=SDS1_SVS
attr <name> device EXCLUDE=SDS1_SVS
attr <name> device EXCLUDE=TYPE=SSCam
If you need more information about device specifications, execute
"get <name> versionNotes 3".
- diffAccept - valid for function diffValue. diffAccept determines the threshold, up to that a calaculated
difference between two straight sequently datasets should be commenly accepted
(default = 20).
Hence faulty DB entries with a disproportional high difference value will be eliminated and
don't tamper the result.
If a threshold overrun happens, the reading "diff_overrun_limit_<diffLimit>" will be
generated (<diffLimit> will be substituted with the present prest attribute value).
The reading contains a list of relevant pair of values. Using verbose=3 this list will also
be reported in the FHEM logfile.
Example report in logfile if threshold of diffAccept=10 overruns:
DbRep Rep.STP5000.etotal -> data ignored while calc diffValue due to threshold overrun (diffAccept = 10):
2016-04-09 08:50:50 0.0340 -> 2016-04-09 12:42:01 13.3440
# The first dataset with a value of 0.0340 is untypical low compared to the next value of 13.3440 and results a untypical
high difference value.
# Now you have to decide if the (second) dataset should be deleted, ignored of the attribute diffAccept should be adjusted.
- dumpComment - User-comment. It will be included in the header of the created dumpfile by
command "dumpMySQL clientSide".
- dumpCompress - if set, the dump files are compressed after operation of "dumpMySQL" bzw. "dumpSQLite"
- dumpDirLocal
Destination directory for creating dumps with "dumpMySQL clientSide" or "dumpSQLite".
Setting this attribute activates the internal version management.
In this directory backup files are searched and deleted if the found number exceeds the attribute value
"dumpFilesKeep".
The attribute is also used to make a locally mounted directory "dumpDirRemote" (for dumpMySQL serverSide)
known to DbRep.
(default: "{global}{modpath}/log/")
Example:
attr <Name> dumpDirLocal /sds1/backup/dumps_FHEM/
- dumpDirRemote - Target directory of database dumps by command "dumpMySQL serverSide"
(default: the Home-directory of MySQL-Server on the MySQL-Host).
- dumpMemlimit - tolerable memory consumption for the SQL-script during generation period (default: 100000 characters).
Please adjust this parameter if you may notice memory bottlenecks and performance problems based
on it on your specific hardware.
- dumpSpeed - Number of Lines which will be selected in source database with one select by dump-command
"dumpMySQL ClientSide" (default: 10000).
This parameter impacts the run-time and consumption of resources directly.
- dumpFilesKeep
The integrated version management leaves the specified number of backup files in the backup directory.
Version management must be enabled by setting the "dumpDirLocal" attribute.
If there are more (older) backup files, they will be deleted after a new backup has been successfully created.
The global attribute "archivesort" is taken into account.
(default: 3)
- executeAfterProc
You can specify a FHEM command or Perl code that should be executed after the command is processed.
Perl code is to be enclosed in {...}. The variables $hash (hash of the DbRep device) and $name
(name of the DbRep device) are available.
Example:
attr <name> executeAfterProc set og_gz_westfenster off;
attr <name> executeAfterProc {adump ($name)}
# "adump" is a function defined in 99_myUtils.
sub adump {
my ($name) = @_;
my $hash = $defs{$name};
# the own function, e.g.
Log3($name, 3, "DbRep $name -> Dump is finished");
return;
}
- executeBeforeProc
A FHEM command or Perl code can be specified which is to be executed before the command is processed.
Perl code is to be enclosed in {...}. The variables $hash (hash of the DbRep device) and $name
(name of the DbRep device) are available.
Example:
attr <name> executeBeforeProc set og_gz_westfenster on;
attr <name> executeBeforeProc {bdump ($name)}
# "bdump" is a function defined in 99_myUtils.
sub bdump {
my ($name) = @_;
my $hash = $defs{$name};
# the own function, e.g.
Log3($name, 3, "DbRep $name -> Dump starts");
return;
}
expimpfile </path/file> [MAXLINES=<lines>]
- Path/filename for data export/import.
The maximum number of datasets which are exported into one file can be specified
with the optional parameter "MAXLINES". In this case several files with extensions
"_part1", "_part2", "_part3" and so on are created.
The filename may contain wildcards which are replaced by corresponding values
(see subsequent table).
Furthermore filename can contain %-wildcards of the POSIX strftime function of the underlying OS (see your
strftime manual).
%L | : is replaced by the value of global logdir attribute |
%TSB | : is replaced by the (calculated) value of the start timestamp of the data selection |
| |
| Common used POSIX-wildcards are: |
%d | : day of month (01..31) |
%m | : month (01..12) |
%Y | : year (1970...) |
%w | : day of week (0..6); 0 represents Sunday |
%j | : day of year (001..366) |
%U | : week number of year with Sunday as first day of week (00..53) |
%W | : week number of year with Monday as first day of week (00..53) |
Examples:
attr <name> expimpfile /sds1/backup/exptest_%TSB.csv
attr <name> expimpfile /sds1/backup/exptest_%Y-%m-%d.csv
About POSIX wildcard usage please see also explanations in
Filelog.
fastStart - Usually every DbRep device is making a short connect to its database when FHEM is started to
retrieve some important informations and the reading "state" switches to "connected" on success.
If this attrbute is set, the initial database connection is executed not till then the
DbRep device is processing its first command.
While the reading "state" is remaining in state "initialized" after FHEM-start.
(default: 1 for TYPE Client)
fetchMarkDuplicates
- Highlighting of multiple occuring datasets in result of "fetchrows" command
fetchRoute [descent | ascent] - specify the direction of data selection of the fetchrows-command.
descent - the data are read descent (default). If
amount of datasets specified by attribut "limit" is exceeded,
the newest x datasets are shown.
ascent - the data are read ascent . If
amount of datasets specified by attribut "limit" is exceeded,
the oldest x datasets are shown.
fetchValueFn - When fetching the database content, you are able to manipulate the value fetched from the
VALUE database field before create the appropriate reading. You have to insert a Perl
function which is enclosed in {} .
The value of the database field VALUE is provided in variable $VALUE.
Example:
attr <name> fetchValueFn { $VALUE =~ s/^.*Used:\s(.*)\sMB,.*/$1." MB"/e }
# From a long line a specific pattern is extracted and will be displayed als VALUE instead
the whole line
ftpUse - FTP Transfer after dump will be switched on (without SSL encoding). The created
database backup file will be transfered non-blocking to the FTP-Server (Attribut "ftpServer").
ftpUseSSL - FTP Transfer with SSL encoding after dump. The created database backup file will be transfered
non-blocking to the FTP-Server (Attribut "ftpServer").
ftpUser - User for FTP-server login, default: "anonymous".
ftpDebug - debugging of FTP communication for diagnostics.
ftpDir - directory on FTP-server in which the file will be send into (default: "/").
ftpDumpFilesKeep - leave the number of dump files in FTP-destination <ftpDir> (default: 3). Are there more
(older) dump files present, these files are deleted after a new dump was transfered successfully.
ftpPassive - set if passive FTP is to be used
ftpPort - FTP-Port, default: 21
ftpPwd - password of FTP-User, is not set by default
ftpServer - name or IP-address of FTP-server. absolutely essential !
ftpTimeout - timeout of FTP-connection in seconds (default: 30).
limit - limits the number of selected datasets by the "fetchrows", or the shown datasets of "delSeqDoublets adviceDelete",
"delSeqDoublets adviceRemain" commands (default: 1000).
This limitation should prevent the browser session from overload and
avoids FHEMWEB from blocking. Please change the attribut according your requirements or change the
selection criteria (decrease evaluation period).
numDecimalPlaces - Sets the number of decimal places for readings with numeric results.
Excludes results from user-specific queries (sqlCmd).
(default: 4)
optimizeTablesBeforeDump - if set to "1", the database tables will be optimized before executing the dump
(default: 0).
Thereby the backup run-time time will be extended.
Note
The table optimizing cause locking the tables and therefore to blocking of
FHEM if DbLog isn't working in asynchronous mode (DbLog-attribute "asyncMode") !
reading - Selection of particular or several readings.
More than one reading can be specified by a comma separated list.
SQL wildcard (%) can be used.
If the reading or the reading list is prepended by "EXCLUDE=", those readings are not
included.
The database selection is executed as a logical AND operation of "reading" and the attribute
device.
Examples:
attr <name> reading etotal
attr <name> reading et%
attr <name> reading etotal,etoday
attr <name> reading eto%,Einspeisung EXCLUDE=etoday
attr <name> reading etotal,etoday,Ein% EXCLUDE=%Wirkleistung
readingNameMap - A part of the created reading name will be replaced by the specified string
role - the role of the DbRep-device. Standard role is "Client".
The role "Agent" is described in section DbRep-Agent.
readingPreventFromDel - comma separated list of readings which are should prevent from deletion when a
new operation starts
seqDoubletsVariance <positive variance [negative variance] [EDGE=negative|positive]>
Accepted variance for the command "set <name> delSeqDoublets".
The value of this attribute describes the variance up to consecutive numeric values (VALUE) of
datasets are handled as identical. If only one numeric value is declared, it is used as
postive as well as negative variance and both form the "deletion corridor".
Optional a second numeric value for a negative variance, separated by blank,can be
declared.
Always absolute, i.e. positive numeric values, have to be declared.
If the supplement "EDGE=negative" is declared, values at a negative edge (e.g. when
value is changed from 4.0 -> 1.0) are not deleted although they are in the "deletion corridor".
Equivalent is valid with "EDGE=positive" for the positive edge (e.g. the change
from 1.2 -> 2.8).
Examples:
attr <name> seqDoubletsVariance 0.0014
attr <name> seqDoubletsVariance 1.45
attr <name> seqDoubletsVariance 3.0 2.0
attr <name> seqDoubletsVariance 1.5 EDGE=negative
showproctime - if set, the reading "sql_processing_time" shows the required execution time (in seconds)
for the sql-requests. This is not calculated for a single sql-statement, but the summary
of all sql-statements necessara for within an executed DbRep-function in background.
showStatus - limits the sample space of command "get <name> dbstatus". SQL-Wildcard (%) can be used.
Example:
attr <name> showStatus %uptime%,%qcache%
# Only readings with containing "uptime" and "qcache" in name will be shown
showVariables - limits the sample space of command "get <name> dbvars". SQL-Wildcard (%) can be used.
Example:
attr <name> showVariables %version%,%query_cache%
# Only readings with containing "version" and "query_cache" in name will be shown
showSvrInfo - limits the sample space of command "get <name> svrinfo". SQL-Wildcard (%) can be used.
Example:
attr <name> showSvrInfo %SQL_CATALOG_TERM%,%NAME%
# Only readings with containing "SQL_CATALOG_TERM" and "NAME" in name will be shown
showTableInfo
Limits the result set of the command "get <name> tableinfo". SQL wildcard (%) can be used.
Example:
attr <name> showTableInfo current,history
# Only information from the "current" and "history" tables is displayed.
sqlCmdHistoryLength
Activates the command history of "sqlCmd" with a value > 0 and defines the number of
SQL statements to be stored.
(default: 0)
sqlCmdVars
Sets the specified SQL session variable(s) or PRAGMA before each SQL statement executed with sqlCmd.
SQL statement.
Example:
attr <name> sqlCmdVars SET @open:=NULL, @closed:=NULL;
attr <name> sqlCmdVars PRAGMA temp_store=MEMORY;PRAGMA synchronous=FULL;PRAGMA journal_mode=WAL;
sqlFormatService
Automated formatting of SQL statements can be activated via an online service.
This option is especially useful for complex SQL statements of the setters sqlCmd, sqlCmdHistory, and sqlSpecial
to improve structuring and readability.
An internet connection is required and the global attribute dnsServer should be set.
(default: none)
sqlResultFieldSep
Sets the used field separator in the result of the command "set ... sqlCmd".
(default: "|")
sqlResultFormat - determines the formatting of the "set <name> sqlCmd" command result.
Possible options are:
separated - every line of the result will be generated sequentially in a single
reading. (default)
mline - the result will be generated as multiline in
Reading SqlResult.
sline - the result will be generated as singleline in
Reading SqlResult.
Datasets are separated by "]|[".
table - the result will be generated as an table in
Reading SqlResult.
json - creates the Reading SqlResult as a JSON
coded hash.
Every hash-element consists of the serial number of the dataset (key)
and its value.
To process the result, you may use a userExitFn in 99_myUtils for example:
sub resfromjson {
my ($name,$reading,$value) = @_;
my $hash = $defs{$name};
if ($reading eq "SqlResult") {
# only reading SqlResult contains JSON encoded data
my $data = decode_json($value);
foreach my $k (keys(%$data)) {
# use your own processing from here for every hash-element
# e.g. output of every element that contains "Cam"
my $ke = $data->{$k};
if($ke =~ m/Cam/i) {
my ($res1,$res2) = split("\\|", $ke);
Log3($name, 1, "$name - extract element $k by userExitFn: ".$res1." ".$res2);
}
}
}
return;
}
timeYearPeriod - By this attribute an annual time period will be determined for database data selection.
The time limits are calculated dynamically during execution time. Every time an annual period is determined.
Periods of less than a year are not possible to set.
This attribute is particularly intended to make reports synchronous to an account period, e.g. of an energy- or gas provider.
Example:
attr <name> timeYearPeriod 06-25 06-24
# evaluates the database within the time limits 25. june AAAA and 24. june BBBB.
# The year AAAA respectively year BBBB is calculated dynamically depending of the current date.
# If the current date >= 25. june and =< 31. december, than AAAA = current year and BBBB = current year+1
# If the current date >= 01. january und =< 24. june, than AAAA = current year-1 and BBBB = current year
timestamp_begin - begin of data selection
The format of timestamp is as used with DbLog "YYYY-MM-DD HH:MM:SS". For the attributes "timestamp_begin", "timestamp_end"
you can also use one of the following entries. The timestamp-attribute will be dynamically set to:
current_year_begin : matches "<current year>-01-01 00:00:00"
current_year_end : matches "<current year>-12-31 23:59:59"
previous_year_begin : matches "<previous year>-01-01 00:00:00"
previous_year_end : matches "<previous year>-12-31 23:59:59"
current_month_begin : matches "<current month first day> 00:00:00"
current_month_end : matches "<current month last day> 23:59:59"
previous_month_begin : matches "<previous month first day> 00:00:00"
previous_month_end : matches "<previous month last day> 23:59:59"
current_week_begin : matches "<first day of current week> 00:00:00"
current_week_end : matches "<last day of current week> 23:59:59"
previous_week_begin : matches "<first day of previous week> 00:00:00"
previous_week_end : matches "<last day of previous week> 23:59:59"
current_day_begin : matches "<current day> 00:00:00"
current_day_end : matches "<current day> 23:59:59"
previous_day_begin : matches "<previous day> 00:00:00"
previous_day_end : matches "<previous day> 23:59:59"
next_day_begin : matches "<next day> 00:00:00"
next_day_end : matches "<next day> 23:59:59"
current_hour_begin : matches "<current hour>:00:00"
current_hour_end : matches "<current hour>:59:59"
previous_hour_begin : matches "<previous hour>:00:00"
previous_hour_end : matches "<previous hour>:59:59"
timestamp_end - end of data selection. If not set the current date/time combination will be used.
The format of timestamp is as used with DbLog "YYYY-MM-DD HH:MM:SS". For the attributes "timestamp_begin", "timestamp_end"
you can also use one of the following entries. The timestamp-attribute will be dynamically set to:
current_year_begin : matches "<current year>-01-01 00:00:00"
current_year_end : matches "<current year>-12-31 23:59:59"
previous_year_begin : matches "<previous year>-01-01 00:00:00"
previous_year_end : matches "<previous year>-12-31 23:59:59"
current_month_begin : matches "<current month first day> 00:00:00"
current_month_end : matches "<current month last day> 23:59:59"
previous_month_begin : matches "<previous month first day> 00:00:00"
previous_month_end : matches "<previous month last day> 23:59:59"
current_week_begin : matches "<first day of current week> 00:00:00"
current_week_end : matches "<last day of current week> 23:59:59"
previous_week_begin : matches "<first day of previous week> 00:00:00"
previous_week_end : matches "<last day of previous week> 23:59:59"
current_day_begin : matches "<current day> 00:00:00"
current_day_end : matches "<current day> 23:59:59"
previous_day_begin : matches "<previous day> 00:00:00"
previous_day_end : matches "<previous day> 23:59:59"
next_day_begin : matches "<next day> 00:00:00"
next_day_end : matches "<next day> 23:59:59"
current_hour_begin : matches "<current hour>:00:00"
current_hour_end : matches "<current hour>:59:59"
previous_hour_begin : matches "<previous hour>:00:00"
previous_hour_end : matches "<previous hour>:59:59"
Make sure that "timestamp_begin" < "timestamp_end" is fulfilled.
Example:
attr <name> timestamp_begin current_year_begin
attr <name> timestamp_end current_year_end
# Analyzes the database between the time limits of the current year.
Note
If the attribute "timeDiffToNow" will be set, the attributes "timestamp_begin" respectively "timestamp_end" will be deleted if they were set before.
The setting of "timestamp_begin" respectively "timestamp_end" causes the deletion of attribute "timeDiffToNow" if it was set before as well.
timeDiffToNow - the begin time of data selection will be set to the timestamp "<current time> -
<timeDiffToNow>" dynamically. The time period will be calculated dynamically at
execution time. Optional can with the additional entry "FullDay" the selection start time
and the selection end time be expanded to the begin / end of the involved days
(take only effect if adjusted time difference is >= 1 day).
Examples for input format:
attr <name> timeDiffToNow 86400
# the start time is set to "current time - 86400 seconds"
attr <name> timeDiffToNow d:2 h:3 m:2 s:10
# the start time is set to "current time - 2 days 3 hours 2 minutes 10 seconds"
attr <name> timeDiffToNow m:600
# the start time is set to "current time - 600 minutes" gesetzt
attr <name> timeDiffToNow h:2.5
# the start time is set to "current time - 2,5 hours"
attr <name> timeDiffToNow y:1 h:2.5
# the start time is set to "current time - 1 year and 2,5 hours"
attr <name> timeDiffToNow y:1.5
# the start time is set to "current time - 1.5 years"
attr <name> timeDiffToNow d:8 FullDay
# the start time is set to "current time - 8 days", the selection time period is expanded to the begin / end of the involved days
If both attributes "timeDiffToNow" and "timeOlderThan" are set, the selection
period will be calculated between of these timestamps dynamically.
timeOlderThan - the end time of data selection will be set to the timestamp "<aktuelle Zeit> -
<timeOlderThan>" dynamically. Always the datasets up to timestamp
"<current time> - <timeOlderThan>" will be considered. The time period will be calculated dynamically at
execution time. Optional can with the additional entry "FullDay" the selection start time
and the selection end time be expanded to the begin / end of the involved days
(take only effect if adjusted time difference is >= 1 day).
Examples for input format:
attr <name> timeOlderThan 86400
# the selection end time is set to "current time - 86400 seconds"
attr <name> timeOlderThan d:2 h:3 m:2 s:10
# the selection end time is set to "current time - 2 days 3 hours 2 minutes 10 seconds"
attr <name> timeOlderThan m:600
# the selection end time is set to "current time - 600 minutes" gesetzt
attr <name> timeOlderThan h:2.5
# the selection end time is set to "current time - 2,5 hours"
attr <name> timeOlderThan y:1 h:2.5
# the selection end time is set to "current time - 1 year and 2,5 hours"
attr <name> timeOlderThan y:1.5
# the selection end time is set to "current time - 1.5 years"
attr <name> timeOlderThan d:8 FullDay
# the end time is set to "current time - 8 days", the selection time period is expanded to the begin / end of the involved days
If both attributes "timeDiffToNow" and "timeOlderThan" are set, the selection
period will be calculated between of these timestamps dynamically.
timeout - set the timeout-value for Blocking-Call Routines in background in seconds (default 86400)
useAdminCredentials
- If set, a before with "set <aame> adminCredentials" saved privileged user is used
for particular database operations.
(only valid if database type is MYSQL and DbRep-type "Client")
userExitFn - provides an interface for executing custom user code.
Basically, the interface works without event generation or does not require an event to function.
The interface can be used with the following variants.
1. call a subroutine, e.g. in 99_myUtils.pm
.
The subroutine to be called is created in 99_myUtils.pm according to the following pattern:
sub UserFunction {
my $name = shift; # the name of the DbRep device.
my $reading = shift; # the name of the reading to create
my $value = shift; # the value of the reading
my $hash = $defs{$name};
...
# e.g. log passed data
Log3 $name, 1, "UserExitFn $name called - transfer parameters are Reading: $reading, Value: $value " ;
...
return;
}
In the attribute the subroutine and optionally a Reading:Value regex
must be specified as an argument. Without this specification all Reading:Value combinations are
evaluated as "true" and passed to the subroutine (equivalent to .*:.*).
Example:
attr userExitFn UserFunction Meter:Energy.*
# "UserFunction" is the subroutine in 99_myUtils.pm.
The regex is checked after the creation of each reading.
If the check is true, the specified function is called.
2. Direct input of custom code
.
The custom code is enclosed in curly braces.
The code is called after the creation of each reading.
In the code, the following variables are available for evaluation:
- $NAME - the name of the DbRep device
- $READING - the name of the reading created
- $VALUE - the value of the reading
{
if ($READING =~ /PrEnergySumHwc1_0_value__DIFF/) {
my $mpk = AttrVal($NAME, 'multiplier', '0');
my $tarf = AttrVal($NAME, 'Tariff', '0'); # cost €/kWh
my $m3 = sprintf "%.3f", $VALUE/10000 * $mpk; # consumed m3
my $kwh = sprintf "%.3f", $m3 * AttrVal($NAME, 'Calorific_kWh/m3', '0'); # conversion m3 -> kWh
my $cost = sprintf "%.2f", $kwh * $tarf;
my $hash = $defs{$NAME};
readingsBulkUpdate ($hash, 'gas_consumption_m3', $m3);
readingsBulkUpdate ($hash, 'gas_consumption_kwh', $kwh);
readingsBulkUpdate ($hash, 'gas_costs_euro', $cost);
}
}
# The readings gas_consumption_m3, gas_consumption_kwh and gas_costs_euro are calculated
And generated in the DbRep device.
valueFilter - Regular expression (REGEXP) to filter datasets within particular functions. The REGEXP is
applied to a particular field or to the whole selected dataset (inclusive Device, Reading and
so on).
Please consider the explanations within the set-commands. Further information is available
with command "get <name> versionNotes 4".
Readings
Regarding to the selected operation the reasults will be shown as readings. At the beginning of a new operation all old readings will be deleted to avoid
that unsuitable or invalid readings would remain.
In addition the following readings will be created:
- state - contains the current state of evaluation. If warnings are occured (state = Warning) compare Readings
"diff_overrun_limit_<diffLimit>" and "less_data_in_period"
- errortext - description about the reason of an error state
- background_processing_time - the processing time spent for operations in background/forked operation
- sql_processing_time - the processing time wasted for all sql-statements used for an operation
- diff_overrun_limit_<diffLimit> - contains a list of pairs of datasets which have overrun the threshold (<diffLimit>)
of calculated difference each other determined by attribute "diffAccept" (default=20).
- less_data_in_period - contains a list of time periods within only one dataset was found. The difference calculation considers
the last value of the aggregation period before the current one. Valid for function "diffValue".
- SqlResult - result of the last executed sqlCmd-command. The formatting can be specified
by attribute sqlResultFormat
- sqlCmd - contains the last executed sqlCmd-command
DbRep Agent - automatic change of device names in databases and DbRep-definitions after FHEM "rename" command
By the attribute "role" the role of DbRep-device will be configured. The standard role is "Client". If the role has changed to "Agent", the DbRep device
react automatically on renaming devices in your FHEM installation. The DbRep device is now called DbRep-Agent.
By the DbRep-Agent the following features are activated when a FHEM-device has being renamed:
- in the database connected to the DbRep-Agent (Internal Database) dataset containing the old device name will be searched and renamed to the
to the new device name in all affected datasets.
- in the DbLog-Device assigned to the DbRep-Agent the definition will be changed to substitute the old device name by the new one. Thereby the logging of
the renamed device will be going on in the database.
- in other existing DbRep-definitions with Type "Client" a possibly set attribute "device = old device name" will be changed to "device = new device name".
Because of that, reporting definitions will be kept consistent automatically if devices are renamed in FHEM.
The following restrictions take place if a DbRep device was changed to an Agent by setting attribute "role" to "Agent". These conditions will be activated
and checked:
- within a FHEM installation only one DbRep-Agent can be configured for every defined DbLog-database. That means, if more than one DbLog-database is present,
you could define same numbers of DbRep-Agents as well as DbLog-devices are defined.
- after changing to DbRep-Agent role only the set-command "renameDevice" will be available and as well as a reduced set of module specific attributes will be
permitted. If a DbRep-device of privious type "Client" has changed an Agent, furthermore not permitted attributes will be deleted if set.
All activities like database changes and changes of other DbRep-definitions will be logged in FHEM Logfile with verbose=3. In order that the renameDevice
function don't running into timeout set the timeout attribute to an appropriate value, especially if there are databases with huge datasets to evaluate.
As well as all the other database operations of this module, the autorename operation will be executed nonblocking.
Example of definition of a DbRep-device as an Agent:
define Rep.Agent DbRep LogDB
attr Rep.Agent devStateIcon connected:10px-kreis-gelb .*disconnect:10px-kreis-rot .*done:10px-kreis-gruen
attr Rep.Agent icon security
attr Rep.Agent role Agent
attr Rep.Agent room DbLog
attr Rep.Agent showproctime 1
attr Rep.Agent stateFormat { ReadingsVal($name, 'state', '') eq 'running' ? 'renaming' : ReadingsVal($name, 'state', ''). ' »; ProcTime: '.ReadingsVal($name, 'sql_processing_time', '').' sec'}
attr Rep.Agent timeout 86400
Note:
Even though the function itself is designed non-blocking, make sure the assigned DbLog-device
is operating in asynchronous mode to avoid FHEMWEB from blocking.
=end html
=begin html_DE
DbRep
Zweck des Moduls ist es, den Inhalt von DbLog-Datenbanken nach bestimmten Kriterien zu durchsuchen, zu managen, das Ergebnis hinsichtlich verschiedener
Aggregationen auszuwerten und als Readings darzustellen. Die Abgrenzung der zu berücksichtigenden Datenbankinhalte erfolgt durch die Angabe von Device, Reading und
die Zeitgrenzen für Auswertungsbeginn bzw. Auswertungsende.
Fast alle Datenbankoperationen werden nichtblockierend ausgeführt. Auf Ausnahmen wird hingewiesen.
Die Ausführungszeit der (SQL)-Hintergrundoperationen kann optional ebenfalls als Reading bereitgestellt
werden (siehe Attribute).
Alle vorhandenen Readings werden vor einer neuen Operation gelöscht. Durch das Attribut "readingPreventFromDel" kann eine Komma separierte Liste von Readings
angegeben werden die nicht gelöscht werden sollen.
Aktuell werden folgende Operationen unterstützt:
- Selektion aller Datensätze innerhalb einstellbarer Zeitgrenzen
- Darstellung der Datensätze einer Device/Reading-Kombination innerhalb einstellbarer Zeitgrenzen.
- Selektion der Datensätze unter Verwendung von dynamisch berechneter Zeitgrenzen zum Ausführungszeitpunkt.
- Dubletten-Hervorhebung bei Datensatzanzeige (fetchrows)
- Berechnung der Anzahl von Datensätzen einer Device/Reading-Kombination unter Berücksichtigung von Zeitgrenzen
und verschiedenen Aggregationen.
- Die Berechnung von Summen-, Differenz-, Maximum-, Minimum- und Durchschnittswerten numerischer Readings
in Zeitgrenzen und verschiedenen Aggregationen.
- Speichern von Summen-, Differenz- , Maximum- , Minimum- und Durchschnittswertberechnungen in der Datenbank
- Löschung von Datensätzen. Die Eingrenzung der Löschung kann durch Device und/oder Reading sowie fixer oder
dynamisch berechneter Zeitgrenzen zum Ausführungszeitpunkt erfolgen.
- Export von Datensätzen in ein File im CSV-Format
- Import von Datensätzen aus File im CSV-Format
- Umbenennen von Device/Readings in Datenbanksätzen
- Ändern von Reading-Werten (VALUES) in der Datenbank (changeValue)
- automatisches Umbenennen von Device-Namen in Datenbanksätzen und DbRep-Definitionen nach FHEM "rename"
Befehl (siehe DbRep-Agent)
- Ausführen von beliebigen Benutzer spezifischen SQL-Kommandos (non-blocking)
- Ausführen von beliebigen Benutzer spezifischen SQL-Kommandos (blocking) zur Verwendung in eigenem Code (sqlCmdBlocking)
- Backups der FHEM-Datenbank im laufenden Betrieb erstellen (MySQL, SQLite)
- senden des Dumpfiles zu einem FTP-Server nach dem Backup incl. Versionsverwaltung
- Restore von SQLite- und MySQL-Dumps
- Optimierung der angeschlossenen Datenbank (optimizeTables, vacuum)
- Ausgabe der existierenden Datenbankprozesse (MySQL)
- leeren der current-Tabelle
- Auffüllen der current-Tabelle mit einem (einstellbaren) Extrakt der history-Tabelle
- Bereinigung sequentiell aufeinander folgender Datensätze mit unterschiedlichen Zeitstempel aber gleichen Werten (sequentielle Dublettenbereinigung)
- Reparatur einer korrupten SQLite Datenbank ("database disk image is malformed")
- Übertragung von Datensätzen aus der Quelldatenbank in eine andere (Standby) Datenbank (syncStandby)
- Reduktion der Anzahl von Datensätzen in der Datenbank (reduceLog)
- Löschen von doppelten Datensätzen (delDoublets)
- Löschen und (Wieder)anlegen der für DbLog und DbRep benötigten Indizes (index)
Zur Aktivierung der Funktion Autorename wird dem definierten DbRep-Device mit dem Attribut "role" die Rolle "Agent" zugewiesen. Die Standardrolle nach Definition
ist "Client". Mehr ist dazu im Abschnitt DbRep-Agent beschrieben.
DbRep stellt dem Nutzer einen UserExit zur Verfügung. Über diese Schnittstelle kann der Nutzer in Abhängigkeit von
frei definierbaren Reading/Value-Kombinationen (Regex) eigenen Code zur Ausführung bringen. Diese Schnittstelle arbeitet
unabhängig von einer Eventgenerierung. Weitere Informationen dazu ist unter userExitFn
beschrieben.
Sobald ein DbRep-Device definiert ist, wird sowohl die Perl Funktion DbReadingsVal als auch das FHEM Kommando
dbReadingsVal zur Verfügung gestellt.
Mit dieser Funktion läßt sich, ähnlich dem allgemeinen ReadingsVal, der Wert eines Readings aus der Datenbank abrufen.
Die Funktionsausführung erfolgt blockierend mit einem Standardtimeout von 10 Sekunden um eine dauerhafte Blockierung von FHEM zu verhindern.
Der Timeout ist mit dem Attribut timeout anpassbar.
Die Befehlssyntax für die Perl Funktion ist:
DbReadingsVal("<name>","<device:reading>","<timestamp>","<default>")
Beispiel:
$ret = DbReadingsVal("Rep.LogDB1","MyWetter:temperature","2018-01-13_08:00:00","");
attr <name> userReadings oldtemp {DbReadingsVal("Rep.LogDB1","MyWetter:temperature","2018-04-13_08:00:00","")}
attr <name> userReadings todayPowerIn
{
my ($sec,$min,$hour,$mday,$month,$year,$wday,$yday,$isdst) = localtime(gettimeofday());
$month++;
$year+=1900;
my $today = sprintf('%04d-%02d-%02d', $year,$month,$mday);
DbReadingsVal("Rep.LogDB1","SMA_Energymeter:Bezug_Wirkleistung_Zaehler",$today."_00:00:00",0)
}
Die Befehlssyntax als FHEM Kommando ist:
dbReadingsVal <name> <device:reading> <timestamp> <default>
Beispiel:
dbReadingsVal Rep.LogDB1 MyWetter:temperature 2018-01-13_08:00:00 0
<name> | : Name des abzufragenden DbRep-Device |
<device:reading> | : Device:Reading dessen Wert geliefert werden soll |
<timestamp> | : Zeitpunkt des zu liefernden Readingwertes (*) im Format "YYYY-MM-DD_hh:mm:ss" |
<default> | : Defaultwert falls kein Readingwert ermittelt werden konnte |
(*) Es wird der zeitlich zu <timestamp> passendste Readingwert zurück geliefert, falls kein Wert exakt zu dem
angegebenen Zeitpunkt geloggt wurde.
FHEM-Forum:
Modul 93_DbRep - Reporting und Management von Datenbankinhalten (DbLog).
FHEM-Wiki:
DbRep - Reporting und Management von DbLog-Datenbankinhalten.
Voraussetzungen
Das Modul setzt den Einsatz einer oder mehrerer DbLog-Instanzen voraus. Es werden die Zugangsdaten dieser
Datenbankdefinition genutzt.
Es werden nur Inhalte der Tabelle "history" berücksichtigt wenn nichts anderes beschrieben ist.
Überblick welche anderen Perl-Module DbRep verwendet:
Net::FTP (nur wenn FTP-Transfer nach Datenbank-Dump genutzt wird)
Net::FTPSSL (nur wenn FTP-Transfer mit Verschlüsselung nach Datenbank-Dump genutzt wird)
POSIX
Time::HiRes
Time::Local
Scalar::Util
DBI
Color (FHEM-Modul)
IO::Compress::Gzip
IO::Uncompress::Gunzip
Blocking (FHEM-Modul)
Definition
define <name> DbRep <Name der DbLog-Instanz>
(<Name der DbLog-Instanz> - es wird der Name der auszuwertenden DbLog-Datenbankdefinition angegeben nicht der Datenbankname selbst)
Für eine gute Operation Performance sollte die Datenbank den Index "Report_Idx" enthalten. Der Index kann nach der
DbRep Devicedefinition mit dem set-Kommando angelegt werden sofern er auf der Datenbank noch nicht existiert:
set <name> index recreate_Report_Idx
Set
Zur Zeit gibt es folgende Set-Kommandos. Über sie werden die Auswertungen angestoßen und definieren selbst die Auswertungsvariante.
Nach welchen Kriterien die Datenbankinhalte durchsucht werden und die Aggregation erfolgt, wird durch Attribute gesteuert.
Hinweis:
In der Detailansicht kann ein Browserrefresh nötig sein um die Operationsergebnisse zu sehen sobald im DeviceOverview "state = done" angezeigt wird.
- adminCredentials <User> <Passwort>
- Speichert einen User / Passwort für den privilegierten bzw. administrativen
Datenbankzugriff. Er wird bei Datenbankoperationen benötigt, die mit einem privilegierten User
ausgeführt werden müssen. Siehe auch Attribut useAdminCredentials.
(nur gültig bei Datenbanktyp MYSQL und DbRep-Typ "Client")
- averageValue [display | writeToDB | writeToDBSingle | writeToDBSingleStart | writeToDBInTime]
Berechnet einen Durchschnittswert des Datenbankfelds "VALUE" in den Zeitgrenzen
der möglichen time.*-Attribute.
Es muss das auszuwertende Reading im Attribut reading
angegeben sein.
Mit dem Attribut averageCalcForm wird die Berechnungsvariante zur
Mittelwertermittlung definiert.
Ist keine oder die Option display angegeben, werden die Ergebnisse nur angezeigt. Mit
den Optionen writeToDB, writeToDBSingle, writeToDBSingleStart bzw. writeToDBInTime
werden die Berechnungsergebnisse mit einem neuen Readingnamen in der Datenbank gespeichert.
writeToDB | : schreibt jeweils einen Wert mit den Zeitstempeln XX:XX:01 und XX:XX:59 innerhalb der jeweiligen Auswertungsperiode |
writeToDBSingle | : schreibt nur einen Wert mit dem Zeitstempel XX:XX:59 am Ende einer Auswertungsperiode |
writeToDBSingleStart | : schreibt nur einen Wert mit dem Zeitstempel XX:XX:01 am Beginn einer Auswertungsperiode |
writeToDBInTime | : schreibt jeweils einen Wert am Anfang und am Ende der Zeitgrenzen einer Auswertungsperiode |
Der neue Readingname wird aus einem Präfix und dem originalen Readingnamen gebildet,
wobei der originale Readingname durch das Attribut "readingNameMap" ersetzt werden kann.
Der Präfix setzt sich aus der Bildungsfunktion und der Aggregation zusammen.
Der Timestamp der neuen Readings in der Datenbank wird von der eingestellten Aggregationsperiode
abgeleitet, sofern kein eindeutiger Zeitpunkt des Ergebnisses bestimmt werden kann.
Das Feld "EVENT" wird mit "calculated" gefüllt.
Beispiel neuer Readingname gebildet aus dem Originalreading "totalpac":
avgam_day_totalpac
# <Bildungsfunktion>_<Aggregation>_<Originalreading>
Zusammengefasst sind die zur Steuerung dieser Funktion relevanten Attribute:
aggregation | : Auswahl einer Aggregationsperiode |
averageCalcForm | : Auswahl der Berechnungsvariante für den Durchschnitt |
device | : einschließen oder ausschließen von Datensätzen die <device> enthalten |
executeBeforeProc | : ausführen FHEM Kommando (oder Perl-Routine) vor Start Operation |
executeAfterProc | : ausführen FHEM Kommando (oder Perl-Routine) nach Ende Operation |
reading | : einschließen oder ausschließen von Datensätzen die <reading> enthalten |
readingNameMap | : die entstehenden Ergebnisreadings werden partiell umbenannt |
time.* | : eine Reihe von Attributen zur Zeitabgrenzung |
valueFilter | : ein zusätzliches REGEXP um die Datenselektion zu steuern. Der REGEXP wird auf das Datenbankfeld 'VALUE' angewendet. |
- cancelDump - bricht einen laufenden Datenbankdump ab.
- changeValue old="<alter String>" new="<neuer String>"
Ändert den gespeicherten Wert eines Readings.
Ist die Selektion auf bestimmte Device/Reading-Kombinationen durch die Attribute
device bzw. reading beschränkt, werden sie genauso
berücksichtigt wie gesetzte Zeitgrenzen (time.* Attribute).
Fehlen diese Beschränkungen, wird die gesamte Datenbank durchsucht und der angegebene Wert
geändert.
"String" kann sein:
<alter String> : | - ein einfacher String mit/ohne Leerzeichen, z.B. "OL 12"
|
| - ein String mit Verwendung von SQL-Wildcard, z.B. "%OL%"
|
| |
| |
<neuer String> : | - ein einfacher String mit/ohne Leerzeichen, z.B. "12 kWh"
|
| - Perl Code eingeschlossen in {"..."} inkl. Quotes, z.B. {"($VALUE,$UNIT) = split(" ",$VALUE)"}
|
| Dem Perl-Ausdruck werden die Variablen $VALUE und $UNIT übergeben. Sie können innerhalb |
| des Perl-Code geändert werden. Der zurückgebene Wert von $VALUE und $UNIT wird in dem Feld |
| VALUE bzw. UNIT des Datensatzes gespeichert. |
Beispiele:
set <name> changeValue old="OL" new="12 OL"
# der alte Feldwert "OL" wird in "12 OL" geändert.
set <name> changeValue old="%OL%" new="12 OL"
# enthält das Feld VALUE den Teilstring "OL", wird es in "12 OL" geändert.
set <name> changeValue old="12 kWh" new={"($VALUE,$UNIT) = split(" ",$VALUE)"}
# der alte Feldwert "12 kWh" wird in VALUE=12 und UNIT=kWh gesplittet und in den Datenbankfeldern gespeichert
set <name> changeValue old="24%" new={"$VALUE = (split(" ",$VALUE))[0]"}
# beginnt der alte Feldwert mit "24", wird er gesplittet und VALUE=24 gespeichert (z.B. "24 kWh")
Zusammengefasst sind die zur Steuerung von changeValue relevanten Attribute:
device | : einschließen oder ausschließen von Datensätzen die <device> enthalten |
reading | : einschließen oder ausschließen von Datensätzen die <reading> enthalten |
time.* | : eine Reihe von Attributen zur Zeitabgrenzung |
executeBeforeProc | : ausführen FHEM Kommando (oder Perl-Routine) vor Start changeValue |
executeAfterProc | : ausführen FHEM Kommando (oder Perl-Routine) nach Ende changeValue |
valueFilter | : ein zusätzliches REGEXP um die Datenselektion zu steuern. Der REGEXP wird auf das Datenbankfeld 'VALUE' angewendet. |
- countEntries [history | current]
- liefert die Anzahl der Tabelleneinträge (default: history) in den gegebenen
Zeitgrenzen (siehe time*-Attribute).
Sind die Timestamps nicht gesetzt, werden alle Einträge der Tabelle gezählt.
Beschränkungen durch die Attribute device bzw. reading
gehen in die Selektion mit ein.
Standardmäßig wird die Summe aller Datensätze, gekennzeichnet mit "ALLREADINGS", erstellt.
Ist das Attribut "countEntriesDetail" gesetzt, wird die Anzahl jedes einzelnen Readings
zusätzlich ausgegeben.
Die für diese Funktion relevanten Attribute sind:
aggregation | : Zusammenfassung/Gruppierung von Zeitintervallen |
countEntriesDetail | : detaillierte Ausgabe der Datensatzanzahl |
device | : einschließen oder ausschließen von Datensätzen die <device> enthalten |
reading | : einschließen oder ausschließen von Datensätzen die <reading> enthalten |
time.* | : eine Reihe von Attributen zur Zeitabgrenzung |
executeBeforeProc | : ausführen FHEM Kommando (oder Perl-Routine) vor Ausführung |
executeAfterProc | : ausführen FHEM Kommando (oder Perl-Routine) nach Ausführung |
readingNameMap | : die entstehenden Ergebnisreadings werden partiell umbenannt |
valueFilter | : ein zusätzliches REGEXP um die Datenselektion zu steuern. Der REGEXP wird auf das Datenbankfeld 'VALUE' angewendet. |
- delDoublets [adviceDelete | delete] - zeigt bzw. löscht doppelte / mehrfach vorkommende Datensätze.
Dazu wird Timestamp, Device,Reading und Value ausgewertet.
Die Attribute zur Aggregation,Zeit-,Device- und Reading-Abgrenzung werden dabei
berücksichtigt. Ist das Attribut "aggregation" nicht oder auf "no" gesetzt, wird im Standard die Aggregation
"day" verwendet.
adviceDelete | : ermittelt die zu löschenden Datensätze (es wird nichts gelöscht !) |
delete | : löscht die Dubletten |
Aus Sicherheitsgründen muss das Attribut allowDeletion für die "delete" Option
gesetzt sein.
Die Anzahl der anzuzeigenden Datensätze des Kommandos "delDoublets adviceDelete" ist zunächst
begrenzt (default 1000) und kann durch das Attribut limit angepasst
werden.
Die Einstellung von "limit" hat keinen Einfluss auf die "delDoublets delete" Funktion, sondern
beeinflusst NUR die Anzeige der Daten.
Vor und nach der Ausführung von "delDoublets" kann ein FHEM-Kommando bzw. Perl-Routine ausgeführt
werden. (siehe Attribute executeBeforeProc,
executeAfterProc)
Beispiel:
Ausgabe der zu löschenden Records inklusive der Anzahl mit "delDoublets adviceDelete":
2018-11-07_14-11-38__Dum.Energy__T 260.9_|_2
2018-11-07_14-12-37__Dum.Energy__T 260.9_|_2
2018-11-07_14-15-38__Dum.Energy__T 264.0_|_2
2018-11-07_14-16-37__Dum.Energy__T 264.0_|_2
Im Werteteil der erzeugten Readings wird nach "_|_" die Anzahl der entsprechenden Datensätze
ausgegeben, die mit "delDoublets delete" gelöscht werden.
Zusammengefasst sind die zur Steuerung dieser Funktion relevanten Attribute:
allowDeletion | : Freischaltung der Löschfunktion |
aggregation | : Auswahl einer Aggregationsperiode |
device | : einschließen oder ausschließen von Datensätzen die <device> enthalten |
limit | : begrenzt NUR die Anzahl der anzuzeigenden Datensätze |
reading | : einschließen oder ausschließen von Datensätzen die <reading> enthalten |
time.* | : eine Reihe von Attributen zur Zeitabgrenzung |
executeBeforeProc | : ausführen FHEM Kommando (oder Perl-Routine) vor Start des Befehls |
executeAfterProc | : ausführen FHEM Kommando (oder Perl-Routine) nach Ende des Befehls |
valueFilter | : ein zusätzliches REGEXP um die Datenselektion zu steuern. Der REGEXP wird auf das Datenbankfeld 'VALUE' angewendet. |
- delEntries [<no>[:<nn>]] - löscht alle oder die durch die Attribute device und/oder
reading definierten Datenbankeinträge. Die Eingrenzung über Timestamps erfolgt
folgendermaßen:
"timestamp_begin" gesetzt -> gelöscht werden DB-Einträge ab diesem Zeitpunkt bis zum aktuellen Datum/Zeit
"timestamp_end" gesetzt -> gelöscht werden DB-Einträge bis bis zu diesem Zeitpunkt
beide Timestamps gesetzt -> gelöscht werden DB-Einträge zwischen diesen Zeitpunkten
"timeOlderThan" gesetzt -> gelöscht werden DB-Einträge älter als aktuelle Zeit minus "timeOlderThan"
"timeDiffToNow" gesetzt -> gelöscht werden DB-Einträge ab aktueller Zeit minus "timeDiffToNow" bis jetzt
Aus Sicherheitsgründen muss das Attribut allowDeletion
gesetzt sein um die Löschfunktion freizuschalten.
Zeitgrenzen (Tage) können als Option angegeben werden. In diesem Fall werden eventuell gesetzte Zeitattribute
übersteuert.
Es werden Datensätze berücksichtigt die älter sind als <no> Tage und (optional) neuer sind als
<nn> Tage.
Die zur Steuerung von delEntries relevanten Attribute:
allowDeletion | : Freischaltung der Löschfunktion |
device | : einschließen oder ausschließen von Datensätzen die <device> enthalten |
reading | : einschließen oder ausschließen von Datensätzen die <reading> enthalten |
readingNameMap | : die entstehenden Ergebnisreadings werden partiell umbenannt |
time.* | : eine Reihe von Attributen zur Zeitabgrenzung |
executeBeforeProc | : ausführen FHEM Kommando (oder Perl-Routine) vor Start delEntries |
executeAfterProc | : ausführen FHEM Kommando (oder Perl-Routine) nach Ende delEntries |
valueFilter | : ein zusätzliches REGEXP um die Datenselektion zu steuern. Der REGEXP wird auf das Datenbankfeld 'VALUE' angewendet. |
- delSeqDoublets [adviceRemain | adviceDelete | delete] - zeigt bzw. löscht aufeinander folgende identische Datensätze.
Dazu wird Device,Reading und Value ausgewertet. Nicht gelöscht werden der erste und der letzte Datensatz
einer Aggregationsperiode (z.B. hour, day, week usw.) sowie die Datensätze vor oder nach einem Wertewechsel
(Datenbankfeld VALUE).
Die Attribute zur Aggregation,Zeit-,Device- und Reading-Abgrenzung werden dabei
berücksichtigt. Ist das Attribut "aggregation" nicht oder auf "no" gesetzt, wird als Standard die Aggregation
"day" verwendet. Für Datensätze mit numerischen Werten kann mit dem Attribut seqDoubletsVariance
eine Abweichung eingestellt werden, bis zu der aufeinander folgende numerische Werte als
identisch angesehen und gelöscht werden sollen.
adviceRemain | : simuliert die nach der Operation in der DB verbleibenden Datensätze (es wird nichts gelöscht !) |
adviceDelete | : simuliert die zu löschenden Datensätze (es wird nichts gelöscht !) |
delete | : löscht die sequentiellen Dubletten (siehe Beispiel) |
Aus Sicherheitsgründen muss das Attribut allowDeletion für die "delete" Option
gesetzt sein.
Die Anzahl der anzuzeigenden Datensätze der Kommandos "delSeqDoublets adviceDelete", "delSeqDoublets adviceRemain" ist
zunächst begrenzt (default 1000) und kann durch das Attribut limit angepasst werden.
Die Einstellung von "limit" hat keinen Einfluss auf die "delSeqDoublets delete" Funktion, sondern beeinflusst NUR die
Anzeige der Daten.
Vor und nach der Ausführung von "delSeqDoublets" kann ein FHEM-Kommando bzw. Perl-Routine ausgeführt werden.
(siehe Attribute executeBeforeProc,
executeAfterProc)
Beispiel - die nach Verwendung der delete-Option in der DB verbleibenden Datensätze sind fett
gekennzeichnet:
2017-11-25_00-00-05__eg.az.fridge_Pwr__power 0
2017-11-25_00-02-26__eg.az.fridge_Pwr__power 0
2017-11-25_00-04-33__eg.az.fridge_Pwr__power 0
2017-11-25_01-06-10__eg.az.fridge_Pwr__power 0
2017-11-25_01-08-21__eg.az.fridge_Pwr__power 0
2017-11-25_01-08-59__eg.az.fridge_Pwr__power 60.32
2017-11-25_01-11-21__eg.az.fridge_Pwr__power 56.26
2017-11-25_01-27-54__eg.az.fridge_Pwr__power 6.19
2017-11-25_01-28-51__eg.az.fridge_Pwr__power 0
2017-11-25_01-31-00__eg.az.fridge_Pwr__power 0
2017-11-25_01-33-59__eg.az.fridge_Pwr__power 0
2017-11-25_02-39-29__eg.az.fridge_Pwr__power 0
2017-11-25_02-41-18__eg.az.fridge_Pwr__power 105.28
2017-11-25_02-41-26__eg.az.fridge_Pwr__power 61.52
2017-11-25_03-00-06__eg.az.fridge_Pwr__power 47.46
2017-11-25_03-00-33__eg.az.fridge_Pwr__power 0
2017-11-25_03-02-07__eg.az.fridge_Pwr__power 0
2017-11-25_23-37-42__eg.az.fridge_Pwr__power 0
2017-11-25_23-40-10__eg.az.fridge_Pwr__power 0
2017-11-25_23-42-24__eg.az.fridge_Pwr__power 1
2017-11-25_23-42-24__eg.az.fridge_Pwr__power 1
2017-11-25_23-45-27__eg.az.fridge_Pwr__power 1
2017-11-25_23-47-07__eg.az.fridge_Pwr__power 0
2017-11-25_23-55-27__eg.az.fridge_Pwr__power 0
2017-11-25_23-48-15__eg.az.fridge_Pwr__power 0
2017-11-25_23-50-21__eg.az.fridge_Pwr__power 59.1
2017-11-25_23-55-14__eg.az.fridge_Pwr__power 52.31
2017-11-25_23-58-09__eg.az.fridge_Pwr__power 51.73
Zusammengefasst sind die zur Steuerung dieser Funktion relevanten Attribute:
allowDeletion | : needs to be set to execute the delete option |
aggregation | : Auswahl einer Aggregationsperiode |
device | : einschließen oder ausschließen von Datensätzen die <device> enthalten |
limit | : begrenzt NUR die Anzahl der anzuzeigenden Datensätze |
reading | : einschließen oder ausschließen von Datensätzen die <reading> enthalten |
readingNameMap | : die entstehenden Ergebnisreadings werden partiell umbenannt |
seqDoubletsVariance | : bis zu diesem Wert werden aufeinander folgende numerische Datensätze als identisch angesehen und werden gelöscht |
time.* | : eine Reihe von Attributen zur Zeitabgrenzung |
executeBeforeProc | : ausführen FHEM Kommando (oder Perl-Routine) vor Start des Befehls |
executeAfterProc | : ausführen FHEM Kommando (oder Perl-Routine) nach Ende des Befehls |
valueFilter | : ein zusätzliches REGEXP um die Datenselektion zu steuern. Der REGEXP wird auf das Datenbankfeld 'VALUE' angewendet. |
- deviceRename <old_name>,<new_name> -
benennt den Namen eines Device innerhalb der angeschlossenen Datenbank (Internal DATABASE) um.
Der Gerätename wird immer in der gesamten Datenbank umgesetzt. Eventuell gesetzte
Zeitgrenzen oder Beschränkungen durch die Attribute device bzw.
reading werden nicht berücksichtigt.
Beispiel:
set <name> deviceRename ST_5000,ST5100
# Die Anzahl der umbenannten Device-Datensätze wird im Reading "device_renamed" ausgegeben.
# Wird der umzubenennende Gerätename in der Datenbank nicht gefunden, wird eine WARNUNG im Reading "device_not_renamed" ausgegeben.
# Entsprechende Einträge erfolgen auch im Logfile mit verbose=3
Hinweis:
Obwohl die Funktion selbst non-blocking ausgelegt ist, sollte das zugeordnete DbLog-Device
im asynchronen Modus betrieben werden um ein Blockieren von FHEMWEB zu vermeiden (Tabellen-Lock).
Zusammengefasst sind die zur Steuerung dieser Funktion relevanten Attribute:
executeBeforeProc | : ausführen FHEM Kommando (oder Perl-Routine) vor Start des Befehls |
executeAfterProc | : ausführen FHEM Kommando (oder Perl-Routine) nach Ende des Befehls |
- diffValue [display | writeToDB]
Berechnet den Differenzwert des Datenbankfelds "VALUE" in den angegebenen Zeitgrenzen
(siehe verschiedenen time*-Attribute).
Es wird die Differenz aus den VALUE-Werten der im Aggregationszeitraum (z.B. day) vorhandenen Datensätze gebildet und
aufsummiert.
Ein Übertragswert aus der Vorperiode (aggregation) zur darauf folgenden
Aggregationsperiode wird berücksichtigt, sofern diese Periode einen Value-Wert enhtält.
In der Standardeinstellung wertet die Funktion nur positive Differenzen aus wie sie z.B. bei einem stetig ansteigenden
Zählerwert auftreten.
Mit dem Attribut diffAccept) kann sowohl die akzeptierte Differenzschwelle als
auch die Möglichkeit negative Differenzen auszuwerten eingestellt werden.
Hinweis:
Im Auswertungs- bzw. Aggregationszeitraum (Tag, Woche, Monat, etc.) sollten dem Modul pro Periode mindestens ein
Datensatz zu Beginn und ein Datensatz gegen Ende des Aggregationszeitraumes zur Verfügung stehen um eine möglichst
genaue Auswertung der Differenzwerte vornehmen zu können.
Wird in einer auszuwertenden Zeit- bzw. Aggregationsperiode nur ein Datensatz gefunden, kann die Differenz in
Verbindung mit dem Differenzübertrag der Vorperiode berechnet werden. in diesem Fall kann es zu einer logischen
Ungenauigkeit in der Zuordnung der Differenz zu der Aggregationsperiode kommen. In diesem Fall wird eine Warnung
im state ausgegeben und das Reading less_data_in_period mit einer Liste der betroffenen Perioden erzeugt.
Ist keine oder die Option display angegeben, werden die Ergebnisse nur angezeigt.
Mit der Option writeToDB werden die Berechnungsergebnisse mit einem neuen Readingnamen
in der Datenbank gespeichert.
Der neue Readingname wird aus einem Präfix und dem originalen Readingnamen gebildet,
wobei der originale Readingname durch das Attribut readingNameMap ersetzt
werden kann.
Der Präfix setzt sich aus der Bildungsfunktion und der Aggregation zusammen.
Der Timestamp der neuen Readings in der Datenbank wird von der eingestellten Aggregationsperiode
abgeleitet, sofern kein eindeutiger Zeitpunkt des Ergebnisses bestimmt werden kann.
Das Feld "EVENT" wird mit "calculated" gefüllt.
Beispiel neuer Readingname gebildet aus dem Originalreading "totalpac":
diff_day_totalpac
# <Bildungsfunktion>_<Aggregation>_<Originalreading>
Die für die Funktion relevanten Attribute sind:
aggregation | : Auswahl einer Aggregationsperiode |
device | : einschließen oder ausschließen von Datensätzen die <device> enthalten |
diffAccept | : akzeptierte positive Werte-Differenz zwischen zwei unmittelbar aufeinander folgenden Datensätzen |
executeBeforeProc | : ausführen FHEM Kommando (oder Perl-Routine) vor Start Operation |
executeAfterProc | : ausführen FHEM Kommando (oder Perl-Routine) nach Ende Operation |
reading | : einschließen oder ausschließen von Datensätzen die <reading> enthalten |
readingNameMap | : die entstehenden Ergebnisreadings werden partiell umbenannt |
time* | : eine Reihe von Attributen zur Zeitabgrenzung |
valueFilter | : ein zusätzliches REGEXP um die Datenselektion zu steuern. Der REGEXP wird auf das Datenbankfeld 'VALUE' angewendet. |
- dumpMySQL [clientSide | serverSide]
Erstellt einen Dump der angeschlossenen MySQL-Datenbank.
Abhängig von der ausgewählten Option wird der Dump auf der Client- bzw. Serverseite erstellt.
Die Varianten unterscheiden sich hinsichtlich des ausführenden Systems, des Erstellungsortes, der
Attributverwendung, des erzielten Ergebnisses und der benötigten Hardwareressourcen.
Die Option "clientSide" benötigt z.B. eine leistungsfähigere Hardware des FHEM-Servers, sichert aber alle
Tabellen inklusive eventuell angelegter Views.
Mit dem Attribut "dumpCompress" kann eine Komprimierung der erstellten Dumpfiles eingeschaltet werden.
Option clientSide
Der Dump wird durch den Client (FHEM-Rechner) erstellt und per default im log-Verzeichnis des Clients
(typisch /opt/fhem/log/) gespeichert.
Das Zielverzeichnis kann mit dem Attribut dumpDirLocal verändert werden und muß auf
dem Client durch FHEM beschreibbar sein.
Vor dem Dump kann eine Tabellenoptimierung (Attribut "optimizeTablesBeforeDump") oder ein FHEM-Kommando
(Attribut "executeBeforeProc") optional zugeschaltet werden.
Nach dem Dump kann ebenfalls ein FHEM-Kommando (siehe Attribut "executeAfterProc") ausgeführt werden.
Achtung !
Um ein Blockieren von FHEM zu vermeiden, muß DbLog im asynchronen Modus betrieben werden wenn die
Tabellenoptimierung verwendet wird !
Über die Attribute dumpMemlimit und dumpSpeed
kann das Laufzeitverhalten der
Funktion beeinflusst werden um eine Optimierung bezüglich Performance und Ressourcenbedarf zu erreichen.
Die für "dumpMySQL clientSide" relevanten Attribute sind:
dumpComment | : User-Kommentar im Dumpfile |
dumpCompress | : Komprimierung des Dumpfiles nach der Erstellung |
dumpDirLocal | : das lokale Zielverzeichnis für die Erstellung des Dump |
dumpMemlimit | : Begrenzung der Speicherverwendung |
dumpSpeed | : Begrenzung die CPU-Belastung |
dumpFilesKeep | : Anzahl der aufzubwahrenden Dumpfiles |
executeBeforeProc | : ausführen FHEM Kommando (oder Perl-Routine) vor dem Dump |
executeAfterProc | : ausführen FHEM Kommando (oder Perl-Routine) nach dem Dump |
optimizeTablesBeforeDump | : Tabelloptimierung vor dem Dump ausführen |
Nach einem erfolgreichen Dump werden alte Dumpfiles gelöscht und nur die Anzahl Files, definiert durch
das Attribut "dumpFilesKeep" (default: 3), verbleibt im Zielverzeichnis "dumpDirLocal". Falls "dumpFilesKeep = 0"
gesetzt ist, werden alle Dumpfiles (auch das aktuell erstellte File), gelöscht.
Diese Einstellung kann sinnvoll sein, wenn FTP aktiviert ist
und die erzeugten Dumps nur im FTP-Zielverzeichnis erhalten bleiben sollen.
Die Namenskonvention der Dumpfiles ist: <dbname>_<date>_<time>.sql[.gzip]
Um die Datenbank aus dem Dumpfile wiederherzustellen kann das Kommmando:
set <name> restoreMySQL <filename>
verwendet werden.
Das erzeugte Dumpfile (unkomprimiert) kann ebenfalls mit:
mysql -u <user> -p <dbname> < <filename>.sql
auf dem MySQL-Server ausgeführt werden um die Datenbank aus dem Dump wiederherzustellen.
Option serverSide
Der Dump wird durch den MySQL-Server erstellt und per default im Home-Verzeichnis des MySQL-Servers
gespeichert.
Es wird die gesamte history-Tabelle (nicht current-Tabelle) im CSV-Format ohne
Einschränkungen exportiert.
Vor dem Dump kann eine Tabellenoptimierung (Attribut "optimizeTablesBeforeDump")
optional zugeschaltet werden .
Achtung !
Um ein Blockieren von FHEM zu vermeiden, muß DbLog im asynchronen Modus betrieben werden wenn die
Tabellenoptimierung verwendet wird !
Vor und nach dem Dump kann ein FHEM-Kommando (siehe Attribute "executeBeforeProc", "executeAfterProc") ausgeführt
werden.
Die für "dumpMySQL serverSide" relevanten Attribute sind:
dumpDirRemote | : das Erstellungsverzeichnis des Dumpfile auf dem entfernten Server |
dumpCompress | : Komprimierung des Dumpfiles nach der Erstellung |
dumpDirLocal | : Directory des lokal gemounteten dumpDirRemote-Verzeichnisses |
dumpFilesKeep | : Anzahl der aufzubwahrenden Dumpfiles |
executeBeforeProc | : ausführen FHEM Kommando (oder Perl-Routine) vor dem Dump |
executeAfterProc | : ausführen FHEM Kommando (oder Perl-Routine) nach dem Dump |
optimizeTablesBeforeDump | : Tabelloptimierung vor dem Dump ausführen |
Das Zielverzeichnis kann mit dem Attribut dumpDirRemote verändert werden.
Es muß sich auf dem MySQL-Host gefinden und durch den MySQL-Serverprozess beschreibbar sein.
Der verwendete Datenbankuser benötigt das FILE Privileg (siehe Wiki).
Hinweis:
Soll die interne Versionsverwaltung und die Dumpfilekompression des Moduls genutzt, sowie die Größe des erzeugten
Dumpfiles ausgegeben werden, ist das Verzeichnis "dumpDirRemote" des MySQL-Servers auf dem Client zu mounten
und im Attribut dumpDirLocal dem DbRep-Device bekannt zu machen.
Gleiches gilt wenn der FTP-Transfer nach dem Dump genutzt werden soll (Attribut "ftpUse" bzw. "ftpUseSSL").
Beispiel:
attr <name> dumpDirRemote /volume1/ApplicationBackup/dumps_FHEM/
attr <name> dumpDirLocal /sds1/backup/dumps_FHEM/
attr <name> dumpFilesKeep 2
# Der Dump wird remote auf dem MySQL-Server im Verzeichnis '/volume1/ApplicationBackup/dumps_FHEM/'
erstellt.
# Die interne Versionsverwaltung sucht im lokal gemounteten Verzeichnis '/sds1/backup/dumps_FHEM/'
vorhandene Dumpfiles und löscht diese bis auf die zwei letzten Versionen.
Wird die interne Versionsverwaltung genutzt, werden nach einem erfolgreichen Dump alte Dumpfiles gelöscht
und nur die Anzahl "dumpFilesKeep" (default: 3) verbleibt im Zielverzeichnis "dumpDirRemote".
FHEM benötigt in diesem Fall Schreibrechte auf dem Verzeichnis "dumpDirLocal".
Die Namenskonvention der Dumpfiles ist: <dbname>_<date>_<time>.csv[.gzip]
Ein Restore der Datenbank aus diesem Backup kann durch den Befehl:
set <name> <restoreMySQL> <filename>.csv[.gzip]
gestartet werden.
FTP Transfer nach Dump
Wenn diese Möglichkeit genutzt werden soll, ist das Attribut ftpUse oder
"ftpUseSSL" zu setzen. Letzteres gilt wenn eine verschlüsselte Übertragung genutzt werden soll.
Das Modul übernimmt ebenfalls die Versionierung der Dumpfiles im FTP-Zielverzeichnis mit Hilfe des Attributes
"ftpDumpFilesKeep".
Für die FTP-Übertragung relevante Attribute sind:
ftpUse | : FTP Transfer nach dem Dump wird eingeschaltet (ohne SSL Verschlüsselung) |
ftpUser | : User zur Anmeldung am FTP-Server, default: anonymous |
ftpUseSSL | : FTP Transfer mit SSL Verschlüsselung nach dem Dump wird eingeschaltet |
ftpDebug | : Debugging des FTP Verkehrs zur Fehlersuche |
ftpDir | : Verzeichnis auf dem FTP-Server in welches das File übertragen werden soll (default: "/") |
ftpDumpFilesKeep | : Es wird die angegebene Anzahl Dumpfiles im <ftpDir> belassen (default: 3) |
ftpPassive | : setzen wenn passives FTP verwendet werden soll |
ftpPort | : FTP-Port, default: 21 |
ftpPwd | : Passwort des FTP-Users, default nicht gesetzt |
ftpServer | : Name oder IP-Adresse des FTP-Servers. notwendig ! |
ftpTimeout | : Timeout für die FTP-Verbindung in Sekunden (default: 30). |
- dumpSQLite - erstellt einen Dump der angeschlossenen SQLite-Datenbank.
Diese Funktion nutzt die SQLite Online Backup API und ermöglicht es konsistente Backups der SQLite-DB
in laufenden Betrieb zu erstellen.
Der Dump wird per default im log-Verzeichnis des FHEM-Rechners gespeichert.
Das Zielverzeichnis kann mit dem dumpDirLocal Attribut verändert werden und muß
durch FHEM beschreibbar sein.
Vor dem Dump kann optional eine Tabellenoptimierung (Attribut "optimizeTablesBeforeDump")
zugeschaltet werden.
Achtung !
Um ein Blockieren von FHEM zu vermeiden, muß DbLog im asynchronen Modus betrieben werden wenn die
Tabellenoptimierung verwendet wird !
Vor und nach dem Dump kann ein FHEM-Kommando (siehe Attribute "executeBeforeProc", "executeAfterProc")
ausgeführt werden.
Die für diese Funktion relevanten Attribute sind:
dumpCompress | : Komprimierung des Dumpfiles nach der Erstellung |
dumpDirLocal | : Zielverzeichnis der Dumpfiles |
dumpFilesKeep | : Anzahl der aufzubwahrenden Dumpfiles |
executeBeforeProc | : ausführen FHEM Kommando (oder Perl-Routine) vor dem Dump |
executeAfterProc | : ausführen FHEM Kommando (oder Perl-Routine) nach dem Dump |
optimizeTablesBeforeDump | : Tabelloptimierung vor dem Dump ausführen |
Nach einem erfolgreichen Dump werden alte Dumpfiles gelöscht und nur die Anzahl Files, definiert durch das
Attribut "dumpFilesKeep" (default: 3), verbleibt im Zielverzeichnis "dumpDirLocal". Falls "dumpFilesKeep = 0" gesetzt, werden
alle Dumpfiles (auch das aktuell erstellte File), gelöscht. Diese Einstellung kann sinnvoll sein, wenn FTP aktiviert ist
und die erzeugten Dumps nur im FTP-Zielverzeichnis erhalten bleiben sollen.
Die Namenskonvention der Dumpfiles ist: <dbname>_<date>_<time>.sqlitebkp[.gzip]
Die Datenbank kann mit "set <name> restoreSQLite <Filename>" wiederhergestellt
werden.
Das erstellte Dumpfile kann auf einen FTP-Server übertragen werden. Siehe dazu die Erläuterungen
unter "dumpMySQL".
- eraseReadings - Löscht alle angelegten Readings im Device, außer dem Reading "state" und Readings, die in der
Ausnahmeliste definiert mit Attribut "readingPreventFromDel" enthalten sind.
- exportToFile [</Pfad/File>] [MAXLINES=<lines>]
- exportiert DB-Einträge im CSV-Format in den gegebenen Zeitgrenzen.
Der Dateiname wird durch das expimpfile Attribut bestimmt.
Alternativ kann "/Pfad/File" als Kommando-Option angegeben werden und übersteuert ein
eventuell gesetztes Attribut "expimpfile". Optional kann über den Parameter "MAXLINES" die
maximale Anzahl von Datensätzen angegeben werden, die in ein File exportiert werden.
In diesem Fall werden mehrere Files mit den Extensions "_part1", "_part2", "_part3" usw.
erstellt (beim Import berücksichtigen !).
Einschränkungen durch die Attribute device bzw.
reading gehen in die Selektion mit ein.
Der Dateiname kann Wildcards enthalten (siehe Attribut "expimpfile").
Durch das Attribut "aggregation" wird der Export der Datensätze in Zeitscheiben der angegebenen Aggregation
vorgenommen. Ist z.B. "aggregation = month" gesetzt, werden die Daten in monatlichen Paketen selektiert und in
das Exportfile geschrieben. Dadurch wird die Hauptspeicherverwendung optimiert wenn sehr große Datenmengen
exportiert werden sollen und vermeidet den "died prematurely" Abbruchfehler.
Die für diese Funktion relevanten Attribute sind:
aggregation | : Festlegung der Selektionspaketierung |
device | : einschließen oder ausschließen von Datensätzen die <device> enthalten |
reading | : einschließen oder ausschließen von Datensätzen die <reading> enthalten |
executeBeforeProc | : FHEM Kommando (oder Perl-Routine) vor dem Export ausführen |
executeAfterProc | : FHEM Kommando (oder Perl-Routine) nach dem Export ausführen |
expimpfile | : der Name des Exportfiles |
time.* | : eine Reihe von Attributen zur Zeitabgrenzung |
valueFilter | : ein zusätzliches REGEXP um die Datenselektion zu steuern. Der REGEXP wird auf das Datenbankfeld 'VALUE' angewendet. |
- fetchrows [history|current]
- liefert alle Tabelleneinträge (default: history)
in den gegebenen Zeitgrenzen bzw. Selektionsbedingungen durch die Attribute
device und reading.
Eine evtl. gesetzte Aggregation wird dabei nicht berücksichtigt.
Die Leserichtung in der Datenbank kann durch das Attribut
fetchRoute bestimmt werden.
Jedes Ergebnisreading setzt sich aus dem Timestring des Datensatzes, einem Dubletten-Index,
dem Device und dem Reading zusammen.
Die Funktion fetchrows ist in der Lage, mehrfach vorkommende Datensätze (Dubletten) zu erkennen.
Solche Dubletten sind mit einem Dubletten-Index > 1 gekennzeichnet. Optional wird noch ein
Unique-Index angehängt, wenn Datensätze mit identischem Timestamp, Device und Reading aber
unterschiedlichem Value vorhanden sind.
Dubletten können mit dem Attribut "fetchMarkDuplicates" farblich hervorgehoben werden.
Hinweis:
Hervorgehobene Readings werden nach einem Restart bzw. nach rereadcfg nicht mehr angezeigt da
sie nicht im statefile gesichert werden (Verletzung erlaubter Readingnamen durch Formatierung).
Dieses Attribut ist mit einigen Farben vorbelegt, kann aber mit dem colorpicker-Widget
überschrieben werden:
attr <name> widgetOverride fetchMarkDuplicates:colorpicker
Die Ergebnisreadings von fetchrows sind nach folgendem Schema aufgebaut:
Beispiel:
2017-10-22_03-04-43__1__SMA_Energymeter__Bezug_WirkP_Kosten_Diff__[1]
# <Datum>_<Zeit>__<Dubletten-Index>__<Device>__<Reading>__[Unique-Index]
Die zur Steuerung von fetchrows relevanten Attribute sind:
device | : einschließen oder ausschließen von Datensätzen die <device> enthalten |
fetchRoute | : Leserichtung der Selektion innerhalb der Datenbank |
fetchMarkDuplicates | : Hervorhebung von gefundenen Dubletten |
fetchValueFn | : der angezeigte Wert des VALUE Datenbankfeldes kann mit einer Funktion vor der Readingerstellung geändert werden |
limit | : begrenzt die Anzahl zu selektierenden bzw. anzuzeigenden Datensätze |
executeBeforeProc | : FHEM Kommando (oder Perl-Routine) vor dem Befehl ausführen |
executeAfterProc | : FHEM Kommando (oder Perl-Routine) nach dem Befehl ausführen |
reading | : einschließen oder ausschließen von Datensätzen die <reading> enthalten |
time.* | : eine Reihe von Attributen zur Zeitabgrenzung |
valueFilter | : filtert die anzuzeigenden Datensätze mit einem regulären Ausdruck (Datenbank spezifischer REGEXP). Der REGEXP wird auf Werte des Datenbankfeldes 'VALUE' angewendet. |
Hinweis:
Auch wenn das Modul bezüglich der Datenbankabfrage nichtblockierend arbeitet, kann eine
zu große Ergebnismenge (Anzahl Zeilen bzw. Readings) die Browsersesssion bzw. FHEMWEB
blockieren. Aus diesem Grund wird die Ergebnismenge mit dem Attribut
limit begrenzt. Bei Bedarf kann dieses Attribut
geändert werden, falls eine Anpassung der Selektionsbedingungen nicht möglich oder
gewünscht ist.
- index <Option>
- Listet die in der Datenbank vorhandenen Indexe auf bzw. legt die benötigten Indexe
an. Ist ein Index bereits angelegt, wird er erneuert (gelöscht und erneut angelegt)
Die möglichen Optionen sind:
list_all | : listet die vorhandenen Indexe auf |
recreate_Search_Idx | : erstellt oder erneuert (falls vorhanden) den Index Search_Idx in Tabelle history (Index für DbLog) |
drop_Search_Idx | : löscht den Index Search_Idx in Tabelle history |
recreate_Report_Idx | : erstellt oder erneuert (falls vorhanden) den Index Report_Idx in Tabelle history (Index für DbRep) |
drop_Report_Idx | : löscht den Index Report_Idx in Tabelle history |
Die für diese Funktion relevanten Attribute sind:
useAdminCredentials | : benutzt einen privilegierten User für die Operation |
Hinweis:
Der verwendete MySQL Datenbank-Nutzer benötigt das ALTER, CREATE und INDEX Privileg.
Diese Rechte können gesetzt werden mit:
set <Name> sqlCmd GRANT INDEX, ALTER, CREATE ON `<db>`.* TO '<user>'@'%';
Das Attribut useAdminCredentials muß gewöhnlich gesetzt sein um
die Rechte des verwendeten Users ändern zu können.
- insert <Datum>,<Zeit>,<Value>,[<Unit>],[<Device>],[<Reading>]
- Manuelles Einfügen eines Datensatzes in die Tabelle "history". Obligatorisch sind Eingabewerte für Datum, Zeit und Value.
Die Werte für die DB-Felder TYPE bzw. EVENT werden mit "manual" gefüllt.
Werden Device, Reading nicht gesetzt, werden diese Werte aus den entsprechenden
Attributen device bzw. reading genommen.
Hinweis:
Nicht belegte Felder innerhalb des insert Kommandos müssen innerhalb des Strings in ","
eingeschlossen werden.
Beispiel:
set <name> insert 2016-08-01,23:00:09,12.03,kW
set <name> insert 2021-02-02,10:50:00,value with space
set <name> insert 2022-05-16,10:55:00,1800,,SMA_Wechselrichter,etotal
set <name> insert 2022-05-16,10:55:00,1800,,,etotal
Die für diese Funktion relevanten Attribute sind:
executeBeforeProc | : FHEM Kommando (oder Perl-Routine) vor dem Befehl ausführen |
executeAfterProc | : FHEM Kommando (oder Perl-Routine) nach dem Befehl ausführen |
- importFromFile [<File>]
- importiert Datensätze im CSV-Format aus einer Datei in die Datenbank.
Der Dateiname wird durch das Attribut expimpfile bestimmt.
Alternativ kann die Datei (/Pfad/Datei) als Kommando-Option angegeben werden und übersteuert ein
eventuell gesetztes Attribut "expimpfile". Der Dateiname kann Wildcards enthalten (siehe
Attribut "expimpfile").
Datensatzformat:
"TIMESTAMP","DEVICE","TYPE","EVENT","READING","VALUE","UNIT"
# Die Felder "TIMESTAMP","DEVICE","TYPE","EVENT","READING" und "VALUE" müssen gesetzt sein. Das Feld "UNIT" ist optional.
Der Fileinhalt wird als Transaktion importiert, d.h. es wird der Inhalt des gesamten Files oder, im Fehlerfall, kein Datensatz des Files importiert.
Wird eine umfangreiche Datei mit vielen Datensätzen importiert, sollte KEIN verbose=5 gesetzt werden. Es würden in diesem Fall sehr viele Sätze in
das Logfile geschrieben werden was FHEM blockieren oder überlasten könnte.
Beispiel:
"2016-09-25 08:53:56","STP_5000","SMAUTILS","etotal: 11859.573","etotal","11859.573",""
Die für diese Funktion relevanten Attribute sind:
executeBeforeProc | : FHEM Kommando (oder Perl-Routine) vor dem Import ausführen |
executeAfterProc | : FHEM Kommando (oder Perl-Routine) nach dem Import ausführen |
expimpfile | : der Name des Importfiles |
- maxValue [display | writeToDB | deleteOther]
Berechnet den Maximalwert des Datenbankfelds "VALUE" in den Zeitgrenzen
(Attribute) "timestamp_begin", "timestamp_end" bzw. "timeDiffToNow / timeOlderThan" etc.
Es muss das auszuwertende Reading über das Attribut reading
angegeben sein.
Die Auswertung enthält den Zeitstempel des ermittelten Maximumwertes innerhalb der
Aggregation bzw. Zeitgrenzen.
Im Reading wird der Zeitstempel des letzten Auftretens vom Maximalwert ausgegeben,
falls dieser Wert im Intervall mehrfach erreicht wird.
Ist keine oder die Option display angegeben, werden die Ergebnisse nur angezeigt. Mit
der Option writeToDB werden die Berechnungsergebnisse mit einem neuen Readingnamen
in der Datenbank gespeichert.
Der neue Readingname wird aus einem Präfix und dem originalen Readingnamen gebildet,
wobei der originale Readingname durch das Attribut readingNameMap ersetzt werden kann.
Der Präfix setzt sich aus der Bildungsfunktion und der Aggregation zusammen.
Der Timestamp des neuen Readings in der Datenbank wird von der eingestellten Aggregationsperiode
abgeleitet.
Das Feld "EVENT" wird mit "calculated" gefüllt.
Wird die Option deleteOther verwendet, werden alle Datensätze außer dem Datensatz mit dem
ermittelten Maximalwert aus der Datenbank innerhalb der definierten Grenzen gelöscht.
Beispiel neuer Readingname gebildet aus dem Originalreading "totalpac":
max_day_totalpac
# <Bildungsfunktion>_<Aggregation>_<Originalreading>
Relevante Attribute sind:
- migrateCollation <Collation>
Migriert den verwendeten Zeichensatz/Kollation der Datenbank und der Tabellen current und history in das
angegebene Format.
Relevante Attribute sind:
- minValue [display | writeToDB | deleteOther]
Berechnet den Minimalwert des Datenbankfelds "VALUE" in den Zeitgrenzen
(Attribute) "timestamp_begin", "timestamp_end" bzw. "timeDiffToNow / timeOlderThan" etc.
Es muss das auszuwertende Reading über das Attribut reading
angegeben sein.
Die Auswertung enthält den Zeitstempel des ermittelten Minimumwertes innerhalb der
Aggregation bzw. Zeitgrenzen.
Im Reading wird der Zeitstempel des ersten Auftretens vom Minimalwert ausgegeben
falls dieser Wert im Intervall mehrfach erreicht wird.
Ist keine oder die Option display angegeben, werden die Ergebnisse nur angezeigt. Mit
der Option writeToDB werden die Berechnungsergebnisse mit einem neuen Readingnamen
in der Datenbank gespeichert.
Der neue Readingname wird aus einem Präfix und dem originalen Readingnamen gebildet,
wobei der originale Readingname durch das Attribut readingNameMap ersetzt werden kann.
Der Präfix setzt sich aus der Bildungsfunktion und der Aggregation zusammen.
Der Timestamp der neuen Readings in der Datenbank wird von der eingestellten Aggregationsperiode
abgeleitet.
Das Feld "EVENT" wird mit "calculated" gefüllt.
Wird die Option deleteOther verwendet, werden alle Datensätze außer dem Datensatz mit dem
ermittelten Maximalwert aus der Datenbank innerhalb der definierten Grenzen gelöscht.
Beispiel neuer Readingname gebildet aus dem Originalreading "totalpac":
min_day_totalpac
# <Bildungsfunktion>_<Aggregation>_<Originalreading>
Relevante Attribute sind:
- optimizeTables [showInfo | execute]
Optimiert die Tabellen in der angeschlossenen Datenbank (MySQL).
showInfo | : zeigt Informationen zum belegten / freien Speicherplatz innerhalb der Datenbank |
execute | : führt die Optimierung aller Tabellen in der Datenbank aus |
Relevante Attribute sind:
- readingRename <[Device:]alterReadingname>,<neuerReadingname>
Benennt den Namen eines Readings innerhalb der angeschlossenen Datenbank (siehe Internal DATABASE) um.
Der Readingname wird immer in der gesamten Datenbank umgesetzt. Eventuell
gesetzte Zeitgrenzen oder Beschränkungen durch die Attribute
device bzw. reading werden nicht berücksichtigt.
Optional kann eine Device angegeben werden. In diesem Fall werden nur die alten Readings
dieses Devices in den neuen Readingnamen umgesetzt.
Beispiele:
set <name> readingRename TotalConsumption,L1_TotalConsumption
set <name> readingRename Dum.Energy:TotalConsumption,L1_TotalConsumption
Die Anzahl der umbenannten Device-Datensätze wird im Reading "reading_renamed" ausgegeben.
Wird der umzubenennende Readingname in der Datenbank nicht gefunden, wird eine WARNUNG im Reading
"reading_not_renamed" ausgegeben.
Entsprechende Einträge erfolgen auch im Logfile mit verbose=3.
Für diese Funktion sind folgende Attribute relevant:
Relevante Attribute sind:
- reduceLog [<no>[:<nn>]] [mode] [EXCLUDE=device1:reading1,device2:reading2,...] [INCLUDE=device:reading]
Reduziert historische Datensätze.
Arbeitsweise ohne Angabe von Befehlszeilenoperatoren
Es werden die Daten innerhalb der durch die time.*-Attribute bestimmten Zeitgrenzen bereinigt.
Es muss mindestens eines der time.*-Attribute gesetzt sein (siehe Tabelle unten).
Die jeweils fehlende Zeitabgrenzung wird in diesem Fall durch das Modul ermittelt.
Der Arbeitsmodus wird durch die optionale Angabe von mode bestimmt:
ohne Angabe von mode | : die Daten werden auf den ersten Eintrag pro Stunde je Device & Reading reduziert |
average | : numerische Werte werden auf einen Mittelwert pro Stunde je Device & Reading reduziert, sonst wie ohne mode |
average=day | : numerische Werte werden auf einen Mittelwert pro Tag je Device & Reading reduziert, sonst wie ohne mode |
| Die FullDay-Option (es werden immer volle Tage selektiert) wird impliziert verwendet. |
max | : numerische Werte werden auf den Maximalwert pro Stunde je Device & Reading reduziert, sonst wie ohne mode |
max=day | : numerische Werte werden auf den Maximalwert pro Tag je Device & Reading reduziert, sonst wie ohne mode |
| Die FullDay-Option (es werden immer volle Tage selektiert) wird impliziert verwendet. |
min | : numerische Werte werden auf den Minimalwert pro Stunde je Device & Reading reduziert, sonst wie ohne mode |
min=day | : numerische Werte werden auf den Minimalwert pro Tag je Device & Reading reduziert, sonst wie ohne mode |
| Die FullDay-Option (es werden immer volle Tage selektiert) wird impliziert verwendet. |
sum | : numerische Werte werden auf die Summe pro Stunde je Device & Reading reduziert, sonst wie ohne mode |
sum=day | : numerische Werte werden auf die Summe pro Tag je Device & Reading reduziert, sonst wie ohne mode |
| Die FullDay-Option (es werden immer volle Tage selektiert) wird impliziert verwendet. |
Mit den Attributen device und reading können die zu berücksichtigenden Datensätze eingeschlossen
bzw. ausgeschlossen werden. Beide Eingrenzungen reduzieren die selektierten Daten und verringern den
Ressourcenbedarf.
Das Reading "reduceLogState" enthält das Ausführungsergebnis des letzten reduceLog-Befehls.
Relevante Attribute sind:
executeBeforeProc,
executeAfterProc,
device,
reading,
numDecimalPlaces,
timeOlderThan,
timeDiffToNow,
timestamp_begin,
timestamp_end,
valueFilter,
userExitFn
Beispiele:
attr <name> timeOlderThan d:200
set <name> reduceLog
# Datensätze die älter als 200 Tage sind, werden auf den ersten Eintrag pro Stunde je Device & Reading
reduziert.
attr <name> timeDiffToNow d:200
set <name> reduceLog average=day
# Datensätze die neuer als 200 Tage sind, werden auf einen Eintrag pro Tag je Device & Reading
reduziert.
attr <name> timeDiffToNow d:30
attr <name> device TYPE=SONOSPLAYER EXCLUDE=Sonos_Kueche
attr <name> reading room% EXCLUDE=roomNameAlias
set <name> reduceLog
# Datensätze die neuer als 30 Tage sind, die Devices vom Typ SONOSPLAYER sind
(außer Device "Sonos_Kueche"), die Readings mit "room" beginnen (außer "roomNameAlias"),
werden auf den ersten Eintrag pro Stunde je Device & Reading reduziert.
attr <name> timeDiffToNow d:10
attr <name> timeOlderThan d:5
attr <name> device Luftdaten_remote
set <name> reduceLog average
# Datensätze die älter als 5 und neuer als 10 Tage sind und DEVICE "Luftdaten_remote" enthalten,
werden bereinigt. Numerische Werte einer Stunde werden auf einen Mittelwert reduziert
Arbeitsweise mit Angabe von Befehlszeilenoperatoren
Es werden Datensätze berücksichtigt die älter sind als <no> Tage und (optional) neuer sind als
<nn> Tage.
Der Arbeitsmodus wird durch die optionale Angabe von mode wie oben beschrieben bestimmt.
Die Zusätze "EXCLUDE" bzw. "INCLUDE" können ergänzt werden um device/reading Kombinationen in reduceLog auszuschließen
bzw. einzuschließen und überschreiben die Einstellung der Attribute "device" und "reading", die in diesem Fall
nicht beachtet werden.
Die Angabe in "EXCLUDE" wird als Regex ausgewertet. Innerhalb von "INCLUDE" können SQL-Wildcards
verwendet werden (weitere Informationen zu SQL-Wildcards siehe mit get <name> versionNotes 6).
Beispiele:
set <name> reduceLog 174:180 average EXCLUDE=SMA_Energymeter:Bezug_Wirkleistung INCLUDE=SMA_Energymeter:%
# Datensätze älter als 174 und neuer als 180 Tage werden auf den Durchschnitt pro Stunde reduziert.
# Es werden alle Readings vom Device "SMA_Energymeter" außer "Bezug_Wirkleistung" berücksichtigt.
reduziert.
Hinweis:
Obwohl die Funktion selbst non-blocking ausgelegt ist, sollte das zugeordnete DbLog-Device
im asynchronen Modus betrieben werden um ein Blockieren von FHEMWEB zu vermeiden
(Tabellen-Lock).
Weiterhin wird dringend empfohlen den standard INDEX 'Search_Idx' in der Tabelle 'history'
anzulegen !
Die Abarbeitung dieses Befehls dauert unter Umständen (ohne INDEX) extrem lange.
- repairSQLite [sec]
Repariert eine korrupte SQLite-Datenbank.
Eine Korruption liegt im Allgemeinen vor, wenn die Fehlermitteilung "database disk image is malformed"
im state des DbLog-Devices erscheint.
Wird dieses Kommando gestartet, wird das angeschlossene DbLog-Device zunächst automatisch für 10 Stunden
(36000 Sekunden) von der Datenbank getrennt (Trennungszeit). Nach Abschluss der Reparatur erfolgt
wieder eine sofortige Neuverbindung zur reparierten Datenbank.
Dem Befehl kann eine abweichende Trennungszeit (in Sekunden) als Argument angegeben werden.
Die korrupte Datenbank wird als <database>.corrupt im gleichen Verzeichnis gespeichert.
Relevante Attribute sind:
Beispiel:
set <name> repairSQLite
# Die Datenbank wird repariert, Trennungszeit beträgt 10 Stunden
set <name> repairSQLite 600
# Die Datenbank wird repariert, Trennungszeit beträgt 10 Minuten
Hinweis:
Es ist nicht garantiert, dass die Reparatur erfolgreich verläuft und keine Daten verloren gehen.
Je nach Schwere der Korruption kann Datenverlust auftreten oder die Reparatur scheitern, auch wenn
kein Fehler im Ablauf signalisiert wird. Ein Backup der Datenbank sollte unbedingt vorhanden
sein!
- restoreMySQL <File>
Stellt die Datenbank aus einem serverSide- oder clientSide-Dump wieder her.
Die Funktion stellt über eine Drop-Down Liste eine Dateiauswahl für den Restore zur Verfügung.
Verwendung eines serverSide-Dumps
Der verwendete Datenbankuser benötigt das FILE Privileg (siehe Wiki).
Es wird der Inhalt der history-Tabelle aus einem serverSide-Dump wiederhergestellt.
Dazu ist das Verzeichnis "dumpDirRemote" des MySQL-Servers auf dem Client zu mounten
und im Attribut dumpDirLocal dem DbRep-Device bekannt zu machen.
Es werden alle Files mit der Endung "csv[.gzip]" und deren Name mit der
verbundenen Datenbank beginnt (siehe Internal DATABASE), aufgelistet.
Verwendung eines clientSide-Dumps
Es werden alle Tabellen und eventuell vorhandenen Views wiederhergestellt.
Das Verzeichnis, in dem sich die Dump-Files befinden, ist im Attribut dumpDirLocal dem
DbRep-Device bekannt zu machen.
Es werden alle Files mit der Endung "sql[.gzip]" und deren Name mit der
verbundenen Datenbank beginnt (siehe Internal DATABASE), aufgelistet.
Die Geschwindigkeit des Restores ist abhängig von der Servervariable "max_allowed_packet". Durch Veränderung
dieser Variable im File my.cnf kann die Geschwindigkeit angepasst werden. Auf genügend verfügbare Ressourcen (insbesondere
RAM) ist dabei zu achten.
Der Datenbankuser benötigt Rechte zum Tabellenmanagement, z.B.:
CREATE, ALTER, INDEX, DROP, SHOW VIEW, CREATE VIEW
Relevante Attribute sind:
- restoreSQLite <File>.sqlitebkp[.gzip]
Stellt das Backup einer SQLite-Datenbank wieder her.
Die Funktion stellt über eine Drop-Down Liste die für den Restore zur Verfügung stehenden Dateien
zur Verfügung. Die aktuell in der Zieldatenbank enthaltenen Daten werden gelöscht bzw.
überschrieben.
Es werden alle Files mit der Endung "sqlitebkp[.gzip]" und deren Name mit dem Namen der
verbundenen Datenbank beginnt, aufgelistet.
Relevante Attribute sind:
- sqlCmd
Führt ein beliebiges benutzerspezifisches Kommando aus.
Enthält dieses Kommando eine Delete-Operation, muss zur Sicherheit das Attribut
allowDeletion gesetzt sein.
sqlCmd akzeptiert ebenfalls das Setzen von SQL Session Variablen wie z.B.
"SET @open:=NULL, @closed:=NULL;" oder die Verwendung von SQLite PRAGMA vor der
Ausführung des SQL-Statements.
Soll die Session Variable oder das PRAGMA vor jeder Ausführung eines SQL Statements
gesetzt werden, kann dafür das Attribut sqlCmdVars
verwendet werden.
Sollen die im Modul gesetzten Attribute device, reading,
timestamp_begin bzw.
timestamp_end im Statement berücksichtigt werden, können die Platzhalter
§device§, §reading§, §timestamp_begin§ bzw.
§timestamp_end§ eingesetzt werden.
Dabei ist zu beachten, dass die Platzhalter §device§ und §reading§ komplex aufgelöst werden
und dementsprechend wie im unten stehenden Beispiel anzuwenden sind.
Soll ein Datensatz upgedated werden, ist dem Statement "TIMESTAMP=TIMESTAMP" hinzuzufügen um eine Änderung des
originalen Timestamps zu verhindern.
Beispiele für Statements:
- set <name> sqlCmd select DEVICE, count(*) from history where TIMESTAMP >= "2017-01-06 00:00:00" group by DEVICE having count(*) > 800
- set <name> sqlCmd select DEVICE, count(*) from history where TIMESTAMP >= "2017-05-06 00:00:00" group by DEVICE
- set <name> sqlCmd select DEVICE, count(*) from history where TIMESTAMP >= §timestamp_begin§ group by DEVICE
- set <name> sqlCmd select * from history where DEVICE like "Te%t" order by `TIMESTAMP` desc
- set <name> sqlCmd select * from history where `TIMESTAMP` > "2017-05-09 18:03:00" order by `TIMESTAMP` desc
- set <name> sqlCmd select * from current order by `TIMESTAMP` desc
- set <name> sqlCmd select sum(VALUE) as 'Einspeisung am 04.05.2017', count(*) as 'Anzahl' FROM history where `READING` = "Einspeisung_WirkP_Zaehler_Diff" and TIMESTAMP between '2017-05-04' AND '2017-05-05'
- set <name> sqlCmd delete from current
- set <name> sqlCmd delete from history where TIMESTAMP < "2016-05-06 00:00:00"
- set <name> sqlCmd update history set TIMESTAMP=TIMESTAMP,VALUE='Val' WHERE VALUE='TestValue'
- set <name> sqlCmd select * from history where DEVICE = "Test"
- set <name> sqlCmd insert into history (TIMESTAMP, DEVICE, TYPE, EVENT, READING, VALUE, UNIT) VALUES ('2017-05-09 17:00:14','Test','manuell','manuell','Tes§e','TestValue','°C')
- set <name> sqlCmd select DEVICE, count(*) from history where §device§ AND TIMESTAMP >= §timestamp_begin§ group by DEVICE
- set <name> sqlCmd select DEVICE, READING, count(*) from history where §device§ AND §reading§ AND TIMESTAMP >= §timestamp_begin§ group by DEVICE, READING
Nachfolgend Beispiele für ein komplexeres Statement (MySQL) unter Mitgabe von
SQL Session Variablen und die SQLite PRAGMA-Verwendung:
- set <name> sqlCmd SET @open:=NULL, @closed:=NULL;
SELECT
TIMESTAMP, VALUE,DEVICE,
@open AS open,
@open := IF(VALUE = 'open', TIMESTAMP, NULL) AS curr_open,
@closed := IF(VALUE = 'closed', TIMESTAMP, NULL) AS closed
FROM history WHERE
DATE(TIMESTAMP) = CURDATE() AND
DEVICE = "HT_Fensterkontakt" AND
READING = "state" AND
(VALUE = "open" OR VALUE = "closed")
ORDER BY TIMESTAMP;
- set <name> sqlCmd PRAGMA temp_store=MEMORY; PRAGMA synchronous=FULL; PRAGMA journal_mode=WAL; PRAGMA cache_size=4000; select count(*) from history;
- set <name> sqlCmd PRAGMA temp_store=FILE; PRAGMA temp_store_directory = '/opt/fhem/'; VACUUM;
Die Ergebnis-Formatierung kann durch das Attribut sqlResultFormat ausgewählt,
sowie der verwendete Feldtrenner durch das Attribut sqlResultFieldSep
festgelegt werden.
Das Modul stellt optional eine Kommando-Historie zur Verfügung sobald ein SQL-Kommando erfolgreich
ausgeführt wurde.
Um diese Option zu nutzen, ist das Attribut sqlCmdHistoryLength mit der
gewünschten Listenlänge zu aktivieren.
Ist die Kommando-Historie aktiviert, ist mit ___list_sqlhistory___ innerhalb des Kommandos
sqlCmdHistory eine indizierte Liste der gespeicherten SQL-Statements verfügbar.
Ein SQL-Statement kann durch Angabe seines Index im ausgeführt werden mit:
set <name> sqlCmd ckey:<Index> (e.g. ckey:4)
Relevante Attribute sind:
Hinweis:
Auch wenn das Modul bezüglich der Datenbankabfrage nichtblockierend arbeitet, kann eine
zu große Ergebnismenge (Anzahl Zeilen bzw. Readings) die Browsersesssion bzw. FHEMWEB
blockieren.
Wenn man sich unsicher ist, sollte man vorsorglich dem Statement ein Limit
hinzufügen.
- sqlCmdHistory
Wenn mit dem Attribut sqlCmdHistoryLength aktiviert, kann
ein gespeichertes SQL-Statement aus einer Liste ausgewählt und ausgeführt werden.
Der SQL Cache wird beim Beenden von FHEM automatisch gesichert und beim Start des Systems wiederhergestellt.
Mit den nachfolgenden Einträgen werden spezielle Funktionen ausgeführt:
___purge_sqlhistory___ | : löscht den History Cache |
___list_sqlhistory___ | : zeigt die aktuell im Cache vorhandenen SQL-Statements incl. ihrem Cache Key (ckey) |
___save_sqlhistory___ | : sichert den History Cache manuell |
___restore_sqlhistory___ | : stellt die letzte Sicherung des History Cache wieder her |
Relevante Attribute sind:
- sqlSpecial
Die Funktion bietet eine Drop-Downliste mit einer Auswahl vorbereiter Auswertungen
an.
Das Ergebnis des Statements wird im Reading "SqlResult" dargestellt.
Die Ergebnis-Formatierung kann durch das Attribut sqlResultFormat
ausgewählt, sowie der verwendete Feldtrenner durch das Attribut sqlResultFieldSep
festgelegt werden.
50mostFreqLogsLast2days | ermittelt die 50 am häufigsten vorkommenden Loggingeinträge der letzten 2 Tage |
allDevCount | alle in der Datenbank vorkommenden Devices und deren Anzahl |
allDevReadCount | alle in der Datenbank vorkommenden Device/Reading-Kombinationen und deren Anzahl |
50DevReadCount | die 50 am häufigsten in der Datenbank enthaltenen Device/Reading-Kombinationen |
recentReadingsOfDevice | ermittelt die neuesten in der Datenbank vorhandenen Datensätze eines Devices. Das auszuwertende |
| Device muß im Attribut device definiert sein. |
readingsDifferenceByTimeDelta | ermittelt die Wertedifferenz aufeinanderfolgender Datensätze eines Readings. Das auszuwertende |
| Device und Reading muß im Attribut device bzw. reading definiert sein. |
| Die Zeitgrenzen der Auswertung werden durch die time.*-Attribute festgelegt. |
Relevante Attribute sind:
- sumValue [display | writeToDB | writeToDBSingle | writeToDBInTime]
Berechnet die Summenwerte des Datenbankfelds "VALUE" in den Zeitgrenzen
der möglichen time.*-Attribute.
Es muss das auszuwertende Reading im Attribut reading
angegeben sein.
Diese Funktion ist sinnvoll wenn fortlaufend Wertedifferenzen eines
Readings in die Datenbank geschrieben werden.
Ist keine oder die Option display angegeben, werden die Ergebnisse nur angezeigt.
Mit den Optionen writeToDB, writeToDBSingle bzw. writeToDBInTime werden die
Berechnungsergebnisse mit einem neuen Readingnamen in der Datenbank gespeichert.
writeToDB | : schreibt jeweils einen Wert mit den Zeitstempeln XX:XX:01 und XX:XX:59 innerhalb der jeweiligen Auswertungsperiode |
writeToDBSingle | : schreibt nur einen Wert mit dem Zeitstempel XX:XX:59 am Ende einer Auswertungsperiode |
writeToDBInTime | : schreibt jeweils einen Wert am Anfang und am Ende der Zeitgrenzen einer Auswertungsperiode |
Der neue Readingname wird aus einem Präfix und dem originalen Readingnamen gebildet,
wobei der originale Readingname durch das Attribut "readingNameMap" ersetzt werden kann.
Der Präfix setzt sich aus der Bildungsfunktion und der Aggregation zusammen.
Der Timestamp der neuen Readings in der Datenbank wird von der eingestellten Aggregationsperiode abgeleitet,
sofern kein eindeutiger Zeitpunkt des Ergebnisses bestimmt werden kann.
Das Feld "EVENT" wird mit "calculated" gefüllt.
Beispiel neuer Readingname gebildet aus dem Originalreading "totalpac":
sum_day_totalpac
# <Bildungsfunktion>_<Aggregation>_<Originalreading>
Relevante Attribute sind:
- syncStandby <DbLog-Device Standby>
Es werden die Datensätze aus der angeschlossenen Datenbank (Quelle) direkt in eine weitere
Datenbank (Standby-Datenbank) übertragen.
Dabei ist "<DbLog-Device Standby>" das DbLog-Device, welches mit der Standby-Datenbank
verbunden ist.
Es werden alle Datensätze übertragen, die durch das timestamp_begin Attribut
bzw. die Attribute "device", "reading" bestimmt sind.
Die Datensätze werden dabei in Zeitscheiben entsprechend der eingestellten Aggregation übertragen.
Hat das Attribut "aggregation" den Wert "no" oder "month", werden die Datensätze automatisch
in Tageszeitscheiben zur Standby-Datenbank übertragen.
Quell- und Standby-Datenbank können unterschiedlichen Typs sein.
Relevante Attribute sind:
- tableCurrentFillup
Die current-Tabelle wird mit einem Extrakt der history-Tabelle aufgefüllt.
Die Attribute zur Zeiteinschränkung bzw. device, reading werden ausgewertet.
Dadurch kann der Inhalt des Extrakts beeinflusst werden.
Im zugehörigen DbLog-Device sollte das Attribut "DbLogType=SampleFill/History" gesetzt sein.
Relevante Attribute sind:
- tableCurrentPurge
Löscht den Inhalt der current-Tabelle.
Es werden keine Limitierungen, z.B. durch die Attribute timestamp_begin,
timestamp_end, device oder reading ausgewertet.
Relevante Attribute sind:
- vacuum
Optimiert die Tabellen in der angeschlossenen Datenbank (SQLite, PostgreSQL).
Insbesondere für SQLite Datenbanken ist unbedingt empfehlenswert die Verbindung des relevanten DbLog-Devices zur
Datenbank vorübergehend zu schließen (siehe DbLog reopen Kommando).
Relevante Attribute sind:
Hinweis:
Bei der Ausführung des vacuum Kommandos wird bei SQLite Datenbanken automatisch das PRAGMA auto_vacuum = FULL
angewendet.
Das vacuum Kommando erfordert zusätzlichen temporären Speicherplatz. Sollte der Platz im Standard TMPDIR Verzeichnis
nicht ausreichen, kann SQLite durch setzen der Umgebungsvariable SQLITE_TMPDIR ein ausreichend großes Verzeichnis
zugewiesen werden.
(siehe: www.sqlite.org/tempfiles)
Get
Die Get-Kommandos von DbRep dienen dazu eine Reihe von Metadaten der verwendeten Datenbankinstanz abzufragen.
Dies sind zum Beispiel eingestellte Serverparameter, Servervariablen, Datenbankstatus- und Tabelleninformationen. Die verfügbaren get-Funktionen
sind von dem verwendeten Datenbanktyp abhängig. So ist für SQLite z.Zt. nur "svrinfo" verfügbar. Die Funktionen liefern nativ sehr viele Ausgabewerte,
die über über funktionsspezifische Attribute abgrenzbar sind. Der Filter ist als kommaseparierte Liste anzuwenden.
Dabei kann SQL-Wildcard (%) verwendet werden.
Hinweis:
Nach der Ausführung einer get-Funktion in der Detailsicht einen Browserrefresh durchführen um die Ergebnisse zu sehen !
- blockinginfo - Listet die aktuell systemweit laufenden Hintergrundprozesse (BlockingCalls) mit ihren Informationen auf.
Zu lange Zeichenketten (z.B. Argumente) werden gekürzt ausgeschrieben.
- dbstatus - Listet globale Informationen zum MySQL Serverstatus (z.B. Informationen zum Cache, Threads, Bufferpools, etc. ).
Es werden zunächst alle verfügbaren Informationen berichtet. Mit dem Attribut showStatus kann die
Ergebnismenge eingeschränkt werden, um nur gewünschte Ergebnisse abzurufen. Detailinformationen zur Bedeutung der einzelnen Readings
sind hier verfügbar.
Beispiel
attr <name> showStatus %uptime%,%qcache%
get <name> dbstatus
# Es werden nur Readings erzeugt die im Namen "uptime" und "qcache" enthaltenen
- dbvars - Zeigt die globalen Werte der MySQL Systemvariablen. Enthalten sind zum Beispiel Angaben zum InnoDB-Home, dem Datafile-Pfad,
Memory- und Cache-Parameter, usw. Die Ausgabe listet zunächst alle verfügbaren Informationen auf. Mit dem Attribut
showVariables kann die Ergebnismenge eingeschränkt werden um nur gewünschte Ergebnisse
abzurufen. Weitere Informationen zur Bedeutung der ausgegebenen Variablen sind
hier verfügbar.
Beispiel
attr <name> showVariables %version%,%query_cache%
get <name> dbvars
# Es werden nur Readings erzeugt die im Namen "version" und "query_cache" enthalten
- initData - Ermittelt einige für die Funktion des Moduls relevante Datenbankeigenschaften.
Der Befehl wird bei der ersten Datenbankverbindung implizit ausgeführt.
- minTimestamp - Ermittelt den Zeitstempel des ältesten Datensatzes in der Datenbank (wird implizit beim Start von
FHEM ausgeführt).
Der Zeitstempel wird als Selektionsbeginn verwendet wenn kein Zeitattribut den Selektionsbeginn
festlegt.
- procinfo - Listet die existierenden Datenbank-Prozesse in einer Tabelle auf (nur MySQL).
Typischerweise werden nur die Prozesse des Verbindungsusers (angegeben in DbLog-Konfiguration)
ausgegeben. Sollen alle Prozesse angezeigt werden, ist dem User das globale Recht "PROCESS"
einzuräumen.
Für bestimmte SQL-Statements wird seit MariaDB 5.3 ein Fortschrittsreporting (Spalte "PROGRESS")
ausgegeben. Zum Beispiel kann der Abarbeitungsgrad bei der Indexerstellung verfolgt werden.
Weitere Informationen sind
hier verfügbar.
- sqlCmdBlocking <SQL-Statement>
Führt das angegebene SQL-Statement blockierend mit einem Standardtimeout von 10 Sekunden aus.
Der Timeout kann mit dem Attribut timeout eingestellt werden.
Beispiele:
{ fhem("get <name> sqlCmdBlocking select device,count(*) from history where timestamp > '2018-04-01' group by device") }
{ CommandGet(undef,"Rep.LogDB1 sqlCmdBlocking select device,count(*) from history where timestamp > '2018-04-01' group by device") }
get <name> sqlCmdBlocking select device,count(*) from history where timestamp > '2018-04-01' group by device
Diese Funktion ist durch ihre Arbeitsweise speziell für den Einsatz in benutzerspezifischen Scripten geeignet.
Die Eingabe akzeptiert Mehrzeiler und gibt ebenso mehrzeilige Ergebisse zurück.
Dieses Kommando akzeptiert ebenfalls das Setzen von SQL Session Variablen wie z.B.
"SET @open:=NULL, @closed:=NULL;" oder PRAGMA für SQLite.
Werden mehrere Felder selektiert und zurückgegeben, erfolgt die Feldtrennung mit dem Trenner
des Attributs sqlResultFieldSep (default "|"). Mehrere Ergebniszeilen
werden mit Newline ("\n") separiert.
Diese Funktion setzt/aktualisiert nur Statusreadings, die Funktion im Attribut "userExitFn"
wird nicht aufgerufen.
Erstellt man eine kleine Routine in 99_myUtils, wie z.B.:
sub dbval {
my $name = shift;
my $cmd = shift;
my $ret = CommandGet(undef,"$name sqlCmdBlocking $cmd");
return $ret;
}
kann sqlCmdBlocking vereinfacht verwendet werden mit Aufrufen wie:
Beispiele:
{ dbval("<name>","select count(*) from history") }
oder
$ret = dbval("<name>","select count(*) from history");
storedCredentials - Listet die im Device gespeicherten User / Passworte für den Datenbankzugriff auf.
(nur gültig bei Datenbanktyp MYSQL)
svrinfo - allgemeine Datenbankserver-Informationen wie z.B. die DBMS-Version, Serveradresse und Port usw. Die Menge der Listenelemente
ist vom Datenbanktyp abhängig. Mit dem Attribut showSvrInfo kann die Ergebnismenge eingeschränkt werden.
Weitere Erläuterungen zu den gelieferten Informationen sind
hier zu finden.
Beispiel
attr <name> showSvrInfo %SQL_CATALOG_TERM%,%NAME%
get <name> svrinfo
# Es werden nur Readings erzeugt die im Namen "SQL_CATALOG_TERM" und "NAME" enthalten
tableinfo - ruft Tabelleninformationen aus der mit dem DbRep-Device verbundenen Datenbank ab (MySQL).
Es werden per default alle in der verbundenen Datenbank angelegten Tabellen ausgewertet.
Mit dem Attribut showTableInfo können die Ergebnisse eingeschränkt werden. Erläuterungen zu den erzeugten
Readings sind hier zu finden.
Beispiel
attr <name> showTableInfo current,history
get <name> tableinfo
# Es werden nur Information der Tabellen "current" und "history" angezeigt
versionNotes [hints | rel | <key>] -
Zeigt Release Informationen und/oder Hinweise zum Modul an.
rel | : zeigt nur Release Informationen |
hints | : zeigt nur Hinweise an |
<key> | : es wird der Hinweis mit der angegebenen Nummer angezeigt |
Sind keine Optionen angegeben, werden sowohl Release Informationen als auch Hinweise angezeigt.
Es sind nur Release Informationen mit Bedeutung für den Modulnutzer enthalten.
Attribute
Über die modulspezifischen Attribute wird die Abgrenzung der Auswertung und die Aggregation der Werte gesteuert.
Die hier aufgeführten Attribute sind nicht für jede Funktion des Moduls bedeutsam. In der Hilfe zu den set/get-Kommandos
wird explizit angegeben, welche Attribute für das jeweilige Kommando relevant sind.
Hinweis zur SQL-Wildcard Verwendung:
Innerhalb der Attribut-Werte für "device" und "reading" kann SQL-Wildcards "%" angegeben werden.
Dabei wird "%" als Platzhalter für beliebig viele Zeichen verwendet.
Das Zeichen "_" wird nicht als SQL-Wildcard supported.
Dies gilt für alle Funktionen ausser "insert", "importFromFile" und "deviceRename".
Die Funktion "insert" erlaubt nicht, dass die genannten Attribute das Wildcard "%" enthalten. Character "_" wird als normales Zeichen gewertet.
In Ergebnis-Readings wird das Wildcardzeichen "%" durch "/" ersetzt um die Regeln für erlaubte Zeichen in Readings einzuhalten.
- aggregation - Zusammenfassung der Device/Reading-Selektionen in Stunden, Tagen, Kalenderwochen, Kalendermonaten, Kalenderjahren
oder "no".
Liefert z.B. die Anzahl der DB-Einträge am Tag (countEntries) oder die Summierung von
Differenzwerten eines Readings (sumValue) usw.
Mit Aggregation "no" (default) wird das Ergebnis aus allen Werten einer Device/Reading-Kombination im
selektierten Zeitraum ermittelt.
- allowDeletion - schaltet die Löschfunktion des Moduls frei
- autoForward - wenn aktiviert, werden die Ergebnisreadings einer Funktion in ein oder mehrere Devices
übertragen.
Die Definition erfolgt in der Form:
{
"<source-reading> => "<dest.device> [=> <dest.-reading>]",
"<source-reading> => "<dest.device> [=> <dest.-reading>]",
...
}
In der Angabe <source-reading> sind Wildcards (.*) erlaubt.
{
".*" => "Dum.Rep.All",
".*AVGAM.*" => "Dum.Rep => average",
".*SUM.*" => "Dum.Rep.Sum => summary",
}
# alle Readings werden zum Device "Dum.Rep.All" übertragen, Readingname bleibt im Ziel erhalten
# Readings mit "AVGAM" im Namen werden zum Device "Dum.Rep" in das Reading "average" übertragen
# Readings mit "SUM" im Namen werden zum Device "Dum.Rep.Sum" in das Reading "summary" übertragen
- averageCalcForm
Legt die Berechnungsvariante für die Ermittlung des Durchschnittswertes mit "averageValue" fest.
Zur Zeit sind folgende Varianten implementiert:
avgArithmeticMean: | Es wird der arithmetische Mittelwert berechnet. (default) |
| |
avgDailyMeanGWS: | Berechnet die Tagesmitteltemperatur entsprechend den |
| Vorschriften des deutschen Wetterdienstes. (siehe "get <name> versionNotes 2") |
| Diese Variante verwendet automatisch die Aggregation "day". |
| |
avgDailyMeanGWSwithGTS: | Wie "avgDailyMeanGWS" und berechnet zusätzlich die Grünlandtemperatursumme. |
| Ist der Wert 200 erreicht, wird das Reading "reachedGTSthreshold" mit dem Datum |
| des erstmaligen Erreichens dieses Schwellenwertes erstellt. |
| Hinweis: Das Attribut timestamp_begin muss auf den Beginn eines Jahres gesetzt werden! |
| (siehe "get <name> versionNotes 5") |
| |
avgTimeWeightMean: | Berechnet den zeitgewichteten Mittelwert. |
| Hinweis: Es müssen mindestens zwei Datenpunkte pro aggregation Periode vorhanden sein. |
- countEntriesDetail - Wenn gesetzt, erstellt die Funktion "countEntries" eine detallierte Ausgabe der Datensatzzahl
pro Reading und Zeitintervall.
Standardmäßig wird nur die Summe aller selektierten Datensätze ausgegeben.
- device - Abgrenzung der DB-Selektionen auf ein bestimmtes oder mehrere Devices.
Es können Geräte-Spezifikationen (devspec) angegeben werden.
In diesem Fall werden die Devicenamen vor der Selektion aus der Geräte-Spezifikationen und den aktuell in FHEM
vorhandenen Devices aufgelöst.
Wird dem Device bzw. der Device-Liste oder Geräte-Spezifikation ein "EXCLUDE=" vorangestellt,
werden diese Devices von der Selektion ausgeschlossen.
Die Datenbankselektion wird als logische UND-Verknüpfung aus "device" und dem Attribut
reading ausgeführt.
Beispiele:
attr <name> device TYPE=DbRep
attr <name> device MySTP_5000
attr <name> device SMA.*,MySTP.*
attr <name> device SMA_Energymeter,MySTP_5000
attr <name> device %5000
attr <name> device TYPE=SSCam EXCLUDE=SDS1_SVS
attr <name> device TYPE=SSCam,TYPE=ESPEasy EXCLUDE=SDS1_SVS
attr <name> device EXCLUDE=SDS1_SVS
attr <name> device EXCLUDE=TYPE=SSCam
Falls weitere Informationen zu Geräte-Spezifikationen benötigt werden, bitte
"get <name> versionNotes 3" ausführen.
- diffAccept [+-]<Schwellenwert>
diffAccept legt für die Funktion diffValue fest, bis zu welchem <Schwellenwert> eine
Werte-Differenz zwischen zwei unmittelbar aufeinander folgenden Datensätzen akzeptiert werden.
Wird dem Schwellenwert +- (optional) vorangestellt, werden sowohl positive als auch negative Differenzen
ausgewertet.
(default: 20, nur positive Differenzen zwischen Vorgänger und Nachfolger)
Beispiel:
attr diffAccept +-10000
Bei Schwellenwertüberschreitungen wird das Reading diff_overrun_limit_<Schwellenwert>
erstellt.
Es enthält eine Liste der relevanten Wertepaare. Mit verbose 3 werden diese Datensätze ebenfalls im Logfile protokolliert.
Beispiel Ausgabe im Logfile beim Überschreiten von diffAccept=10:
DbRep Rep.STP5000.etotal -> data ignored while calc diffValue due to threshold overrun (diffAccept = 10):
2016-04-09 08:50:50 0.0340 -> 2016-04-09 12:42:01 13.3440
# Der Differenz zwischen dem ersten Datensatz mit einem Wert von 0.0340 zum nächsten Wert 13.3440 ist untypisch hoch
und führt zu einem zu hohen Differenzwert.
# Es ist zu entscheiden ob der Datensatz gelöscht, ignoriert, oder das Attribut diffAccept angepasst werden sollte.
- dumpComment - User-Kommentar. Er wird im Kopf des durch den Befehl "dumpMyQL clientSide" erzeugten Dumpfiles
eingetragen.
- dumpCompress - wenn gesetzt, werden die Dumpfiles nach "dumpMySQL" bzw. "dumpSQLite" komprimiert
- dumpDirLocal
Zielverzeichnis für die Erstellung von Dumps mit "dumpMySQL clientSide" oder "dumpSQLite".
Durch Setzen dieses Attributes wird die interne Versionsverwaltung aktiviert.
In diesem Verzeichnis werden Backup Dateien gesucht und gelöscht wenn die gefundene Anzahl den Attributwert
"dumpFilesKeep" überschreitet.
Mit dem Attribut wird ebenfalls ein lokal gemountetes Verzeichnis "dumpDirRemote" (bei dumpMySQL serverSide)
DbRep bekannt gemacht.
(default: {global}{modpath}/log/)
Beispiel:
attr <Name> dumpDirLocal /sds1/backup/dumps_FHEM/
- dumpDirRemote
Zielverzeichnis für die Erstellung von Dumps mit "dumpMySQL serverSide".
(default: das Home-Dir des MySQL-Servers auf dem MySQL-Host)
- dumpMemlimit - erlaubter Speicherverbrauch für das Dump SQL-Script zur Generierungszeit (default: 100000 Zeichen).
Bitte den Parameter anpassen, falls es zu Speicherengpässen und damit verbundenen Performanceproblemen
kommen sollte.
- dumpSpeed - Anzahl der abgerufenen Zeilen aus der Quelldatenbank (default: 10000) pro Select durch "dumpMySQL ClientSide".
Dieser Parameter hat direkten Einfluß auf die Laufzeit und den Ressourcenverbrauch zur Laufzeit.
- dumpFilesKeep
Die integrierte Versionsverwaltung belässt die angegebene Anzahl Backup Dateien im Backup Verzeichnis.
Die Versionsverwaltung muß durch Setzen des Attributs "dumpDirLocal" eingeschaltet sein.
Sind mehr (ältere) Backup Dateien vorhanden, werden diese gelöscht nachdem ein neues Backup erfolgreich erstellt wurde.
Das globale Attribut "archivesort" wird berücksichtigt.
(default: 3)
- executeAfterProc
Es kann ein FHEM-Kommando oder Perl Code angegeben werden der nach der Befehlsabarbeitung ausgeführt
werden soll.
Perl Code ist in {...} einzuschließen. Es stehen die Variablen $hash (Hash des DbRep Devices) und $name
(Name des DbRep-Devices) zur Verfügung.
Beispiel:
attr <name> executeAfterProc set og_gz_westfenster off;
attr <name> executeAfterProc {adump ($name)}
# "adump" ist eine in 99_myUtils definierte Funktion.
sub adump {
my ($name) = @_;
my $hash = $defs{$name};
# die eigene Funktion, z.B.
Log3($name, 3, "DbRep $name -> Dump ist beendet");
return;
}
- executeBeforeProc
Es kann ein FHEM-Kommando oder Perl Code angegeben werden der vor der Befehlsabarbeitung ausgeführt
werden soll.
Perl Code ist in {...} einzuschließen. Es stehen die Variablen $hash (Hash des DbRep Devices) und $name
(Name des DbRep-Devices) zur Verfügung.
Beispiel:
attr <name> executeBeforeProc set og_gz_westfenster on;
attr <name> executeBeforeProc {bdump ($name)}
# "bdump" ist eine in 99_myUtils definierte Funktion.
sub bdump {
my ($name) = @_;
my $hash = $defs{$name};
# die eigene Funktion, z.B.
Log3($name, 3, "DbRep $name -> Dump startet");
return;
}
expimpfile </Pfad/Filename> [MAXLINES=<lines>]
- Pfad/Dateiname für Export/Import in/aus einem File.
Optional kann über den Parameter "MAXLINES" die maximale Anzahl von Datensätzen angegeben
werden, die in ein File exportiert werden. In diesem Fall werden mehrere Files mit den
Extensions "_part1", "_part2", "_part3" usw. erstellt.
Der Dateiname kann Platzhalter enthalten die gemäß der nachfolgenden Tabelle ersetzt werden.
Weiterhin können %-wildcards der POSIX strftime-Funktion des darunterliegenden OS enthalten
sein (siehe auch strftime Beschreibung).
%L | : wird ersetzt durch den Wert des global logdir Attributs |
%TSB | : wird ersetzt durch den (berechneten) Wert des Starttimestamps der Datenselektion |
| |
| Allgemein gebräuchliche POSIX-Wildcards sind: |
%d | : Tag des Monats (01..31) |
%m | : Monat (01..12) |
%Y | : Jahr (1970...) |
%w | : Wochentag (0..6); beginnend mit Sonntag (0) |
%j | : Tag des Jahres (001..366) |
%U | : Wochennummer des Jahres, wobei Wochenbeginn = Sonntag (00..53) |
%W | : Wochennummer des Jahres, wobei Wochenbeginn = Montag (00..53) |
Beispiele:
attr <name> expimpfile /sds1/backup/exptest_%TSB.csv
attr <name> expimpfile /sds1/backup/exptest_%Y-%m-%d.csv
Zur POSIX Wildcardverwendung siehe auch die Erläuterungen zum Filelog Modul.
fastStart - Normalerweise verbindet sich jedes DbRep-Device beim FHEM-Start kurz mit seiner Datenbank um
benötigte Informationen abzurufen und das Reading "state" springt bei Erfolg auf "connected".
Ist dieses Attribut gesetzt, erfolgt die initiale Datenbankverbindung erst dann wenn das
DbRep-Device sein erstes Kommando ausführt.
Das Reading "state" verbleibt nach FHEM-Start solange im Status "initialized".
(default: 1 für TYPE Client)
fetchMarkDuplicates
- Markierung von mehrfach vorkommenden Datensätzen im Ergebnis des "fetchrows" Kommandos
fetchRoute [descent | ascent] - bestimmt die Leserichtung des fetchrows-Befehl.
descent - die Datensätze werden absteigend gelesen (default). Wird
die durch das Attribut "limit" festgelegte Anzahl der Datensätze
überschritten, werden die neuesten x Datensätze angezeigt.
ascent - die Datensätze werden aufsteigend gelesen. Wird
die durch das Attribut "limit" festgelegte Anzahl der Datensätze
überschritten, werden die ältesten x Datensätze angezeigt.
fetchValueFn - Der angezeigte Wert des Datenbankfeldes VALUE kann vor der Erstellung des entsprechenden
Readings geändert werden. Das Attribut muss eine Perl Funktion eingeschlossen in {}
enthalten.
Der Wert des Datenbankfeldes VALUE wird in der Variable $VALUE zur Verfügung gestellt.
Beispiel:
attr <name> fetchValueFn { $VALUE =~ s/^.*Used:\s(.*)\sMB,.*/$1." MB"/e }
# Von einer langen Ausgabe wird ein spezifisches Zeichenmuster extrahiert und als VALUE
anstatt der gesamten Zeile im Reading angezeigt.
ftpUse - FTP Transfer nach einem Dump wird eingeschaltet (ohne SSL Verschlüsselung). Das erzeugte
Datenbank Backupfile wird non-blocking zum angegebenen FTP-Server (Attribut "ftpServer")
übertragen.
ftpUseSSL - FTP Transfer mit SSL Verschlüsselung nach einem Dump wird eingeschaltet. Das erzeugte
Datenbank Backupfile wird non-blocking zum angegebenen FTP-Server (Attribut "ftpServer")
übertragen.
ftpUser - User zur Anmeldung am FTP-Server nach einem Dump, default: "anonymous".
ftpDebug - Debugging der FTP Kommunikation zur Fehlersuche.
ftpDir - Verzeichnis des FTP-Servers in welches das File nach einem Dump übertragen werden soll
(default: "/").
ftpDumpFilesKeep - Es wird die angegebene Anzahl Dumpfiles im <ftpDir> belassen (default: 3). Sind mehr
(ältere) Dumpfiles vorhanden, werden diese gelöscht nachdem ein neuer Dump erfolgreich
übertragen wurde.
ftpPassive - setzen wenn passives FTP verwendet werden soll
ftpPort - FTP-Port, default: 21
ftpPwd - Passwort des FTP-Users, default nicht gesetzt
ftpServer - Name oder IP-Adresse des FTP-Servers zur Übertragung von Files nach einem Dump.
ftpTimeout - Timeout für eine FTP-Verbindung in Sekunden (default: 30).
limit - begrenzt die Anzahl der resultierenden Datensätze im select-Statement von "fetchrows", bzw. der anzuzeigenden Datensätze
der Kommandos "delSeqDoublets adviceDelete", "delSeqDoublets adviceRemain" (default 1000).
Diese Limitierung soll eine Überlastung der Browsersession und ein
blockieren von FHEMWEB verhindern. Bei Bedarf entsprechend ändern bzw. die
Selektionskriterien (Zeitraum der Auswertung) anpassen.
numDecimalPlaces - Legt die Anzahl der Nachkommastellen bei Readings mit numerischen Ergebnissen fest.
Ausgenommen sind Ergebnisse aus userspezifischen Abfragen (sqlCmd).
(default: 4)
optimizeTablesBeforeDump - wenn "1", wird vor dem Datenbankdump eine Tabellenoptimierung ausgeführt (default: 0).
Dadurch verlängert sich die Laufzeit des Dump.
Hinweis
Die Tabellenoptimierung führt zur Sperrung der Tabellen und damit zur Blockierung von
FHEM falls DbLog nicht im asynchronen Modus (DbLog-Attribut "asyncMode") betrieben wird !
reading - Abgrenzung der DB-Selektionen auf ein bestimmtes oder mehrere Readings sowie exkludieren von
Readings.
Mehrere Readings werden als Komma separierte Liste angegeben.
Es können SQL Wildcard (%) verwendet werden.
Wird dem Reading bzw. der Reading-Liste ein "EXCLUDE=" vorangestellt, werden diese Readings
nicht inkludiert.
Die Datenbankselektion wird als logische UND Verknüpfung aus "reading" und dem Attribut
device ausgeführt.
Beispiele:
attr <name> reading etotal
attr <name> reading et%
attr <name> reading etotal,etoday
attr <name> reading eto%,Einspeisung EXCLUDE=etoday
attr <name> reading etotal,etoday,Ein% EXCLUDE=%Wirkleistung
readingNameMap - ein Teil des erstellten Readingnamens wird mit dem angegebenen String ersetzt.
readingPreventFromDel - Komma separierte Liste von Readings die vor einer neuen Operation nicht gelöscht
werden sollen
role - die Rolle des DbRep-Device. Standard ist "Client". Die Rolle "Agent" ist im Abschnitt
"DbRep-Agent" beschrieben.
Siehe auch Abschnitt DbRep-Agent.
seqDoubletsVariance <positive Abweichung [negative Abweichung] [EDGE=negative|positive]>
Akzeptierte Abweichung für das Kommando "set <name> delSeqDoublets".
Der Wert des Attributs beschreibt die Abweichung bis zu der aufeinanderfolgende numerische
Werte (VALUE) von Datensätzen als gleich angesehen werden sollen.
Ist in "seqDoubletsVariance" nur ein Zahlenwert angegeben, wird er sowohl als positive als
auch negative Abweichung verwendet und bilden den "Löschkorridor".
Optional kann ein zweiter Zahlenwert für eine negative Abweichung, getrennt durch
Leerzeichen, angegeben werden.
Es sind immer absolute, d.h. positive Zahlenwerte anzugeben.
Ist der Zusatz "EDGE=negative" angegeben, werden Werte an einer negativen Flanke
(z.B. beim Wechel von 4.0 -> 1.0) nicht gelöscht auch wenn sie sich im "Löschkorridor"
befinden. Entsprechendes gilt bei "EDGE=positive" für die positive Flanke (z.B. beim Wechel
von 1.2 -> 2.8).
Beispiele:
attr <name> seqDoubletsVariance 0.0014
attr <name> seqDoubletsVariance 1.45
attr <name> seqDoubletsVariance 3.0 2.0
attr <name> seqDoubletsVariance 1.5 EDGE=negative
showproctime - wenn gesetzt, zeigt das Reading "sql_processing_time" die benötigte Abarbeitungszeit (in Sekunden)
für die SQL-Ausführung der durchgeführten Funktion. Dabei wird nicht ein einzelnes
SQl-Statement, sondern die Summe aller notwendigen SQL-Abfragen innerhalb der jeweiligen
Funktion betrachtet.
showStatus - grenzt die Ergebnismenge des Befehls "get <name> dbstatus" ein. Es können
SQL-Wildcard (%) verwendet werden.
Bespiel:
attr <name> showStatus %uptime%,%qcache%
# Es werden nur Readings erzeugt die im Namen "uptime" und "qcache" enthalten
showVariables - grenzt die Ergebnismenge des Befehls "get <name> dbvars" ein. Es können
SQL-Wildcard (%) verwendet werden.
Bespiel:
attr <name> showVariables %version%,%query_cache%
# Es werden nur Readings erzeugt die im Namen "version" und "query_cache" enthalten
showSvrInfo - grenzt die Ergebnismenge des Befehls "get <name> svrinfo" ein. Es können
SQL-Wildcard (%) verwendet werden.
Bespiel:
attr <name> showSvrInfo %SQL_CATALOG_TERM%,%NAME%
# Es werden nur Readings erzeugt die im Namen "SQL_CATALOG_TERM" und "NAME" enthalten
showTableInfo
Grenzt die Ergebnismenge des Befehls "get <name> tableinfo" ein. Es können SQL-Wildcard (%) verwendet werden.
Bespiel:
attr <name> showTableInfo current,history
# Es werden nur Information der Tabellen "current" und "history" angezeigt
sqlCmdHistoryLength
Aktiviert mit einem Wert > 0 die Kommandohistorie von "sqlCmd" und legt die Anzahl der zu speichernden
SQL Statements fest.
(default: 0)
sqlCmdVars
Setzt die angegebene(n) SQL Session Variable(n) oder PRAGMA vor jedem mit sqlCmd ausgeführten
SQL-Statement.
Beispiel:
attr <name> sqlCmdVars SET @open:=NULL, @closed:=NULL;
attr <name> sqlCmdVars PRAGMA temp_store=MEMORY;PRAGMA synchronous=FULL;PRAGMA journal_mode=WAL;
sqlFormatService
Über einen Online-Dienst kann eine automatisierte Formatierung von SQL-Statements aktiviert werden.
Diese Möglichkeit ist insbesondere für komplexe SQL-Statements der Setter sqlCmd, sqlCmdHistory und sqlSpecial
hilfreich um die Strukturierung und Lesbarkeit zu verbessern.
Eine Internetverbindung wird benötigt und es sollte das globale Attribut dnsServer gesetzt sein.
(default: none)
sqlResultFieldSep
Legt den verwendeten Feldseparator im Ergebnis des Kommandos "set ... sqlCmd" fest.
(default: "|")
sqlResultFormat - legt die Formatierung des Ergebnisses des Kommandos "set <name> sqlCmd" fest.
Mögliche Optionen sind:
separated - die Ergebniszeilen werden als einzelne Readings fortlaufend
generiert. (default)
mline - das Ergebnis wird als Mehrzeiler im Reading
SqlResult dargestellt.
sline - das Ergebnis wird als Singleline im Reading
SqlResult dargestellt. Satztrenner ist"]|[".
table - das Ergebnis wird als Tabelle im Reading
SqlResult dargestellt.
json - erzeugt das Reading SqlResult als
JSON-kodierten Hash.
Jedes Hash-Element (Ergebnissatz) setzt sich aus der laufenden Nummer
des Datensatzes (Key) und dessen Wert zusammen.
Die Weiterverarbeitung des Ergebnisses kann z.B. mit der folgenden userExitFn in 99_myUtils.pm erfolgen:
sub resfromjson {
my ($name,$reading,$value) = @_;
my $hash = $defs{$name};
if ($reading eq "SqlResult") {
# nur Reading SqlResult enthält JSON-kodierte Daten
my $data = decode_json($value);
foreach my $k (keys(%$data)) {
# ab hier eigene Verarbeitung für jedes Hash-Element
# z.B. Ausgabe jedes Element welches "Cam" enthält
my $ke = $data->{$k};
if($ke =~ m/Cam/i) {
my ($res1,$res2) = split("\\|", $ke);
Log3($name, 1, "$name - extract element $k by userExitFn: ".$res1." ".$res2);
}
}
}
return;
}
timeYearPeriod - Mit Hilfe dieses Attributes wird eine jährliche Zeitperiode für die Datenbankselektion bestimmt.
Die Zeitgrenzen werden zur Ausführungszeit dynamisch berechnet. Es wird immer eine Jahresperiode
bestimmt. Eine unterjährige Angabe ist nicht möglich.
Dieses Attribut ist vor allem dazu gedacht Auswertungen synchron zu einer Abrechnungsperiode, z.B. der eines
Energie- oder Gaslieferanten, anzufertigen.
Beispiel:
attr <name> timeYearPeriod 06-25 06-24
# wertet die Datenbank in den Zeitgrenzen 25. Juni AAAA bis 24. Juni BBBB aus.
# Das Jahr AAAA bzw. BBBB wird in Abhängigkeit des aktuellen Datums errechnet.
# Ist das aktuelle Datum >= 25. Juni und =< 31. Dezember, dann ist AAAA = aktuelles Jahr und BBBB = aktuelles Jahr+1
# Ist das aktuelle Datum >= 01. Januar und =< 24. Juni, dann ist AAAA = aktuelles Jahr-1 und BBBB = aktuelles Jahr
timestamp_begin - der zeitliche Beginn für die Datenselektion
Das Format von Timestamp ist "YYYY-MM-DD HH:MM:SS". Für die Attribute "timestamp_begin", "timestamp_end"
kann ebenso eine der folgenden Eingaben verwendet werden. Dabei wird das timestamp-Attribut dynamisch belegt:
current_year_begin : entspricht "<aktuelles Jahr>-01-01 00:00:00"
current_year_end : entspricht "<aktuelles Jahr>-12-31 23:59:59"
previous_year_begin : entspricht "<vorheriges Jahr>-01-01 00:00:00"
previous_year_end : entspricht "<vorheriges Jahr>-12-31 23:59:59"
current_month_begin : entspricht "<aktueller Monat erster Tag> 00:00:00"
current_month_end : entspricht "<aktueller Monat letzter Tag> 23:59:59"
previous_month_begin : entspricht "<Vormonat erster Tag> 00:00:00"
previous_month_end : entspricht "<Vormonat letzter Tag> 23:59:59"
current_week_begin : entspricht "<erster Tag der akt. Woche> 00:00:00"
current_week_end : entspricht "<letzter Tag der akt. Woche> 23:59:59"
previous_week_begin : entspricht "<erster Tag Vorwoche> 00:00:00"
previous_week_end : entspricht "<letzter Tag Vorwoche> 23:59:59"
current_day_begin : entspricht "<aktueller Tag> 00:00:00"
current_day_end : entspricht "<aktueller Tag> 23:59:59"
previous_day_begin : entspricht "<Vortag> 00:00:00"
previous_day_end : entspricht "<Vortag> 23:59:59"
next_day_begin : entspricht "<nächster Tag> 00:00:00"
next_day_end : entspricht "<nächster Tag> 23:59:59"
current_hour_begin : entspricht "<aktuelle Stunde>:00:00"
current_hour_end : entspricht "<aktuelle Stunde>:59:59"
previous_hour_begin : entspricht "<vorherige Stunde>:00:00"
previous_hour_end : entspricht "<vorherige Stunde>:59:59"
timestamp_end - das zeitliche Ende für die Datenselektion. Wenn nicht gesetzt wird immer die aktuelle
Datum/Zeit-Kombi für das Ende der Selektion eingesetzt.
Das Format von Timestamp ist "YYYY-MM-DD HH:MM:SS". Für die Attribute "timestamp_begin", "timestamp_end"
kann ebenso eine der folgenden Eingaben verwendet werden. Dabei wird das timestamp-Attribut dynamisch belegt:
current_year_begin : entspricht "<aktuelles Jahr>-01-01 00:00:00"
current_year_end : entspricht "<aktuelles Jahr>-12-31 23:59:59"
previous_year_begin : entspricht "<vorheriges Jahr>-01-01 00:00:00"
previous_year_end : entspricht "<vorheriges Jahr>-12-31 23:59:59"
current_month_begin : entspricht "<aktueller Monat erster Tag> 00:00:00"
current_month_end : entspricht "<aktueller Monat letzter Tag> 23:59:59"
previous_month_begin : entspricht "<Vormonat erster Tag> 00:00:00"
previous_month_end : entspricht "<Vormonat letzter Tag> 23:59:59"
current_week_begin : entspricht "<erster Tag der akt. Woche> 00:00:00"
current_week_end : entspricht "<letzter Tag der akt. Woche> 23:59:59"
previous_week_begin : entspricht "<erster Tag Vorwoche> 00:00:00"
previous_week_end : entspricht "<letzter Tag Vorwoche> 23:59:59"
current_day_begin : entspricht "<aktueller Tag> 00:00:00"
current_day_end : entspricht "<aktueller Tag> 23:59:59"
previous_day_begin : entspricht "<Vortag> 00:00:00"
previous_day_end : entspricht "<Vortag> 23:59:59"
next_day_begin : entspricht "<nächster Tag> 00:00:00"
next_day_end : entspricht "<nächster Tag> 23:59:59"
current_hour_begin : entspricht "<aktuelle Stunde>:00:00"
current_hour_end : entspricht "<aktuelle Stunde>:59:59"
previous_hour_begin : entspricht "<vorherige Stunde>:00:00"
previous_hour_end : entspricht "<vorherige Stunde>:59:59"
Natürlich sollte man immer darauf achten dass "timestamp_begin" < "timestamp_end" ist.
Beispiel:
attr <name> timestamp_begin current_year_begin
attr <name> timestamp_end current_year_end
# Wertet die Datenbank in den Zeitgrenzen des aktuellen Jahres aus.
Hinweis
Wird das Attribut "timeDiffToNow" gesetzt, werden die eventuell gesetzten anderen Zeit-Attribute
("timestamp_begin","timestamp_end","timeYearPeriod") gelöscht.
Das Setzen von "timestamp_begin" bzw. "timestamp_end" bedingt die Löschung von anderen Zeit-Attribute falls sie vorher
gesetzt waren.
timeDiffToNow - der Selektionsbeginn wird auf den Zeitpunkt "<aktuelle Zeit> - <timeDiffToNow>"
gesetzt. Die Timestampermittlung erfolgt dynamisch zum Ausführungszeitpunkt. Optional kann mit
der Zusatzangabe "FullDay" der Selektionsbeginn und das Selektionsende auf Beginn / Ende der
jeweiligen Selektionstage erweitert werden (wirkt nur wenn eingestellte Zeitdifferenz ist >= 1 Tag).
Eingabeformat Beispiele:
attr <name> timeDiffToNow 86400
# die Startzeit wird auf "aktuelle Zeit - 86400 Sekunden" gesetzt
attr <name> timeDiffToNow d:2 h:3 m:2 s:10
# die Startzeit wird auf "aktuelle Zeit - 2 Tage 3 Stunden 2 Minuten 10 Sekunden" gesetzt
attr <name> timeDiffToNow m:600
# die Startzeit wird auf "aktuelle Zeit - 600 Minuten" gesetzt
attr <name> timeDiffToNow h:2.5
# die Startzeit wird auf "aktuelle Zeit - 2,5 Stunden" gesetzt
attr <name> timeDiffToNow y:1 h:2.5
# die Startzeit wird auf "aktuelle Zeit - 1 Jahr und 2,5 Stunden" gesetzt
attr <name> timeDiffToNow y:1.5
# die Startzeit wird auf "aktuelle Zeit - 1,5 Jahre gesetzt
attr <name> timeDiffToNow d:8 FullDay
# die Startzeit wird auf "aktuelle Zeit - 8 Tage gesetzt, der Selektionszeitraum wird auf Beginn / Ende der beteiligten Tage erweitert
Sind die Attribute "timeDiffToNow" und "timeOlderThan" gleichzeitig gesetzt, wird der
Selektionszeitraum zwischen diesen Zeitpunkten dynamisch kalkuliert.
timeOlderThan - das Selektionsende wird auf den Zeitpunkt "<aktuelle Zeit> - <timeOlderThan>"
gesetzt. Dadurch werden alle Datensätze bis zu dem Zeitpunkt "<aktuelle
Zeit> - <timeOlderThan>" berücksichtigt. Die Timestampermittlung erfolgt
dynamisch zum Ausführungszeitpunkt. Optional kann mit der Zusatzangabe
"FullDay" der Selektionsbeginn und das Selektionsende auf Beginn / Ende der jeweiligen
Selektionstage erweitert werden (wirkt nur wenn eingestellte Zeitdifferenz ist >= 1 Tag).
Eingabeformat Beispiele:
attr <name> timeOlderThan 86400
# das Selektionsende wird auf "aktuelle Zeit - 86400 Sekunden" gesetzt
attr <name> timeOlderThan d:2 h:3 m:2 s:10
# das Selektionsende wird auf "aktuelle Zeit - 2 Tage 3 Stunden 2 Minuten 10 Sekunden" gesetzt
attr <name> timeOlderThan m:600
# das Selektionsende wird auf "aktuelle Zeit - 600 Minuten" gesetzt
attr <name> timeOlderThan h:2.5
# das Selektionsende wird auf "aktuelle Zeit - 2,5 Stunden" gesetzt
attr <name> timeOlderThan y:1 h:2.5
# das Selektionsende wird auf "aktuelle Zeit - 1 Jahr und 2,5 Stunden" gesetzt
attr <name> timeOlderThan y:1.5
# das Selektionsende wird auf "aktuelle Zeit - 1,5 Jahre gesetzt
attr <name> timeOlderThan d:8 FullDay
# das Selektionsende wird auf "aktuelle Zeit - 8 Tage gesetzt, der Selektionszeitraum wird auf Beginn / Ende der beteiligten Tage erweitert
Sind die Attribute "timeDiffToNow" und "timeOlderThan" gleichzeitig gesetzt, wird der
Selektionszeitraum zwischen diesen Zeitpunkten dynamisch kalkuliert.
timeout - das Attribut setzt den Timeout-Wert für die Blocking-Call Routinen in Sekunden
(Default: 86400)
useAdminCredentials
- Wenn gesetzt, wird ein zuvor mit "set <Name> adminCredentials" gespeicherter
privilegierter User für bestimmte Datenbankoperationen verwendet.
(nur gültig für Datenbanktyp MYSQL und DbRep-Typ "Client")
userExitFn - stellt eine Schnittstelle zur Ausführung eigenen Usercodes zur Verfügung.
Grundsätzlich arbeitet die Schnittstelle ohne Eventgenerierung bzw. benötigt zur Funktion
keinen Event.
Die Schnittstelle kann mit folgenden Varianten verwendet werden.
1. Aufruf einer Subroutine, z.B. in 99_myUtils.pm
Die aufzurufende Subroutine wird in 99_myUtils.pm nach folgendem Muster erstellt:
sub UserFunction {
my $name = shift; # der Name des DbRep-Devices
my $reading = shift; # der Namen des erstellen Readings
my $value = shift; # der Wert des Readings
my $hash = $defs{$name};
...
# z.B. übergebene Daten loggen
Log3 $name, 1, "UserExitFn $name called - transfer parameter are Reading: $reading, Value: $value " ;
...
return;
}
Im Attribut wird die Subroutine und optional ein Reading:Value Regex
als Argument angegeben. Ohne diese Angabe werden alle Wertekombinationen als "wahr"
gewertet und an die Subroutine übergeben (entspricht .*:.*).
Beispiel:
attr userExitFn UserFunction Meter:Energy.*
# "UserFunction" ist die Subroutine in 99_myUtils.pm.
Die Regexprüfung nach der Erstellung jedes Readings.
Ist die Prüfung wahr, wird die angegebene Funktion aufgerufen.
2. direkte Eingabe von eigenem Code
Der eigene Code wird in geschweifte Klammern eingeschlossen.
Der Aufruf des Codes erfolgt nach der Erstellung jedes Readings.
Im Code stehen folgende Variablen für eine Auswertung zur Verfügung:
- $NAME - der Name des DbRep-Devices
- $READING - der Namen des erstellen Readings
- $VALUE - der Wert des Readings
{
if ($READING =~ /PrEnergySumHwc1_0_value__DIFF/) {
my $mpk = AttrVal($NAME, 'Multiplikator', '0');
my $tarf = AttrVal($NAME, 'Tarif', '0'); # Kosten €/kWh
my $m3 = sprintf "%.3f", $VALUE/10000 * $mpk; # verbrauchte m3
my $kwh = sprintf "%.3f", $m3 * AttrVal($NAME, 'Brennwert_kWh/m3', '0'); # Umrechnung m3 -> kWh
my $cost = sprintf "%.2f", $kwh * $tarf;
my $hash = $defs{$NAME};
readingsBulkUpdate ($hash, 'gas_consumption_m3', $m3);
readingsBulkUpdate ($hash, 'gas_consumption_kwh', $kwh);
readingsBulkUpdate ($hash, 'gas_costs_euro', $cost);
}
}
# Es werden die Readings gas_consumption_m3, gas_consumption_kwh und gas_costs_euro berechnet
und im DbRep-Device erzeugt.
valueFilter - Regulärer Ausdruck (REGEXP) zur Filterung von Datensätzen innerhalb bestimmter Funktionen.
Der REGEXP wird auf ein bestimmtes Feld oder den gesamten selektierten Datensatz (inkl. Device,
Reading usw.) angewendet.
Bitte beachten sie die Erläuterungen zu den entsprechenden Set-Kommandos. Weitere Informationen
sind mit "get <name> versionNotes 4" verfügbar.
Readings
Abhängig von der ausgeführten DB-Operation werden die Ergebnisse in entsprechenden Readings dargestellt. Zu Beginn einer neuen Operation
werden alle alten Readings einer vorangegangenen Operation gelöscht um den Verbleib unpassender bzw. ungültiger Readings zu vermeiden.
Zusätzlich werden folgende Readings erzeugt (Auswahl):
- state - enthält den aktuellen Status der Auswertung. Wenn Warnungen auftraten (state = Warning) vergleiche Readings
"diff_overrun_limit_<diffLimit>" und "less_data_in_period"
- errortext - Grund eines Fehlerstatus
- background_processing_time - die gesamte Prozesszeit die im Hintergrund/Blockingcall verbraucht wird
- diff_overrun_limit_<diffLimit> - enthält eine Liste der Wertepaare die eine durch das Attribut "diffAccept" festgelegte Differenz
<diffLimit> (Standard: 20) überschreiten. Gilt für Funktion "diffValue".
- less_data_in_period - enthält eine Liste der Zeitperioden in denen nur ein einziger Datensatz gefunden wurde. Die
Differenzberechnung berücksichtigt den letzten Wert der Vorperiode. Gilt für Funktion "diffValue".
- sql_processing_time - der Anteil der Prozesszeit die für alle SQL-Statements der ausgeführten
Operation verbraucht wird
- SqlResult - Ergebnis des letzten sqlCmd-Kommandos. Die Formatierung erfolgt entsprechend
des sqlResultFormat Attributes
- sqlCmd - das letzte ausgeführte sqlCmd-Kommando
DbRep Agent - automatisches Ändern von Device-Namen in Datenbanken und DbRep-Definitionen nach FHEM "rename" Kommando
Mit dem Attribut "role" wird die Rolle des DbRep-Device festgelegt. Die Standardrolle ist "Client". Mit der Änderung der Rolle in "Agent" wird das Device
veranlasst auf Umbenennungen von Geräten in der FHEM Installation zu reagieren.
Durch den DbRep-Agenten werden folgende Features aktiviert wenn ein Gerät in FHEM mit "rename" umbenannt wird:
- in der dem DbRep-Agenten zugeordneten Datenbank (Internal Database) wird nach Datensätzen mit dem alten Gerätenamen gesucht und dieser Gerätename in
allen betroffenen Datensätzen in den neuen Namen geändert.
- in dem DbRep-Agenten zugeordneten DbLog-Device wird in der Definition das alte durch das umbenannte Device ersetzt. Dadurch erfolgt ein weiteres Logging
des umbenannten Device in der Datenbank.
- in den existierenden DbRep-Definitionen vom Typ "Client" wird ein evtl. gesetztes Attribut "device = alter Devicename" in "device = neuer Devicename"
geändert. Dadurch werden Auswertungsdefinitionen bei Geräteumbenennungen automatisch konstistent gehalten.
Mit der Änderung in einen Agenten sind folgende Restriktionen verbunden die mit dem Setzen des Attributes "role = Agent" eingeschaltet
und geprüft werden:
- es kann nur einen Agenten pro Datenbank in der FHEM-Installation geben. Ist mehr als eine Datenbank mit DbLog definiert, können
ebenso viele DbRep-Agenten eingerichtet werden
- mit der Umwandlung in einen Agenten wird nur noch das Set-Komando "renameDevice" verfügbar sein sowie nur ein eingeschränkter Satz von DbRep-spezifischen
Attributen zugelassen. Wird ein DbRep-Device vom bisherigen Typ "Client" in einen Agenten geändert, werden evtl. gesetzte und nun nicht mehr zugelassene
Attribute glöscht.
Die Aktivitäten wie Datenbankänderungen bzw. Änderungen an anderen DbRep-Definitionen werden im Logfile mit verbose=3 protokolliert. Damit die renameDevice-Funktion
bei großen Datenbanken nicht in ein timeout läuft, sollte das Attribut "timeout" entsprechend dimensioniert werden. Wie alle Datenbankoperationen des Moduls
wird auch das Autorename nonblocking ausgeführt.
Beispiel für die Definition eines DbRep-Device als Agent:
define Rep.Agent DbRep LogDB
attr Rep.Agent devStateIcon connected:10px-kreis-gelb .*disconnect:10px-kreis-rot .*done:10px-kreis-gruen
attr Rep.Agent icon security
attr Rep.Agent role Agent
attr Rep.Agent room DbLog
attr Rep.Agent showproctime 1
attr Rep.Agent stateFormat { ReadingsVal($name, 'state', '') eq 'running' ? 'renaming' : ReadingsVal($name, 'state', ''). ' »; ProcTime: '.ReadingsVal($name, 'sql_processing_time', '').' sec'}
attr Rep.Agent timeout 86400
Hinweis:
Obwohl die Funktion selbst non-blocking ausgelegt ist, sollte das zugeordnete DbLog-Device
im asynchronen Modus betrieben werden um ein Blockieren von FHEMWEB zu vermeiden (Tabellen-Lock).
=end html_DE
=for :application/json;q=META.json 93_DbRep.pm
{
"abstract": "Reporting and management of DbLog database content.",
"x_lang": {
"de": {
"abstract": "Reporting und Management von DbLog Datenbankinhalten."
}
},
"keywords": [
"dblog",
"database",
"reporting",
"logging",
"analyze"
],
"version": "v1.1.1",
"release_status": "stable",
"author": [
"Heiko Maaz "
],
"x_fhem_maintainer": [
"DS_Starter"
],
"x_fhem_maintainer_github": [
"nasseeder1"
],
"prereqs": {
"runtime": {
"requires": {
"FHEM": 5.00918799,
"perl": 5.014,
"POSIX": 0,
"Time::HiRes": 0,
"Scalar::Util": 0,
"DBI": 0,
"DBI::Const::GetInfoType": 0,
"Blocking": 0,
"Color": 0,
"Time::Local": 0,
"Encode": 0
},
"recommends": {
"Net::FTP": 0,
"IO::Compress::Gzip": 0,
"IO::Uncompress::Gunzip": 0,
"FHEM::Meta": 0
},
"suggests": {
"Net::FTPSSL": 0
}
}
},
"resources": {
"x_wiki": {
"web": "https://wiki.fhem.de/wiki/DbRep_-_Reporting_und_Management_von_DbLog-Datenbankinhalten",
"title": "DbRep - Reporting und Management von DbLog-Datenbankinhalten"
},
"repository": {
"x_dev": {
"type": "svn",
"url": "https://svn.fhem.de/trac/browser/trunk/fhem/contrib/DS_Starter",
"web": "https://svn.fhem.de/trac/browser/trunk/fhem/contrib/DS_Starter/93_DbRep.pm",
"x_branch": "dev",
"x_filepath": "fhem/contrib/",
"x_raw": "https://svn.fhem.de/fhem/trunk/fhem/contrib/DS_Starter/93_DbRep.pm"
}
}
}
}
=end :application/json;q=META.json
=cutt